Пример #1
0
        public ActionResult SendTestSms()
        {
            UserProfile profile = CurrentUserProfileOrThrow;

            string smsPhone = profile.AspNetIdentityUser().PhoneNumber;

            if (string.IsNullOrWhiteSpace(smsPhone))
            {
                AddUserMessage("Test Text Message not sent", "You must add a phone number before you can receive SMS text messages.", UserMessageType.Warning);
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Profile, UserActionActionEnum.Profile_SendTestSms, "No Phone Number", false, smsPhone: smsPhone);
                return(RedirectToAction("Index"));
            }

            if (!profile.AspNetIdentityUser().PhoneNumberConfirmed)
            {
                AddUserMessage("Test Text Message not sent", "You must confirm your phone number before you can receive SMS text messages.", UserMessageType.Warning);
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Profile, UserActionActionEnum.Profile_SendTestSms, "Phone Number Not Confirmed", false, smsPhone: smsPhone);
                return(RedirectToAction("Index"));
            }

            Client     client     = CurrentClientOrThrow;
            StoreFront storeFront = CurrentStoreFrontOrThrow;

            string textBody = "Test Text Message from " + storeFront.CurrentConfig().Name + " - " + Request.BindingHostName();


            bool result = this.SendSms(smsPhone, textBody);

            if (result)
            {
                AddUserMessage("Test Text Message Sent!", "Test SMS Text Message was sent to '" + profile.AspNetIdentityUser().PhoneNumber.ToHtml() + "'.", UserMessageType.Success);
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Profile, UserActionActionEnum.Profile_SendTestSms, smsPhone, true, smsPhone: smsPhone);
            }
            else
            {
                AddUserMessage("Test Text Message Not Sent!", "Test Text Message was NOT sent. This store does not have SMS Text send activated.", UserMessageType.Warning);
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Profile, UserActionActionEnum.Profile_SendTestSms, "Sms Disabled", false, smsPhone: smsPhone);
            }
            return(RedirectToAction("Index"));
        }
Пример #2
0
        /// <summary>
        /// Gets a specific blog and logs events and sets user messages if not found
        /// does not log event if blog found
        /// </summary>
        /// <param name="blogUrlName"></param>
        /// <returns></returns>
        protected Blog GetBlog(string blogUrlName)
        {
            if (string.IsNullOrWhiteSpace(blogUrlName))
            {
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Blog, UserActionActionEnum.Blog_View, "no blog name", false);
                AddUserMessage("Blog not found.", "Sorry, the blog you are looking for cannot be found. Please try another blog.", UserMessageType.Warning);
                return(null);
            }

            //find the blog, check visibility, log if fail,
            Blog blog = CurrentStoreFrontOrThrow.Blogs.Where(b => b.UrlName.ToLower() == blogUrlName.Trim().ToLower()).SingleOrDefault();

            if (blog == null)
            {
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Blog, UserActionActionEnum.Blog_View, "blog not found: " + blogUrlName, false);
                AddUserMessage("Blog not found.", "Sorry, the blog '" + blogUrlName.ToHtml() + "' cannot be found. Please try another blog.", UserMessageType.Warning);
                return(null);
            }

            if (!blog.IsActiveDirect())
            {
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Blog, UserActionActionEnum.Blog_View, "blog is inactive: " + blogUrlName, false, blogId: blog.BlogId);
                AddUserMessage("Blog Is Not Active.", "Sorry, the blog '" + blogUrlName.ToHtml() + "' is not active. Please try another blog.", UserMessageType.Warning);
                return(null);
            }

            if (blog.ForAnonymousOnly && !blog.ForRegisteredOnly && User.IsRegistered())
            {
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Blog, UserActionActionEnum.Blog_View, "blog anonymous only: " + blogUrlName, false, blogId: blog.BlogId);
                AddUserMessage("Blog Unavailable.", "Sorry, the blog '" + blogUrlName.ToHtml() + "' is for anonymous users only. Please try another blog.", UserMessageType.Warning);
                return(null);
            }
            else if (blog.ForRegisteredOnly && !blog.ForAnonymousOnly && User.IsAnonymous())
            {
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Blog, UserActionActionEnum.Blog_View, "blog registered only: " + blogUrlName, false, blogId: blog.BlogId);
                throw new LoginRequiredException(blog.Name, null);
            }

            return(blog);
        }
Пример #3
0
        public virtual ActionResult Create(WebFormEditAdminViewModel WebFormEditAdminViewModel)
        {
            Client client      = CurrentClientOrThrow;
            bool   nameIsValid = GStoreDb.ValidateWebFormName(this, WebFormEditAdminViewModel.Name, CurrentClientOrThrow.ClientId, null);

            if (nameIsValid && ModelState.IsValid)
            {
                try
                {
                    WebForm webForm = null;
                    webForm = GStoreDb.CreateWebForm(WebFormEditAdminViewModel, CurrentStoreFrontOrThrow, CurrentUserProfileOrThrow);
                    AddUserMessage("Web Form Created!", "Web Form '" + webForm.Name.ToHtml() + "' [" + webForm.WebFormId + "] was created successfully for Client '" + client.Name.ToHtml() + "' [" + client.ClientId + "]", UserMessageType.Success);
                    if (CurrentStoreFrontOrThrow.Authorization_IsAuthorized(CurrentUserProfileOrThrow, GStoreAction.WebForms_View))
                    {
                        return(RedirectToAction("Details", new { id = webForm.WebFormId }));
                    }
                    return(RedirectToAction("Index", "StoreAdmin"));
                }
                catch (Exception ex)
                {
                    string errorMessage = "An error occurred while Creating Web Form '" + WebFormEditAdminViewModel.Name.ToHtml() + "' for Client '" + client.Name.ToHtml() + "' [" + client.ClientId + "] \nError: " + ex.GetType().FullName;

                    if (CurrentUserProfileOrThrow.AspNetIdentityUserIsInRoleSystemAdmin())
                    {
                        errorMessage += " \nException.ToString(): " + ex.ToString();
                    }
                    AddUserMessage("Error Creating Web Form!", errorMessage.ToHtmlLines(), UserMessageType.Danger);
                    ModelState.AddModelError("Ajax", errorMessage);
                }
            }
            else
            {
                AddUserMessage("Web Form Create Error", "There was an error with your entry for new Web Form '" + WebFormEditAdminViewModel.Name.ToHtml() + "' for Client '" + client.Name.ToHtml() + "' [" + client.ClientId + "]. Please correct it below and save.", UserMessageType.Danger);
            }
            WebFormEditAdminViewModel.IsStoreAdminEdit = true;
            WebFormEditAdminViewModel.IsCreatePage     = true;
            WebFormEditAdminViewModel.IsActiveDirect   = !(WebFormEditAdminViewModel.IsPending || (WebFormEditAdminViewModel.StartDateTimeUtc > DateTime.UtcNow) || (WebFormEditAdminViewModel.EndDateTimeUtc < DateTime.UtcNow));

            return(View("Create", WebFormEditAdminViewModel));
        }
Пример #4
0
        public virtual ActionResult AdvancedCreate(NavBarItemEditAdminViewModel navBarItemEditViewModel)
        {
            StoreFront storeFront  = CurrentStoreFrontOrThrow;
            bool       nameIsValid = GStoreDb.ValidateNavBarItemName(this, navBarItemEditViewModel.Name, storeFront.StoreFrontId, storeFront.ClientId, null);

            if (nameIsValid && ModelState.IsValid)
            {
                try
                {
                    NavBarItem navBarItem = GStoreDb.CreateNavBarItem(navBarItemEditViewModel, storeFront, CurrentUserProfileOrThrow);
                    AddUserMessage("Menu Item Created!", "Menu Item '" + navBarItem.Name.ToHtml() + "' [" + navBarItem.NavBarItemId + "] was created successfully for Store Front '" + storeFront.CurrentConfig().Name.ToHtml() + "' [" + storeFront.StoreFrontId + "]", UserMessageType.Success);
                    if (CurrentStoreFrontOrThrow.Authorization_IsAuthorized(CurrentUserProfileOrThrow, GStoreAction.NavBarItems_View))
                    {
                        return(RedirectToAction("AdvancedDetails", new { id = navBarItem.NavBarItemId, ReturnToManager = navBarItemEditViewModel.ReturnToManager }));
                    }
                    return(RedirectToAction("AdvancedManager"));
                }
                catch (Exception ex)
                {
                    string errorMessage = "An error occurred while Creating Menu Item '" + navBarItemEditViewModel.Name + "' for Store Front '" + storeFront.CurrentConfig().Name.ToHtml() + "' [" + storeFront.StoreFrontId + "] \nError: " + ex.GetType().FullName;

                    if (CurrentUserProfileOrThrow.AspNetIdentityUserIsInRoleSystemAdmin())
                    {
                        errorMessage += " \nException.ToString(): " + ex.ToString();
                    }
                    AddUserMessage("Error Creating Menu Item!", errorMessage.ToHtmlLines(), UserMessageType.Danger);
                    ModelState.AddModelError("Ajax", errorMessage);
                }
            }
            else
            {
                AddUserMessage("Create Menu Item Error", "There was an error with your entry for new menu item '" + navBarItemEditViewModel.Name.ToHtml() + "' for Store Front '" + storeFront.CurrentConfig().Name.ToHtml() + "' [" + storeFront.StoreFrontId + "]. Please correct it below and save.", UserMessageType.Danger);
            }

            navBarItemEditViewModel.FillListsIfEmpty(storeFront.Client, storeFront);
            navBarItemEditViewModel.IsCreatePage = true;

            return(View("AdvancedCreate", navBarItemEditViewModel));
        }
Пример #5
0
        protected ActionResult ViewBlog(Blog blog, bool blogEntryUrlNameIsAll)
        {
            if (blog == null)
            {
                throw new ArgumentNullException("blog");
            }

            if (!blogEntryUrlNameIsAll && blog.AutoDisplayLatestEntry)
            {
                BlogEntry firstEntry = blog.BlogEntriesForUser(User.IsRegistered()).FirstOrDefault();
                if (firstEntry != null)
                {
                    return(RedirectToAction("Index", RouteDataForIndex(blog.UrlName, firstEntry.UrlName)));
                }
            }

            GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Blog, UserActionActionEnum.Blog_View, blog.UrlName, true, blogId: blog.BlogId);

            SetMetaTagsAndTheme(blog);

            return(View("ViewBlog", blog));
        }
Пример #6
0
        public ActionResult Create(StoreBinding storeBinding, bool?clientIdChanged, bool?storeFrontIdChanged)
        {
            if (ModelState.IsValid && !(clientIdChanged ?? false) && !(storeFrontIdChanged ?? false))
            {
                storeBinding = GStoreDb.StoreBindings.Create(storeBinding);
                storeBinding.UpdateAuditFields(CurrentUserProfileOrThrow);
                storeBinding = GStoreDb.StoreBindings.Add(storeBinding);
                GStoreDb.SaveChanges();
                AddUserMessage("Store Binding Added", "Store Binding [" + storeBinding.StoreBindingId + "] created successfully!", UserMessageType.Success);
                return(RedirectToAction("Index"));
            }

            int?clientId = null;

            if (storeBinding.ClientId != default(int))
            {
                clientId = storeBinding.ClientId;
            }

            if (clientIdChanged ?? false)
            {
                storeBinding.StoreFrontId = 0;
                storeBinding.StoreFrontConfigurationId = 0;
            }
            if (storeFrontIdChanged ?? false)
            {
                storeBinding.StoreFrontConfigurationId = 0;
            }

            int?storeFrontId = null;

            if (storeBinding.StoreFrontId != default(int))
            {
                storeFrontId = storeBinding.StoreFrontId;
            }

            this.BreadCrumbsFunc = html => this.BindingBreadcrumb(html, storeBinding.ClientId, storeBinding.StoreFront, storeBinding);
            return(View(storeBinding));
        }
Пример #7
0
        public ActionResult EditConfig(int?id, CartConfigViewModel config)
        {
            if (!id.HasValue)
            {
                return(HttpBadRequest("store front config id (ID) is null"));
            }

            if (id.Value != config.StoreFrontConfigurationId)
            {
                return(HttpBadRequest("store front configuration id mismatch. Url id: " + id.Value + " view model value: " + config.StoreFrontConfigurationId));
            }

            StoreFrontConfiguration configToEdit = GetConfigAndAccessCheck(id);

            if (config == null)
            {
                return(HttpBadRequest("No config found for store front config id [" + (id ?? 0) + "]"));
            }

            if (ModelState.IsValid)
            {
                configToEdit.CopyValuesFromCartConfigViewModel(config);
                GStoreDb.StoreFrontConfigurations.Update(configToEdit);
                GStoreDb.SaveChanges();

                AddUserMessage("Cart Configuration updated.", "Your changes have been saved for configuration '" + configToEdit.ConfigurationName.ToHtml() + "' [" + configToEdit.StoreFrontConfigurationId + "]", UserMessageType.Success);

                return(RedirectToAction("Preview", new { id = configToEdit.StoreFrontConfigurationId }));
            }

            AddUserMessage("Form Error.", "There was an error in your form values. Please correct the error below.", UserMessageType.Warning);

            Cart cart = configToEdit.StoreFront.GetPreviewCart(Session.SessionID, 1, null, CurrentUserProfileOrNull);
            CartConfigViewModel cartConfig = configToEdit.CartConfigViewModel(false, false);

            ViewData.Add("CartConfig", cartConfig);
            ViewData.Add("IsEditConfig", true);
            return(View("Index", cart));
        }
Пример #8
0
        public ActionResult ViewBundleByName(string urlName)
        {
            if (string.IsNullOrWhiteSpace(urlName))
            {
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Catalog, UserActionActionEnum.Catalog_ViewBundle, "Bad Url", false);
                return(Index());
            }

            ProductBundle bundle = CurrentStoreFrontOrThrow.ProductBundles.AsQueryable().Where(prod => prod.UrlName.ToLower() == urlName.ToLower()).WhereIsActive().SingleOrDefault();

            if (bundle == null)
            {
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Catalog, UserActionActionEnum.Catalog_ViewBundleNotFound, urlName, false, productBundleUrlName: urlName);
                return(BundleNotFound(urlName));
            }

            GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Catalog, UserActionActionEnum.Catalog_ViewBundle, urlName, true, productBundleUrlName: urlName);

            SetMetaTags(bundle);

            return(ViewBundle(bundle));
        }
Пример #9
0
        protected BlogEntry GetBlogEntry(Blog blog, string blogEntryUrlName)
        {
            if (string.IsNullOrWhiteSpace(blogEntryUrlName))
            {
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Blog, UserActionActionEnum.Blog_ViewEntry, "no blog entry name", false, blogId: blog.BlogId);
                AddUserMessage("Blog Post not found.", "Sorry, the blog post you are looking for cannot be found. Please try another blog post.", UserMessageType.Warning);
                return(null);
            }

            BlogEntry blogEntry = blog.BlogEntries.AsQueryable().WhereIsActive().WhereRegisteredAnonymousCheck(User.IsRegistered()).SingleOrDefault(be => be.UrlName.ToLower() == blogEntryUrlName.Trim().ToLower());

            if (blogEntry == null)
            {
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Blog, UserActionActionEnum.Blog_ViewEntry, "blog entry not found: " + blogEntryUrlName, false);
                AddUserMessage("Blog Post not found.", "Sorry, the blog post '" + blogEntryUrlName.ToHtml() + "' cannot be found. Please try another blog post.", UserMessageType.Warning);
                return(null);
            }

            if (!blog.IsActiveDirect())
            {
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Blog, UserActionActionEnum.Blog_ViewEntry, "blog entry is inactive: " + blogEntryUrlName, false, blogId: blog.BlogId, blogEntryId: blogEntry.BlogEntryId);
                AddUserMessage("Blog Post Is Not Active.", "Sorry, the blog post '" + blogEntryUrlName.ToHtml() + "' is not active. Please try another blog post.", UserMessageType.Warning);
                return(null);
            }

            if (blog.ForAnonymousOnly && !blog.ForRegisteredOnly && User.IsRegistered())
            {
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Blog, UserActionActionEnum.Blog_ViewEntry, "blog entry anonymous only: " + blogEntryUrlName, false, blogId: blog.BlogId, blogEntryId: blogEntry.BlogEntryId);
                AddUserMessage("Blog Post Unavailable.", "Sorry, the blog post '" + blogEntryUrlName.ToHtml() + "' is for anonymous users only. Please try another blog post.", UserMessageType.Warning);
                return(null);
            }
            else if (blogEntry.ForRegisteredOnly && !blogEntry.ForAnonymousOnly && User.IsAnonymous())
            {
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Blog, UserActionActionEnum.Blog_ViewEntry, "blog entry registered only: " + blogEntryUrlName, false, blogId: blog.BlogId, blogEntryId: blogEntry.BlogEntryId);
                throw new LoginRequiredException(blog.Name, blogEntry.Name);
            }

            return(blogEntry);
        }
Пример #10
0
        public ActionResult LogInOrGuest(CheckoutLogInOrGuestViewModel viewModel)
        {
            StoreFrontConfiguration config = CurrentStoreFrontConfigOrThrow;
            Cart cart = config.StoreFront.GetCart(Session.SessionID, CurrentUserProfileOrNull);

            if (!cart.CartIsValidForCheckout(this))
            {
                return(RedirectToAction("Index", "Cart"));
            }

            if (!cart.StatusStartedCheckout)
            {
                return(RedirectToAction("Index"));
            }

            cart = cart.ValidateCartAndSave(this);

            if (config.CheckoutLogInOrGuestWebForm != null)
            {
                FormProcessorExtensions.ValidateFields(this, config.CheckoutLogInOrGuestWebForm);
            }

            if (ModelState.IsValid)
            {
                WebFormResponse webFormResponse = cart.LoginOrGuestProcessWebForm(this);
                if (webFormResponse != null)
                {
                    cart.LoginOrGuestWebFormResponseId = webFormResponse.WebFormResponseId;
                }
                cart.StatusSelectedLogInOrGuest = true;
                GStoreDb.Carts.Update(cart);
                GStoreDb.SaveChanges();
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Checkout, UserActionActionEnum.Checkout_SelectedLogInOrGuest, "", true, cartId: cart.CartId);
                return(RedirectToAction("DeliveryInfo"));
            }

            viewModel.UpdateForRepost(config, cart, RouteData.Action());
            return(View("LogInOrGuest", viewModel));
        }
Пример #11
0
        public ActionResult Messages()
        {
            if (!CheckIsChatEnabled())
            {
                return(BounceToHomeResult(null));
            }

            if (!CheckAccess())
            {
                return(BounceToLoginNoAccessResult("Login is Required to use Chat."));
            }

            string chatName = ChatName();

            if (chatName == null)
            {
                return(RedirectToAction("Index"));
            }

            GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Chat, UserActionActionEnum.Chat_Start, "Chat Name: " + chatName, true);
            return(View("Messages", model: chatName));
        }
Пример #12
0
        public ActionResult ListItemEdit(ValueListItem valueListItem)
        {
            ValueList valueList = GStoreDb.ValueLists.FindById(valueListItem.ValueListId);

            if (valueListItem == null)
            {
                return(HttpNotFound("Value List not found. Value List id: " + valueListItem.ValueListId));
            }

            if (ModelState.IsValid)
            {
                valueListItem.UpdateAuditFields(CurrentUserProfileOrThrow);
                valueListItem = GStoreDb.ValueListItems.Update(valueListItem);
                GStoreDb.SaveChanges();
                AddUserMessage("Value List Item Updated", "Changes saved successfully to Value List Item '" + valueListItem.Name.ToHtml() + "' [" + valueListItem.ValueListItemId + "]", UserMessageType.Success);
                return(RedirectToAction("ListItemIndex", new { id = valueListItem.ValueListId }));
            }

            valueListItem.ValueList = valueList;
            this.BreadCrumbsFunc    = htmlHelper => this.ValueListItemBreadcrumb(htmlHelper, valueListItem, false);
            return(View(valueListItem));
        }
Пример #13
0
        public async Task <ActionResult> ResetPassword(ResetPasswordViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }
            var user = await UserManager.FindByNameAsync(model.Email);

            if (user == null)
            {
                GStoreDb.LogSecurityEvent_PasswordResetFailedUnknownUser(HttpContext, RouteData, model.Email, this);

                // Don't reveal that the user does not exist
                return(RedirectToAction("ResetPasswordConfirmation", "Account", new { CheckingOut = model.CheckingOut }));
            }
            var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);

            if (result.Succeeded)
            {
                UserProfile profile = GStoreDb.GetUserProfileByEmail(model.Email, false);
                GStoreDb.LogSecurityEvent_PasswordResetSuccess(HttpContext, RouteData, model.Email, profile, this);

                return(RedirectToAction("ResetPasswordConfirmation", "Account", new { CheckingOut = model.CheckingOut }));
            }

            UserProfile profileFailed = GStoreDb.GetUserProfileByEmail(model.Email, false);

            GStoreDb.LogSecurityEvent_PasswordResetFailed(HttpContext, RouteData, model.Email, result.Errors, profileFailed, this);

            AddErrors(result);

            ResetPasswordViewModel viewModel = new ResetPasswordViewModel()
            {
                CheckingOut = model.CheckingOut
            };

            return(View(viewModel));
        }
Пример #14
0
        public ActionResult Create(NavBarItemEditAdminViewModel viewModel)
        {
            StoreFront storeFront  = CurrentStoreFrontOrThrow;
            bool       nameIsValid = GStoreDb.ValidateNavBarItemName(this, viewModel.Name, storeFront.StoreFrontId, storeFront.ClientId, null);

            if (nameIsValid && ModelState.IsValid)
            {
                try
                {
                    NavBarItem navBarItem = GStoreDb.CreateNavBarItem(viewModel, storeFront, CurrentUserProfileOrThrow);
                    AddUserMessage("Menu Item Created!", "Menu Item '" + navBarItem.Name.ToHtml() + "' [" + navBarItem.NavBarItemId + "] was created successfully for Store Front '" + storeFront.CurrentConfig().Name.ToHtml() + "' [" + storeFront.StoreFrontId + "]", UserMessageType.Success);

                    return(RedirectToAction("Manager"));
                }
                catch (Exception ex)
                {
                    string errorMessage = "An error occurred while Creating Menu Item '" + viewModel.Name + "' for Store Front '" + storeFront.CurrentConfig().Name.ToHtml() + "' [" + storeFront.StoreFrontId + "] \nError: " + ex.GetType().FullName;

                    if (CurrentUserProfileOrThrow.AspNetIdentityUserIsInRoleSystemAdmin())
                    {
                        errorMessage += " \nException.ToString(): " + ex.ToString();
                    }
                    AddUserMessage("Error Creating Menu Item!", errorMessage.ToHtmlLines(), UserMessageType.Danger);
                    ModelState.AddModelError("Ajax", errorMessage);
                }
            }
            else
            {
                AddUserMessage("Create Menu Item Error", "There was an error with your entry for new menu item '" + viewModel.Name.ToHtml() + "' for Store Front '" + storeFront.CurrentConfig().Name.ToHtml() + "' [" + storeFront.StoreFrontId + "]. Please correct it below and save.", UserMessageType.Danger);
            }

            viewModel.FillListsIfEmpty(storeFront.Client, storeFront);
            viewModel.UpdateParentNavBarItem(CurrentStoreFrontOrThrow.NavBarItems.SingleOrDefault(nb => nb.NavBarItemId == viewModel.ParentNavBarItemId));

            viewModel.IsSimpleCreatePage = true;

            return(View("Create", viewModel));
        }
Пример #15
0
        public async Task <ActionResult> ConfirmEmail(string userId, string code, bool?CheckingOut)
        {
            if (userId == null || code == null)
            {
                return(HttpBadRequest("ConfirmEmail UserId and Code are blank"));
            }
            IdentityResult result;

            try
            {
                result = await UserManager.ConfirmEmailAsync(userId, code);
            }
            catch (InvalidOperationException ioe)
            {
                // ConfirmEmailAsync throws when the userId is not found.
                GStoreDb.LogSecurityEvent_EmailConfirmFailedUserNotFound(HttpContext, RouteData, userId, code, this);
                ViewBag.errorMessage = ioe.Message;
                return(HttpBadRequest("ConfirmEmail InvalidOperationException"));
            }

            if (result.Succeeded)
            {
                UserProfile profile = GStoreDb.GetUserProfileByAspNetUserId(userId);
                GStoreDb.LogSecurityEvent_EmailConfirmed(HttpContext, RouteData, profile, this);
                ViewBag.CheckingOut = CheckingOut;
                return(View());
            }

            // If we got this far, something failed.
            UserProfile profileFailed = GStoreDb.GetUserProfileByAspNetUserId(userId, false);

            GStoreDb.LogSecurityEvent_EmailConfirmFailed(HttpContext, RouteData, userId, code, result.Errors, profileFailed, this);

            AddErrors(result);
            ViewBag.errorMessage = "ConfirmEmail failed";
            return(HttpBadRequest("ConfirmEmail failed"));
        }
Пример #16
0
        public ActionResult FieldFastAdd(int webFormId, string stringValue)
        {
            if (string.IsNullOrEmpty(stringValue))
            {
                AddUserMessage("Field not added", "You must enter text to add a Web Form Field", UserMessageType.Danger);
                return(RedirectToAction("FieldIndex", new { id = webFormId }));
            }

            WebForm webForm = GStoreDb.WebForms.FindById(webFormId);

            if (webForm == null)
            {
                return(HttpBadRequest("Web Form not found by id: " + webFormId));
            }

            if (webForm.WebFormFields.Any(vl => vl.Name.ToLower() == stringValue.ToLower()))
            {
                AddUserMessage("Field not added", "Field with name '" + stringValue.ToHtml() + "' already exists in this Web Form. Use a different Field Name or remove the old Field first.", UserMessageType.Danger);
                return(RedirectToAction("FieldIndex", new { id = webFormId }));
            }

            WebFormField webFormField = GStoreDb.WebFormFields.Create();

            webFormField.SetDefaultsForNew(webForm);
            webFormField.Name                = stringValue;
            webFormField.Description         = stringValue;
            webFormField.LabelText           = stringValue;
            webFormField.Watermark           = "Enter a " + stringValue;
            webFormField.HelpLabelTopText    = string.Empty;
            webFormField.HelpLabelBottomText = string.Empty;

            GStoreDb.WebFormFields.Add(webFormField);
            GStoreDb.SaveChanges();

            AddUserMessage("Field added to Web Form", "Field '" + stringValue.ToHtml() + "' [" + webFormField.WebFormFieldId + "] was successfully added to the Web Form", UserMessageType.Success);
            return(RedirectToAction("FieldIndex", new { id = webFormId }));
        }
Пример #17
0
        public ActionResult AdvancedEdit(NavBarItemEditAdminViewModel viewModel, string Tab)
        {
            StoreFront storeFront = CurrentStoreFrontOrThrow;

            bool nameIsValid = GStoreDb.ValidateNavBarItemName(this, viewModel.Name, storeFront.StoreFrontId, storeFront.ClientId, viewModel.NavBarItemId);

            NavBarItem navBarItem = storeFront.NavBarItems.SingleOrDefault(nb => nb.NavBarItemId == viewModel.NavBarItemId);

            if (navBarItem == null)
            {
                AddUserMessage("Menu Item not found", "Sorry, the Menu Item you are trying to edit cannot be found. Menu Item Id: [" + viewModel.NavBarItemId + "] for Store Front '" + storeFront.CurrentConfig().Name.ToHtml() + "' [" + storeFront.StoreFrontId + "]", UserMessageType.Danger);
                if (viewModel.ReturnToManager)
                {
                    return(RedirectToAction("Manager"));
                }
                else
                {
                    return(RedirectToAction("AdvancedManager"));
                }
            }

            if (ModelState.IsValid && nameIsValid)
            {
                navBarItem = GStoreDb.UpdateNavBarItem(viewModel, storeFront, CurrentUserProfileOrThrow);
                AddUserMessage("Menu Item updated successfully!", "Menu Item updated successfully. Menu Item '" + navBarItem.Name.ToHtml() + "' [" + navBarItem.NavBarItemId + "] for Store Front '" + storeFront.CurrentConfig().Name.ToHtml() + "' [" + storeFront.StoreFrontId + "]", UserMessageType.Success);
                if (viewModel.ReturnToManager)
                {
                    return(RedirectToAction("Manager"));
                }
                else
                {
                    return(RedirectToAction("AdvancedManager"));
                }
            }

            return(View("AdvancedEdit", viewModel));
        }
Пример #18
0
        public ActionResult ListItemFastAdd(int valueListId, string stringValue)
        {
            if (string.IsNullOrEmpty(stringValue))
            {
                AddUserMessage("Item not added", "You must enter text to add a value list item", UserMessageType.Danger);
                return(RedirectToAction("ListItemIndex", new { id = valueListId }));
            }

            ValueList valueList = GStoreDb.ValueLists.FindById(valueListId);

            if (valueList == null)
            {
                return(HttpBadRequest("Value List not found by id: " + valueListId));
            }

            if (valueList.ValueListItems.Any(vl => vl.Name.ToLower() == stringValue.ToLower()))
            {
                AddUserMessage("Item not added", "Item with name '" + stringValue.ToHtml() + "' already exists in this list. Use a different item name or remove the old item first.", UserMessageType.Danger);
                return(RedirectToAction("ListItemIndex", new { id = valueListId }));
            }

            ValueListItem listItem = GStoreDb.ValueListItems.Create();

            listItem.SetDefaultsForNew(valueList);
            listItem.Name        = stringValue;
            listItem.Description = stringValue;
            listItem.IsPending   = false;
            listItem.IsString    = true;
            listItem.StringValue = stringValue;

            GStoreDb.ValueListItems.Add(listItem);
            GStoreDb.SaveChanges();

            AddUserMessage("Item added to List", "Item '" + stringValue.ToHtml() + "' [" + listItem.ValueListItemId + "] was successfully added to the list", UserMessageType.Success);
            return(RedirectToAction("ListItemIndex", new { id = valueListId }));
        }
Пример #19
0
        public async Task <ActionResult> AddPhoneNumber(AddPhoneNumberViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(View(model));
            }


            var code = await UserManager.GenerateChangePhoneNumberTokenAsync(User.Identity.GetUserId(), model.Number);

            StoreFront storeFront  = CurrentStoreFrontOrNull;
            string     messageBody = StoreFrontExtensions.AddPhoneNumberMessage(storeFront, code, Request.Url);

            if (!Settings.AppEnableSMS)
            {
                //if app set to not enable SMS, just store phone number unverified

                return(AddPhoneNumberNoSms(model, messageBody));
            }

            Client client = CurrentClientOrNull;

            if (client == null || !client.UseTwilioSms)
            {
                //if client is set to not enable SMS, just store phone number unverified
                return(AddPhoneNumberNoSms(model, messageBody));
            }

            GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Profile, UserActionActionEnum.Profile_AddPhoneNumber, model.Number, true, smsPhone: model.Number);

            // Generate the token and send it

            bool result = this.SendSms(model.Number, messageBody);

            return(RedirectToAction("VerifyPhoneNumber", new { PhoneNumber = model.Number }));
        }
Пример #20
0
        public ActionResult UpdateDiscountCode(string discountCode)
        {
            if (!CheckAccess())
            {
                return(BounceToLogin());
            }
            StoreFront storeFront = CurrentStoreFrontOrThrow;
            Cart       cart       = CurrentStoreFrontOrThrow.GetCart(Session.SessionID, CurrentUserProfileOrNull);
            bool       success    = false;

            cart = cart.UpdateDiscountCode(discountCode, this, out success);

            if (success)
            {
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Cart, UserActionActionEnum.Cart_ApplyDiscountCodeSuccess, "", success, discountCode: discountCode, cartId: (cart == null ? (int?)null : cart.CartId));
            }
            else
            {
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Cart, UserActionActionEnum.Cart_ApplyDiscountCodeFailure, "", success, discountCode: discountCode, cartId: (cart == null ? (int?)null : cart.CartId));
            }

            cart.CancelCheckout(GStoreDb);
            return(RedirectToAction("Index"));
        }
Пример #21
0
        public ActionResult SyncFiles(int?productCategoryId, bool eraseFileNameIfNotFound = true, bool searchForFileIfBlank = true, bool preview = true, bool verbose = true, bool returnToFrontEnd = false)
        {
            StringBuilder results = new StringBuilder();

            bool hasDbChanges = false;
            StoreFrontConfiguration storeFrontConfig = CurrentStoreFrontConfigOrAny;

            ProductCategory productCategory = null;

            if (productCategoryId.HasValue)
            {
                productCategory = storeFrontConfig.StoreFront.ProductCategories.SingleOrDefault(pc => pc.ProductCategoryId == productCategoryId.Value);
                if (productCategory == null)
                {
                    return(HttpBadRequest("Product category not found. Id: " + productCategoryId.Value));
                }
            }

            results.AppendLine("Starting Product File sync" + (productCategory == null ? " for all products" : " for Category '" + productCategory.Name + "' [" + productCategory.ProductCategoryId + "]"));

            List <Product> products = null;

            if (productCategory == null)
            {
                products = storeFrontConfig.StoreFront.Products.AsQueryable().ApplyDefaultSort().ToList();
            }
            else
            {
                products = productCategory.Products.AsQueryable().ApplyDefaultSort().ToList();
            }

            string applicationPath = Request.ApplicationPath;
            int    counter         = 0;

            foreach (Product product in products)
            {
                bool hasDbChangesProduct = false;

                //ImageFile
                bool   hasDbChangesImageFile;
                string resultImageFile = product.SyncImageFile(eraseFileNameIfNotFound, searchForFileIfBlank, preview, verbose, applicationPath, RouteData, Server, out hasDbChangesImageFile);
                hasDbChangesProduct = hasDbChangesImageFile;
                if (!string.IsNullOrEmpty(resultImageFile))
                {
                    results.Append(resultImageFile);
                }


                //DigitalDownloadFile
                bool   hasDbChangesDigitalDownloadFile;
                string resultDigitalDownloadFile = product.SyncDigitalDownloadFile(eraseFileNameIfNotFound, searchForFileIfBlank, preview, verbose, applicationPath, RouteData, Server, out hasDbChangesDigitalDownloadFile);
                hasDbChangesProduct = hasDbChangesProduct || hasDbChangesDigitalDownloadFile;
                if (!string.IsNullOrEmpty(resultDigitalDownloadFile))
                {
                    results.Append(resultDigitalDownloadFile);
                }

                //SampleAudioFile
                bool   hasDbChangesSampleAudioFile;
                string resultSampleAudioFile = product.SyncSampleAudioFile(eraseFileNameIfNotFound, searchForFileIfBlank, preview, verbose, applicationPath, RouteData, Server, out hasDbChangesSampleAudioFile);
                hasDbChangesProduct = hasDbChangesProduct || hasDbChangesSampleAudioFile;
                if (!string.IsNullOrEmpty(resultSampleAudioFile))
                {
                    results.Append(resultSampleAudioFile);
                }

                //SampleDownloadFile
                bool   hasDbChangesSampleDownloadFile;
                string resultSampleDownloadFile = product.SyncSampleDownloadFile(eraseFileNameIfNotFound, searchForFileIfBlank, preview, verbose, applicationPath, RouteData, Server, out hasDbChangesSampleDownloadFile);
                hasDbChangesProduct = hasDbChangesProduct || hasDbChangesSampleDownloadFile;
                if (!string.IsNullOrEmpty(resultSampleDownloadFile))
                {
                    results.Append(resultSampleDownloadFile);
                }

                //SampleImageFile
                bool   hasDbChangesSampleImageFile;
                string resultSampleImageFile = product.SyncSampleImageFile(eraseFileNameIfNotFound, searchForFileIfBlank, preview, verbose, applicationPath, RouteData, Server, out hasDbChangesSampleImageFile);
                hasDbChangesProduct = hasDbChangesProduct || hasDbChangesSampleImageFile;
                if (!string.IsNullOrEmpty(resultSampleImageFile))
                {
                    results.Append(resultSampleImageFile);
                }

                hasDbChanges = hasDbChanges || hasDbChangesProduct;
                if (hasDbChangesProduct)
                {
                    counter++;
                    if (preview)
                    {
                        results.AppendLine("- - - - - Product update needed for '" + product.Name + "' [" + product.ProductId + "] - - - - -");
                    }
                    else
                    {
                        GStoreDb.Products.Update(product);
                        results.AppendLine("- - - - - Product updated '" + product.Name + "' [" + product.ProductId + "] - - - - -");
                    }
                }
                else
                {
                    if (verbose)
                    {
                        results.AppendLine("OK - No Product update needed for '" + product.Name + "' [" + product.ProductId + "]");
                    }
                }
                if (verbose)
                {
                    results.AppendLine();
                }
            }

            if (hasDbChanges)
            {
                if (preview)
                {
                    results.AppendLine("- - - - - Database update needed for " + counter.ToString("N0") + " Product" + (counter == 1 ? "" : "s") + ". - - - - -");
                }
                else
                {
                    GStoreDb.SaveChangesDirect();
                    results.AppendLine("- - - - - Database updated successfully for " + counter.ToString("N0") + " Product" + (counter == 1 ? "" : "s") + ". - - - - -");
                }
            }
            else
            {
                results.AppendLine("No changes to save to database. Up-to-date.");
            }


            AddUserMessage("Category Image Sync Results", results.ToString().ToHtmlLines(), UserMessageType.Info);
            if (storeFrontConfig.StoreFront.Authorization_IsAuthorized(CurrentUserProfileOrThrow, GStoreAction.Categories_Manager))
            {
                return(RedirectToAction("Manager", new { returnToFrontEnd = returnToFrontEnd }));
            }
            return(RedirectToAction("Index", "CatalogAdmin", new { returnToFrontEnd = returnToFrontEnd }));
        }
Пример #22
0
        public ActionResult Edit(ProductEditAdminViewModel viewModel, string saveAndView, int?addToBundleId, string addTobundle, int?addToBundleQty, int?removeAltCategoryId)
        {
            StoreFront storeFront = CurrentStoreFrontOrThrow;

            bool nameIsValid = GStoreDb.ValidateProductUrlName(this, viewModel.UrlName, storeFront.StoreFrontId, storeFront.ClientId, viewModel.ProductId);

            Product product = storeFront.Products.SingleOrDefault(p => p.ProductId == viewModel.ProductId);

            if (product == null)
            {
                AddUserMessage("Product not found", "Sorry, the Product you are trying to edit cannot be found. Product Id: [" + viewModel.ProductId + "] for Store Front '" + storeFront.CurrentConfig().Name.ToHtml() + "' [" + storeFront.StoreFrontId + "]", UserMessageType.Danger);
                if (viewModel.ReturnToFrontEnd)
                {
                    return(RedirectToAction("ViewProductByName", "Catalog", new { area = "", urlName = viewModel.UrlName }));
                }
                if (storeFront.Authorization_IsAuthorized(CurrentUserProfileOrThrow, GStoreAction.Products_Manager))
                {
                    return(RedirectToAction("Manager"));
                }
                return(RedirectToAction("Index", "CatalogAdmin"));
            }

            if (ModelState.IsValid && nameIsValid)
            {
                ProcessFileUploads(viewModel, storeFront);
                bool addedToBundle = false;
                if (!string.IsNullOrEmpty(addTobundle) && addToBundleId.HasValue && addToBundleId.Value != 0)
                {
                    ProductBundleItem newItem = GStoreDb.CreateProductBundleItemFastAdd(addToBundleId.Value, product, storeFront, CurrentUserProfileOrThrow, addToBundleQty ?? 1);
                    addedToBundle = true;
                }

                product = GStoreDb.UpdateProduct(viewModel, storeFront, CurrentUserProfileOrThrow);
                AddUserMessage("Product updated successfully!", "Product updated successfully. Product '" + product.Name.ToHtml() + "' [" + product.ProductId + "] for Store Front '" + storeFront.CurrentConfig().Name.ToHtml() + "' [" + storeFront.StoreFrontId + "]", UserMessageType.Success);

                if (removeAltCategoryId.HasValue && removeAltCategoryId.Value != 0)
                {
                    ProductCategoryAltProduct removeAltProduct = product.CategoryAltProducts.SingleOrDefault(p => p.ProductCategoryId == removeAltCategoryId.Value);
                    if (removeAltProduct == null)
                    {
                        AddUserMessage("Error removing cross-sell Category", "Category Id [" + removeAltCategoryId.Value + "] could not be found in product alt categories.", UserMessageType.Danger);
                    }
                    else
                    {
                        string oldName = removeAltProduct.Category.Name;
                        GStoreDb.ProductCategoryAltProducts.Delete(removeAltProduct);
                        GStoreDb.SaveChanges();
                        AddUserMessage("Removed cross-sell Catergory", oldName.ToHtml() + " was removed.", UserMessageType.Info);
                    }
                }

                if (removeAltCategoryId.HasValue)
                {
                    return(RedirectToAction("Edit", new { id = product.ProductId, returnToFrontEnd = viewModel.ReturnToFrontEnd, Tab = viewModel.ActiveTab }));
                }
                if (!string.IsNullOrWhiteSpace(saveAndView) || addedToBundle)
                {
                    return(RedirectToAction("Details", new { id = product.ProductId, returnToFrontEnd = viewModel.ReturnToFrontEnd, Tab = viewModel.ActiveTab }));
                }
                if (viewModel.ReturnToFrontEnd)
                {
                    return(RedirectToAction("ViewProductByName", "Catalog", new { area = "", urlName = viewModel.UrlName }));
                }
                if (storeFront.Authorization_IsAuthorized(CurrentUserProfileOrThrow, GStoreAction.Products_Manager))
                {
                    return(RedirectToAction("Manager", new { productCategoryId = viewModel.ProductCategoryId }));
                }
                return(RedirectToAction("Index", "CatalogAdmin"));
            }

            if (Request.HasFiles())
            {
                AddUserMessage("Files not uploaded", "You must correct the form values below and re-upload your files", UserMessageType.Danger);
            }
            viewModel.UpdateProduct(product);
            ViewData.Add("ReturnToFrontEnd", viewModel.ReturnToFrontEnd);
            return(View("CreateOrEdit", viewModel));
        }
Пример #23
0
        public ActionResult DeleteConfirmed(int?id, bool returnToFrontEnd = false)
        {
            if (!id.HasValue)
            {
                return(HttpBadRequest("ProductId = null"));
            }

            StoreFront storeFront = CurrentStoreFrontOrThrow;
            Product    product    = storeFront.Products.Where(p => p.ProductId == id.Value).SingleOrDefault();

            if (product == null)
            {
                AddUserMessage("Product not found", "Sorry, the Product you are trying to Delete cannot be found. It may have been deleted already. Product Id: [" + id.Value + "] for Store Front '" + storeFront.CurrentConfig().Name.ToHtml() + "' [" + storeFront.StoreFrontId + "]", UserMessageType.Danger);
                if (returnToFrontEnd)
                {
                    return(RedirectToAction("Index", "Catalog", new { area = "" }));
                }
                if (storeFront.Authorization_IsAuthorized(CurrentUserProfileOrThrow, GStoreAction.Products_Manager))
                {
                    return(RedirectToAction("Manager"));
                }
                return(RedirectToAction("Index", "CatalogAdmin"));
            }

            string productName     = product.Name;
            string categoryUrlName = product.Category.UrlName;

            try
            {
                bool deleted = GStoreDb.Products.DeleteById(id.Value);
                GStoreDb.SaveChanges();
                if (deleted)
                {
                    AddUserMessage("Product Deleted", "Product '" + productName.ToHtml() + "' [" + id + "] was deleted successfully.", UserMessageType.Success);
                    if (returnToFrontEnd)
                    {
                        return(RedirectToAction("ViewCategoryByName", "Catalog", new { area = "", urlName = categoryUrlName }));
                    }
                    if (storeFront.Authorization_IsAuthorized(CurrentUserProfileOrThrow, GStoreAction.Products_Manager))
                    {
                        return(RedirectToAction("Manager"));
                    }
                    return(RedirectToAction("Index", "CatalogAdmin"));
                }
                AddUserMessage("Product Delete Error", "There was an error deleting Product '" + productName.ToHtml() + "' [" + id + "]. It may have already been deleted.", UserMessageType.Warning);
                if (returnToFrontEnd)
                {
                    return(RedirectToAction("ViewCategoryByName", "Catalog", new { area = "", urlName = categoryUrlName }));
                }
                if (storeFront.Authorization_IsAuthorized(CurrentUserProfileOrThrow, GStoreAction.Products_Manager))
                {
                    return(RedirectToAction("Manager"));
                }
                return(RedirectToAction("Index", "CatalogAdmin"));
            }
            catch (Exception ex)
            {
                string errorMessage = "There was an error deleting Product '" + productName + "' [" + id + "]. <br/>Error: '" + ex.GetType().FullName + "'";
                if (CurrentUserProfileOrThrow.AspNetIdentityUserIsInRoleSystemAdmin())
                {
                    errorMessage += " \nException.ToString(): " + ex.ToString();
                }
                AddUserMessage("Product Delete Error", errorMessage.ToHtml(), UserMessageType.Danger);
                if (returnToFrontEnd)
                {
                    return(RedirectToAction("ViewCategoryByName", "Catalog", new { area = "", urlName = categoryUrlName }));
                }
                if (storeFront.Authorization_IsAuthorized(CurrentUserProfileOrThrow, GStoreAction.Products_Manager))
                {
                    return(RedirectToAction("Manager"));
                }
                return(RedirectToAction("Index", "CatalogAdmin"));
            }
        }
Пример #24
0
        public ActionResult PayPalAccountConfirmed(string paymentId, string token, string PayerId)
        {
            StoreFrontConfiguration storeFrontConfig = CurrentStoreFrontConfigOrThrow;
            Cart cart = storeFrontConfig.StoreFront.GetCart(Session.SessionID, CurrentUserProfileOrNull);

            if (!cart.CartIsValidForCheckout(this))
            {
                return(RedirectToAction("Index", "Cart"));
            }

            if (!cart.StatusStartedCheckout)
            {
                return(RedirectToAction("Index"));
            }
            if (!cart.StatusSelectedLogInOrGuest)
            {
                return(RedirectToAction("LogInOrGuest"));
            }

            cart = cart.ValidateCartAndSave(this);

            if (!cart.StatusCompletedDeliveryInfo)
            {
                return(RedirectToAction("DeliveryInfo"));
            }
            if (!cart.StatusSelectedDeliveryMethod)
            {
                return(RedirectToAction("DeliveryMethod"));
            }
            if (!cart.CartPaymentInfoId.HasValue)
            {
                throw new ApplicationException("Cart.PaymentInfo is null");
            }
            if (string.IsNullOrEmpty(cart.CartPaymentInfo.PayPalPaymentId))
            {
                throw new ArgumentNullException("cart.CartPaymentInfo.PayPalPaymentId", "cart.CartPaymentInfo.PayPalPaymentId = null. Be sure paypalpaymentid is being set before going to PayPal.");
            }
            if (string.IsNullOrWhiteSpace(paymentId))
            {
                return(HttpBadRequest("paymentId cannot be null"));
            }
            if (string.IsNullOrWhiteSpace(token))
            {
                return(HttpBadRequest("token cannot be null"));
            }
            if (string.IsNullOrWhiteSpace(PayerId))
            {
                return(HttpBadRequest("PayerId cannot be null"));
            }
            if (cart.CartPaymentInfo.PayPalPaymentId.ToLower() != paymentId.ToLower())
            {
                return(HttpBadRequest("PayPal Payment id mismatch"));
            }

            cart.CartPaymentInfo.PayPalReturnPaymentId = paymentId;
            cart.CartPaymentInfo.PayPalReturnPayerId   = PayerId;
            cart.CartPaymentInfo.PayPalReturnToken     = token;

            cart.StatusPaymentInfoConfirmed = true;
            cart = GStoreDb.Carts.Update(cart);
            GStoreDb.SaveChanges();

            return(RedirectToAction("ConfirmOrder"));
        }
Пример #25
0
        /// <summary>
        /// Starts a PayPal payment and returns a redirect result to PayPal (or payment info page if an error occurs)
        /// </summary>
        /// <param name="viewModel"></param>
        /// <returns></returns>
        protected ActionResult Payment_PayPalStartPayment(CheckoutPaymentInfoViewModel viewModel, WebFormResponse webFormResponse)
        {
            StoreFrontConfiguration storeFrontConfig = CurrentStoreFrontConfigOrThrow;
            Cart cart = storeFrontConfig.StoreFront.GetCart(Session.SessionID, CurrentUserProfileOrNull);

            Uri returnUri = new Uri(Url.Action("PayPalAccountConfirmed", null, null, Request.Url.Scheme));
            Uri cancelUri = new Uri(Url.Action("PayPalCanceled", null, null, Request.Url.Scheme));

            PayPalPaymentClient paypalClient = new PayPalPaymentClient();

            PayPalPaymentData response;

            try
            {
                response = paypalClient.StartPayPalPayment(storeFrontConfig, cart, returnUri, cancelUri);
            }
            catch (PayPalExceptionOAuthFailed exOAuth)
            {
                string message = "Sorry, this store's configuration for PayPal OAuth is not operational. Please contact us for other payment options."
                                 + (exOAuth.IsSandbox ? "\nError in Sandbox Config." : "\nError in Live Config");
                AddUserMessage("PayPal Error", message, UserMessageType.Danger);

                if (CurrentUserProfileOrNull != null && CurrentUserProfileOrThrow.AspNetIdentityUserIsInRoleSystemAdmin())
                {
                    string adminMessage = exOAuth.ToString()
                                          + "\n\nHTTP Response:\n" + exOAuth.ResponseString
                                          + "\n\nHTTP Headers:\n" + exOAuth.ResponseHeaders;
                    AddUserMessage("PayPal Error (admin info)", "Error " + adminMessage, UserMessageType.Danger);
                }

                return(RedirectToAction("PaymentInfo"));
            }
            catch (PayPalExceptionCreatePaymentFailed exPaymentFailed)
            {
                string message = "Sorry, there was an error sending your order to PayPal for payment. Please contact us for other payment options."
                                 + (exPaymentFailed.IsSandbox ? "\nError in Sandbox." : "\nError in Live Site.");

                AddUserMessage("PayPal Error", message, UserMessageType.Danger);

                if (CurrentUserProfileOrNull != null && CurrentUserProfileOrThrow.AspNetIdentityUserIsInRoleSystemAdmin())
                {
                    string adminMessage = exPaymentFailed.ToString()
                                          + "\n\nHTTP Response:\n" + exPaymentFailed.ResponseString
                                          + "\n\nHTTP Headers:\n" + exPaymentFailed.ResponseHeaders;
                    AddUserMessage("PayPal Error (admin info)", "Error " + adminMessage, UserMessageType.Danger);
                }

                return(RedirectToAction("PaymentInfo"));
            }
            catch (Exception ex)
            {
                string message = "Sorry, there was an error starting starting your order with PayPal. Please contact us for other payment options.";
                AddUserMessage("PayPal Error", message, UserMessageType.Danger);

                if (CurrentUserProfileOrNull != null && CurrentUserProfileOrThrow.AspNetIdentityUserIsInRoleSystemAdmin())
                {
                    string adminMessage = "Exception: " + ex.ToString();
                    AddUserMessage("PayPal Error (admin info)", "Error " + adminMessage, UserMessageType.Danger);
                }
                return(RedirectToAction("PaymentInfo"));
            }

            CartPaymentInfo cartPaymentInfo = cart.CartPaymentInfo;

            if (cartPaymentInfo == null)
            {
                cartPaymentInfo = GStoreDb.CartPaymentInfos.Create();
                cartPaymentInfo.SetFromPayPalResponse(cart, response);
                if (webFormResponse != null)
                {
                    cartPaymentInfo.WebFormResponseId = webFormResponse.WebFormResponseId;
                }
                cartPaymentInfo = GStoreDb.CartPaymentInfos.Add(cartPaymentInfo);
            }
            else
            {
                cartPaymentInfo.SetFromPayPalResponse(cart, response);
                if (webFormResponse != null)
                {
                    cartPaymentInfo.WebFormResponseId = webFormResponse.WebFormResponseId;
                }
                cartPaymentInfo = GStoreDb.CartPaymentInfos.Update(cartPaymentInfo);
            }

            GStoreDb.SaveChanges();

            cart.CartPaymentInfoId          = cartPaymentInfo.CartPaymentInfoId;
            cart.StatusPaymentInfoConfirmed = false;
            cart = GStoreDb.Carts.Update(cart);
            GStoreDb.SaveChanges();

            PayPalLinkData confirmLink = response.links.Where(l => l.rel == "approval_url").SingleOrDefault();

            if (string.IsNullOrEmpty(confirmLink.href))
            {
                string message = "Sorry, there was an error getting your order info from PayPal. Please contact us for other payment options.";
                AddUserMessage("PayPal Error", message, UserMessageType.Danger);
                if (CurrentUserProfileOrNull != null && CurrentUserProfileOrThrow.AspNetIdentityUserIsInRoleSystemAdmin())
                {
                    string adminMessage = "PayPal Response parse error. Cannot find link with method: approval_url";
                    AddUserMessage("PayPal Error (admin info)", "Error " + adminMessage, UserMessageType.Danger);
                }
                return(RedirectToAction("PaymentInfo"));
            }

            return(Redirect(confirmLink.href));
        }
Пример #26
0
        public ActionResult PaymentInfo(CheckoutPaymentInfoViewModel viewModel)
        {
            StoreFrontConfiguration config = CurrentStoreFrontConfigOrThrow;
            Cart cart = config.StoreFront.GetCart(Session.SessionID, CurrentUserProfileOrNull);

            if (!cart.CartIsValidForCheckout(this))
            {
                return(RedirectToAction("Index", "Cart"));
            }

            if (!cart.StatusStartedCheckout)
            {
                return(RedirectToAction("Index"));
            }
            if (!cart.StatusSelectedLogInOrGuest)
            {
                return(RedirectToAction("LogInOrGuest"));
            }

            cart = cart.ValidateCartAndSave(this);

            if (!cart.StatusCompletedDeliveryInfo)
            {
                return(RedirectToAction("DeliveryInfo"));
            }
            if (!cart.StatusSelectedDeliveryMethod)
            {
                return(RedirectToAction("DeliveryMethod"));
            }

            if (config.CheckoutPaymentInfoWebForm != null)
            {
                FormProcessorExtensions.ValidateFields(this, config.CheckoutPaymentInfoWebForm);
            }

            if (ModelState.IsValid)
            {
                WebFormResponse webFormResponse = cart.PaymentInfoProcessWebForm(this);
                if (config.PaymentMethod_PayPal_Enabled)
                {
                    return(Payment_PayPalStartPayment(viewModel, webFormResponse));
                }


                //payment with pay after order/no automated processing
                CartPaymentInfo cartPaymentInfo = null;
                if (cart.CartPaymentInfo == null)
                {
                    cartPaymentInfo = GStoreDb.CartPaymentInfos.Create();
                    cartPaymentInfo.SetDefaults(CurrentUserProfileOrNull);
                    cartPaymentInfo.Client           = CurrentClientOrThrow;
                    cartPaymentInfo.ClientId         = cartPaymentInfo.Client.ClientId;
                    cartPaymentInfo.StoreFront       = CurrentStoreFrontOrThrow;
                    cartPaymentInfo.StoreFrontId     = cartPaymentInfo.StoreFront.StoreFrontId;
                    cartPaymentInfo.StartDateTimeUtc = DateTime.UtcNow.AddMinutes(-1);
                    cartPaymentInfo.EndDateTimeUtc   = DateTime.UtcNow.AddYears(100);
                    cartPaymentInfo.Cart             = cart;
                    cartPaymentInfo.CartId           = cart.CartId;
                    if (webFormResponse != null)
                    {
                        cartPaymentInfo.WebFormResponseId = webFormResponse.WebFormResponseId;
                    }

                    cartPaymentInfo = GStoreDb.CartPaymentInfos.Add(cartPaymentInfo);
                }
                else
                {
                    cartPaymentInfo = cart.CartPaymentInfo;
                    if (webFormResponse != null)
                    {
                        cartPaymentInfo.WebFormResponseId = webFormResponse.WebFormResponseId;
                    }
                    cartPaymentInfo = GStoreDb.CartPaymentInfos.Update(cartPaymentInfo);
                }

                //add/remove/etc
                cart.StatusPaymentInfoConfirmed = true;
                GStoreDb.Carts.Update(cart);
                GStoreDb.SaveChanges();

                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Checkout, UserActionActionEnum.Checkout_ConfirmedPaymentInfo, "", true, cartId: cart.CartId);

                return(RedirectToAction("ConfirmOrder"));
            }

            viewModel.UpdateForRepost(config, cart, RouteData.Action());
            return(View("PaymentInfo", viewModel));
        }
Пример #27
0
        public ActionResult DeliveryInfoShipping(CheckoutDeliveryInfoShippingViewModel viewModel)
        {
            StoreFrontConfiguration config = CurrentStoreFrontConfigOrThrow;
            Cart cart = config.StoreFront.GetCart(Session.SessionID, CurrentUserProfileOrNull);

            if (!cart.CartIsValidForCheckout(this))
            {
                return(RedirectToAction("Index", "Cart"));
            }

            if (!cart.StatusStartedCheckout)
            {
                return(RedirectToAction("Index"));
            }
            if (!cart.StatusSelectedLogInOrGuest)
            {
                return(RedirectToAction("LogInOrGuest"));
            }

            cart = cart.ValidateCartAndSave(this);

            if (cart.AllItemsAreDigitalDownload)
            {
                return(RedirectToAction("DeliveryInfo"));
            }

            //check if custom form is valid
            if (config.CheckoutDeliveryInfoShippingWebForm != null)
            {
                FormProcessorExtensions.ValidateFields(this, config.CheckoutDeliveryInfoShippingWebForm);
            }

            if (ModelState.IsValid)
            {
                WebFormResponse webFormResponse = cart.DeliveryInfoShippingProcessWebForm(this);

                DeliveryInfoShipping info = null;
                if (cart.DeliveryInfoShipping == null)
                {
                    info = GStoreDb.DeliveryInfoShippings.Create();
                    info.SetDefaults(CurrentUserProfileOrNull);
                    info.Client           = CurrentClientOrThrow;
                    info.ClientId         = info.Client.ClientId;
                    info.StoreFront       = CurrentStoreFrontOrThrow;
                    info.StoreFrontId     = info.StoreFront.StoreFrontId;
                    info.StartDateTimeUtc = DateTime.UtcNow.AddMinutes(-1);
                    info.EndDateTimeUtc   = DateTime.UtcNow.AddYears(100);
                    info.Cart             = cart;
                    info.CartId           = cart.CartId;

                    info.AdddressL1   = viewModel.AdddressL1;
                    info.AdddressL2   = viewModel.AdddressL2;
                    info.EmailAddress = viewModel.EmailAddress;
                    info.FullName     = viewModel.FullName;
                    info.City         = viewModel.City;
                    info.State        = viewModel.State;
                    info.PostalCode   = viewModel.PostalCode;
                    info.CountryCode  = viewModel.CountryCode.Value;
                    if (webFormResponse != null)
                    {
                        info.WebFormResponseId = webFormResponse.WebFormResponseId;
                    }
                    info = GStoreDb.DeliveryInfoShippings.Add(info);
                }
                else
                {
                    info              = cart.DeliveryInfoShipping;
                    info.AdddressL1   = viewModel.AdddressL1;
                    info.AdddressL2   = viewModel.AdddressL2;
                    info.EmailAddress = viewModel.EmailAddress;
                    info.FullName     = viewModel.FullName;
                    info.City         = viewModel.City;
                    info.State        = viewModel.State;
                    info.PostalCode   = viewModel.PostalCode;
                    info.CountryCode  = viewModel.CountryCode.Value;
                    if (webFormResponse != null)
                    {
                        info.WebFormResponseId = webFormResponse.WebFormResponseId;
                    }
                    info = GStoreDb.DeliveryInfoShippings.Update(info);
                }

                cart.DeliveryInfoShipping = info;
                cart.Email    = viewModel.EmailAddress;
                cart.FullName = viewModel.FullName;
                cart.StatusCompletedDeliveryInfo = true;
                GStoreDb.Carts.Update(cart);
                GStoreDb.SaveChanges();

                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Checkout, UserActionActionEnum.Checkout_CompletedDeliveryInfo, "", true, cartId: cart.CartId);

                return(RedirectToAction("DeliveryMethod"));
            }

            viewModel.UpdateForRepost(config, cart, RouteData.Action());
            return(View("DeliveryInfoShipping", viewModel));
        }
Пример #28
0
        public virtual bool TryDisplayErrorView(Exception ex, Exceptions.ErrorPage errorPage, int httpStatusCode, bool throwErrorIfAny)
        {
            try
            {
                if (this.ControllerContext == null)
                {
                    throw new ApplicationException("Controller context not set. Be sure to call InitContext on base controller before displaying an error view.");
                }
                string areaName       = (RouteData != null && RouteData.DataTokens.ContainsKey("area") ? RouteData.DataTokens["area"].ToString() : null);
                string controllerName = (RouteData != null && RouteData.Values.ContainsKey("controller") ? RouteData.Values["controller"].ToString() : null);
                string actionName     = (RouteData != null && RouteData.Values.ContainsKey("action") ? RouteData.Values["action"].ToString() : null);

                if (string.IsNullOrEmpty(areaName))
                {
                    actionName = "(unknown area)";
                }
                if (string.IsNullOrEmpty(controllerName))
                {
                    controllerName = "(unknown controller)";
                }
                if (string.IsNullOrEmpty(actionName))
                {
                    actionName = "(unknown action)";
                }


                string     ipAddress = this.Request.UserHostAddress;
                StoreFront currentStoreFrontOrNull = null;
                StoreFrontConfiguration currentStoreFrontConfigOrNull = null;
                _throwErrorIfAnonymous               = false;
                _throwErrorIfStoreFrontNotFound      = false;
                _throwErrorIfUserProfileNotFound     = false;
                _useInactiveStoreFrontAsActive       = true;
                _useInactiveStoreFrontConfigAsActive = true;
                try
                {
                    currentStoreFrontOrNull       = CurrentStoreFrontOrNull;
                    currentStoreFrontConfigOrNull = CurrentStoreFrontConfigOrNull;
                }
                catch (Exception)
                {
                }

                Response.Clear();
                Response.StatusCode = httpStatusCode;
                string errorPageFileName = errorPage.ErrorPageFileName();
                if (!Enum.IsDefined(typeof(Exceptions.ErrorPage), errorPage))
                {
                    return(false);
                }

                string errorViewName = Enum.GetName(typeof(Exceptions.ErrorPage), errorPage);

                if (string.IsNullOrEmpty(Request["NotFound"]) && errorPage == ErrorPage.Error_NotFound && CurrentStoreFrontIdOrNull != null && currentStoreFrontConfigOrNull.NotFoundErrorPage != null && currentStoreFrontConfigOrNull.NotFoundErrorPage.IsActiveBubble())
                {
                    string urlRedirect = currentStoreFrontConfigOrNull.NotFoundErrorPage.UrlResolved(Url) + "?NotFound=1";
                    AddUserMessage("Page Not Found", "Sorry, the URL you were looking for was not found. '" + Request.Url.ToString().ToHtml() + "'", UserMessageType.Danger);
                    new RedirectResult(urlRedirect, false).ExecuteResult(this.ControllerContext);
                    return(true);
                }

                if (string.IsNullOrEmpty(Request["StoreError"]) && (errorPage == ErrorPage.Error_AppError || errorPage == ErrorPage.Error_BadRequest || errorPage == ErrorPage.Error_HttpError || errorPage == ErrorPage.Error_InvalidOperation || errorPage == ErrorPage.Error_UnknownError) && CurrentStoreFrontIdOrNull != null && currentStoreFrontConfigOrNull.StoreErrorPage != null && currentStoreFrontConfigOrNull.StoreErrorPage.IsActiveBubble())
                {
                    string urlRedirect = currentStoreFrontConfigOrNull.StoreErrorPage.UrlResolved(Url) + "?StoreError=1";
                    AddUserMessage("Server Error", "Sorry, there was a server error processing your request for URL '" + Request.Url.ToString().ToHtml() + "'", UserMessageType.Danger);
                    new RedirectResult(urlRedirect, false).ExecuteResult(this.ControllerContext);
                    return(true);
                }

                GStoreErrorInfo model = new GStoreErrorInfo(errorPage, ex, RouteData, controllerName, actionName, ipAddress, currentStoreFrontOrNull, Request.RawUrl, Request.Url.ToString());
                View(errorViewName, model).ExecuteResult(this.ControllerContext);

                return(true);
            }
            catch (Exception exDisplay)
            {
                string message = "Error in Controller Error View."
                                 + " \n --Controller: " + this.GetType().FullName
                                 + " \n --Url: " + Request.Url.ToString()
                                 + " \n --RawUrl: " + Request.RawUrl
                                 + " \n --ErrorPage: " + "[" + ((int)errorPage).ToString() + "] " + errorPage.ToString()
                                 + " \n --Exception: " + exDisplay.ToString()
                                 + " \n --Source: " + exDisplay.Source
                                 + " \n --TargetSiteName: " + exDisplay.TargetSite.Name
                                 + " \n --StackTrace: " + exDisplay.StackTrace
                                 + " \n --Original Exception: " + ex.Message.ToString()
                                 + " \n --Original Source: " + ex.Source
                                 + " \n --Original TargetSiteName: " + ex.TargetSite.Name
                                 + " \n --Original StackTrace: " + ex.StackTrace;

                System.Diagnostics.Trace.WriteLine("--" + message);
                string exceptionMessage      = exDisplay.Message;
                string baseExceptionMessage  = ex.GetBaseException().Message;
                string baseExceptionToString = ex.GetBaseException().ToString();
                GStoreDb.LogSystemEvent(HttpContext, RouteData, RouteData.ToSourceString(), SystemEventLevel.ApplicationException, message, exceptionMessage, baseExceptionMessage, baseExceptionToString, this);
                if (throwErrorIfAny)
                {
                    throw new ApplicationException(message, exDisplay);
                }
                return(false);
            }
        }
Пример #29
0
        /// <summary>
        /// Flow: is both params are null, system will search for blogs. If no blogs or multiple blogs are found, a list will be returned.
        /// If only one blog is found, it will be displayed
        ///
        /// </summary>
        /// <param name="blogUrlName"></param>
        /// <param name="blogEntryUrlName"></param>
        /// <returns></returns>
        public ActionResult Index(string blogUrlName, string blogEntryUrlName)
        {
            bool blogUrlNameIsAll      = (!string.IsNullOrEmpty(blogUrlName) && blogUrlName.Trim().ToLower() == "all");
            bool blogEntryUrlNameIsAll = (!string.IsNullOrEmpty(blogEntryUrlName) && blogEntryUrlName.Trim().ToLower() == "all");

            if (string.IsNullOrWhiteSpace(blogUrlName) || blogUrlNameIsAll)
            {
                //no blog name, get list of blogs and auto-feed first
                List <Blog> blogs = CurrentStoreFrontOrThrow.BlogsForUser(User.IsRegistered());
                if (blogs.Count == 1 && !blogUrlNameIsAll)
                {
                    List <BlogEntry> entries = blogs[0].BlogEntriesForUser(User.IsRegistered());
                    if (entries.Count == 1)
                    {
                        return(RedirectToAction("Index", RouteDataForIndex(blogs[0].UrlName, entries[0].UrlName)));
                    }
                    return(RedirectToAction("Index", RouteDataForIndex(blogs[0].UrlName, "")));
                }
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Blog, UserActionActionEnum.Blog_List, "", true);
                return(ListBlogs(blogs));
            }

            //blog was specified, look it up
            Blog blog = null;

            try
            {
                blog = GetBlog(blogUrlName);
            }
            catch (LoginRequiredException ex)
            {
                string message = "You must log in to view blog '" + ex.BlogName.ToHtml() + "'.";
                return(BounceToLoginNoAccessResult(message));
            }
            catch (Exception)
            {
                throw;
            }
            if (blog == null)
            {
                //blog not found or no access, display user messages
                return(RedirectToAction("Index", RouteDataForIndex("", "")));
            }

            if (string.IsNullOrWhiteSpace(blogEntryUrlName) || blogEntryUrlNameIsAll)
            {
                //blog is passed but no blog entry selected
                List <BlogEntry> entries = blog.BlogEntriesForUser(User.IsRegistered());
                if (entries.Count == 1 && !blogEntryUrlNameIsAll)
                {
                    return(RedirectToAction("Index", RouteDataForIndex(blog.UrlName, entries[0].UrlName)));
                }
                return(ViewBlog(blog, blogEntryUrlNameIsAll));
            }

            BlogEntry blogEntry = null;

            try
            {
                blogEntry = GetBlogEntry(blog, blogEntryUrlName);
            }
            catch (LoginRequiredException ex)
            {
                string message = "Sorry, you must log in to view blog entry '" + ex.BlogEntryName.ToHtml() + "' from the blog '" + ex.BlogName.ToHtml() + "'.";
                return(BounceToLoginNoAccessResult(message));
            }
            catch (Exception)
            {
                throw;
            }
            if (blogEntry == null)
            {
                //blog entry not found or no access, show user messages
                return(RedirectToAction("Index", RouteDataForIndex(blog.UrlName, "")));
            }

            return(ViewBlogEntry(blogEntry));
        }
Пример #30
0
        public ActionResult Add(string id, int?qty, string type, bool?Login, bool?buyNow)
        {
            //remove old item and add new item
            if (!CheckAccess())
            {
                return(BounceToLogin());
            }

            int quantity = 1;

            if (qty.HasValue && qty.Value > 0 && qty.Value < 10000)
            {
                quantity = qty.Value;
            }

            StoreFront storeFront = CurrentStoreFrontOrThrow;
            Cart       cart       = storeFront.GetCart(Session.SessionID, CurrentUserProfileOrNull);

            if (string.IsNullOrWhiteSpace(id))
            {
                AddUserMessage("Add to Cart Error", "Item not found. Please try again.", UserMessageType.Danger);
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Cart, UserActionActionEnum.Cart_AddToCartFailure, "Bad Url", false, cartId: (cart == null ? (int?)null : cart.CartId), productUrlName: id);
                return(RedirectToAction("Index"));
            }

            Product product = storeFront.Products.AsQueryable().CanAddToCart(storeFront).SingleOrDefault(p => p.UrlName.ToLower() == id.ToLower());

            if (product == null)
            {
                AddUserMessage("Add to Cart Error", "Item '" + id.ToHtml() + "' could not be found to add to your cart. Please try again.", UserMessageType.Danger);
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Cart, UserActionActionEnum.Cart_AddToCartFailure, "Item Not Found", false, cartId: (cart == null ? (int?)null : cart.CartId), productUrlName: id);
                return(RedirectToPreviousPageOrCartIndex());
            }

            if (!product.AvailableForPurchase)
            {
                AddUserMessage("Add to Cart Error", "Item '" + id.ToHtml() + "' is not available for purchase online. Please try again.", UserMessageType.Danger);
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Cart, UserActionActionEnum.Cart_AddToCartFailure, "Product not available for purchase", false, cartId: (cart == null ? (int?)null : cart.CartId), productUrlName: id);
                return(RedirectToPreviousPageOrCartIndex());
            }

            //if item with same variant is already added, increment the quantity
            if (!CurrentStoreFrontConfigOrThrow.UseShoppingCart)
            {
                if (cart != null && cart.CartItems.Count > 0)
                {
                    //if storefront is not set to use a cart, dump previous items and start with a new cart.
                    CurrentStoreFrontOrThrow.DumpCartNoSave(GStoreDb, cart);
                    GStoreDb.SaveChanges();
                    cart = storeFront.GetCart(Session.SessionID, CurrentUserProfileOrNull);
                }
            }

            CartItem cartItemExisting = cart.FindItemInCart(product, type, false);

            if (cartItemExisting != null)
            {
                int newQty = cartItemExisting.Quantity + quantity;
                cartItemExisting = cartItemExisting.UpdateQuantityAndSave(GStoreDb, newQty, this);

                if (newQty <= cartItemExisting.Product.MaxQuantityPerOrder)
                {
                    AddUserMessage("Item Added to Cart", "'" + cartItemExisting.Product.Name.ToHtml() + "' was added to your cart. Now you have " + cartItemExisting.Quantity + " of them in your cart.<br/><a href=" + Url.Action("Index", "Cart") + ">Click here to view your cart.</a>", UserMessageType.Success);
                    cart.CancelCheckout(GStoreDb);
                }
                else
                {
                    //quantity is over max, user messages are already set
                }
                GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Cart, UserActionActionEnum.Cart_AddToCartSuccess, "Added to Existing", true, cartId: cart.CartId, productUrlName: id);

                if (buyNow ?? false)
                {
                    return(RedirectToAction("Index", "Checkout"));
                }
                return(RedirectToPreviousPageOrCartIndex());
            }
            CartItem cartItem = cart.AddToCart(product, quantity, type, this);

            AddUserMessage("Item Added to Cart", "'" + product.Name.ToHtml() + "' is now in your shopping cart.<br/><a href=" + Url.Action("Index", "Cart") + ">Click here to view your cart.</a>", UserMessageType.Success);

            GStoreDb.LogUserActionEvent(HttpContext, RouteData, this, UserActionCategoryEnum.Cart, UserActionActionEnum.Cart_AddToCartSuccess, "Added", true, cartId: cartItem.CartId, productUrlName: id);

            cart.CancelCheckout(GStoreDb);

            if (buyNow.HasValue && buyNow.Value)
            {
                return(RedirectToAction("Index", "Checkout"));
            }

            return(RedirectToPreviousPageOrCartIndex());
        }