Ejemplo n.º 1
0
        /// <summary>
        /// Create default URL
        /// </summary>
        /// <param name="pageNumber">Page number</param>
        /// <returns>URL</returns>
        protected virtual string CreateDefaultUrl(int pageNumber)
        {
            var routeValues = new RouteValueDictionary();

            var parametersWithEmptyValues = new List <string>();

            foreach (var key in viewContext.HttpContext.Request.Query.Keys.Where(key => key != null))
            {
                //TODO test new implementation (QueryString, keys). And ensure no null exception is thrown when invoking ToString(). Is "StringValues.IsNullOrEmpty" required?
                var value = viewContext.HttpContext.Request.Query[key].ToString();
                if (renderEmptyParameters && string.IsNullOrEmpty(value))
                {
                    //we store query string parameters with empty values separately
                    //we need to do it because they are not properly processed in the UrlHelper.GenerateUrl method (dropped for some reasons)
                    parametersWithEmptyValues.Add(key);
                }
                else
                {
                    if (booleanParameterNames.Contains(key, StringComparer.InvariantCultureIgnoreCase))
                    {
                        //little hack here due to ugly MVC implementation
                        //find more info here: http://www.mindstorminteractive.com/topics/jquery-fix-asp-net-mvc-checkbox-truefalse-value/
                        if (!string.IsNullOrEmpty(value) && value.Equals("true,false", StringComparison.InvariantCultureIgnoreCase))
                        {
                            value = "true";
                        }
                    }
                    routeValues[key] = value;
                }
            }

            if (pageNumber > 1)
            {
                routeValues[pageQueryName] = pageNumber;
            }
            else
            {
                //SEO. we do not render pageindex query string parameter for the first page
                if (routeValues.ContainsKey(pageQueryName))
                {
                    routeValues.Remove(pageQueryName);
                }
            }

            IWebHelper webHelper = ServiceProviderFactory.ServiceProvider.GetService <IWebHelper>();
            var        url       = webHelper.GetThisPageUrl(false);

            foreach (var routeValue in routeValues)
            {
                url = webHelper.ModifyQueryString(url, routeValue.Key, routeValue.Value?.ToString());
            }
            if (renderEmptyParameters && parametersWithEmptyValues.Any())
            {
                foreach (var key in parametersWithEmptyValues)
                {
                    url = webHelper.ModifyQueryString(url, key);
                }
            }
            return(url);
        }
Ejemplo n.º 2
0
 public void Can_modify_queryString()
 {
     //first param (?)
     _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value2", "param1=value3", null)
     .ShouldEqual("http://www.example.com/?param1=value3&param2=value2");
     //second param (&)
     _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value2", "param2=value3", null)
     .ShouldEqual("http://www.example.com/?param1=value1&param2=value3");
     //non-existing param
     _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value2", "param3=value3", null)
     .ShouldEqual("http://www.example.com/?param1=value1&param2=value2&param3=value3");
 }
Ejemplo n.º 3
0
        public void Can_modify_queryString()
        {
            //empty URL
            _webHelper.ModifyQueryString(null, null).ShouldEqual(string.Empty);

            //empty key
            _webHelper.ModifyQueryString("http://www.example.com/", null).ShouldEqual("http://www.example.com/");

            //empty value
            _webHelper.ModifyQueryString("http://www.example.com/", "param").ShouldEqual("http://www.example.com/?param=");

            //first param (?)
            _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value1", "param1", "value2")
            .ShouldEqual("http://www.example.com/?param1=value2&param2=value1");

            //second param (&)
            _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value1", "param2", "value2")
            .ShouldEqual("http://www.example.com/?param1=value1&param2=value2");

            //non-existing param
            _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value1", "param3", "value1")
            .ShouldEqual("http://www.example.com/?param1=value1&param2=value1&param3=value1");

            //multiple values
            _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value1", "param1", "value1", "value2", "value3")
            .ShouldEqual("http://www.example.com/?param1=value1,value2,value3&param2=value1");

            //with fragment
            _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value1#fragment", "param1", "value2")
            .ShouldEqual("http://www.example.com/?param1=value2&param2=value1#fragment");
        }
Ejemplo n.º 4
0
 public void Can_modify_queryString()
 {
     _httpContext = new FakeHttpContext("~/", "GET", null, null, null, null, null, null);
     _webHelper   = new WebHelper(_httpContext);
     //first param (?)
     _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value2", "param1=value3", null)
     .ShouldEqual("http://www.example.com/?param1=value3&param2=value2");
     //second param (&)
     _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value2", "param2=value3", null)
     .ShouldEqual("http://www.example.com/?param1=value1&param2=value3");
     //non-existing param
     _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value2", "param3=value3", null)
     .ShouldEqual("http://www.example.com/?param1=value1&param2=value2&param3=value3");
 }
Ejemplo n.º 5
0
        public void Passess_ModifyQueryString_Success()
        {
            string url = "/Request?parameter=123#nav1";

            _httpContext = new FakeHttpContext("~/");
            _webHelper   = new WebHelper(_httpContext);

            //不覆盖
            _webHelper.ModifyQueryString(url, "property=abc", "nva2").ToLower()
            .TestEqual("/Request?parameter=123&property=abc#nva2".ToLower());

            //覆盖
            _webHelper.ModifyQueryString(url, "property=abc&parameter=456", "nva2").ToLower()
            .TestEqual("/Request?parameter=456&property=abc#nva2".ToLower());
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Generate affilaite URL
        /// </summary>
        /// <param name="affiliate">Affiliate</param>
        /// <param name="webHelper">Web helper</param>
        /// <returns>Generated affilaite URL</returns>
        public static string GenerateUrl(this Affiliate affiliate, IWebHelper webHelper = null)
        {
            if (webHelper == null)
                webHelper = EngineContext.Current.Resolve<IWebHelper>();

            string storeUrl = webHelper.GetStoreLocation(false);
            if (!string.IsNullOrWhiteSpace(affiliate.FriendlyUrlName))
                storeUrl = webHelper.ModifyQueryString(storeUrl,
                    string.Format("{0}={1}", Affiliate.AFFILIATE_FRIENDLYURLNAME_QUERY_PARAMETER_NAME,
                        affiliate.FriendlyUrlName), null);
            else
                storeUrl = webHelper.ModifyQueryString(storeUrl,
                    string.Format("{0}={1}", Affiliate.AFFILIATE_ID_QUERY_PARAMETER_NAME, affiliate.Id), null);
            return storeUrl;
        }
Ejemplo n.º 7
0
 public void Can_modify_queryString_with_anchor()
 {
     _httpContext = new FakeHttpContext("~/", "GET", null, null, null, null, null, null);
     _webHelper   = new WebHelper(_httpContext);
     _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value2", "param1=value3", "Test")
     .ShouldEqual("http://www.example.com/?param1=value3&param2=value2#test");
 }
Ejemplo n.º 8
0
 public void Can_modify_queryString_new_anchor_should_remove_previous_one()
 {
     _httpContext = new FakeHttpContext("~/", "GET", null, null, null, null, null, null);
     _webHelper   = new WebHelper(_httpContext);
     _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value2#test1", "param1=value3", "Test2")
     .ShouldEqual("http://www.example.com/?param1=value3&param2=value2#test2");
 }
 public void CanModifyQueryString_NewAnchorShouldRemovePreviousOne()
 {
     _httpContext = new FakeHttpContext("~/", "GET", null, null, null, null, null, null);
     _webHelper   = new WebHelper(_httpContext);
     _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value2#test1", "param1=value3", "Test2")
     .ShouldEqual("http://www.example.com/?param1=value3&param2=value2#test2");
 }
Ejemplo n.º 10
0
        /// <summary>
        /// Assigns customer roles, publishes an event, sends email messages, signs the customer in depending on configuration & returns appropriate redirect.
        /// </summary>
        private async Task <IActionResult> FinalizeCustomerRegistrationAsync(Customer customer, string returnUrl)
        {
            await AssignCustomerRolesAsync(customer);

            // Add reward points for customer registration (if enabled).
            if (_rewardPointsSettings.Enabled && _rewardPointsSettings.PointsForRegistration > 0)
            {
                customer.AddRewardPointsHistoryEntry(_rewardPointsSettings.PointsForRegistration, T("RewardPoints.Message.RegisteredAsCustomer"));
            }

            await Services.EventPublisher.PublishAsync(new CustomerRegisteredEvent { Customer = customer });

            // Notifications
            if (_customerSettings.NotifyNewCustomerRegistration)
            {
                await _messageFactory.SendCustomerRegisteredNotificationMessageAsync(customer, _localizationSettings.DefaultAdminLanguageId);
            }

            switch (_customerSettings.UserRegistrationType)
            {
            case UserRegistrationType.EmailValidation:
            {
                // Send an email with generated token.
                var code = await _userManager.GenerateEmailConfirmationTokenAsync(customer);

                customer.GenericAttributes.AccountActivationToken = code;
                await _db.SaveChangesAsync();

                await _messageFactory.SendCustomerEmailValidationMessageAsync(customer, Services.WorkContext.WorkingLanguage.Id);

                return(RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.EmailValidation }));
            }

            case UserRegistrationType.AdminApproval:
            {
                return(RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.AdminApproval }));
            }

            case UserRegistrationType.Standard:
            {
                // Send customer welcome message.
                await _messageFactory.SendCustomerWelcomeMessageAsync(customer, Services.WorkContext.WorkingLanguage.Id);

                await _signInManager.SignInAsync(customer, isPersistent : false);

                var redirectUrl = Url.RouteUrl("RegisterResult", new { resultId = (int)UserRegistrationType.Standard });
                if (returnUrl.HasValue())
                {
                    redirectUrl = _webHelper.ModifyQueryString(redirectUrl, "returnUrl=" + HttpUtility.UrlEncode(returnUrl), null);
                }

                return(Redirect(redirectUrl));
            }

            default:
            {
                return(RedirectToRoute("Homepage"));
            }
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Generate affiliate URL
        /// </summary>
        /// <param name="affiliate">Affiliate</param>
        /// <returns>Generated affiliate URL</returns>
        public virtual string GenerateUrl(Affiliate affiliate)
        {
            if (affiliate == null)
            {
                throw new ArgumentNullException(nameof(affiliate));
            }

            var storeUrl = _webHelper.GetStoreLocation(false);
            var url      = !string.IsNullOrEmpty(affiliate.FriendlyUrlName) ?
                           //use friendly URL
                           _webHelper.ModifyQueryString(storeUrl, QNetAffiliateDefaults.AffiliateQueryParameter, affiliate.FriendlyUrlName) :
                           //use ID
                           _webHelper.ModifyQueryString(storeUrl, QNetAffiliateDefaults.AffiliateIdQueryParameter, affiliate.Id.ToString());

            return(url);
        }
Ejemplo n.º 12
0
        public virtual void PrepareSortingOptions(CatalogPagingFilteringModel pagingFilteringModel, CatalogPagingFilteringModel command)
        {
            if (pagingFilteringModel == null)
            {
                throw new ArgumentNullException("pagingFilteringModel");
            }

            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            var allDisabled = _catalogSettings.ProductSortingEnumDisabled.Count == Enum.GetValues(typeof(ProductSortingEnum)).Length;

            pagingFilteringModel.AllowProductSorting = _catalogSettings.AllowProductSorting && !allDisabled;

            var activeOptions = Enum.GetValues(typeof(ProductSortingEnum)).Cast <int>()
                                .Except(_catalogSettings.ProductSortingEnumDisabled)
                                .Select((idOption) =>
            {
                int order;
                return(new KeyValuePair <int, int>(idOption, _catalogSettings.ProductSortingEnumDisplayOrder.TryGetValue(idOption, out order) ? order : idOption));
            })
                                .OrderBy(x => x.Value);

            if (command.OrderBy == null)
            {
                command.OrderBy = allDisabled ? 0 : activeOptions.First().Key;
            }

            if (pagingFilteringModel.AllowProductSorting)
            {
                foreach (var option in activeOptions)
                {
                    var currentPageUrl = _webHelper.GetThisPageUrl(true);
                    var sortUrl        = _webHelper.ModifyQueryString(currentPageUrl, "orderby=" + (option.Key).ToString(), null);

                    var sortValue = ((ProductSortingEnum)option.Key).GetLocalizedEnum(_localizationService, _workContext);
                    pagingFilteringModel.AvailableSortOptions.Add(new SelectListItem
                    {
                        Text     = sortValue,
                        Value    = sortUrl,
                        Selected = option.Key == command.OrderBy
                    });
                }
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Generate affilaite URL
        /// </summary>
        /// <param name="affiliate">Affiliate</param>
        /// <param name="webHelper">Web helper</param>
        /// <returns>Generated affilaite URL</returns>
        public static string GenerateUrl(this Affiliate affiliate, IWebHelper webHelper)
        {
            if (affiliate == null)
                throw new ArgumentNullException("affiliate");

            if (webHelper == null)
                throw new ArgumentNullException("webHelper");

            var storeUrl = webHelper.GetStoreLocation(false);
            var url = !String.IsNullOrEmpty(affiliate.FriendlyUrlName) ?
                //use friendly URL
                webHelper.ModifyQueryString(storeUrl, "affiliate=" + affiliate.FriendlyUrlName, null):
                //use ID
                webHelper.ModifyQueryString(storeUrl, "affiliateid=" + affiliate.Id, null);

            return url;
        }
Ejemplo n.º 14
0
        public ActionResult Register(RegisterModel model, string returnUrl, bool captchaValid)
        {
            //check whether registration is allowed
            if (AppSettings.Get <bool>("UserRegistrationDisabled"))
            {
                return(RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.Disabled }));
            }

            if (_workContext.CurrentStudent.IsRegistered())
            {
                //Already registered customer.
                _authenticationService.SignOut();
            }

            //Create a new record
            _workContext.CurrentStudent = CreateNewStudentObject();

            var student = _workContext.CurrentStudent;

            //validate CAPTCHA
            if (AppSettings.Get <bool>("CaptchaEnabled") && !captchaValid)
            {
                ModelState.AddModelError("", "Wrong Captcha");
            }

            if (ModelState.IsValid)
            {
                model.Username = model.Username.Trim();

                var registrationRequest = new StudentRegistrationRequest(_workContext.CurrentStudent ?? new Student(), model.Username, model.Password);
                var registrationResult  = _studentRegistrationService.RegisterStudent(registrationRequest);
                if (registrationResult.Success)
                {
                    //activity log
                    _studentActivityService.InsertActivity("Game.Registration", "ActivityLog.Game.Registration", student);

                    //login student now
                    _authenticationService.SignIn(student, true);

                    //send customer welcome message
                    var redirectUrl = Url.Action("RegisterResult", new { resultId = (int)UserRegistrationType.Standard });
                    if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                    {
                        redirectUrl = _webHelper.ModifyQueryString(redirectUrl, "returnurl=" + HttpUtility.UrlEncode(returnUrl), null);
                    }
                    return(Redirect(redirectUrl));
                }

                //errors
                foreach (var error in registrationResult.Errors)
                {
                    ModelState.AddModelError("", error);
                }
            }

            //If we got this far, something failed, redisplay form
            return(View(model));
        }
            public virtual void LoadSpecsFilters(Category category,
                                                 ISpecificationAttributeService specificationAttributeService, IWebHelper webHelper,
                                                 IWorkContext workContext)
            {
                if (category == null)
                {
                    throw new ArgumentNullException("category");
                }

                var alreadyFilteredOptions = GetAlreadyFilteredSpecs(specificationAttributeService, webHelper, workContext);
                var notFilteredOptions     = GetNotFilteredSpecs(category.Id,
                                                                 specificationAttributeService, webHelper, workContext);

                if (alreadyFilteredOptions.Count > 0 || notFilteredOptions.Count > 0)
                {
                    this.Enabled = true;

                    this.AlreadyFilteredItems = alreadyFilteredOptions.ToList().Select(x =>
                    {
                        var item = new SpecificationFilterItem();
                        item.SpecificationAttributeName       = x.SpecificationAttributeName;
                        item.SpecificationAttributeOptionName = x.SpecificationAttributeOptionName;

                        return(item);
                    }).ToList();

                    this.NotFilteredItems = notFilteredOptions.ToList().Select(x =>
                    {
                        var item = new SpecificationFilterItem();
                        item.SpecificationAttributeName       = x.SpecificationAttributeName;
                        item.SpecificationAttributeOptionName = x.SpecificationAttributeOptionName;

                        //filter URL
                        var alreadyFilteredOptionIds = GetAlreadyFilteredSpecOptionIds(webHelper);
                        if (!alreadyFilteredOptionIds.Contains(x.SpecificationAttributeOptionId))
                        {
                            alreadyFilteredOptionIds.Add(x.SpecificationAttributeOptionId);
                        }
                        string newQueryParam = GenerateFilteredSpecQueryParam(alreadyFilteredOptionIds);
                        string filterUrl     = webHelper.ModifyQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM + "=" + newQueryParam, null);
                        filterUrl            = ExcludeQueryStringParams(filterUrl, webHelper);
                        item.FilterUrl       = filterUrl;


                        return(item);
                    }).ToList();


                    //remove filter URL
                    string removeFilterUrl = webHelper.RemoveQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM);
                    removeFilterUrl      = ExcludeQueryStringParams(removeFilterUrl, webHelper);
                    this.RemoveFilterUrl = removeFilterUrl;
                }
                else
                {
                    this.Enabled = false;
                }
            }
Ejemplo n.º 16
0
        public void Can_modify_queryString()
        {
            /*
             * summary
             *  changes "param1=value1" into "param1=value3"
             *  or if particlar param doesn't exist - adds it at end
             */

            _fakeHttpContext = new FakeHttpContext("~/", "GET", null, null, null, null, null, null);
            _webHelper       = new WebHelper(_fakeHttpContext);

            Assert.AreEqual("http://www.example.com/?param1=value3&param2=value2",
                            _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value2", "param1=value3", null));
            Assert.AreEqual("http://www.example.com/?param1=value1&param2=value99",
                            _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value2", "param2=value99", null));
            Assert.AreEqual("http://www.example.com/?param1=value1&param2=value2&param321=value1000",
                            _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value2", "param321=value1000", null));
        }
Ejemplo n.º 17
0
        protected virtual void PrepareSortingOptions(CatalogPagingFilteringModel pagingFilteringModel, CatalogPagingFilteringModel command)
        {
            if (pagingFilteringModel == null)
            {
                throw new ArgumentNullException("pagingFilteringModel");
            }

            if (command == null)
            {
                throw new ArgumentNullException("command");
            }

            pagingFilteringModel.AllowItemSorting = true;

            var activeOptions = Enum.GetValues(typeof(ItemSortingEnum)).Cast <int>()
                                .Select((idOption) =>
            {
                int order;
                return(new KeyValuePair <int, int>(idOption, idOption));
            })
                                .OrderBy(x => x.Value);

            if (command.OrderBy == null)
            {
                command.OrderBy = activeOptions.First().Key;
            }

            if (pagingFilteringModel.AllowItemSorting)
            {
                foreach (var option in activeOptions)
                {
                    var currentPageUrl = _webHelper.GetThisPageUrl(true);
                    var sortUrl        = _webHelper.ModifyQueryString(currentPageUrl, "orderby=" + (option.Key).ToString(), null);

                    var sortValue = ((ItemSortingEnum)option.Key).ToString();
                    pagingFilteringModel.AvailableSortOptions.Add(new SelectListItem
                    {
                        Text     = sortValue,
                        Value    = sortUrl,
                        Selected = option.Key == command.OrderBy
                    });
                }
            }
        }
Ejemplo n.º 18
0
        public void Can_modify_queryString_new_anchor_should_remove_previous_one()
        {
            //removes existsing "#existinganchor" and replaces with "#anotheranchor" at end

            _fakeHttpContext = new FakeHttpContext("~/", "GET", null, null, null, null, null, null);
            _webHelper       = new WebHelper(_fakeHttpContext);

            Assert.AreEqual("http://www.example.com/?param1=value3&param2=value2#anotheranchor",
                            _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value2#existinganchor", "param1=value3", "anotheranchor"));
        }
Ejemplo n.º 19
0
        public void Can_modify_queryString_with_anchor()
        {
            //adds "#anchorrrtest" at end

            _fakeHttpContext = new FakeHttpContext("~/", "GET", null, null, null, null, null, null);
            _webHelper       = new WebHelper(_fakeHttpContext);

            Assert.AreEqual("http://www.example.com/?param1=value3&param2=value2#anchorrrtest",
                            _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value2", "param1=value3", "anchorrrtest"));
        }
Ejemplo n.º 20
0
        public virtual void PrepareQuantFilters(bool isQuant, IWebHelper webHelper, IWorkContext workContext)
        {
            const string QUERYSTRINGPARAM = "QuantFilter";

            string filterUrl = webHelper.ModifyQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM + "=" + !isQuant, null);

            filterUrl = ExcludeQueryStringParams(filterUrl, webHelper);
            ShowWithPositiveQuantityUrl = filterUrl;
            ShowWithPositiveQuantity    = isQuant;
        }
Ejemplo n.º 21
0
            protected virtual string ExcludeQueryStringParams(string url, IWebHelper webHelper)
            {
                const string excludedQueryStringParams         = "pagenumber";
                var          excludedQueryStringParamsSplitted = excludedQueryStringParams.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                foreach (string exclude in excludedQueryStringParamsSplitted)
                {
                    url = webHelper.ModifyQueryString(url, exclude, null);
                }
                return(url);
            }
Ejemplo n.º 22
0
        /// <summary>
        /// Generate affiliate URL
        /// </summary>
        /// <param name="affiliate">Affiliate</param>
        /// <param name="webHelper">Web helper</param>
        /// <returns>Generated affiliate URL</returns>
        public static string GenerateUrl(this Affiliate affiliate, IWebHelper webHelper)
        {
            if (affiliate == null)
            {
                throw new ArgumentNullException(nameof(affiliate));
            }

            if (webHelper == null)
            {
                throw new ArgumentNullException(nameof(webHelper));
            }

            var storeUrl = webHelper.GetStoreLocation(false);
            var url      = !string.IsNullOrEmpty(affiliate.FriendlyUrlName) ?
                           //use friendly URL
                           webHelper.ModifyQueryString(storeUrl, NopAffiliateDefaults.AffiliateQueryParameter, affiliate.FriendlyUrlName) :
                           //use ID
                           webHelper.ModifyQueryString(storeUrl, NopAffiliateDefaults.AffiliateIdQueryParameter, affiliate.Id.ToString());

            return(url);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Generate affilaite URL
        /// </summary>
        /// <param name="affiliate">Affiliate</param>
        /// <param name="webHelper">Web helper</param>
        /// <returns>Generated affilaite URL</returns>
        public static string GenerateUrl(this Affiliate affiliate, IWebHelper webHelper)
        {
            if (affiliate == null)
            {
                throw new ArgumentNullException("affiliate");
            }

            if (webHelper == null)
            {
                throw new ArgumentNullException("webHelper");
            }

            var storeUrl = webHelper.GetStoreLocation(false);
            var url      = !String.IsNullOrEmpty(affiliate.FriendlyUrlName) ?
                           //use friendly URL
                           webHelper.ModifyQueryString(storeUrl, "affiliate=" + affiliate.FriendlyUrlName, null):
                           //use ID
                           webHelper.ModifyQueryString(storeUrl, "affiliateid=" + affiliate.Id, null);

            return(url);
        }
Ejemplo n.º 24
0
        private void PrepareAffiliateModel(AffiliateModel model, Affiliate affiliate, bool excludeProperties)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            if (affiliate != null)
            {
                model.Id  = affiliate.Id;
                model.Url = _webHelper.ModifyQueryString(_webHelper.GetStoreLocation(false), "affiliateid=" + affiliate.Id, null);
                if (!excludeProperties)
                {
                    model.Active  = affiliate.Active;
                    model.Address = affiliate.Address.ToModel();
                }
            }

            //address
            model.Address.AvailableCountries.Add(new SelectListItem()
            {
                Text = _localizationService.GetResource("Admin.Address.SelectCountry"), Value = "0"
            });
            foreach (var c in _countryService.GetAllCountries(true))
            {
                model.Address.AvailableCountries.Add(new SelectListItem()
                {
                    Text = c.Name, Value = c.Id.ToString(), Selected = (affiliate != null && c.Id == affiliate.Address.CountryId)
                });
            }

            var states = model.Address.CountryId.HasValue ? _stateProvinceService.GetStateProvincesByCountryId(model.Address.CountryId.Value, true).ToList() : new List <StateProvince>();

            if (states.Count > 0)
            {
                foreach (var s in states)
                {
                    model.Address.AvailableStates.Add(new SelectListItem()
                    {
                        Text = s.Name, Value = s.Id.ToString(), Selected = (affiliate != null && s.Id == affiliate.Address.StateProvinceId)
                    });
                }
            }
            else
            {
                model.Address.AvailableStates.Add(new SelectListItem()
                {
                    Text = _localizationService.GetResource("Admin.Address.OtherNonUS"), Value = "0"
                });
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Prepare view modes
        /// </summary>
        /// <param name="pagingFilteringModel">Catalog paging filtering model</param>
        /// <param name="command">Catalog paging filtering command</param>
        public virtual void PrepareViewModes(CatalogPagingFilteringModel pagingFilteringModel, CatalogPagingFilteringModel command)
        {
            if (pagingFilteringModel == null)
            {
                throw new ArgumentNullException(nameof(pagingFilteringModel));
            }

            if (command == null)
            {
                throw new ArgumentNullException(nameof(command));
            }

            pagingFilteringModel.AllowProductViewModeChanging = _catalogSettings.AllowProductViewModeChanging;

            var viewMode = !string.IsNullOrEmpty(command.ViewMode)
                ? command.ViewMode
                : _catalogSettings.DefaultViewMode;

            pagingFilteringModel.ViewMode = viewMode;
            if (pagingFilteringModel.AllowProductViewModeChanging)
            {
                var currentPageUrl = _webHelper.GetThisPageUrl(true);
                //grid
                pagingFilteringModel.AvailableViewModes.Add(new SelectListItem
                {
                    Text     = _localizationService.GetResource("Catalog.ViewMode.Grid"),
                    Value    = _webHelper.ModifyQueryString(currentPageUrl, "viewmode", "grid"),
                    Selected = viewMode == "grid"
                });
                //list
                pagingFilteringModel.AvailableViewModes.Add(new SelectListItem
                {
                    Text     = _localizationService.GetResource("Catalog.ViewMode.List"),
                    Value    = _webHelper.ModifyQueryString(currentPageUrl, "viewmode", "list"),
                    Selected = viewMode == "list"
                });
            }
        }
Ejemplo n.º 26
0
        public ActionResult ProcessRoute(Core.Domain.Customers.Customer customer, string returnUrl)
        {
            var registerResult = Utilities.ViewPath(_storeName, "RegisterResult");


            switch (_customerSettings.UserRegistrationType)

            {
            case UserRegistrationType.EmailValidation:
            {
                //email validation message
                _genericAttributeService.SaveAttribute(customer, SystemCustomerAttributeNames.AccountActivationToken,
                                                       Guid.NewGuid().ToString());
                _workflowMessageService.SendCustomerEmailValidationMessage(customer, _workContext.WorkingLanguage.Id);

                //result
                return(RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.EmailValidation }));
            }

            case UserRegistrationType.AdminApproval:
            {
                return(RedirectToRoute("RegisterResult", new { resultId = (int)UserRegistrationType.AdminApproval }));
            }

            case UserRegistrationType.Standard:
            {
                //send customer welcome message
                _workflowMessageService.SendCustomerWelcomeMessage(customer, _workContext.WorkingLanguage.Id);

                var redirectUrl = Url.RouteUrl(registerResult, new { resultId = (int)UserRegistrationType.Standard });

                if (!String.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
                {
                    redirectUrl = _webHelper.ModifyQueryString(redirectUrl, "returnurl=" + HttpUtility.UrlEncode(returnUrl), null);
                }

                return(Redirect(redirectUrl));
            }

            default:
            {
                return(RedirectToRoute("HomePage"));
            }
            }
        }
Ejemplo n.º 27
0
 public void CanModifyQueryString()
 {
     //empty URL
     _webHelper.ModifyQueryString(null, null).Should().Be(string.Empty);
     //empty key
     _webHelper.ModifyQueryString($"http://{NopTestsDefaults.HostIpAddress}/", null).Should().Be($"http://{NopTestsDefaults.HostIpAddress}/");
     //empty value
     _webHelper.ModifyQueryString($"http://{NopTestsDefaults.HostIpAddress}/", "param").Should().Be($"http://{NopTestsDefaults.HostIpAddress}/?param=");
     //first param (?)
     _webHelper.ModifyQueryString($"http://{NopTestsDefaults.HostIpAddress}/?param1=value1&param2=value1", "Param1", "value2")
     .Should().Be($"http://{NopTestsDefaults.HostIpAddress}/?param1=value2&param2=value1");
     //second param (&)
     _webHelper.ModifyQueryString($"http://{NopTestsDefaults.HostIpAddress}/?param1=value1&param2=value1", "param2", "value2")
     .Should().Be($"http://{NopTestsDefaults.HostIpAddress}/?param1=value1&param2=value2");
     //non-existing param
     _webHelper.ModifyQueryString($"http://{NopTestsDefaults.HostIpAddress}/?param1=value1&param2=value1", "param3", "value1")
     .Should().Be($"http://{NopTestsDefaults.HostIpAddress}/?param1=value1&param2=value1&param3=value1");
     //multiple values
     _webHelper.ModifyQueryString($"http://{NopTestsDefaults.HostIpAddress}/?param1=value1&param2=value1", "param1", "value1", "value2", "value3")
     .Should().Be($"http://{NopTestsDefaults.HostIpAddress}/?param1=value1,value2,value3&param2=value1");
     //with fragment
     _webHelper.ModifyQueryString($"http://{NopTestsDefaults.HostIpAddress}/?param1=value1&param2=value1#fragment", "param1", "value2")
     .Should().Be($"http://{NopTestsDefaults.HostIpAddress}/?param1=value2&param2=value1#fragment");
 }
Ejemplo n.º 28
0
            /// <summary>
            /// Load price range filters
            /// </summary>
            /// <param name="webHelper">Web helper</param>
            public virtual void LoadAreaFilters(IWebHelper webHelper)
            {
                var areaList = GetAreaList();

                if (areaList.Any())
                {
                    this.Enabled = true;

                    var selectedArea = GetSelectedArea(webHelper);

                    for (int i = 0; i < areaList.Count; i++)
                    {
                        string str  = areaList.ElementAt(i);
                        var    item = new AreaFilterItem();
                        item.Area = str;

                        //is selected?
                        if (selectedArea != null &&
                            selectedArea == i.ToString())
                        {
                            item.Selected = true;
                        }

                        //filter URL
                        string url = webHelper.ModifyQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM + "=" + i, null);
                        url            = ExcludeQueryStringParams(url, webHelper);
                        item.FilterUrl = url;
                        this.Items.Add(item);
                    }

                    if (selectedArea != null)
                    {
                        //remove filter URL
                        string url = webHelper.RemoveQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM);
                        url = ExcludeQueryStringParams(url, webHelper);
                        this.RemoveFilterUrl = url;
                    }
                }
                else
                {
                    this.Enabled = false;
                }
            }
Ejemplo n.º 29
0
        private CcCartReturnToEditReplacementModel GetCcCartReturnToEditItems()
        {
            var model      = new CcCartReturnToEditReplacementModel();
            var ccSettings = _settingService.LoadSetting <CcSettings>();

            var customer = _workContext.CurrentCustomer;
            var cart     = customer.ShoppingCartItems
                           .Where(sci => sci.ShoppingCartType == ShoppingCartType.ShoppingCart)
                           .LimitPerStore(_storeContext.CurrentStore.Id)
                           .ToList();

            foreach (var shoppingCartItem in cart)
            {
                var attributeMappings =
                    _productAttributeParser.ParseProductAttributeMappings(shoppingCartItem.AttributesXml);
                foreach (var attributeMapping in attributeMappings)
                {
                    if (attributeMapping.ProductAttributeId == ccSettings.CcIdAttributeId)
                    {
                        var editCartItemUrl = Url.Action("EditorPage", "CcWidget", new { productId = shoppingCartItem.Product.Id });
                        editCartItemUrl += "&quantity=" + shoppingCartItem.Quantity + "&updateCartItemId=" + shoppingCartItem.Id;

                        var oldUrl = Url.RouteUrl("Product", new { SeName = shoppingCartItem.Product.GetSeName() });
                        oldUrl = _webHelper.ModifyQueryString(oldUrl, "updatecartitemid=" + shoppingCartItem.Id, null);

                        model.Items.Add(new CcCartReturnToEditReplacementModel.Item()
                        {
                            CartItemId = shoppingCartItem.Id,
                            OldUrl     = oldUrl,
                            Url        = editCartItemUrl
                        });
                    }
                }
            }
            return(model);
        }
Ejemplo n.º 30
0
            public virtual async Task PrepareSpecsFilters(IList <string> alreadyFilteredSpecOptionIds,
                                                          IList <string> filterableSpecificationAttributeOptionIds,
                                                          ISpecificationAttributeService specificationAttributeService,
                                                          IWebHelper webHelper, IWorkContext workContext, ICacheManager cacheManager)
            {
                Enabled = false;
                var optionIds = filterableSpecificationAttributeOptionIds != null
                    ? string.Join(",", filterableSpecificationAttributeOptionIds.Union(alreadyFilteredSpecOptionIds)) : string.Empty;

                var cacheKey = string.Format(ModelCacheEventConst.SPECS_FILTER_MODEL_KEY, optionIds, workContext.WorkingLanguage.Id);

                var allFilters = await cacheManager.GetAsync(cacheKey, async() =>
                {
                    var _allFilters = new List <SpecificationAttributeOptionFilter>();
                    foreach (var sao in filterableSpecificationAttributeOptionIds.Union(alreadyFilteredSpecOptionIds))
                    {
                        var sa = await specificationAttributeService.GetSpecificationAttributeByOptionId(sao);
                        if (sa != null)
                        {
                            _allFilters.Add(new SpecificationAttributeOptionFilter
                            {
                                SpecificationAttributeId                 = sa.Id,
                                SpecificationAttributeName               = sa.GetLocalized(x => x.Name, workContext.WorkingLanguage.Id),
                                SpecificationAttributeDisplayOrder       = sa.DisplayOrder,
                                SpecificationAttributeOptionId           = sao,
                                SpecificationAttributeOptionName         = sa.SpecificationAttributeOptions.FirstOrDefault(x => x.Id == sao).GetLocalized(x => x.Name, workContext.WorkingLanguage.Id),
                                SpecificationAttributeOptionDisplayOrder = sa.SpecificationAttributeOptions.FirstOrDefault(x => x.Id == sao).DisplayOrder,
                                SpecificationAttributeOptionColorRgb     = sa.SpecificationAttributeOptions.FirstOrDefault(x => x.Id == sao).ColorSquaresRgb,
                            });
                        }
                    }
                    return(_allFilters.ToList());
                });

                if (!allFilters.Any())
                {
                    return;
                }

                //sort loaded options
                allFilters = allFilters.OrderBy(saof => saof.SpecificationAttributeDisplayOrder)
                             .ThenBy(saof => saof.SpecificationAttributeName)
                             .ThenBy(saof => saof.SpecificationAttributeOptionDisplayOrder)
                             .ThenBy(saof => saof.SpecificationAttributeOptionName).ToList();

                //prepare the model properties
                Enabled = true;
                var removeFilterUrl = webHelper.ModifyQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM, null);

                RemoveFilterUrl = ExcludeQueryStringParams(removeFilterUrl, webHelper);

                //get already filtered specification options
                var alreadyFilteredOptions = allFilters.Where(x => alreadyFilteredSpecOptionIds.Contains(x.SpecificationAttributeOptionId));

                AlreadyFilteredItems = alreadyFilteredOptions.Select(x =>
                {
                    var filterUrl = webHelper.ModifyQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM, GenerateFilteredSpecQueryParam(alreadyFilteredOptions.Where(y => y.SpecificationAttributeOptionId != x.SpecificationAttributeOptionId).Select(z => z.SpecificationAttributeOptionId).ToList()));
                    return(new SpecificationFilterItem
                    {
                        SpecificationAttributeName = x.SpecificationAttributeName,
                        SpecificationAttributeOptionName = x.SpecificationAttributeOptionName,
                        SpecificationAttributeOptionColorRgb = x.SpecificationAttributeOptionColorRgb,
                        FilterUrl = ExcludeQueryStringParams(filterUrl, webHelper)
                    });
                }).ToList();

                //get not filtered specification options
                NotFilteredItems = allFilters.Except(alreadyFilteredOptions).Select(x =>
                {
                    //filter URL
                    var alreadyFiltered = alreadyFilteredSpecOptionIds.Concat(new List <string> {
                        x.SpecificationAttributeOptionId
                    });
                    var filterUrl = webHelper.ModifyQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM, GenerateFilteredSpecQueryParam(alreadyFiltered.ToList()));
                    return(new SpecificationFilterItem()
                    {
                        SpecificationAttributeName = x.SpecificationAttributeName,
                        SpecificationAttributeOptionName = x.SpecificationAttributeOptionName,
                        SpecificationAttributeOptionColorRgb = x.SpecificationAttributeOptionColorRgb,
                        FilterUrl = ExcludeQueryStringParams(filterUrl, webHelper)
                    });
                }).ToList();
            }
        public void Can_modify_queryString_new_anchor_should_remove_previous_one()
        {
            _httpContext = new FakeHttpContext("~/", "GET", null, null, null, null, null, null);
            _webHelper = new WebHelper(_httpContext);
            _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value2#test1", "param1=value3", "Test2")
							.ShouldEqual("http://www.example.com/?param1=value3&param2=value2#test2");
        }
 public void Can_modify_queryString_with_anchor()
 {
     _httpContext = new FakeHttpContext("~/", "GET", null, null, null, null, null, null);
     _webHelper = new WebHelper(_httpContext);
     _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value2", "param1=value3", "Test")
         .ShouldEqual("http://www.example.com/?param1=value3&param2=value2#test");
 }
        public void Can_modify_queryString()
        {
            _httpContext = new FakeHttpContext("~/", "GET", null, null, null, null, null, null);
            _webHelper = new WebHelper(_httpContext);
            //first param (?)
            _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value2", "param1=value3", null)
							.ShouldEqual("http://www.example.com/?param1=value3&param2=value2");
            //second param (&)
            _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value2", "param2=value3", null)
							.ShouldEqual("http://www.example.com/?param1=value1&param2=value3");
            //non-existing param
            _webHelper.ModifyQueryString("http://www.example.com/?param1=value1&param2=value2", "param3=value3", null)
							.ShouldEqual("http://www.example.com/?param1=value1&param2=value2&param3=value3");
        }
            public virtual void PrepareSpecsFilters(IList<string> alreadyFilteredSpecOptionIds,
                IList<string> filterableSpecificationAttributeOptionIds,
                ISpecificationAttributeService specificationAttributeService, 
                IWebHelper webHelper,
                IWorkContext workContext,
                ICacheManager cacheManager)
            {
                string cacheKey = string.Format(ModelCacheEventConsumer.SPECS_FILTER_MODEL_KEY,
                    filterableSpecificationAttributeOptionIds != null ? string.Join(",", filterableSpecificationAttributeOptionIds) : "",
                    workContext.WorkingLanguage.Id);

                var allFilters = cacheManager.Get(cacheKey, () =>
                {
                    var _allFilters = new List<SpecificationAttributeOptionFilter>();
                    foreach (var sao in filterableSpecificationAttributeOptionIds)
                    {
                        int _specificationAttributeId = Convert.ToInt32(sao.Split(':').FirstOrDefault().ToString());
                        int _specificationAttributeOptionId = Convert.ToInt32(sao.Split(':').LastOrDefault().ToString());
                        var sa = EngineContext.Current.Resolve<ISpecificationAttributeService>().GetSpecificationAttributeById(_specificationAttributeId);
                        if (sa != null)
                        {
                            _allFilters.Add(new SpecificationAttributeOptionFilter
                            {
                                SpecificationAttributeId = sa.Id,
                                SpecificationAttributeName = sa.GetLocalized(x => x.Name, workContext.WorkingLanguage.Id),
                                SpecificationAttributeDisplayOrder = sa.DisplayOrder,
                                SpecificationAttributeOptionId = sao, //_specificationAttributeOptionId.ToString(),  //sa.SpecificationAttributeOptions.FirstOrDefault(x=>x.Id == ),
                                SpecificationAttributeOptionName = sa.SpecificationAttributeOptions.FirstOrDefault(x => x.Id == _specificationAttributeOptionId).GetLocalized(x => x.Name, workContext.WorkingLanguage.Id),
                                SpecificationAttributeOptionDisplayOrder = sa.SpecificationAttributeOptions.FirstOrDefault(x => x.Id == _specificationAttributeOptionId).DisplayOrder
                            });
                        }
                    }
                    return _allFilters.ToList();
                });

                //sort loaded options
                allFilters = allFilters.OrderBy(saof => saof.SpecificationAttributeDisplayOrder)
                    .ThenBy(saof => saof.SpecificationAttributeName)
                    .ThenBy(saof => saof.SpecificationAttributeOptionDisplayOrder)
                    .ThenBy(saof => saof.SpecificationAttributeOptionName).ToList();

                //get already filtered specification options
                var alreadyFilteredOptions = allFilters
                    .Where(x => alreadyFilteredSpecOptionIds.Contains(x.SpecificationAttributeOptionId))
                    .Select(x => x)
                    .ToList();

                //get not filtered specification options
                var notFilteredOptions = new List<SpecificationAttributeOptionFilter>();
                foreach (var saof in allFilters)
                {
                    //do not add already filtered specification options
                    if (alreadyFilteredOptions.FirstOrDefault(x => x.SpecificationAttributeId == saof.SpecificationAttributeId) != null)
                        continue;

                    //else add it
                    notFilteredOptions.Add(saof);
                }

                //prepare the model properties
                if (alreadyFilteredOptions.Count > 0 || notFilteredOptions.Count > 0)
                {
                    this.Enabled = true;

                    this.AlreadyFilteredItems = alreadyFilteredOptions.ToList().Select(x =>
                    {
                        var item = new SpecificationFilterItem();
                        item.SpecificationAttributeName = x.SpecificationAttributeName;
                        item.SpecificationAttributeOptionName = x.SpecificationAttributeOptionName;

                        return item;
                    }).ToList();

                    this.NotFilteredItems = notFilteredOptions.ToList().Select(x =>
                    {
                        var item = new SpecificationFilterItem();
                        item.SpecificationAttributeName = x.SpecificationAttributeName;
                        item.SpecificationAttributeOptionName = x.SpecificationAttributeOptionName;

                        //filter URL
                        var alreadyFilteredOptionIds = GetAlreadyFilteredSpecOptionIds(webHelper);
                        if (!alreadyFilteredOptionIds.Contains(x.SpecificationAttributeOptionId.ToString()))
                            alreadyFilteredOptionIds.Add(x.SpecificationAttributeOptionId.ToString());
                        string newQueryParam = GenerateFilteredSpecQueryParam(alreadyFilteredOptionIds);
                        string filterUrl = webHelper.ModifyQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM + "=" + newQueryParam, null);
                        filterUrl = ExcludeQueryStringParams(filterUrl, webHelper);
                        item.FilterUrl = filterUrl;

                        return item;
                    }).ToList();

                    //remove filter URL
                    string removeFilterUrl = webHelper.RemoveQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM);
                    removeFilterUrl = ExcludeQueryStringParams(removeFilterUrl, webHelper);
                    this.RemoveFilterUrl = removeFilterUrl;
                }
                else
                {
                    this.Enabled = false;
                }
            }
            public virtual void PrepareSpecsFilters(IList<int> alreadyFilteredSpecOptionIds,
                IList<int> filterableSpecificationAttributeOptionIds,
                ISpecificationAttributeService specificationAttributeService, 
                IWebHelper webHelper,
                IWorkContext workContext)
            {
                var allFilters = new List<SpecificationAttributeOptionFilter>();
                var specificationAttributeOptions = specificationAttributeService
                    .GetSpecificationAttributeOptionsByIds(filterableSpecificationAttributeOptionIds != null ?
                    filterableSpecificationAttributeOptionIds.ToArray() : null);
                foreach (var sao in specificationAttributeOptions)
                {
                    var sa = sao.SpecificationAttribute;
                    if (sa != null)
                    {
                        allFilters.Add(new SpecificationAttributeOptionFilter
                        {
                            SpecificationAttributeId = sa.Id,
                            SpecificationAttributeName = sa.GetLocalized(x => x.Name, workContext.WorkingLanguage.Id),
                            SpecificationAttributeDisplayOrder = sa.DisplayOrder,
                            SpecificationAttributeOptionId = sao.Id,
                            SpecificationAttributeOptionName = sao.GetLocalized(x => x.Name, workContext.WorkingLanguage.Id),
                            SpecificationAttributeOptionDisplayOrder = sao.DisplayOrder
                        });
                    }
                }

                //sort loaded options
                allFilters = allFilters.OrderBy(saof => saof.SpecificationAttributeDisplayOrder)
                    .ThenBy(saof => saof.SpecificationAttributeName)
                    .ThenBy(saof => saof.SpecificationAttributeOptionDisplayOrder)
                    .ThenBy(saof => saof.SpecificationAttributeOptionName).ToList();

                //get already filtered specification options
                var alreadyFilteredOptions = allFilters
                    .Where(x => alreadyFilteredSpecOptionIds.Contains(x.SpecificationAttributeOptionId))
                    .Select(x => x)
                    .ToList();

                //get not filtered specification options
                var notFilteredOptions = new List<SpecificationAttributeOptionFilter>();
                foreach (var saof in allFilters)
                {
                    //do not add already filtered specification options
                    if (alreadyFilteredOptions.FirstOrDefault(x => x.SpecificationAttributeId == saof.SpecificationAttributeId) != null)
                        continue;

                    //else add it
                    notFilteredOptions.Add(saof);
                }

                //prepare the model properties
                if (alreadyFilteredOptions.Count > 0 || notFilteredOptions.Count > 0)
                {
                    this.Enabled = true;

                    this.AlreadyFilteredItems = alreadyFilteredOptions.ToList().Select(x =>
                    {
                        var item = new SpecificationFilterItem();
                        item.SpecificationAttributeName = x.SpecificationAttributeName;
                        item.SpecificationAttributeOptionName = x.SpecificationAttributeOptionName;

                        return item;
                    }).ToList();

                    this.NotFilteredItems = notFilteredOptions.ToList().Select(x =>
                    {
                        var item = new SpecificationFilterItem();
                        item.SpecificationAttributeName = x.SpecificationAttributeName;
                        item.SpecificationAttributeOptionName = x.SpecificationAttributeOptionName;

                        //filter URL
                        var alreadyFilteredOptionIds = GetAlreadyFilteredSpecOptionIds(webHelper);
                        if (!alreadyFilteredOptionIds.Contains(x.SpecificationAttributeOptionId))
                            alreadyFilteredOptionIds.Add(x.SpecificationAttributeOptionId);
                        string newQueryParam = GenerateFilteredSpecQueryParam(alreadyFilteredOptionIds);
                        string filterUrl = webHelper.ModifyQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM + "=" + newQueryParam, null);
                        filterUrl = ExcludeQueryStringParams(filterUrl, webHelper);
                        item.FilterUrl = filterUrl;

                        return item;
                    }).ToList();

                    //remove filter URL
                    string removeFilterUrl = webHelper.RemoveQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM);
                    removeFilterUrl = ExcludeQueryStringParams(removeFilterUrl, webHelper);
                    this.RemoveFilterUrl = removeFilterUrl;
                }
                else
                {
                    this.Enabled = false;
                }
            }
Ejemplo n.º 36
0
            public virtual void LoadSpecsFilters(Category category, 
                ISpecificationAttributeService specificationAttributeService, IWebHelper webHelper, 
                IWorkContext workContext)
            {
                if (category == null)
                    throw new ArgumentNullException("category");

                var alreadyFilteredOptions = GetAlreadyFilteredSpecs(specificationAttributeService, webHelper, workContext);
                var notFilteredOptions = GetNotFilteredSpecs(category.Id,
                    specificationAttributeService, webHelper, workContext);

                if (alreadyFilteredOptions.Count > 0 || notFilteredOptions.Count > 0)
                {
                    this.Enabled = true;

                    this.AlreadyFilteredItems = alreadyFilteredOptions.ToList().Select(x =>
                    {
                        var item = new SpecificationFilterItem();
                        item.SpecificationAttributeName = x.SpecificationAttributeName;
                        item.SpecificationAttributeOptionName = x.SpecificationAttributeOptionName;

                        return item;
                    }).ToList();

                    this.NotFilteredItems = notFilteredOptions.ToList().Select(x =>
                    {
                        var item = new SpecificationFilterItem();
                        item.SpecificationAttributeName = x.SpecificationAttributeName;
                        item.SpecificationAttributeOptionName = x.SpecificationAttributeOptionName;

                        //filter URL
                        var alreadyFilteredOptionIds = GetAlreadyFilteredSpecOptionIds(webHelper);
                        if (!alreadyFilteredOptionIds.Contains(x.SpecificationAttributeOptionId))
                            alreadyFilteredOptionIds.Add(x.SpecificationAttributeOptionId);
                        string newQueryParam = GenerateFilteredSpecQueryParam(alreadyFilteredOptionIds);
                        string filterUrl = webHelper.ModifyQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM + "=" + newQueryParam, null);
                        filterUrl = ExcludeQueryStringParams(filterUrl, webHelper);
                        item.FilterUrl = filterUrl;

                        return item;
                    }).ToList();

                    //remove filter URL
                    string removeFilterUrl = webHelper.RemoveQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM);
                    removeFilterUrl = ExcludeQueryStringParams(removeFilterUrl, webHelper);
                    this.RemoveFilterUrl = removeFilterUrl;
                }
                else
                {
                    this.Enabled = false;
                }
            }
Ejemplo n.º 37
0
            public virtual void LoadPriceRangeFilters(string priceRangeStr, IWebHelper webHelper, IPriceFormatter priceFormatter)
            {
                var priceRangeList = GetPriceRangeList(priceRangeStr);

                if (priceRangeList.Any())
                {
                    this.Enabled = true;

                    var selectedPriceRange = GetSelectedPriceRange(webHelper, priceRangeStr);

                    this.Items = priceRangeList.ToList().Select(x =>
                    {
                        //from&to
                        var item = new PriceRangeFilterItem();
                        if (x.From.HasValue)
                        {
                            item.From = priceFormatter.FormatPrice(x.From.Value, true, false);
                        }
                        if (x.To.HasValue)
                        {
                            item.To = priceFormatter.FormatPrice(x.To.Value, true, false);
                        }
                        string fromQuery = string.Empty;
                        if (x.From.HasValue)
                        {
                            fromQuery = x.From.Value.ToString(new CultureInfo("en-US"));
                        }
                        string toQuery = string.Empty;
                        if (x.To.HasValue)
                        {
                            toQuery = x.To.Value.ToString(new CultureInfo("en-US"));
                        }

                        //is selected?
                        if (selectedPriceRange != null &&
                            selectedPriceRange.From == x.From &&
                            selectedPriceRange.To == x.To)
                        {
                            item.Selected = true;
                        }

                        //filter URL
                        string url     = webHelper.ModifyQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM, $"{fromQuery}-{toQuery}");
                        url            = ExcludeQueryStringParams(url, webHelper);
                        item.FilterUrl = url;


                        return(item);
                    }).ToList();

                    if (selectedPriceRange != null)
                    {
                        //remove filter URL
                        string url = webHelper.ModifyQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM, null);
                        url = ExcludeQueryStringParams(url, webHelper);
                        this.RemoveFilterUrl = url;
                    }
                }
                else
                {
                    this.Enabled = false;
                }
            }
Ejemplo n.º 38
0
            /// <summary>
            /// Prepare model
            /// </summary>
            /// <param name="alreadyFilteredSpecOptionIds">IDs of already filtered specification options</param>
            /// <param name="filterableSpecificationAttributeOptionIds">IDs of filterable specification options</param>
            /// <param name="specificationAttributeService"></param>
            /// <param name="webHelper">Web helper</param>
            /// <param name="workContext">Work context</param>
            /// <param name="cacheManager">Cache manager</param>
            public virtual void PrepareSpecsFilters(IList<int> alreadyFilteredSpecOptionIds,
                int[] filterableSpecificationAttributeOptionIds,
                ISpecificationAttributeService specificationAttributeService, 
                IWebHelper webHelper, IWorkContext workContext, ICacheManager cacheManager)
            {
                Enabled = false;
                var optionIds = filterableSpecificationAttributeOptionIds != null
                    ? string.Join(",", filterableSpecificationAttributeOptionIds) : string.Empty;
                var cacheKey = string.Format(ModelCacheEventConsumer.SPECS_FILTER_MODEL_KEY, optionIds, workContext.WorkingLanguage.Id);

                var allOptions = specificationAttributeService.GetSpecificationAttributeOptionsByIds(filterableSpecificationAttributeOptionIds);
                var allFilters = cacheManager.Get(cacheKey, () => allOptions.Select(sao =>
                    new SpecificationAttributeOptionFilter
                    {
                        SpecificationAttributeId = sao.SpecificationAttribute.Id,
                        SpecificationAttributeName = sao.SpecificationAttribute.GetLocalized(x => x.Name, workContext.WorkingLanguage.Id),
                        SpecificationAttributeDisplayOrder = sao.SpecificationAttribute.DisplayOrder,
                        SpecificationAttributeOptionId = sao.Id,
                        SpecificationAttributeOptionName = sao.GetLocalized(x => x.Name, workContext.WorkingLanguage.Id),
                        SpecificationAttributeOptionColorRgb = sao.ColorSquaresRgb,
                        SpecificationAttributeOptionDisplayOrder = sao.DisplayOrder
                    }).ToList());

                if (!allFilters.Any())
                    return;

                //sort loaded options
                allFilters = allFilters.OrderBy(saof => saof.SpecificationAttributeDisplayOrder)
                    .ThenBy(saof => saof.SpecificationAttributeName)
                    .ThenBy(saof => saof.SpecificationAttributeOptionDisplayOrder)
                    .ThenBy(saof => saof.SpecificationAttributeOptionName).ToList();

                //prepare the model properties
                Enabled = true;
                var removeFilterUrl = webHelper.RemoveQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM);
                RemoveFilterUrl = ExcludeQueryStringParams(removeFilterUrl, webHelper);

                //get already filtered specification options
                var alreadyFilteredOptions = allFilters.Where(x => alreadyFilteredSpecOptionIds.Contains(x.SpecificationAttributeOptionId));
                AlreadyFilteredItems = alreadyFilteredOptions.Select(x =>
                    new SpecificationFilterItem
                    {
                        SpecificationAttributeName = x.SpecificationAttributeName,
                        SpecificationAttributeOptionName = x.SpecificationAttributeOptionName,
                        SpecificationAttributeOptionColorRgb = x.SpecificationAttributeOptionColorRgb
                    }).ToList();

                //get not filtered specification options
                NotFilteredItems = allFilters.Except(alreadyFilteredOptions).Select(x =>
                {
                    //filter URL
                    var alreadyFiltered = alreadyFilteredSpecOptionIds.Concat(new List<int> { x.SpecificationAttributeOptionId });
                    var queryString = string.Format("{0}={1}", QUERYSTRINGPARAM, GenerateFilteredSpecQueryParam(alreadyFiltered.ToList()));
                    var filterUrl = webHelper.ModifyQueryString(webHelper.GetThisPageUrl(true), queryString, null);

                    return new SpecificationFilterItem()
                    {
                        SpecificationAttributeName = x.SpecificationAttributeName,
                        SpecificationAttributeOptionName = x.SpecificationAttributeOptionName,
                        SpecificationAttributeOptionColorRgb = x.SpecificationAttributeOptionColorRgb,
                        FilterUrl = ExcludeQueryStringParams(filterUrl, webHelper)
                    };
                }).ToList();
            }
Ejemplo n.º 39
0
        protected virtual void PrepareAffiliateModel(AffiliateModel model, Affiliate affiliate, bool excludeProperties,
                                                     bool prepareEntireAddressModel = true)
        {
            if (model == null)
            {
                throw new ArgumentNullException("model");
            }

            if (affiliate != null)
            {
                model.Id  = affiliate.Id;
                model.Url = _webHelper.ModifyQueryString(_webHelper.GetStoreLocation(false), "affiliateid=" + affiliate.Id, null);
                if (!excludeProperties)
                {
                    model.AdminComment = affiliate.AdminComment;
                    model.Active       = affiliate.Active;
                    model.Address      = affiliate.Address.ToModel();
                }
            }

            if (prepareEntireAddressModel)
            {
                model.Address.FirstNameEnabled      = true;
                model.Address.FirstNameRequired     = true;
                model.Address.LastNameEnabled       = true;
                model.Address.LastNameRequired      = true;
                model.Address.EmailEnabled          = true;
                model.Address.EmailRequired         = true;
                model.Address.CompanyEnabled        = true;
                model.Address.CountryEnabled        = true;
                model.Address.StateProvinceEnabled  = true;
                model.Address.CityEnabled           = true;
                model.Address.CityRequired          = true;
                model.Address.StreetAddressEnabled  = true;
                model.Address.StreetAddressRequired = true;
                model.Address.StreetAddress2Enabled = true;
                model.Address.ZipPostalCodeEnabled  = true;
                model.Address.ZipPostalCodeRequired = true;
                model.Address.PhoneEnabled          = true;
                model.Address.PhoneRequired         = true;
                model.Address.FaxEnabled            = true;

                //address
                model.Address.AvailableCountries.Add(new SelectListItem {
                    Text = _localizationService.GetResource("Admin.Address.SelectCountry"), Value = "0"
                });
                foreach (var c in _countryService.GetAllCountries(true))
                {
                    model.Address.AvailableCountries.Add(new SelectListItem {
                        Text = c.Name, Value = c.Id.ToString(), Selected = (affiliate != null && c.Id == affiliate.Address.CountryId)
                    });
                }

                var states = model.Address.CountryId.HasValue ? _stateProvinceService.GetStateProvincesByCountryId(model.Address.CountryId.Value, true).ToList() : new List <StateProvince>();
                if (states.Count > 0)
                {
                    foreach (var s in states)
                    {
                        model.Address.AvailableStates.Add(new SelectListItem {
                            Text = s.Name, Value = s.Id.ToString(), Selected = (affiliate != null && s.Id == affiliate.Address.StateProvinceId)
                        });
                    }
                }
                else
                {
                    model.Address.AvailableStates.Add(new SelectListItem {
                        Text = _localizationService.GetResource("Admin.Address.OtherNonUS"), Value = "0"
                    });
                }
            }
        }
            public virtual void LoadPriceRangeFilters(string priceRangeStr, IWebHelper webHelper, IPriceFormatter priceFormatter)
            {
                var priceRangeList = GetPriceRangeList(priceRangeStr);
                if (priceRangeList.Count > 0)
                {
                    this.Enabled = true;

                    var selectedPriceRange = GetSelectedPriceRange(webHelper, priceRangeStr);

                    this.Items = priceRangeList.ToList().Select(x =>
                    {
                        //from&to
                        var item = new PriceRangeFilterItem();
                        if (x.From.HasValue)
                            item.From = priceFormatter.FormatPrice(x.From.Value, true, false);
                        if (x.To.HasValue)
                            item.To = priceFormatter.FormatPrice(x.To.Value, true, false);
                        string fromQuery = string.Empty;
                        if (x.From.HasValue)
                            fromQuery = x.From.Value.ToString(new CultureInfo("en-US"));
                        string toQuery = string.Empty;
                        if (x.To.HasValue)
                            toQuery = x.To.Value.ToString(new CultureInfo("en-US"));

                        //is selected?
                        if (selectedPriceRange != null
                            && selectedPriceRange.From == x.From
                            && selectedPriceRange.To == x.To)
                            item.Selected = true;

                        //filter URL
                        string url = webHelper.ModifyQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM + "=" + fromQuery + "-" + toQuery, null);
                        url = ExcludeQueryStringParams(url, webHelper);
                        item.FilterUrl = url;

                        return item;
                    }).ToList();

                    if (selectedPriceRange != null)
                    {
                        //remove filter URL
                        string url = webHelper.RemoveQueryString(webHelper.GetThisPageUrl(true), QUERYSTRINGPARAM);
                        url = ExcludeQueryStringParams(url, webHelper);
                        this.RemoveFilterUrl = url;
                    }
                }
                else
                {
                    this.Enabled = false;
                }
            }