public virtual async Task <IActionResult> ListRss(string languageId) { var feed = new RssFeed( string.Format("{0}: News", _storeContext.CurrentStore.GetLocalized(x => x.Name, _workContext.WorkingLanguage.Id)), "News", new Uri(_webHelper.GetStoreLocation()), DateTime.UtcNow); if (!_newsSettings.Enabled) { return(new RssActionResult(feed, _webHelper.GetThisPageUrl(false))); } var items = new List <RssItem>(); var newsItems = await _newsService.GetAllNews(_storeContext.CurrentStore.Id); foreach (var n in newsItems) { string newsUrl = Url.RouteUrl("NewsItem", new { SeName = n.GetSeName(_workContext.WorkingLanguage.Id) }, _webHelper.IsCurrentConnectionSecured() ? "https" : "http"); items.Add(new RssItem(n.Title, n.Short, new Uri(newsUrl), String.Format("urn:store:{0}:news:blog:{1}", _storeContext.CurrentStore.Id, n.Id), n.CreatedOnUtc)); } feed.Items = items; return(new RssActionResult(feed, _webHelper.GetThisPageUrl(false))); }
public virtual async Task <IActionResult> ListRss(string languageId) { var feed = new RssFeed( string.Format("{0}: Blog", _storeContext.CurrentStore.GetLocalized(x => x.Name, _workContext.WorkingLanguage.Id)), "Blog", new Uri(_webHelper.GetStoreLocation()), DateTime.UtcNow); if (!_blogSettings.Enabled) { return(new RssActionResult(feed, _webHelper.GetThisPageUrl(false))); } var items = new List <RssItem>(); var blogPosts = await _blogService.GetAllBlogPosts(_storeContext.CurrentStore.Id); foreach (var blogPost in blogPosts) { string blogPostUrl = Url.RouteUrl("BlogPost", new { SeName = blogPost.GetSeName(_workContext.WorkingLanguage.Id) }, _webHelper.IsCurrentConnectionSecured() ? "https" : "http"); items.Add(new RssItem(blogPost.Title, blogPost.Body, new Uri(blogPostUrl), String.Format("urn:store:{0}:blog:post:{1}", _storeContext.CurrentStore.Id, blogPost.Id), blogPost.CreatedOnUtc)); } feed.Items = items; return(new RssActionResult(feed, _webHelper.GetThisPageUrl(false))); }
public virtual IActionResult ListRss(int languageId) { var feed = new RssFeed( $"{_localizationService.GetLocalized(_storeContext.CurrentStore, x => x.Name)}: News", "News", new Uri(_webHelper.GetStoreLocation()), DateTime.UtcNow); if (!_newsSettings.Enabled) { return(new RssActionResult(feed, _webHelper.GetThisPageUrl(false))); } var items = new List <RssItem>(); var newsItems = _newsService.GetAllNews(languageId, _storeContext.CurrentStore.Id); foreach (var n in newsItems) { var newsUrl = Url.RouteUrl("NewsItem", new { SeName = _urlRecordService.GetSeName(n, n.LanguageId, ensureTwoPublishedLanguages: false) }, _webHelper.CurrentRequestProtocol); items.Add(new RssItem(n.Title, n.Short, new Uri(newsUrl), $"urn:store:{_storeContext.CurrentStore.Id}:news:blog:{n.Id}", n.CreatedOnUtc)); } feed.Items = items; return(new RssActionResult(feed, _webHelper.GetThisPageUrl(false))); }
/// <summary> /// Called before the action executes, after model binding is complete /// </summary> /// <param name="context">A context for action filters</param> public void OnActionExecuting(ActionExecutingContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.HttpContext.Request == null) { return; } //only in GET requests if (!context.HttpContext.Request.Method.Equals(WebRequestMethods.Http.Get, StringComparison.InvariantCultureIgnoreCase)) { return; } if (!DataSettingsManager.DatabaseIsInstalled) { return; } //check whether we store last visited page URL if (!_customerSettings.StoreLastVisitedPage) { return; } // changed //get current page //var pageUrl = _uriHelper.ToBaseRelativePath(_uriHelper.GetBaseUri(), _uriHelper.GetAbsoluteUri()); //_webHelper.GetThisPageUrl(true); var pageUrl = _webHelper.GetThisPageUrl(true); if (string.IsNullOrEmpty(pageUrl)) { return; } //get previous last page var previousPageUrl = _genericAttributeService.GetAttribute <string>(_workContext.CurrentCustomer, NopCustomerDefaults.LastVisitedPageAttribute); //save new one if don't match if (!pageUrl.Equals(previousPageUrl, StringComparison.InvariantCultureIgnoreCase)) { _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, NopCustomerDefaults.LastVisitedPageAttribute, pageUrl); } }
public async Task Invoke(HttpContext context, IWebHelper webHelper) { if (!DataSettingsManager.DatabaseIsInstalled) { var installUrl = $"{webHelper.GetLocation()}{HttpDefaults.InstallPath}"; if (!webHelper.GetThisPageUrl(false) .StartsWith(installUrl, StringComparison.InvariantCultureIgnoreCase)) { //redirect context.Response.Redirect(installUrl); return; } } await _next(context); }
public virtual IActionResult Search(SearchModel model, CatalogPagingFilteringModel command) { //'Continue shopping' URL _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, NopCustomerDefaults.LastContinueShoppingPageAttribute, _webHelper.GetThisPageUrl(false), _storeContext.CurrentStore.Id); if (model == null) { model = new SearchModel(); } model = _catalogModelFactory.PrepareSearchModel(model, command); return(View(model)); }
/// <summary> /// Invoke middleware actions /// </summary> /// <param name="context">HTTP context</param> /// <param name="webHelper">Web helper</param> /// <returns>Task</returns> public async Task InvokeAsync(HttpContext context, IWebHelper webHelper) { //whether database is installed if (await DataSettingsManager.IsDatabaseInstalledAsync()) { //keep alive page requested (we ignore it to prevent creating a guest customer records) var keepAliveUrl = $"{webHelper.GetStoreLocation()}{NopCommonDefaults.KeepAlivePath}"; if ((webHelper.GetThisPageUrl(false)).StartsWith(keepAliveUrl, StringComparison.InvariantCultureIgnoreCase)) { return; } } //or call the next middleware in the request pipeline await _next(context); }
/// <summary> /// Invoke middleware actions /// </summary> /// <param name="context">HTTP context</param> /// <param name="webHelper">Web helper</param> /// <returns>Task</returns> public async Task Invoke(HttpContext context, IWebHelper webHelper) { //whether database is installed if (!DataSettingsManager.DatabaseIsInstalled) { var installUrl = $"{webHelper.GetStoreLocation()}{NopHttpDefaults.InstallPath}"; if (!webHelper.GetThisPageUrl(false).StartsWith(installUrl, StringComparison.InvariantCultureIgnoreCase)) { //redirect context.Response.Redirect(installUrl); return; } } //or call the next middleware in the request pipeline await _next(context); }
/// <summary> /// Invoke middleware actions /// </summary> /// <param name="context">HTTP context</param> /// <param name="webHelper">Web helper</param> /// <returns>Task</returns> public async Task Invoke(Microsoft.AspNetCore.Http.HttpContext context, IWebHelper webHelper) { //whether database is installed if (!DataSettingsHelper.DatabaseIsInstalled()) { var installUrl = string.Format("{0}install", webHelper.GetStoreLocation()); if (!webHelper.GetThisPageUrl(false).StartsWith(installUrl, StringComparison.OrdinalIgnoreCase)) { //redirect context.Response.Redirect(installUrl); return; } } //or call the next middleware in the request pipeline await _next(context); }
/// <summary> /// Invoke middleware actions /// </summary> /// <param name="context">HTTP context</param> /// <param name="webHelper">Web helper</param> /// <returns>Task</returns> public async Task Invoke(Microsoft.AspNetCore.Http.HttpContext context, IWebHelper webHelper) { //判断数据库是否已安装和配置,如果没有,那么跳转至Install页面中 if (!MainDataSettingsHelper.DatabaseIsInstalled()) { var installUrl = $"{webHelper.GetTenantLocation()}install"; if (!webHelper.GetThisPageUrl(false).StartsWith(installUrl, StringComparison.InvariantCultureIgnoreCase)) { //重定向 context.Response.Redirect(installUrl); return; } } //如果已安装则进入下一个中间件 await _next(context); }
public async Task Invoke(HttpContext context, IWebHelper webHelper) { //TODO test. ensure that no guest record is created //判断数据库是否已经完成安装与配置 if (MainDataSettingsHelper.DatabaseIsInstalled()) { //未完成则继续等待 var keepAliveUrl = $"{webHelper.GetTenantLocation()}keepalive/index"; if (webHelper.GetThisPageUrl(false).StartsWith(keepAliveUrl, StringComparison.InvariantCultureIgnoreCase)) { return; } } //进入下一个中间件 await _next(context); }
/// <summary> /// Invoke middleware actions /// </summary> /// <param name="context">HTTP context</param> /// <param name="webHelper">Web helper</param> /// <returns>Task</returns> public async Task Invoke(HttpContext context, IWebHelper webHelper) { //TODO test. ensure that no guest record is created //whether database is installed if (DataSettingsHelper.DatabaseIsInstalled()) { //keep alive page requested (we ignore it to prevent creating a guest customer records) var keepAliveUrl = $"{webHelper.GetStoreLocation()}keepalive/index"; if (webHelper.GetThisPageUrl(false).StartsWith(keepAliveUrl, StringComparison.InvariantCultureIgnoreCase)) { return; } } //or call the next middleware in the request pipeline await _next(context); }
public ActionResult OrderReturn(FormCollection form) { var answerKey = _webHelper.QueryString <string>("answer"); var ordenId = _webHelper.QueryString <string>("ordenId"); int id; Int32.TryParse(ordenId, out id); String b = _webHelper.GetThisPageUrl(true); var processor = _paymentService.LoadPaymentMethodBySystemName("Payments.TodoPago") as TodoPagoPaymentProcessor; if (processor == null || !processor.IsPaymentMethodActive(_paymentSettings) || !processor.PluginDescriptor.Installed) { throw new NopException("TodoPago module cannot be loaded"); } var order = _orderService.GetOrderById(id); if (order == null || order.Deleted) { //No order found with the specified id return(RedirectToAction("Index", "Home", new { area = "" })); } if (order != null) { Dictionary <string, object> responseGaa = processor.TodoPagoSecondStep(answerKey, order); int statusCode = (int)responseGaa[TODOPAGO_STATUS_CODE]; if (statusCode == -1) { return(RedirectToRoute("CheckoutCompleted", new { orderId = order.Id })); } else { _httpContext.Session["OrderPaymentInfo"] = (string)responseGaa[TODOPAGO_STATUS_MESSAGE]; return(RedirectToAction("OrderStatusTP", new { id = order.Id })); } } return(RedirectToAction("Index", "Home", new { area = "" })); }
/// <summary> /// Inserts a log item /// </summary> /// <param name="logLevel">Log level</param> /// <param name="shortMessage">The short message</param> /// <param name="fullMessage">The full message</param> /// <param name="customer">The customer to associate log record with</param> /// <returns>A log item</returns> public virtual async Task <Log> InsertLog(LogLevel logLevel, string shortMessage, string fullMessage = "", Customer customer = null) { var log = new Log { LogLevelId = (int)logLevel, ShortMessage = shortMessage, FullMessage = fullMessage, IpAddress = _webHelper.GetCurrentIpAddress(), CustomerId = customer != null ? customer.Id : "", PageUrl = _webHelper.GetThisPageUrl(true), ReferrerUrl = _webHelper.GetUrlReferrer(), CreatedOnUtc = DateTime.UtcNow }; await _logRepository.InsertAsync(log); return(log); }
/// <summary> /// Inserts a log item /// </summary> /// <param name="logLevel">Log level</param> /// <param name="shortMessage">The short message</param> /// <param name="fullMessage">The full message</param> /// <param name="customer">The customer to associate log record with</param> /// <returns>A log item</returns> public virtual Log InsertLog(LogLevel logLevel, string shortMessage, string fullMessage = "", Customer customer = null) { var log = new Log() { LogLevel = logLevel, ShortMessage = shortMessage, FullMessage = fullMessage, IpAddress = _webHelper.GetCurrentIpAddress(), Customer = customer, PageUrl = _webHelper.GetThisPageUrl(true), ReferrerUrl = _webHelper.GetUrlReferrer(), CreatedOnUtc = DateTime.UtcNow }; _logRepository.Insert(log); return(log); }
public async Task <Log> InsertLogAsync(LogLevel logLevel, string shortMessage, string fullMessage = "", User user = null) { var log = new Log { LogLevel = logLevel, ShortMessage = shortMessage, FullMessage = fullMessage, IpAddress = _webHelper.GetCurrentIpAddress(), User = user, PageUrl = _webHelper.GetThisPageUrl(true), ReferrerUrl = _webHelper.GetUrlReferrer(), CreatedOnUtc = DateTime.UtcNow }; await _logRepository.InsertAsync(log); return(log); }
private void LogException(Exception ex) { var customer = _workContext.CurrentCustomer; Log _error = new Log() { LogLevel = LogLevel.Error, ShortMessage = ex.Message, FullMessage = ex.StackTrace, IpAddress = _webHelper.GetCurrentIpAddress(), Customer = customer, PageUrl = _webHelper.GetThisPageUrl(true), ReferrerUrl = _webHelper.GetUrlReferrer(), CreatedOnUtc = DateTime.UtcNow }; _logRepository.Insert(_error); _unitOfWork.Commit(); }
/// <summary> /// Post process payment (used by payment gateways that require redirecting to a third-party URL) /// </summary> /// <param name="postProcessPaymentRequest">Payment info required for an order processing</param> public void PostProcessPayment(PostProcessPaymentRequest postProcessPaymentRequest) { var order = postProcessPaymentRequest.Order; var orderUniqueId = postProcessPaymentRequest.Order.OrderGuid.ToString(); var roundedOrderTotal = Math.Round(order.OrderTotal, 2); var roundedOrderTotalPesewas = Convert.ToInt32(roundedOrderTotal * 100); _genericAttributeService.SaveAttribute(postProcessPaymentRequest.Order, PaystackHelper.OrderTotalSentToPaystack, roundedOrderTotal); var secretKey = _paystackStandardPaymentSettings.UseSandbox ? _paystackStandardPaymentSettings.TestSecretToken : _paystackStandardPaymentSettings.LiveSecretToken; var payStackApi = new PayStackApi(secretKey); var request = new TransactionInitializeRequest { Email = order.Customer.Email, Reference = orderUniqueId, AmountInKobo = roundedOrderTotalPesewas, Currency = "GHS", }; AddOrderInfoMetaData(request, postProcessPaymentRequest); if (_paystackStandardPaymentSettings.PassProductNamesAndTotals) { AddOrderItemsMetaData(request, postProcessPaymentRequest); } var response = payStackApi.Transactions.Initialize(request); if (response.Status) { _httpContextAccessor.HttpContext.Response.Redirect(response.Data.AuthorizationUrl); } else { var thisPage = _webHelper.GetThisPageUrl(true); _httpContextAccessor.HttpContext.Response.Redirect(thisPage); } }
/// <summary> /// Invoke middleware actions /// </summary> /// <param name="context">HTTP context</param> /// <param name="webHelper">Web helper</param> /// <param name="workContext">Work context</param> /// <returns>Task</returns> public Task Invoke(HttpContext context, IWebHelper webHelper) { //set culture if (webHelper.IsStaticResource()) { _next(context); } var adminAreaUrl = $"{webHelper.GetStoreLocation()}admin"; if (webHelper.GetThisPageUrl(false).StartsWith(adminAreaUrl, StringComparison.InvariantCultureIgnoreCase)) { var culture = new CultureInfo("en-US"); CultureInfo.CurrentCulture = culture; CultureInfo.CurrentUICulture = culture; } //call the next middleware in the request pipeline return(_next(context)); }
/// <summary> /// Inserts a log item /// </summary> /// <param name="logLevel">Log level</param> /// <param name="shortMessage">The short message</param> /// <param name="fullMessage">The full message</param> /// <param name="user">The user.</param> /// <param name="userId">The user id.</param> /// <returns> /// A log item /// </returns> public Log InsertLog(LogLevel logLevel, string shortMessage, string fullMessage = "", string user = "", int?userId = null) { var log = new Log { LogLevel = logLevel, ShortMessage = shortMessage, FullMessage = fullMessage, IpAddress = webHelper.GetCurrentIpAddress(), User = user, UserId = userId, PageUrl = webHelper.GetThisPageUrl(true), ReferrerUrl = webHelper.GetUrlReferrer(), CreatedOnUtc = DateTime.UtcNow }; repository.Add(log); unitOfWork.Commit(); return(log); }
/// <summary> /// Called before the action executes, after model binding is complete /// </summary> /// <param name="context">A context for action filters</param> public void OnActionExecuting(ActionExecutingContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.HttpContext.Request == null) { return; } //only in GET requests if (!context.HttpContext.Request.Method.Equals(WebRequestMethods.Http.Get, StringComparison.InvariantCultureIgnoreCase)) { return; } //check whether we store last visited page URL if (!_customerSettings.StoreLastVisitedPage) { return; } //get current page var pageUrl = _webHelper.GetThisPageUrl(true); if (string.IsNullOrEmpty(pageUrl)) { return; } //get previous last page var previousPageUrl = _workContext.CurrentCustomer.GetAttribute <string>(SystemCustomerAttributeNames.LastVisitedPage); //save new one if don't match if (!pageUrl.Equals(previousPageUrl, StringComparison.InvariantCultureIgnoreCase)) { _genericAttributeService.SaveAttribute(_workContext.CurrentCustomer, SystemCustomerAttributeNames.LastVisitedPage, pageUrl); } }
public void Log(LogLevel logLevel, Exception exception, string format, params object[] args) { IWebHelper _webHelper = EngineContext.Current.Resolve <IWebHelper>(); var log = new ExceptionLogInfo() { Source = exception.Source, InnerException = exception.InnerException == null ? string.Empty : exception.InnerException.Message, EventStackTrace = exception == null ? string.Empty : exception.StackTrace, EventType = exception == null ? string.Empty : exception.GetType().FullName, EventDetail = exception == null ? string.Empty : exception.Message, EventMessage = args == null || args.Length == 0 ? format : string.Format(format, args), HostName = _webHelper.GetCurrentHostName(), LogLevelName = logLevel.ToString(), IpAddress = _webHelper.GetCurrentIpAddress(), PageUrl = _webHelper.GetThisPageUrl(), ReferrerUrl = _webHelper.GetUrlReferrer(), }; _logRepository.Insert(log); }
/// <summary> /// Inserts a log item /// </summary> /// <param name="logLevel">Log level</param> /// <param name="shortMessage">The short message</param> /// <param name="fullMessage">The full message</param> /// <param name="customer">The customer to associate log record with</param> /// <returns>A log item</returns> public virtual Log InsertLog(LogLevel logLevel, string shortMessage, string fullMessage = "") { //check ignore word/phrase list? //if (IgnoreLog(shortMessage) || IgnoreLog(fullMessage)) // return null; var log = new Log { LogLevel = logLevel, ShortMessage = shortMessage, FullMessage = fullMessage, IpAddress = _webHelper.GetCurrentIpAddress(), PageUrl = _webHelper.GetThisPageUrl(true), ReferrerUrl = _webHelper.GetUrlReferrer(), CreatedOnUtc = DateTime.UtcNow }; _logRepository.Insert(log); return(log); }
public Log InsertLog(LogLevel logLevel, string shortMessage, string fullMessage = "", Customer customer = null) { if (IgnoreLog(shortMessage) || IgnoreLog(fullMessage)) { return(null); } var log = new Log() { LogLevel = logLevel, ShortMessage = shortMessage, FullMessage = fullMessage, IpAddress = _webHelper.GetCurrentIpAddress(), Customer = customer, PageUrl = _webHelper.GetThisPageUrl(true), ReferrerUrl = _webHelper.GetUrlReferrer(), CreatedOnUtc = DateTime.Now }; _logRepostiroy.Insert(log); return(log); }
/// <summary> /// 插入一条日志 /// </summary> /// <param name="logLevel">日志等级</param> /// <param name="shortMessage">简短消息</param> /// <param name="fullMessage">完整消息</param> /// <param name="customer">触发日志记录的用户</param> /// <returns>日志</returns> public virtual Log InsertLog(LogLevel logLevel, string shortMessage, string fullMessage = "", Customer customer = null) { //检查该日志消息是否存在忽略列表中 if (IgnoreLog(shortMessage) || IgnoreLog(fullMessage)) { return(null); } var log = new Log { LogLevel = logLevel, ShortMessage = shortMessage, FullMessage = fullMessage, IpAddress = _webHelper.GetCurrentIpAddress(), Customer = customer, PageUrl = _webHelper.GetThisPageUrl(true), ReferrerUrl = _webHelper.GetUrlReferrer() }; _logRepository.Insert(log); return(log); }
/// <summary> /// Inserts a log item /// </summary> /// <param name="logLevel">Log level</param> /// <param name="shortMessage">The short message</param> /// <param name="fullMessage">The full message</param> /// <param name="customer">The customer to associate log record with</param> /// <returns>A log item</returns> public virtual Log InsertLog(LogLevel logLevel, string shortMessage, string fullMessage = "", Customer customer = null) { //check ignore word/phrase list? if (IgnoreLog(shortMessage) && IgnoreLog(fullMessage)) { return(null); } var log = new Log { LogLevel = logLevel, ShortMessage = shortMessage, FullMessage = fullMessage, IpAddress = _webHelper.GetCurrentIpAddress(), PageUrl = _webHelper.GetThisPageUrl(true), ReferrerUrl = _webHelper.GetUrlReferrer(), CreatedOn = DateTime.Now }; _logRepository.Insert(log); return(log); }
/// <summary> /// Inserts a log item /// </summary> /// <param name="logLevel">Log level</param> /// <param name="shortMessage">The short message</param> /// <param name="fullMessage">The full message</param> /// <param name="property">The property to associate log record with</param> /// <returns>A log item</returns> public virtual Log InsertLog(LogLevel logLevel, string shortMessage, string fullMessage = "", AccountUser property = null) { //check ignore word/phrase list? if (IgnoreLog(shortMessage) || IgnoreLog(fullMessage)) { return(null); } var log = new Log { LogLevel = logLevel, ShortMessage = shortMessage, FullMessage = fullMessage, AccountUser = property, IpAddress = _webHelper.GetCurrentIpAddress(), PageUrl = _webHelper.GetThisPageUrl(true), ReferrerUrl = _webHelper.GetUrlReferrer() }; _logRepository.Insert(log); return(log); }
/// <summary> /// Called early in the filter pipeline to confirm request is authorized /// </summary> /// <param name="context">Authorization filter context</param> /// <returns>A task that on completion indicates the filter has executed</returns> private async Task ValidateHoneypotAsync(AuthorizationFilterContext context) { if (context == null) { throw new ArgumentNullException(nameof(context)); } if (context.HttpContext.Request == null) { return; } if (!await DataSettingsManager.IsDatabaseInstalledAsync()) { return; } //whether honeypot is enabled if (!_securitySettings.HoneypotEnabled) { return; } //try get honeypot input value var inputValue = context.HttpContext.Request.Form[_securitySettings.HoneypotInputName]; //if exists, bot is caught if (!StringValues.IsNullOrEmpty(inputValue)) { //warning admin about it await _logger.WarningAsync("A bot detected. Honeypot."); //and redirect to the original page var page = _webHelper.GetThisPageUrl(true); context.Result = new RedirectResult(page); } }
/// <summary> /// Called early in the filter pipeline to confirm request is authorized /// </summary> /// <param name="filterContext">Authorization filter context</param> public void OnAuthorization(AuthorizationFilterContext filterContext) { if (filterContext == null) { throw new ArgumentNullException(nameof(filterContext)); } if (filterContext.HttpContext.Request == null) { return; } if (!DataSettingsManager.DatabaseIsInstalled) { return; } //whether honeypot is enabled if (!_securitySettings.HoneypotEnabled) { return; } //try get honeypot input value var inputValue = filterContext.HttpContext.Request.Form[_securitySettings.HoneypotInputName]; //if exists, bot is caught if (!StringValues.IsNullOrEmpty(inputValue)) { //warning admin about it _logger.Warning("A bot detected. Honeypot."); //and redirect to the original page filterContext.Result = new RedirectResult(_webHelper.GetThisPageUrl(true)); } }
/// <summary> /// Set working culture /// </summary> /// <param name="webHelper">Web helper</param> /// <param name="workContext">Work context</param> protected void SetWorkingCulture(IWebHelper webHelper, IWorkContext workContext) { if (!DataSettingsManager.DatabaseIsInstalled) { return; } if (webHelper.IsStaticResource()) { return; } var adminAreaUrl = $"{webHelper.GetStoreLocation()}admin"; if (webHelper.GetThisPageUrl(false).StartsWith(adminAreaUrl, StringComparison.InvariantCultureIgnoreCase)) { //we set culture of admin area to 'en-US' because current implementation of Telerik grid doesn't work well in other cultures //e.g., editing decimal value in russian culture // Custom //CommonHelper.SetTelerikCulture(); var culture = new CultureInfo(workContext.WorkingLanguage.LanguageCulture); CultureInfo.CurrentCulture = culture; CultureInfo.CurrentUICulture = culture; //set work context to admin mode workContext.IsAdmin = true; } else { //set working language culture var culture = new CultureInfo(workContext.WorkingLanguage.LanguageCulture); CultureInfo.CurrentCulture = culture; CultureInfo.CurrentUICulture = culture; } }
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; } }
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; } }
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; } }
/// <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(); }
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; } }