public static Boolean createAccount(string email, string first, string last, string password, string gender, DateTime birthday)
        {
            try
            {
                SIEBUEntities db = new SIEBUEntities();
                if (db.Users.Where(u => u.email == email).Count() == 0)
                {
                    //populate user object with general information
                    User n_customer = new User();
                    n_customer.email = email;
                    n_customer.firstName = first;
                    n_customer.lastName = last;
                    n_customer.dob = birthday;
                    n_customer.joindate = DateTime.Now;
                    n_customer.gender = (gender == "female") ? true : false;
                    // encryption/salt creation
                    byte[] salt = new byte[48];
                    new RNGCryptoServiceProvider().GetBytes(salt);
                    n_customer.salt = salt;
                    n_customer.password = encrypt(email, password, salt);

                    db.Users.Add(n_customer);
                    db.SaveChanges();
                    return true;
                }
                return false;

            }

            catch (Exception e)
            {
                Console.WriteLine("The Error is " + e.ToString());
                return false;
            }
        }
        public static Boolean createAccount(string email, string first, string last, string password)
        {
            SIEBUEntities db = new SIEBUEntities();
            if (db.Users.Where(u => u.email == email).Count() == 0)
            {
                WebSecurity.CreateUserAndAccount(email, password, new { firstname = first, lastname = last, joindate = DateTime.Now });

                //Current User Confirmation
                /*
                string confirmationToken = WebSecurity.CreateUserAndAccount(email, password, new { firstname = first, lastname = last, joindate =                       DateTime.Now }, true);
                WebSecurity.Login(email, password);
                dynamic confirmationEmail = new Email("ConfirmEmail");
                confirmationEmail.to = email;
                confirmationEmail.firstname = first;
                confirmationEmail.from = "*****@*****.**";
                confirmationEmail.ConfirmationToken = confirmationToken;
                confirmationEmail.Send(); */

                /** Old user registration **/
                /*User n_customer = new User();
                n_customer.email = email;
                n_customer.firstName = first;
                n_customer.lastName = last;
                n_customer.joindate = DateTime.Now;
                    encryption/salt creation
                byte[] salt = new byte[48];
                new RNGCryptoServiceProvider().GetBytes(salt);
                n_customer.salt = salt;
                n_customer.password = encrypt(email, password, salt);
                db.Users.Add(n_customer);
                db.SaveChanges();*/
                return true;
            }
            return false;
        }
        /// <summary>
        /// Confirmation Page before payment processing.
        /// </summary>
        /// <returns></returns>
        public ActionResult ConfirmationPage()
        {
            if (!Request.IsAuthenticated)
                return RedirectToAction("LogOn", "Account");
            ShoppingCartModel shoppingCart = Siebu.Models.ShoppingCartModel.GetInstance(WebSecurity.CurrentUserId);
            shoppingCart.storeCartInDB(WebSecurity.CurrentUserId);

            ConfirmationViewModel model = new ConfirmationViewModel();
            using (SIEBUEntities context = new SIEBUEntities())
            {
                model.shoppingCart = ShoppingCartModel.getCartFromDB(WebSecurity.CurrentUserId);

                Transaction progressTransaction = db.Transactions.OrderByDescending(tr => tr.datecreated).Where(tr =>
                    tr.payer_id == WebSecurity.CurrentUserId && tr.is_processed == false).FirstOrDefault();
                if (progressTransaction == null)
                {
                    Debug.WriteLine("Confirmation Page Error.  Progress Transaction Does not exist");
                    return Json(false, JsonRequestBehavior.AllowGet);
                }
                model.chosen_addresses = progressTransaction.Address;
                model.billing_address = progressTransaction.Address1;

                decimal discount = (decimal)progressTransaction.discount;
                if (model.shoppingCart.cartTotal == discount)
                {
                    model.usePaypal = false;
                    model.discount = discount;
                }
                else
                {
                    model.usePaypal = true;
                }
            }
            return PartialView(model);
        }
        public ActivityHistoryViewModel(int user_id, Boolean show_purchases = false, Boolean show_sales = false)
        {
            SIEBUEntities db = new SIEBUEntities();

            history = new List<ActivityHistoryModel>();

            if (show_purchases)
            {
                foreach (Transaction purchase in db.Transactions.Where(t => t.payer_id == user_id && t.is_processed == true).OrderBy(t => t.dateprocessed))
                    history.Add(new ActivityHistoryModel(purchase, db));

                //List<User_Purchase_History> purchaseHistory = db.User_Purchase_History.Where(pr =>
                //    pr.user_id == user_id).ToList();
                //foreach (User_Purchase_History pHist in purchaseHistory)
                //    history.Add(new ActivityHistoryModel(pHist, db));
                type = purchaseActivity;
            }

            if (show_sales)
            {
                foreach (Transaction_Subtransaction sale in db.Transaction_Subtransaction.Where(st => st.Store.creator_id == user_id && st.Transaction.is_processed == true).OrderByDescending(st => st.Transaction.dateprocessed))
                    history.Add(new ActivityHistoryModel(sale, db));

                //List<User_Credit_History> creditHistory = db.User_Credit_History.OrderByDescending(cr => cr.date).Where(cr =>
                //    cr.user_id == user_id).ToList();
                //foreach (User_Credit_History cHist in creditHistory)
                //    history.Add(new ActivityHistoryModel(cHist, db));
                type = salesActivity;
            }

            if (show_sales && show_purchases) type = allActivity;
            history = history.OrderByDescending(o => o.date).ToList();
        }
        public BlogEntryModel(int id, bool expanded = false, SIEBUEntities db = null)
        {
            if (db == null) db = new SIEBUEntities();
            Store_NewsItem ni = db.Store_NewsItem.FirstOrDefault(i => i.sn_id == id);
            id = ni.sn_id;
            author_name = ni.User.firstName + " " + ni.User.lastName;
            title = ni.title;
            description = getSummary(ni);
            img = ni.img;
            is_draft = ni.is_draft == true;
            is_featured = ni.is_featured == true;

            if (ni.date_added.HasValue) {
                dateadded = ni.date_added.Value;
                dateadded_short = String.Format("{0:MMMM d}", ni.date_added.Value);
            }

            if (expanded)
            {
                body_text = ni.text;

                if (ni.last_modified.HasValue)
                {
                    lastmodified = ni.last_modified.Value;
                    lastmodified_short = String.Format("{0:MMMM d}", ni.last_modified.Value);
                }
            }
        }
        public ActionResult SubscriptionsPartial()
        {
            SIEBUEntities db = new SIEBUEntities();
            User user = db.Users.Where(u => u.id == WebSecurity.CurrentUserId).FirstOrDefault();

            if (user == null) return PartialView("_SubscriptionsViewPartial", null);
            else return PartialView("_SubscriptionsPartial", SubscriptionModel.getSubscriptions(user));
        }
 public ActivityHistoryModel(Transaction trans, SIEBUEntities db = null)
 {
     if (db == null) db = new SIEBUEntities();
     value = trans.total.Value;
     date = (DateTime)trans.dateprocessed;
     invoice = trans.invoice;
     transaction = trans.t_id;
     is_purchase = true;
 }
 public ActivityHistoryModel(Transaction_Subtransaction sub, SIEBUEntities db = null)
 {
     if (db == null) db = new SIEBUEntities();
     value = sub.total.Value;
     date = (DateTime)sub.Transaction.dateprocessed;
     invoice = sub.Transaction.invoice;
     transaction = sub.st_id;
     is_purchase = false;
 }
        public ActivityHistoryViewModel(Store s, SIEBUEntities db = null)
        {
            if (db == null) db = new SIEBUEntities();

            foreach (Transaction_Subtransaction sub in db.Transaction_Subtransaction.Where(st => st.store_id == s.s_id && st.Transaction.is_processed == true).OrderByDescending(st => st.Transaction.dateprocessed))
                history.Add(new ActivityHistoryModel(sub, db));

            type = salesActivity;
        }
        public static Boolean checkNamespaceAvailability(String ns)
        {
            String[] invalid_names = { "new", "manage", "customize", "blogs" };

            if (invalid_names.Contains(ns.ToLower())) return true;

            SIEBUEntities db = new SIEBUEntities();
            return db.Stores.Any(s => s.name_space == ns);
        }
        /// <summary>
        /// BlogManagePartial loads the blog management partial using blog id
        /// </summary>
        /// <param name="id">blog post id</param>
        /// <returns></returns>
        public ActionResult BlogManagePartial(int id = 0)
        {
            BlogEntryModel model = new BlogEntryModel();

            SIEBUEntities db = new SIEBUEntities();
            Store_NewsItem cur_blog = db.Store_NewsItem.FirstOrDefault(ni => ni.sn_id == id);
            if (cur_blog != null)
                model = new BlogEntryModel(id, expanded: true, db: db);

            return PartialView("_BlogManagePartial", model);
        }
        public ActionResult about(String store_namespace)
        {
            SIEBUEntities db = new SIEBUEntities();

            Store cur_store = db.Stores.FirstOrDefault(s => s.name_space == store_namespace);
            if (cur_store == null)
                return RedirectToAction("LandingPage", "Landing");

            if (User.Identity.IsAuthenticated)
                Response.Cookies.Add(NavigationModel.updateStoreViewHistory(WebSecurity.CurrentUserId, Request.Cookies["store_hist"], cur_store));
            return View(new StoreInformationModel(cur_store, db: db));
        }
        public static List<StoreModel> getOwnedStores()
        {
            List<StoreModel> output = new List<StoreModel>();
            SIEBUEntities db = new SIEBUEntities();
            User current = db.Users.FirstOrDefault(u => u.id == WebSecurity.CurrentUserId);

            foreach (Store s in current.Stores)
            {
                output.Add(new StoreModel(s, true));
            }
            return output;
        }
        public ActionResult blog(String store_namespace, int id = 0)
        {
            SIEBUEntities db = new SIEBUEntities();

            Store cur_store = db.Stores.FirstOrDefault(s => s.name_space == store_namespace);
            if (cur_store == null || (id != 0 && !db.Store_NewsItem.Any(ni => ni.sn_id == id && ni.store_id == cur_store.s_id)))
                return RedirectToAction("LandingPage", "Landing");

            if (User.Identity.IsAuthenticated)
                Response.Cookies.Add(NavigationModel.updateStoreViewHistory(WebSecurity.CurrentUserId, Request.Cookies["store_hist"], cur_store));
            if (id == 0)
                return View(new StoreBlogModel(cur_store, display: 6, db: db));
            else return View(new StoreBlogModel(id, db: db));
        }
 public static void createPurchaseHistory(int customerID, decimal amountPaid, int transaction_id, Boolean isPaypal)
 {
     SIEBUEntities db = new SIEBUEntities();
     //CREATE THE USER CREDIT HISTORY AND PURCHASE HISTORY
     User_Purchase_History purchaseHistory = new User_Purchase_History();
     purchaseHistory.user_id = customerID;
     purchaseHistory.value = amountPaid;
     purchaseHistory.date = DateTime.Now;
     if (isPaypal)
     {
         purchaseHistory.paypal_transaction_id = transaction_id;
     }
     else
     {
         purchaseHistory.transaction_id = transaction_id;
     }
     db.User_Purchase_History.Add(purchaseHistory);
     db.SaveChanges();
 }
        public Boolean LikeProduct(int p_id)
        {
            SIEBUEntities db = new SIEBUEntities();

            Product_Like p_like = db.Product_Like.FirstOrDefault(pl => pl.product_id == p_id && pl.user_id == WebSecurity.CurrentUserId);
            if (p_like != null)
            {
                db.Product_Like.Remove(p_like);
                db.SaveChanges();
                return false;
            }

            p_like = new Product_Like();
            p_like.user_id = WebSecurity.CurrentUserId;
            p_like.product_id = p_id;

            db.Product_Like.Add(p_like);
            db.SaveChanges();
            return true;
        }
        /// <summary>
        /// Dashboard action routes the request based on two parameters, store namespace and goto (for sub-directories)
        /// </summary>
        /// <param name="Store">Store namespace</param>
        /// <param name="goto">Subrouting: One of Inventory, Store, Customize, Dashboard, Reports or Feedback</param>
        /// <returns></returns>
        public ActionResult Dashboard(String Store, String @goto)
        {
            SIEBUEntities db = new SIEBUEntities();

            //if url provided is /manage?store=new, open customize panel
            if (Store == "new") return View("customize", new StoreCustomizationModel(db));

            Store cur_store = db.Stores.FirstOrDefault(s => s.name_space == Store);
            if (cur_store == null)
                return RedirectToAction("LandingPage", "Landing");

            if (@goto == null) return View("dashboard", new DashboardModel(cur_store, db));

            switch (@goto.ToLower())
            {
                //case "dashboard": return View(@goto, new DashboardModel(cur_store, db)); default case is dashboard
                case "inventory": return View(@goto, new CatalogueModel(cur_store, 24, 0, false));
                case "blogs": return View(@goto, new StoreBlogModel(cur_store, include_draft: true, db: db));
                case "customize": return View(@goto, new StoreCustomizationModel(cur_store, db));
                case "transactions": return View(@goto, new StoreTransactionsModel(cur_store, db));
                default: return View("dashboard", new DashboardModel(cur_store, db));
            }
        }
 public static String editProfile(String email, String firstName, String lastName, String gender, DateTime Birthday, String about)
 {
     SIEBUEntities context = new SIEBUEntities();
     if (context.Users.Where(u => u.email == email).Count() != 0)
     {
         try
         {
             User user = context.Users.First(c => c.email == email); // Must check if user is in the database
             user.firstName = firstName;
             user.lastName = lastName;
             user.gender = (gender == "female") ? true : false;
             user.dob = Birthday;
             user.about = about;
             context.SaveChanges();
             return "";
         }
         catch
         {
             return "Changes to your account could not be made at this time"; // Changes could not be made/
         }
     }
     //Could not find email
     return "Could not find account with associated Email";
 }
        public static void createCreditHistory(Dictionary<int, int> subtransactionIds, Boolean isPaypal)
        {
            SIEBUEntities db = new SIEBUEntities();
            foreach (var pair in subtransactionIds)
            {
                int subtransactions = pair.Value;
                User_Credit_History creditHistory = new User_Credit_History();
                //get the store's user id.
                creditHistory.date = DateTime.Now;
                creditHistory.value = (decimal)db.Transaction_Subtransaction.Where(sub => sub.st_id == subtransactions).FirstOrDefault().total;
                creditHistory.user_id = pair.Key;
                if (isPaypal)
                {
                    creditHistory.paypal_subtransaction_id = subtransactions;
                }
                else
                {
                    creditHistory.subtransaction_id = subtransactions;
                }

                db.User_Credit_History.Add(creditHistory);
            }
            db.SaveChanges();
        }
        public DashboardModel(Store s, SIEBUEntities db = null)
        {
            if (db == null) db = new SIEBUEntities();

            id = s.s_id;
            name = s.name;
            description = s.description;
            logo = s.logo;
            banner = s.banner_img;
            background = s.background_img;
            owner_name = s.User.firstName + " " + s.User.lastName;
            store_namespace = s.name_space;
            social_media = SocialMediaModel.getSocialMedia(s, db);
            credit = Math.Round(s.credit.Value, 2);

            if (s.created_on.HasValue)
                created_date = s.created_on.Value;

            status_caption = s.Store_Status.caption;
            category_caption = s.Store_Category.text;

            catalogue = getCatalogue(s, count: 6, active: true, db: db);
            recent_blogs = StoreBlogModel.getEntries(s.s_id, count: 4, db: db);
        }
        public ActionResult products(String store_namespace, int id = 0)
        {
            SIEBUEntities db = new SIEBUEntities();

            Store cur_store = db.Stores.FirstOrDefault(s => s.name_space == store_namespace);
            if (cur_store == null || (id != 0 && !db.Products.Any(p => p.p_id == id && p.store_id == cur_store.s_id)))
                return RedirectToAction("LandingPage", "Landing");

            Product product = db.Products.FirstOrDefault(p => p.p_id == id);
            //updateViewHistory(cur_store.s_id, id);
            if (product == null) // && db.Products.Count(p => p.p_id == product && p.store_id == cur_store.s_id) > 0) {
                return View(new CatalogueModel(cur_store, 16, 0, active: true, db: db));
            else
            {
                if (User.Identity.IsAuthenticated)
                {
                    Response.Cookies.Add(NavigationModel.updateViewCookieHistory(WebSecurity.CurrentUserId, Request.Cookies["item_hist"], cur_store.s_id, id));
                    Response.Cookies.Add(NavigationModel.updateStoreViewHistory(WebSecurity.CurrentUserId, Request.Cookies["store_hist"], cur_store));
                }
                //logPageView(WebSecurity.CurrentUserId, cur_store.s_id, id);
                ViewBag.is_Liked = db.Product_Like.Any(pl => pl.product_id == id && pl.user_id == WebSecurity.CurrentUserId);
                return View(new CatalogueModel(product, db));
            }
        }
        public StoreCustomizationModel(SIEBUEntities db = null)
        {
            if (db == null) db = new SIEBUEntities();

            category_list = new Dictionary<int, string>();
            foreach (Store_Category cat in db.Store_Category)
                category_list.Add(cat.c_id, cat.text);
            status_list = new Dictionary<int, string>();
            foreach (Store_Status stat in db.Store_Status)
                status_list.Add(stat.status_id, stat.caption);
        }
        public ActionResult UpdateStore(StoreModel update)
        {
            //StoreModel update = JsonConvert.DeserializeObject<StoreModel>(obj);
            SIEBUEntities db = new SIEBUEntities();
            Store target_store = db.Stores.FirstOrDefault(s => s.s_id == update.id);

            //if no store is found, create one
            bool add_new = false;
            if (target_store == null)
            {
                add_new = true;
                target_store = new Store();
                target_store.creator_id = WebSecurity.CurrentUserId;
                target_store.created_on = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
                target_store.credit = 0;
            }

            //check for conflicting namespace
            if (ValidationController.checkNamespaceAvailability(update.store_namespace) != true)
                return Json(new { error = "The namespace is unavailable for use." }, JsonRequestBehavior.AllowGet);

            target_store.name = update.name;
            target_store.name_space = update.store_namespace;
            target_store.description = update.description;

            target_store.category_id = update.category;
            target_store.status = update.status;

            //create store before connections required
            if (add_new)
            {
                db.Stores.Add(target_store);
                db.SaveChanges();
            }

            if (target_store.logo == null || !(update.logo + "").Contains(target_store.logo)) //(!(target_store.logo == update.logo || update.logo.Contains(target_store.logo)))
                target_store.logo = update.logo != null ? ImageController.UploadFile(update.logo, "logo" + target_store.s_id) : null;

            if (target_store.banner_img == null || !(update.banner + "").Contains(target_store.banner_img))
                target_store.banner_img = update.banner != null ? ImageController.UploadFile(update.banner, "banner" + target_store.s_id) : null;

            if (target_store.background_img == null || !(update.background + "").Contains(target_store.background_img)) //) CHANGED FOR PARTIAL URLS
                target_store.background_img = update.background != null ? ImageController.UploadFile(update.background, "background" + target_store.s_id) : null;

            //update social media
            foreach (SocialMediaModel sm in update.social_media)
            {
                Store_Contact ssm = db.Store_Contact.FirstOrDefault(q => q.store == update.id && q.Contact.caption == sm.type);

                bool add_new_sm = false;
                if (ssm == null)
                {
                    add_new = true;
                    ssm = new Store_Contact();
                }
                ssm.value = sm.url;

                if (add_new_sm) db.Store_Contact.Add(ssm);
            }

            db.SaveChanges();

            return Json(target_store.name_space, JsonRequestBehavior.AllowGet);
        }
        public ActionResult UpdateProduct(ProductModel update)
        {
            SIEBUEntities db = new SIEBUEntities();
            Product target_product = db.Products.FirstOrDefault(p => p.p_id == update.id);

            Product_History history = new Product_History();

            //if no product is found, create one
            bool add_new = false;
            if (target_product == null)
            {
                add_new = true;
                target_product = new Product();
                target_product.dateadded = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
            }

            target_product.lastmodified = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
            history.datemodified = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
            bool change_made = false;
            if (target_product.name != update.name || target_product.sku != update.sku)
            {
                change_made = true;
                history.name = target_product.name;
                history.sku = target_product.sku;
                target_product.name = update.name;
                target_product.sku = update.sku;
            }

            if (!((target_product.cost + target_product.shipping_cost).Equals(update.cost + update.shipping_cost)))
            {
                change_made = true;
                history.cost = target_product.cost;
                history.shipping_cost = target_product.shipping_cost;
                target_product.cost = Convert.ToDecimal(update.cost, CultureInfo.GetCultureInfo("en"));
                target_product.shipping_cost = Convert.ToDecimal(update.shipping_cost, CultureInfo.GetCultureInfo("en"));
            }

            if (target_product.avail_inventory != update.avail_inventory)
            {
                change_made = true;
                history.avail_inventory = target_product.avail_inventory;
                target_product.avail_inventory = update.avail_inventory;
            }

            target_product.short_description = update.short_description;
            target_product.description = update.description;

            if (target_product.status != update.status)
            {
                change_made = true;
                history.status = target_product.status;
                target_product.status = update.status;
            }

            if (target_product.is_featured != update.is_featured)
            {
                change_made = true;
                history.is_featured = target_product.is_featured;
                target_product.is_featured = update.is_featured;
                if (update.is_featured)
                {
                    target_product.featured_since = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
                }
                else
                {
                    target_product.featured_since = null;
                }
            }

            if (add_new)
            {
                target_product.store_id = update.store_id;
                db.Products.Add(target_product);
                db.SaveChanges(); //changes must be saved so that product_id exists for image/tag/history foreign key relationships
            }

            foreach (ProductImageModel pim in update.images)
            {
                Product_Image target_image = db.Product_Image.FirstOrDefault(p => p.pi_id == pim.id);

                //only save up to 8 images per product
                if (db.Product_Image.Count(p => p.product_id == target_product.p_id) <= 8)
                {

                    bool add_new_img = false;
                    if (target_image == null)
                    {
                        add_new_img = true;
                        target_image = new Product_Image();
                    }

                    target_image.product_id = target_product.p_id;
                    target_image.sort = pim.order;

                    //check to make sure update does not match existing content
                    if ((target_image.url == null || !(pim.url + "").Contains(target_image.url)) && pim.url != null)
                    {
                        //if different from original, determine whether value is blank (for purpose of removing images)
                        if (pim.url != null)
                            target_image.url = ImageController.UploadFile(pim.url, target_image.product_id + "" + target_image.pi_id + "" + target_product.lastmodified.Value.ToString("ffffff"));
                        else target_image.url = null;
                    }

                    if (add_new_img) db.Product_Image.Add(target_image);
                }

                if (pim.delete) db.Product_Image.Remove(target_image);
            }

            foreach (ProductTagModel ptm in update.tags)
            {
                //create tag if non-existent
                Tag ref_tag = db.Tags.FirstOrDefault(t => t.caption == ptm.caption.Trim().ToLower());
                if (ref_tag == null)
                {
                    ref_tag = new Tag();
                    ref_tag.caption = ptm.caption.Trim().ToLower();
                    db.Tags.Add(ref_tag);
                    db.SaveChanges();
                }

                //tolower to compare captions
                Product_Tag target_tag = db.Product_Tag.FirstOrDefault(t => t.product_id == update.id && t.Tag.t_id == ref_tag.t_id);
                bool add_new_tag = false;
                if (target_tag == null)
                {
                    add_new_tag = true;
                    target_tag = new Product_Tag();
                }

                target_tag.product_id = target_product.p_id;
                target_tag.tag_id = ref_tag.t_id;

                if (add_new_tag) db.Product_Tag.Add(target_tag);
                if (ptm.delete) db.Product_Tag.Remove(target_tag);
            }

            if (change_made) db.Product_History.Add(history);
            history.product_id = target_product.p_id;

            db.SaveChanges();
            return Json(target_product.p_id, JsonRequestBehavior.AllowGet);
        }
        public ActionResult UpdateBlog(BlogEntryModel update)
        {
            SIEBUEntities db = new SIEBUEntities();
            Store_NewsItem target_entry = db.Store_NewsItem.FirstOrDefault(ni => ni.sn_id == update.id);

            //if no id is given, create new blog entry
            bool add_new = false;
            if (target_entry == null)
            {
                add_new = true;
                target_entry = new Store_NewsItem();
                target_entry.store_id = update.store_id;
                target_entry.author_id = WebSecurity.CurrentUserId;
                target_entry.date_added = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
            }

            target_entry.title = update.title;
            target_entry.last_modified = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));
            target_entry.description = update.description;
            target_entry.text = update.body_text;

            target_entry.is_featured = update.is_featured;
            if (update.is_featured)
            {
                target_entry.featured_since = TimeZoneInfo.ConvertTimeFromUtc(DateTime.UtcNow, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));

            }
            else
            {
                target_entry.featured_since = null;
            }

            target_entry.is_draft = update.is_draft;

            if (add_new)
            {
                db.Store_NewsItem.Add(target_entry);
                db.SaveChanges();
            }

            //if the update is not equal to the target image
            if (target_entry.img == null || !(update.img + "").Contains(target_entry.img)) //target_entry.img != update.img)
                target_entry.img = update.img != null ? ImageController.UploadFile(update.img, update.store_id + "" + target_entry.sn_id) : null; //no unique file name required  + "" + target_entry.last_modified.Value.ToString("ffffff")

            db.SaveChanges();
            return Json(target_entry.sn_id, JsonRequestBehavior.AllowGet);
        }
        /// <summary>
        /// ProductManagePartial loads the manage partial using the product ID
        /// </summary>
        /// <param name="id">product id</param>
        /// <returns></returns>
        public ActionResult ProductManagePartial(int id = 0)
        {
            ProductModel model = new ProductModel();

            SIEBUEntities db = new SIEBUEntities();
            Product cur_product = db.Products.FirstOrDefault(p => p.p_id == id);
            if (cur_product != null)
                model = new ProductModel(cur_product, db: db);

            return PartialView("_ProductManagePartial", model);
        }
        public ActionResult DeleteProducts(string[] id_list)
        {
            try
            {
                SIEBUEntities db = new SIEBUEntities();
                for (int i = 0; i < id_list.Length; i++)
                {
                    int id = int.Parse(id_list[i]);
                    db.Products.FirstOrDefault(p => p.p_id == id).is_deleted = true;
                }

                db.SaveChanges();
                return Json(true, JsonRequestBehavior.AllowGet);
            } catch (Exception e) {
                return Json(false, JsonRequestBehavior.AllowGet);
            }
        }
        public ActionResult ExternalLoginCallback(string returnUrl)
        {
            AuthenticationResult result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", new { ReturnUrl = returnUrl }));
            if (!result.IsSuccessful)
            {
                return RedirectToAction("ExternalLoginFailure");
            }

            if (OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie: false))
            {
                return RedirectToLocal(returnUrl);
            }

            if (User.Identity.IsAuthenticated)
            {
                // If the current user is logged in add the new account
                OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name);
                return RedirectToLocal(returnUrl);
            }
            else
            {
                // User is new, ask for their desired membership name
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl = returnUrl;
                try
                {
                    SIEBUEntities db = new SIEBUEntities();
                    if (!(db.Users.Where(u => u.email == result.UserName).Count() == 0))
                    {
                        return View("ExternalEmailLinkConfirmation", new RegisterExternalLoginModel { email = result.UserName, ExternalLoginData = loginData });
                    }
                    else
                    {
                        return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { email = result.UserName, ExternalLoginData = loginData });
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("The Error is " + e.ToString());
                    return View();
                }

            }
             /*   else
            {
                // User is new, ask for their desired membership name
                string loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId);
                ViewBag.ProviderDisplayName = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName;
                ViewBag.ReturnUrl = returnUrl;
                return View("ExternalLoginConfirmation", new RegisterExternalLoginModel { UserName = result.UserName, ExternalLoginData = loginData });
            } */
        }
        public ActionResult DeleteBlog(string blog_id)
        {
            try
            {
                SIEBUEntities db = new SIEBUEntities();
                int id = int.Parse(blog_id);
                db.Store_NewsItem.FirstOrDefault(ni => ni.sn_id == id).is_deleted = true;

                db.SaveChanges();
                return Json(true, JsonRequestBehavior.AllowGet);
            } catch (Exception e) {
                return Json(false, JsonRequestBehavior.AllowGet);
            }
        }
        public StoreCustomizationModel(Store s, SIEBUEntities db = null)
        {
            if (db == null) db = new SIEBUEntities();

            id = s.s_id;
            status = (s.status.HasValue ? s.status.Value : -1);
            category = s.category_id;
            name = s.name;
            description = s.description;
            logo = s.logo;
            banner = s.banner_img;
            background = s.background_img;
            owner_name = s.User.firstName + " " + s.User.lastName;
            store_namespace = s.name_space;
            social_media = SocialMediaModel.getSocialMedia(s, db);

            if (s.created_on.HasValue)
                created_date = s.created_on.Value;

            category_list = new Dictionary<int, string>();
            foreach (Store_Category cat in db.Store_Category)
                category_list.Add(cat.c_id, cat.text);
            status_list = new Dictionary<int, string>();
            foreach (Store_Status stat in db.Store_Status)
                status_list.Add(stat.status_id, stat.caption);
        }