public DateTokens( IClock clock, IDateTimeLocalization dateTimeLocalization, IWorkContextAccessor workContextAccessor) { _clock = clock; _dateTimeLocalization = dateTimeLocalization; _workContextAccessor = workContextAccessor; _cultureInfo = new Lazy<CultureInfo>(() => CultureInfo.GetCultureInfo(_workContextAccessor.GetContext().CurrentCulture)); _timeZone = new Lazy<TimeZoneInfo>(() => _workContextAccessor.GetContext().CurrentTimeZone); T = NullLocalizer.Instance; }
public UrlFilter(IWorkContextAccessor wca, IRepository<FilteredRequestRecord> filteredRequestRecords, ICachedUrlProtectorRules cachedUrlProtectorRules, IOrchardServices orchardServices) { _wca = wca; _filteredRequestRecords = filteredRequestRecords; _cachedUrlProtectorRules = cachedUrlProtectorRules; _orchardServices = orchardServices; Logger = NullLogger.Instance; UserAgent = _wca.GetContext().HttpContext.Request.UserAgent; UserHostAddress = _wca.GetContext().HttpContext.Request.UserHostAddress; RequestUrl = _wca.GetContext().HttpContext.Request.Url; }
public MissingSettingsBanner(IOrchardServices orchardServices, IWorkContextAccessor workContextAccessor) { _orchardServices = orchardServices; _workContext = workContextAccessor.GetContext(); T = NullLocalizer.Instance; }
public CampaignController( ICampaignService campaignService, ITShirtCostService tshirtService, IProductService productService, IPromotionService promotionService, IRepository<CurrencyRecord> currencyRepository, IWorkContextAccessor wca, INotifier notifier, IOrchardServices services, ICookieCultureService cookieCultureService, ICountryService countryService) { _currencyRepository = currencyRepository; Services = services; _tshirtService = tshirtService; _productService = productService; _campaignService = campaignService; _promotionService = promotionService; _wca = wca; _notifier = notifier; Logger = NullLogger.Instance; _cookieCultureService = cookieCultureService; //var culture = _wca.GetContext().CurrentCulture.Trim(); _cultureUsed = _wca.GetContext().CurrentCulture.Trim(); //cultureUsed = culture == "en-SG" ? "en-SG" : (culture == "id-ID" ? "id-ID" : "en-MY"); _countryService = countryService; }
public LocalizationBucket(ICultureManager cultureManager, IWorkContextAccessor workContextAccessor) { var currentCultureName = cultureManager.GetCurrentCulture(workContextAccessor.GetContext().HttpContext); var defaultCultureName = cultureManager.GetSiteCulture(); CurrentCulture = cultureManager.GetCultureByName(currentCultureName); DefaultCulture = cultureManager.GetCultureByName(defaultCultureName); IsCurrentCultureDefault = CurrentCulture != null && CurrentCulture.Id == DefaultCulture.Id; }
public AdminCultureSelectorFactory( IWorkContextAccessor workContextAccessor, IShapeFactory shapeFactory, ICultureManager cultureManager) { _cultureManager = cultureManager; _workContext = workContextAccessor.GetContext(); Shape = shapeFactory; }
public InlineShapeFactory(IAuthorizer authorizer, IWorkContextAccessor workContextAccessor, IShapeTableManager shapeTableManager, IThemeManager themeManager) { _authorizer = authorizer; _shapeTableManager = shapeTableManager; _themeManager = themeManager; _workContext = workContextAccessor.GetContext(); }
public AdminCostController(ITShirtCostService costService, IOrchardServices services, IWorkContextAccessor workContextAccessor) { _costService = costService; Services = services; _workContextAccessor = workContextAccessor; culture = _workContextAccessor.GetContext().CurrentCulture.Trim(); cultureSearch = culture == "en-SG" ? "en-SG" : (culture == "id-ID" ? "id-ID" : "en-MY"); }
public PaymentController(IWorkContextAccessor workContextAccessor, IPaymentSettingsService paymentSettingsService, IOrchardServices services) { _workContextAccessor = workContextAccessor; _paymentSettingsService = paymentSettingsService; Services = services; var culture = _workContextAccessor.GetContext().CurrentCulture.Trim(); cultureUsed = culture == "en-SG" ? "en-SG" : (culture == "id-ID" ? "id-ID" : "en-MY"); }
public AdminWizardController(IFontService fontService, IOrchardServices services, IWorkContextAccessor workContextAccessor) { _fontService = fontService; Services = services; _workContextAccessor = workContextAccessor; var culture = _workContextAccessor.GetContext().CurrentCulture.Trim(); cultureUsed = culture == "en-SG" ? "en-SG" : (culture == "id-ID" ? "id-ID" : "en-MY"); }
public FieldTokens( IDateTimeLocalization dateTimeLocalization, IWorkContextAccessor workContextAccessor) { _dateTimeLocalization = dateTimeLocalization; _workContextAccessor = workContextAccessor; _cultureInfo = new Lazy<CultureInfo>(() => CultureInfo.GetCultureInfo(_workContextAccessor.GetContext().CurrentCulture)); T = NullLocalizer.Instance; }
public TinyMceShapeDisplayEvent( ICacheManager cacheManager, IVirtualPathProvider virtualPathProvider, IWorkContextAccessor workContextAccessor, ISignals signals) { _signals = signals; _cacheManager = cacheManager; _virtualPathProvider = virtualPathProvider; _workContext = workContextAccessor.GetContext(); }
public RemoteStorageSettingsPartHandler(IRepository<RemoteStorageSettingsPartRecord> repository, IWorkContextAccessor workContextAccessor) { T = NullLocalizer.Instance; Filters.Add(new ActivatingFilter<RemoteStorageSettingsPart>("Site")); Filters.Add(StorageFilter.For(repository)); Filters.Add(new TemplateFilterForRecord<RemoteStorageSettingsPartRecord>("RemoteStorageSettings", "Parts/MediaFolder.RemoteStorageSettings", "media")); OnInitializing<RemoteStorageSettingsPart>( (context, part) => { part.Record.MediaLocation = workContextAccessor.GetContext().HttpContext.Server.MapPath("~/Media"); }); }
public ShapeTracingFactory( IWorkContextAccessor workContextAccessor, IShapeTableManager shapeTableManager, IThemeManager themeManager, IWebSiteFolder webSiteFolder, IAuthorizer authorizer ) { _workContext = workContextAccessor.GetContext(); _shapeTableManager = shapeTableManager; _themeManager = themeManager; _webSiteFolder = webSiteFolder; _authorizer = authorizer; }
public SnippetElementHarvester( IWorkContextAccessor workContextAccessor, Work<IShapeFactory> shapeFactory, Work<ISiteThemeService> siteThemeService, Work<IShapeTableLocator> shapeTableLocator, Work<IElementFactory> elementFactory) { _shapeFactory = shapeFactory; _siteThemeService = siteThemeService; _shapeTableLocator = shapeTableLocator; _elementFactory = elementFactory; workContextAccessor.GetContext(); }
public CurrentContentHandler(IWorkContextAccessor workContextAccessor) { _workContextAccessor = workContextAccessor; OnGetDisplayShape<TermsPart>((context, part) => { if (context.DisplayType == "Detail") { var workContext = _workContextAccessor.GetContext(); string ContentTermsIds = String.Join(",", part.TermParts.Select(t => t.TermPart.Id).ToArray()); workContext.SetState("ContentTermsIds", ContentTermsIds); } }); OnGetDisplayShape<TermPart>((context, part) => { if (context.DisplayType == "Detail") { var workContext = _workContextAccessor.GetContext(); workContext.SetState("ContentTermsIds", part.Id.ToString()); } }); }
public LinkRewriteService( IWorkContextAccessor wca, IRepository<LinkRewriteSettingsRecord> rewriteRuleRepository, IContentManager contentManager, ICacheManager cacheManager, ISignals signals) { _context = wca.GetContext(); _rewriteRuleRepository = rewriteRuleRepository; _contentManager = contentManager; _cacheManager = cacheManager; _signals = signals; T = NullLocalizer.Instance; }
public DateTokens( IClock clock, IDateTimeFormatProvider dateTimeLocalization, IWorkContextAccessor workContextAccessor, IDateServices dateServices) { _clock = clock; _dateTimeLocalization = dateTimeLocalization; _workContextAccessor = workContextAccessor; _cultureInfo = new Lazy<CultureInfo>(() => CultureInfo.GetCultureInfo(_workContextAccessor.GetContext().CurrentCulture)); _dateServices = dateServices; T = NullLocalizer.Instance; }
public CacheSettingsPartHandler( IRepository<CacheSettingsPartRecord> repository, IWorkContextAccessor workContextAccessor, ICacheService cacheService, RequestContext requestContext) { _workContextAccessor = workContextAccessor; _cacheService = cacheService; _requestContext = requestContext; Filters.Add(new ActivatingFilter<CacheSettingsPart>("Site")); Filters.Add(StorageFilter.For(repository)); // initializing default cache settings values OnInitializing<CacheSettingsPart>((context, part) => { part.DefaultCacheDuration = 300; }); // evict modified routable content when updated OnPublished<IContent>( (context, part) => { // list of cache keys to evict var evict = new List<CacheItem>(); var workContext = _workContextAccessor.GetContext(); Action<IContent> findAndEvict = p => { foreach (var cacheItem in _cacheService.GetCacheItems()) { var urlHelper = new UrlHelper(_requestContext); if (String.Equals(cacheItem.Url, VirtualPathUtility.ToAbsolute("~/" + urlHelper.ItemDisplayUrl(p)), StringComparison.OrdinalIgnoreCase)) { evict.Add(cacheItem); } } }; findAndEvict(part); // search the cache for containers too var commonPart = part.As<CommonPart>(); if (commonPart != null) { if (commonPart.Container != null) { findAndEvict(commonPart.Container); } } // remove all content to evict foreach (var cacheItem in evict) { _cacheService.Evict(cacheItem.CacheKey, workContext.HttpContext); } }); }
public AdminCommonSettingsController( IOrchardServices orchardServices, IRepository<CommonSettingsRecord> commonSettingsRepository, IRepository<CheckoutCampaignRequest> checkoutRequestRepository, ITeeyootMessagingService teeyootMessagingService, IWorkContextAccessor workContextAccessor) { _orchardServices = orchardServices; _commonSettingsRepository = commonSettingsRepository; _checkoutRequestRepository = checkoutRequestRepository; _teeyootMessagingService = teeyootMessagingService; _workContextAccessor = workContextAccessor; var culture = _workContextAccessor.GetContext().CurrentCulture.Trim(); cultureUsed = culture == "en-SG" ? "en-SG" : (culture == "id-ID" ? "id-ID" : "en-MY"); T = NullLocalizer.Instance; Logger = NullLogger.Instance; }
public ThreadPartHandler(IWorkContextAccessor workContextAccessor, IWaveNotificationWrapper waveNotificationWrapper) { _workContextAccessor = workContextAccessor; _waveNotificationWrapper = waveNotificationWrapper; OnPublished<PostPart>((context, postPart) => { if (postPart.IsParentThread()) return; var threadPart = postPart.ThreadPart; var forumPart = threadPart.ForumPart; var workContext = _workContextAccessor.GetContext(); var location = new UrlHelper(workContext.HttpContext.Request.RequestContext).PostView(postPart); _waveNotificationWrapper.NotifyPostCreated(threadPart.Id, forumPart.Id, threadPart.Id, postPart.Id, postPart.RepliedOn.Value, location, postPart.Text); _waveNotificationWrapper.NotifyPostCreated(forumPart.Id, forumPart.Id, threadPart.Id, postPart.Id, postPart.RepliedOn.Value, location, postPart.Text); }); }
public ArtworkController( ISiteService siteService, IOrchardServices orchardServices, IRepository<ArtRecord> artRepository, IShapeFactory shapeFactory, IWorkContextAccessor workContextAccessor) { _siteService = siteService; _orchardServices = orchardServices; _artRepository = artRepository; Shape = shapeFactory; T = NullLocalizer.Instance; Logger = NullLogger.Instance; _workContextAccessor = workContextAccessor; var culture = _workContextAccessor.GetContext().CurrentCulture.Trim(); cultureUsed = culture == "en-SG" ? "en-SG" : (culture == "id-ID" ? "id-ID" : "en-MY"); }
public SnippetElementHarvester( IWorkContextAccessor workContextAccessor, Work<IShapeFactory> shapeFactory, Work<ISiteThemeService> siteThemeService, Work<IShapeTableLocator> shapeTableLocator, Work<IElementFactory> elementFactory, Work<IShapeDisplay> shapeDisplay, Work<ITokenizer> tokenizer, Work<ICurrentThemeShapeBindingResolver> currentThemeShapeBindingResolver) { _shapeFactory = shapeFactory; _siteThemeService = siteThemeService; _shapeTableLocator = shapeTableLocator; _elementFactory = elementFactory; _shapeDisplay = shapeDisplay; _tokenizer = tokenizer; _currentThemeShapeBindingResolver = currentThemeShapeBindingResolver; workContextAccessor.GetContext(); }
public AdminCurrenciesController( ISiteService siteService, IOrchardServices orchardServices, IShapeFactory shapeFactory, IRepository<CurrencyRecord> currencyRepository, IRepository<CountryRecord> countryRepository, IWorkContextAccessor workContextAccessor) { var culture = workContextAccessor.GetContext().CurrentCulture.Trim(); _cultureUsed = culture == "en-SG" ? "en-SG" : (culture == "id-ID" ? "id-ID" : "en-MY"); _siteService = siteService; _orchardServices = orchardServices; Shape = shapeFactory; _currencyRepository = currencyRepository; _countryRepository = countryRepository; _imageFileHelper = new ImageFileHelper("currency_{0}_flag.png", "/Modules/Teeyoot.Module/Content/images", () => Server); }
public NotificationWidgetPartHandler(INotificationsToUserDispatcher notificationDispatcher, IWorkContextAccessor wca, ISiteService siteService) { OnActivated<NotificationWidgetPart>((context, part) => { part.UnreadNotificationsField.Loader(() => { var currentUser = wca.GetContext().CurrentUser; if (currentUser == null) { return Enumerable.Empty<INotification>().ToList(); } var notificationCount = siteService.GetSiteSettings().As<NotificationWidgetSettingsPart>().NotificationCount; var unreadNotifications = notificationDispatcher .GetRecentNotificationsForUser(currentUser, notificationCount, true) .ToList(); return unreadNotifications; }); }); }
public ColourController( ISiteService siteService, IOrchardServices orchardServices, IRepository<ProductColorRecord> productColourRepository, IRepository<SwatchRecord> swatchRecordRepository, IShapeFactory shapeFactory, IWorkContextAccessor workContextAccessor) { _siteService = siteService; _orchardServices = orchardServices; _productColourRepository = productColourRepository; _swatchColourRepository = swatchRecordRepository; Shape = shapeFactory; T = NullLocalizer.Instance; Logger = NullLogger.Instance; _workContextAccessor = workContextAccessor; var culture = _workContextAccessor.GetContext().CurrentCulture.Trim(); cultureUsed = culture == "en-SG" ? "en-SG" : (culture == "id-ID" ? "id-ID" : "en-MY"); }
public WizardController(IOrchardServices orchardServices, ICampaignService campaignService, IimageHelper imageHelper, IFontService fontService, IProductService productService, ISwatchService swatchService, ITShirtCostService costService, ITeeyootMessagingService teeyootMessagingService, IRepository<CommonSettingsRecord> commonSettingsRepository, IRepository<ArtRecord> artRepository, IRepository<CheckoutCampaignRequest> checkoutCampaignRequestRepository, ShellSettings shellSettings, IWorkContextAccessor workContextAccessor, IRepository<CurrencyRecord> currencyRepository) { _orchardServices = orchardServices; _campaignService = campaignService; _imageHelper = imageHelper; _fontService = fontService; _productService = productService; _swatchService = swatchService; Logger = NullLogger.Instance; _costService = costService; _teeyootMessagingService = teeyootMessagingService; _commonSettingsRepository = commonSettingsRepository; _checkoutCampaignRequestRepository = checkoutCampaignRequestRepository; _shellSettings = shellSettings; T = NullLocalizer.Instance; _artRepository = artRepository; _workContextAccessor = workContextAccessor; var culture = _workContextAccessor.GetContext().CurrentCulture.Trim(); cultureUsed = culture == "en-SG" ? "en-SG" : (culture == "id-ID" ? "id-ID" : "en-MY"); _currencyRepository = currencyRepository; }
public DeliverySettingsController( ISiteService siteService, IOrchardServices orchardServices, IDeliverySettingsService deliverySettingService, IRepository<DeliverySettingRecord> deliverySettingsRepository, IRepository<CountryRecord> countryRepository, IShapeFactory shapeFactory, IWorkContextAccessor workContextAccessor) { _siteService = siteService; _orchardServices = orchardServices; _deliverySettingService = deliverySettingService; _deliverySettingsRepository = deliverySettingsRepository; _countryRepository = countryRepository; Shape = shapeFactory; _workContextAccessor = workContextAccessor; var culture = _workContextAccessor.GetContext().CurrentCulture.Trim(); cultureUsed = culture == "en-SG" ? "en-SG" : (culture == "id-ID" ? "id-ID" : "en-MY"); T = NullLocalizer.Instance; Logger = NullLogger.Instance; }
public ForumPartHandler(IWorkContextAccessor workContextAccessor, IWaveNotificationWrapper waveNotificationWrapper) { _workContextAccessor = workContextAccessor; _waveNotificationWrapper = waveNotificationWrapper; OnPublished<PostPart>((context, postPart) => { if (!postPart.IsParentThread()) return; var threadPart = postPart.ThreadPart; var forumPart = threadPart.ForumPart; var workContext = _workContextAccessor.GetContext(); var location = new UrlHelper(workContext.HttpContext.Request.RequestContext).ThreadView(threadPart); _waveNotificationWrapper.NotifyThreadCreated(forumPart.Id, threadPart.Id, postPart.Id, location); }); OnRemoved<ThreadPart>((context, threadPart) => { var forumPart = threadPart.ForumPart; _waveNotificationWrapper.NotifyThreadRemoved(forumPart.Id, threadPart.Id); }); }
public void OnActionExecuted(ActionExecutedContext filterContext) { if (filterContext.Controller is PaymentController && filterContext.ActionDescriptor.ActionName.Equals("Info")) { var viewResult = filterContext.Result as ViewResult; if (viewResult != null) { var model = viewResult.Model as PaymentVM; if (model != null && model.Record != null && model.Record.Success) { // We only have to inject GTM stuff if Statistical cookies are allowed if (_GTMProductService.ShoulAddEcommerceTags()) { // select the contentitemid which is the id of the order var orderId = model.Record.ContentItemId; // select order var order = _contentManager.Get <OrderPart>(orderId); // verify if existing record var existing = _addedMeauringPurchaseRepository .Fetch(mp => mp.OrderPartRecord == order.Record && mp.AddedScript == true); if (!existing.Any()) { var checkoutItems = order.Items.ToList(); var products = _contentManager .GetMany <IContent>( checkoutItems.Select(p => p.ProductId).Distinct(), VersionOptions.Published, QueryHints.Empty) .ToList(); // initialize list of GTMProductVM (now using interface IGAProductVM to manage GA4ProductVM too) var productList = new List <IGAProductVM>(); foreach (var p in products) { // populate list of GTMProductVM var part = p.As <GTMProductPart>(); _GTMProductService.FillPart(part); var vm = _GTMProductService.GetViewModel(part); var checkoutItem = checkoutItems .Where(c => c.ProductId == p.Id) .FirstOrDefault(); // add quantity vm.Quantity = checkoutItem == null ? 0 : checkoutItem.Quantity; productList.Add(vm); } // GA4 management if (_GTMProductService.UseGA4()) { var purchaseVM = new GA4PurchaseVM(); purchaseVM.ActionField = new GA4ActionField { TransactionId = model.Record.TransactionId, Affiliation = "", Value = model.Record.Amount, Tax = _GTMMeasuringPurchaseService.GetVatDue(order), // shipping with VAT Shipping = order.ShippingOption.Price, Currency = order.CurrencyCode }; purchaseVM.ProductList = productList; // add coupon information to the ActionField var xCoupons = order.AdditionalElements .Where(el => CouponingUtilities.CouponAlterationType.Equals(el.Name.ToString(), StringComparison.InvariantCultureIgnoreCase)); if (xCoupons.Any()) { purchaseVM.ActionField.Coupon = string.Join(",", xCoupons.Select(el => el.Attr(CouponingUtilities.CouponAttributeName).ToString())); } // add the record to store the operation _addedMeauringPurchaseRepository.Create(new AddedMeasuringPurchase { OrderPartRecord = order.Record, AddedScript = true }); _workContextAccessor.GetContext(filterContext) .Layout.Zones.Head .Add(_shapeFactory.GA4Purchase(GA4PurchaseVM: purchaseVM)); } else { // populate ViewModel to send at shape var purchaseVM = new GTMPurchaseVM(); purchaseVM.ActionField = new GTMActionField { Id = model.Record.TransactionId, Revenue = model.Record.Amount, Tax = _GTMMeasuringPurchaseService.GetVatDue(order), // shipping with VAT Shipping = order.ShippingOption.Price }; purchaseVM.ProductList = productList; // add coupon information to the ActionField var xCoupons = order.AdditionalElements .Where(el => CouponingUtilities.CouponAlterationType.Equals(el.Name.ToString(), StringComparison.InvariantCultureIgnoreCase)); if (xCoupons.Any()) { purchaseVM.ActionField.Coupon = string.Join(",", xCoupons.Select(el => el.Attr(CouponingUtilities.CouponAttributeName).ToString())); } // add the record to store the operation _addedMeauringPurchaseRepository.Create(new AddedMeasuringPurchase { OrderPartRecord = order.Record, AddedScript = true }); _workContextAccessor.GetContext(filterContext) .Layout.Zones.Head .Add(_shapeFactory.GTMPurchase(GTMPurchaseVM: purchaseVM)); } } } } } } }
public DefaultCacheStorageProvider(IWorkContextAccessor workContextAccessor, ShellSettings shellSettings) { _workContext = workContextAccessor.GetContext(); _tenantName = shellSettings.Name; }
public dynamic Format(dynamic display, object value, dynamic formState) { var culture = _workContextAccessor.GetContext().CurrentCulture; return(NumericPropertyForm.FormatNumber(Convert.ToDecimal(value, new System.Globalization.CultureInfo(culture)), formState, culture)); }
public AdminDirectionalityFactory( IWorkContextAccessor workContextAccessor) { _workContext = workContextAccessor.GetContext(); }
private int ValidityTime() { return(_workContextAccessor.GetContext().CurrentSite.As <NonceLoginSettingsPart>().NonceMinutesValidity); }
private void RecordContentTypeAuditTrail(string eventName, IDictionary <string, object> eventData, string contentTypeName) { _auditTrailManager.CreateRecord <ContentTypeAuditTrailEventProvider>(eventName, _wca.GetContext().CurrentUser, properties: null, eventData: eventData, eventFilterKey: "contenttype", eventFilterData: contentTypeName); }
public dynamic Format(dynamic display, object value, dynamic formState) { var culture = _workContextAccessor.GetContext().CurrentCulture; return(DateTimePropertyForm.FormatDateTime(display, Convert.ToDateTime(value, new System.Globalization.CultureInfo(culture)), formState, culture)); }
public void OnActionExecuting(ActionExecutingContext filterContext) { // use the action in the cacheKey so that the same route can't return cache for different actions _actionName = filterContext.ActionDescriptor.ActionName; // apply OutputCacheAttribute logic if defined var outputCacheAttribute = filterContext.ActionDescriptor.GetCustomAttributes(typeof(OutputCacheAttribute), true).Cast <OutputCacheAttribute>().FirstOrDefault(); if (outputCacheAttribute != null) { if (outputCacheAttribute.Duration <= 0 || outputCacheAttribute.NoStore) { Logger.Debug("Request ignored based on OutputCache attribute"); return; } } // saving the current datetime _now = _clock.UtcNow; // before executing an action, we check if a valid cached result is already // existing for this context (url, theme, culture, tenant) Logger.Debug("Request on: " + filterContext.RequestContext.HttpContext.Request.RawUrl); // don't cache POST requests if (filterContext.HttpContext.Request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase)) { Logger.Debug("Request ignored on POST"); return; } // don't cache the admin if (AdminFilter.IsApplied(new RequestContext(filterContext.HttpContext, new RouteData()))) { Logger.Debug("Request ignored on Admin section"); return; } // ignore child actions, e.g. HomeController is using RenderAction() if (filterContext.IsChildAction) { Logger.Debug("Request ignored on Child actions"); return; } _workContext = _workContextAccessor.GetContext(); // don't return any cached content, or cache any content, if the user is authenticated if (_workContext.CurrentUser != null) { Logger.Debug("Request ignored on Authenticated user"); return; } // caches the default cache duration to prevent a query to the settings _cacheDuration = _cacheManager.Get("CacheSettingsPart.Duration", context => { context.Monitor(_signals.When(CacheSettingsPart.CacheKey)); return(_workContext.CurrentSite.As <CacheSettingsPart>().DefaultCacheDuration); } ); // caches the default max age duration to prevent a query to the settings _maxAge = _cacheManager.Get("CacheSettingsPart.MaxAge", context => { context.Monitor(_signals.When(CacheSettingsPart.CacheKey)); return(_workContext.CurrentSite.As <CacheSettingsPart>().DefaultMaxAge); } ); // caches the ignored urls to prevent a query to the settings _ignoredUrls = _cacheManager.Get("CacheSettingsPart.IgnoredUrls", context => { context.Monitor(_signals.When(CacheSettingsPart.CacheKey)); return(_workContext.CurrentSite.As <CacheSettingsPart>().IgnoredUrls); } ); // caches the culture setting _applyCulture = _cacheManager.Get("CacheSettingsPart.ApplyCulture", context => { context.Monitor(_signals.When(CacheSettingsPart.CacheKey)); return(_workContext.CurrentSite.As <CacheSettingsPart>().ApplyCulture); } ); // caches the ignored urls to prevent a query to the settings _debugMode = _cacheManager.Get("CacheSettingsPart.DebugMode", context => { context.Monitor(_signals.When(CacheSettingsPart.CacheKey)); return(_workContext.CurrentSite.As <CacheSettingsPart>().DebugMode); } ); CacheItem cacheItem = null; var queryString = filterContext.RequestContext.HttpContext.Request.QueryString; var parameters = new Dictionary <string, object>(filterContext.ActionParameters); foreach (var key in queryString.AllKeys) { parameters[key] = queryString[key]; } // compute the cache key _cacheKey = ComputeCacheKey(filterContext, parameters); _invariantCacheKey = ComputeCacheKey(filterContext, null); // don't retrieve cache content if refused // in this case the result of the action will update the current cached version if (filterContext.RequestContext.HttpContext.Request.Headers["Cache-Control"] != "no-cache") { // fetch cached data cacheItem = filterContext.HttpContext.Cache[_cacheKey] as CacheItem; if (cacheItem == null) { Logger.Debug("Cached version not found"); } } else { Logger.Debug("Cache-Control = no-cache requested"); } var response = filterContext.HttpContext.Response; // render cached content if (cacheItem != null) { Logger.Debug("Cache item found, expires on " + cacheItem.ValidUntilUtc); var output = cacheItem.Output; /* * * There is no need to replace the AntiForgeryToken as it is not used for unauthenticated requests * and at this point, the request can't be authenticated * * * * // replace any anti forgery token with a fresh value * if (output.Contains(AntiforgeryBeacon)) * { * var viewContext = new ViewContext * { * HttpContext = filterContext.HttpContext, * Controller = filterContext.Controller * }; * * var htmlHelper = new HtmlHelper(viewContext, new ViewDataContainer()); * var siteSalt = _workContext.CurrentSite.SiteSalt; * var token = htmlHelper.AntiForgeryToken(siteSalt); * output = output.Replace(AntiforgeryBeacon, token.ToString()); * } * */ // adds some caching information to the output if requested if (_debugMode) { output += "\r\n<!-- Cached on " + cacheItem.CachedOnUtc + " (UTC) until " + cacheItem.ValidUntilUtc + " (UTC) -->"; } filterContext.Result = new ContentResult { Content = output, ContentType = cacheItem.ContentType }; response.StatusCode = cacheItem.StatusCode; ApplyCacheControl(cacheItem, response, output); return; } // no cache content available, intercept the execution results for caching response.Filter = _filter = new CapturingResponseFilter(response.Filter); }
public DeveiceFilter(IWorkContextAccessor workContextAccessor) { T = NullLocalizer.Instance; _workContextAccessor = workContextAccessor; _cultureInfo = new Lazy <CultureInfo>(() => CultureInfo.GetCultureInfo(_workContextAccessor.GetContext().CurrentSite.SiteCulture)); }
protected override DriverResult Display(TicketsForContentItemPart part, string displayType, dynamic shapeHelper) { if (this.crmContentOwnershipService.IsCurrentUserOperator() && displayType == "Detail") { var context = workContextAccessor.GetContext(); var layout = context.Layout; // for the ticket related pages, we don't render any menu if (layout.TicketRelatedPage != null && layout.TicketRelatedPage == true) { return(null); } var settings = part.TypePartDefinition.Settings.GetModel <TicketsForContentItemPartSettings>(); if (!settings.DoNotRenderTicketsFlipFlop) { this.RenderFlipFlop(shapeHelper); } var statusRecords = this.basicDataService.GetStatusRecords().OrderBy(c => c.OrderId).ToList(); var contentQuery = searchTicketService.CreateQuery(new PostedTicketSearchViewModel { Users = new int[] { }, BusinessUnits = new int[] { }, RelatedContentItemId = part.ContentItem.Id, IncludeAllVisibleItemsBySelectedGroupsAndUsers = true }); var ticketsCountByStateIds = groupQuery.GetCount(contentQuery, "TicketPartRecord", "StatusRecord.Id"); var ticketsCountWithLabels = new Collection <dynamic>(); CRMHelper.AddStatusGroupRecordsToModel(statusRecords, ticketsCountByStateIds, ticketsCountWithLabels); // overrude items of current users var overrudeTicketCount = searchTicketService.CountByDatabase(new PostedTicketSearchViewModel { Users = new int[] { }, BusinessUnits = new int[] { }, RelatedContentItemId = part.ContentItem.Id, DueDate = PostedTicketSearchViewModel.OverDueDate, IncludeAllVisibleItemsBySelectedGroupsAndUsers = true }); var unassignedTicketCount = searchTicketService.CountByDatabase(new PostedTicketSearchViewModel { Users = new int[] { }, BusinessUnits = new int[] { }, RelatedContentItemId = part.ContentItem.Id, Unassigned = true }); dynamic model = new ExpandoObject(); model.TicketsGroupByStatus = ticketsCountWithLabels; model.OverrudeTicketCount = overrudeTicketCount; model.UnAssignedTicketCount = unassignedTicketCount; model.Part = part; return(ContentShape("Parts_TicketsForContentItem", () => shapeHelper.Parts_TicketsForContentItem( Model: model ))); } else { return(null); } }
public bool UseLocalStorage() { return(_wca.GetContext().CurrentUser == null); }
protected override DriverResult Display(MenuWidgetPart part, string displayType, dynamic shapeHelper) { return(ContentShape("Parts_MenuWidget", () => { var menu = _menuService.GetMenu(part.MenuContentItemId); if (menu == null) { return null; } var menuName = menu.As <TitlePart>().Title.HtmlClassify(); var currentCulture = _workContextAccessor.GetContext().CurrentCulture; var menuItems = _navigationManager.BuildMenu(menu); var localized = new List <MenuItem>(); foreach (var menuItem in menuItems) { // if there is no associated content, it as culture neutral if (menuItem.Content == null) { localized.Add(menuItem); } // if the menu item is culture neutral or of the current culture else if (String.IsNullOrEmpty(menuItem.Culture) || String.Equals(menuItem.Culture, currentCulture, StringComparison.OrdinalIgnoreCase)) { localized.Add(menuItem); } } menuItems = localized; var request = _workContextAccessor.GetContext().HttpContext.Request; var routeData = request.RequestContext.RouteData; var selectedPath = NavigationHelper.SetSelectedPath(menuItems, request, routeData); var menuShape = shapeHelper.Menu(); if (part.Breadcrumb) { menuItems = selectedPath ?? new Stack <MenuItem>(); foreach (var menuItem in menuItems) { menuItem.Items = Enumerable.Empty <MenuItem>(); } // apply level limits to breadcrumb menuItems = menuItems.Skip(part.StartLevel - 1); if (part.Levels > 0) { menuItems = menuItems.Take(part.Levels); } var result = new List <MenuItem>(menuItems); // inject the home page if (part.AddHomePage) { result.Insert(0, new MenuItem { Href = _navigationManager.GetUrl("~/", null), Text = T("Home") }); } // inject the current page if (!part.AddCurrentPage && selectedPath != null) { result.RemoveAt(result.Count - 1); } // prevent the home page to be added as the home page and the current page if (result.Count == 2 && String.Equals(result[0].Href, result[1].Href, StringComparison.OrdinalIgnoreCase)) { result.RemoveAt(1); } menuItems = result; menuShape = shapeHelper.Breadcrumb(); } else { var topLevelItems = menuItems.ToList(); // apply start level by pushing children as top level items. When the start level is // greater than 1 (ie. below the top level), only menu items along the selected path // will be displayed. for (var i = 0; topLevelItems.Any() && i < part.StartLevel - 1; i++) { var temp = new List <MenuItem>(); // should the menu be filtered on the currently displayed page ? if (part.ShowFullMenu) { foreach (var menuItem in topLevelItems) { temp.AddRange(menuItem.Items); } } else if (selectedPath != null) { topLevelItems = topLevelItems.Intersect(selectedPath.Where(x => x.Selected)).ToList(); foreach (var menuItem in topLevelItems) { temp.AddRange(menuItem.Items); } } topLevelItems = temp; } // limit the number of levels to display (down from and including the start level) if (part.Levels > 0) { var current = topLevelItems.ToList(); for (var i = 1; current.Any() && i < part.Levels; i++) { var temp = new List <MenuItem>(); foreach (var menuItem in current) { temp.AddRange(menuItem.Items); } current = temp; } // cut the sub-levels beneath any menu items that are at the lowest level being displayed foreach (var menuItem in current) { menuItem.Items = Enumerable.Empty <MenuItem>(); } } menuItems = topLevelItems; } menuShape.MenuName(menuName); menuShape.ContentItem(menu); NavigationHelper.PopulateMenu(shapeHelper, menuShape, menuShape, menuItems); return shapeHelper.Parts_MenuWidget(Menu: menuShape); })); }
protected override void OnDisplaying(Menu element, ElementDisplayingContext context) { var menu = _menuService.GetMenu(element.MenuContentItemId); if (menu == null) { return; } var menuName = menu.As <TitlePart>().Title.HtmlClassify(); var currentCulture = _workContextAccessor.GetContext().CurrentCulture; var menuItems = _navigationManager.BuildMenu(menu); var localized = new List <MenuItem>(); foreach (var menuItem in menuItems) { // If there is no associated content, it as culture neutral. if (menuItem.Content == null) { localized.Add(menuItem); } // If the menu item is culture neutral or of the current culture. else if (String.IsNullOrEmpty(menuItem.Culture) || String.Equals(menuItem.Culture, currentCulture, StringComparison.OrdinalIgnoreCase)) { localized.Add(menuItem); } } menuItems = localized; var shapeHelper = New; var request = _workContextAccessor.GetContext().HttpContext.Request; var routeData = request.RequestContext.RouteData; var selectedPath = NavigationHelper.SetSelectedPath(menuItems, request, routeData); var menuShape = shapeHelper.Menu(); var topLevelItems = menuItems.ToList(); // Apply start level by pushing children as top level items. When the start level is // greater than 1 (ie. below the top level), only menu items along the selected path // will be displayed. for (var i = 0; topLevelItems.Any() && i < element.StartLevel - 1; i++) { var temp = new List <MenuItem>(); // Should the menu be filtered on the currently displayed page? if (element.ShowFullMenu) { foreach (var menuItem in topLevelItems) { temp.AddRange(menuItem.Items); } } else if (selectedPath != null) { topLevelItems = topLevelItems.Intersect(selectedPath.Where(x => x.Selected)).ToList(); foreach (var menuItem in topLevelItems) { temp.AddRange(menuItem.Items); } } topLevelItems = temp; } // Limit the number of levels to display (down from and including the start level). if (element.Levels > 0) { var current = topLevelItems.ToList(); for (var i = 1; current.Any() && i < element.Levels; i++) { var temp = new List <MenuItem>(); foreach (var menuItem in current) { temp.AddRange(menuItem.Items); } current = temp; } // Cut the sub-levels beneath any menu items that are at the lowest level being displayed. foreach (var menuItem in current) { menuItem.Items = Enumerable.Empty <MenuItem>(); } } menuItems = topLevelItems; menuShape.MenuName(menuName); menuShape.ContentItem(menu); NavigationHelper.PopulateMenu(shapeHelper, menuShape, menuShape, menuItems); context.ElementShape.Menu = menuShape; }
public bool TryCheckAccess(Permission permission, IUser user, IContent content) { var context = new CheckAccessContext { Permission = permission, User = user, Content = content }; _authorizationServiceEventHandler.Checking(context); for (var adjustmentLimiter = 0; adjustmentLimiter != 3; ++adjustmentLimiter) { if (!context.Granted && context.User != null) { if (!String.IsNullOrEmpty(_workContextAccessor.GetContext().CurrentSite.SuperUser) && String.Equals(context.User.UserName, _workContextAccessor.GetContext().CurrentSite.SuperUser, StringComparison.Ordinal)) { context.Granted = true; } } if (!context.Granted) { // determine which set of permissions would satisfy the access check var grantingNames = PermissionNames(context.Permission, Enumerable.Empty <string>()).Distinct().ToArray(); // determine what set of roles should be examined by the access check IEnumerable <string> rolesToExamine; if (context.User == null) { rolesToExamine = AnonymousRole; } else if (context.User.Has <IUserRoles>()) { // the current user is not null, so get his roles and add "Authenticated" to it rolesToExamine = context.User.As <IUserRoles>().Roles; // when it is a simulated anonymous user in the admin if (!rolesToExamine.Contains(AnonymousRole[0])) { rolesToExamine = rolesToExamine.Concat(AuthenticatedRole); } } else { // the user is not null and has no specific role, then it's just "Authenticated" rolesToExamine = AuthenticatedRole; } foreach (var role in rolesToExamine) { foreach (var permissionName in _roleService.GetPermissionsForRoleByName(role)) { string possessedName = permissionName; if (grantingNames.Any(grantingName => String.Equals(possessedName, grantingName, StringComparison.OrdinalIgnoreCase))) { context.Granted = true; } if (context.Granted) { break; } } if (context.Granted) { break; } } } context.Adjusted = false; _authorizationServiceEventHandler.Adjust(context); if (!context.Adjusted) { break; } } _authorizationServiceEventHandler.Complete(context); return(context.Granted); }
public void OnActionExecuting(ActionExecutingContext filterContext) { Logger.Debug("Incoming request for URL '{0}'.", filterContext.RequestContext.HttpContext.Request.RawUrl); // This filter is not reentrant (multiple executions within the same request are // not supported) so child actions are ignored completely. if (filterContext.IsChildAction) { Logger.Debug("Action '{0}' ignored because it's a child action.", filterContext.ActionDescriptor.ActionName); return; } _now = _clock.UtcNow; _workContext = _workContextAccessor.GetContext(); if (!RequestIsCacheable(filterContext)) { return; } // Computing the cache key after we know that the request is cacheable means that we are only performing this calculation on requests that require it _cacheKey = ComputeCacheKey(filterContext, GetCacheKeyParameters(filterContext)); _invariantCacheKey = ComputeCacheKey(filterContext, null); Logger.Debug("Cache key '{0}' was created.", _cacheKey); // The cache key lock for a given cache key is used to synchronize requests to // ensure only a single request is regenerating the item. var cacheKeyLock = _cacheKeyLocks.GetOrAdd(_cacheKey, x => new object()); try { // Is there a cached item, and are we allowed to serve it? var allowServeFromCache = filterContext.RequestContext.HttpContext.Request.Headers["Cache-Control"] != "no-cache" || CacheSettings.IgnoreNoCache; var cacheItem = GetCacheItem(_cacheKey); if (allowServeFromCache && cacheItem != null) { Logger.Debug("Item '{0}' was found in cache.", _cacheKey); // Is the cached item in its grace period? if (cacheItem.IsInGracePeriod(_now)) { // Render the content unless another request is already doing so. if (Monitor.TryEnter(cacheKeyLock)) { Logger.Debug("Item '{0}' is in grace period and not currently being rendered; rendering item...", _cacheKey); BeginRenderItem(filterContext); return; } } // Cached item is not yet in its grace period, or is already being // rendered by another request; serve it from cache. Logger.Debug("Serving item '{0}' from cache.", _cacheKey); ServeCachedItem(filterContext, cacheItem); return; } // No cached item found, or client doesn't want it; acquire the cache key // lock to render the item. Logger.Debug("Item '{0}' was not found in cache or client refuses it. Acquiring cache key lock...", _cacheKey); if (Monitor.TryEnter(cacheKeyLock, TimeSpan.FromSeconds(20))) { Logger.Debug("Cache key lock for item '{0}' was acquired.", _cacheKey); // Item might now have been rendered and cached by another request; if so serve it from cache. if (allowServeFromCache) { cacheItem = GetCacheItem(_cacheKey); if (cacheItem != null) { Logger.Debug("Item '{0}' was now found; releasing cache key lock and serving from cache.", _cacheKey); Monitor.Exit(cacheKeyLock); ServeCachedItem(filterContext, cacheItem); return; } } } // Either we acquired the cache key lock and the item was still not in cache, or // the lock acquisition timed out. In either case render the item. Logger.Debug("Rendering item '{0}'...", _cacheKey); BeginRenderItem(filterContext); } catch { // Remember to release the cache key lock in the event of an exception! Logger.Debug("Exception occurred for item '{0}'; releasing any acquired lock.", _cacheKey); if (Monitor.IsEntered(cacheKeyLock)) { Monitor.Exit(cacheKeyLock); } throw; } }
/// <summary> /// 获取租户文化。 /// </summary> /// <returns>文化名称。</returns> public string GetTenantCulture() { return(_workContextAccessor.GetContext().CurrentTenant == null ? null : _workContextAccessor.GetContext().CurrentTenant.TenantCulture); }
public string GetCurrentCulture(HttpContextBase requestContext) { return(_workContextAccessor.GetContext().CurrentCulture); }
public void BuildOrder(IShoppingCartService ShoppingCartService, IContent Order) { var customer = _customersService.GetCustomer(); if (customer == null) { return; } OrderAddressRecord billingAddress = null, shippingAddress = null; Int32 billingAddressId = ShoppingCartService.GetProperty <int>("BillingAddressId"); if (billingAddressId > 0) { var customerBillingAddress = customer.Addresses.Where(a => a.Id == billingAddressId).FirstOrDefault(); if (customerBillingAddress != null) { billingAddress = new OrderAddressRecord(); customerBillingAddress.CopyTo(billingAddress); } } Int32 shippingAddressId = ShoppingCartService.GetProperty <int>("ShippingAddressId"); if (shippingAddressId > 0) { if (shippingAddressId == billingAddressId) { shippingAddress = billingAddress; } else { var customerShippingAddress = customer.Addresses.Where(a => a.Id == shippingAddressId).FirstOrDefault(); if (customerShippingAddress != null) { shippingAddress = new OrderAddressRecord(); customerShippingAddress.CopyTo(shippingAddress); } } } var customerOrderPart = Order.As <CustomerOrderPart>(); if (customerOrderPart != null) { customerOrderPart.Customer = customer; } var orderPart = Order.As <OrderPart>(); if (orderPart != null && billingAddress != null) { orderPart.BillingAddress = billingAddress; } var shippingPart = Order.As <OrderShippingPart>(); if (shippingPart != null) { // Shipping address if (shippingAddress != null) { // Set address shippingPart.ShippingAddress = shippingAddress; // Set shipping zone var workContext = _workContextAccessor.GetContext(); if (shippingAddress.State != null && shippingAddress.State.Enabled && shippingAddress.State.ShippingZoneRecord != null) { workContext.SetState("OShop.Orders.ShippingZone", shippingAddress.State.ShippingZoneRecord); } else if (shippingAddress.Country != null && shippingAddress.Country.Enabled && shippingAddress.Country.ShippingZoneRecord != null) { workContext.SetState("OShop.Orders.ShippingZone", shippingAddress.Country.ShippingZoneRecord); } } } }
protected override DriverResult Display(FeaturedCampaignsWidgetPart part, string displayType, dynamic shapeHelper) { var culture = _workContextAccessor.GetContext().CurrentCulture.Trim(); var campaignsInFeatured = _campaignsService.GetAllCampaigns().Where(c => c.IsFeatured && !c.IsPrivate && c.IsActive && c.IsApproved).OrderByDescending(c => c.ProductCountSold).ToList(); var featuredCampaigns = new List <CampaignRecord>(); if (campaignsInFeatured.Count >= 8) { featuredCampaigns = campaignsInFeatured; } else { featuredCampaigns = campaignsInFeatured; int countTopCamp = 8 - campaignsInFeatured.Count; var ordersFromOneDay = _featuredCampaignsService.GetOrderForOneDay().Where(c => c.Products != null && c.Products.Count > 0).ToList(); if (ordersFromOneDay != null && ordersFromOneDay.Count > 0) { int[] ordersIdFromOneDay = ordersFromOneDay.Select(c => c.Id).ToArray(); Dictionary <CampaignRecord, int> campaignsFromOrderForDay = _featuredCampaignsService.GetCampaignsFromOrderForOneDay(ordersIdFromOneDay); int take = campaignsFromOrderForDay.Count > 16 ? 16 : campaignsFromOrderForDay.Count; campaignsFromOrderForDay = campaignsFromOrderForDay.OrderByDescending(c => c.Value).OrderBy(c => c.Key.Title).Skip(0).Take(take).ToDictionary(p => p.Key, p => p.Value); Random rand = new Random(); int insertCamp = campaignsFromOrderForDay.Count() <= countTopCamp?campaignsFromOrderForDay.Count() : countTopCamp; for (int i = 0; i < insertCamp; i++) { var campNum = rand.Next(take); var campKey = campaignsFromOrderForDay.ElementAt(campNum).Key; if (!featuredCampaigns.Contains(campKey)) { featuredCampaigns.Add(campKey); } } } if (featuredCampaigns.Count() < 8) { countTopCamp = 8 - featuredCampaigns.Count(); var otherCampaigns = _campaignsService.GetAllCampaigns().Where(c => !c.IsPrivate && c.IsActive && c.IsApproved).ToList(); foreach (var camp in campaignsInFeatured) { if (otherCampaigns.Exists(c => c.Id == camp.Id)) { otherCampaigns.Remove(camp); } } int max = otherCampaigns.Count(); if ((max + featuredCampaigns.Count()) < 8) { featuredCampaigns.AddRange(otherCampaigns.ToArray()); } else { Random rand = new Random(); for (int i = 0; i < countTopCamp; i++) { var res = false; while (!res) { var camp = otherCampaigns.ElementAt(rand.Next(max)); if (!featuredCampaigns.Exists(c => c.Id == camp.Id)) { featuredCampaigns.Add(camp); res = true; } } } } } } var currenciesandprices = new Dictionary <int, Dictionary <string, double> >(); foreach (var c in featuredCampaigns) { Dictionary <string, double> prices = new Dictionary <string, double>(); foreach (var item in _currencies.Table) { var price = c.Products.First().Price; prices.Add(item.Code, _priceconvertorservice.ConvertPrice(price, c.CurrencyRecord, item).Value); } currenciesandprices.Add(c.Id, prices); } return(ContentShape("Parts_FeaturedCampaignsWidget", () => shapeHelper.Parts_FeaturedCampaignsWidget(Campaigns: featuredCampaigns, currency: _countries.GetDefaultCurrecny().Code, prices: currenciesandprices))); }
private void BuildMenu(NavigationItemBuilder menu) { var advertises = _advertiseService.Get().Where(x => _authorizationService.TryCheckAccess(Permissions.ManageAdvertise, _workContextAccessor.GetContext().CurrentUser, x)).ToArray(); var advertiseCount = advertises.Count(); var singleAdvertise = advertiseCount == 1 ? advertises.ElementAt(0) : null; if (advertiseCount > 0 && singleAdvertise == null) { menu.Add(T("Manage Advertises"), "3", item => item.Action("List", "AdvertiseAdmin", new { area = "Orchard.Advertise" }).Permission(Permissions.ManageAdvertise)); } else if (singleAdvertise != null) { menu.Add(T("Manage Advertise"), "1.0", item => item.Action("Item", "AdvertiseAdmin", new { area = "Orchard.Advertise", advertiseId = singleAdvertise.Id }).Permission(Permissions.ManageOwnAdvertise)); } menu.Add(T("New Advertise"), "1.2", item => item.Action("Create", "AdvertiseAdmin", new { area = "Orchard.Advertise" }).Permission(Permissions.ManageAdvertise)); }
public void OnActionExecuting(ActionExecutingContext filterContext) { // use the action in the cacheKey so that the same route can't return cache for different actions _actionName = filterContext.ActionDescriptor.ActionName; // apply OutputCacheAttribute logic if defined var actionAttributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(OutputCacheAttribute), true); var controllerAttributes = filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(OutputCacheAttribute), true); var outputCacheAttribute = actionAttributes.Concat(controllerAttributes).Cast <OutputCacheAttribute>().FirstOrDefault(); if (outputCacheAttribute != null) { if (outputCacheAttribute.Duration <= 0 || outputCacheAttribute.NoStore) { Logger.Debug("Request ignored based on OutputCache attribute"); return; } } // saving the current datetime _now = _clock.UtcNow; // before executing an action, we check if a valid cached result is already // existing for this context (url, theme, culture, tenant) Logger.Debug("Request on: " + filterContext.RequestContext.HttpContext.Request.RawUrl); // don't cache POST requests if (filterContext.HttpContext.Request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase)) { Logger.Debug("Request ignored on POST"); return; } // don't cache the admin if (AdminFilter.IsApplied(new RequestContext(filterContext.HttpContext, new RouteData()))) { Logger.Debug("Request ignored on Admin section"); return; } // ignore child actions, e.g. HomeController is using RenderAction() if (filterContext.IsChildAction) { Logger.Debug("Request ignored on Child actions"); return; } _workContext = _workContextAccessor.GetContext(); // don't return any cached content, or cache any content, if the user is authenticated if (_workContext.CurrentUser != null) { Logger.Debug("Request ignored on Authenticated user"); return; } // caches the default cache duration to prevent a query to the settings _cacheDuration = _cacheManager.Get("CacheSettingsPart.Duration", context => { context.Monitor(_signals.When(CacheSettingsPart.CacheKey)); return(_workContext.CurrentSite.As <CacheSettingsPart>().DefaultCacheDuration); } ); // caches the default max age duration to prevent a query to the settings _maxAge = _cacheManager.Get("CacheSettingsPart.MaxAge", context => { context.Monitor(_signals.When(CacheSettingsPart.CacheKey)); return(_workContext.CurrentSite.As <CacheSettingsPart>().DefaultMaxAge); } ); _varyQueryStringParameters = _cacheManager.Get("CacheSettingsPart.VaryQueryStringParameters", context => { context.Monitor(_signals.When(CacheSettingsPart.CacheKey)); var varyQueryStringParameters = _workContext.CurrentSite.As <CacheSettingsPart>().VaryQueryStringParameters; return(string.IsNullOrWhiteSpace(varyQueryStringParameters) ? null : varyQueryStringParameters.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray()); } ); var varyRequestHeadersFromSettings = _cacheManager.Get("CacheSettingsPart.VaryRequestHeaders", context => { context.Monitor(_signals.When(CacheSettingsPart.CacheKey)); var varyRequestHeaders = _workContext.CurrentSite.As <CacheSettingsPart>().VaryRequestHeaders; return(string.IsNullOrWhiteSpace(varyRequestHeaders) ? null : varyRequestHeaders.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray()); } ); _varyRequestHeaders = (varyRequestHeadersFromSettings == null) ? new HashSet <string>() : new HashSet <string>(varyRequestHeadersFromSettings); // different tenants with the same urls have different entries _varyRequestHeaders.Add("HOST"); // Set the Vary: Accept-Encoding response header. // This instructs the proxies to cache two versions of the resource: one compressed, and one uncompressed. // The correct version of the resource is delivered based on the client request header. // This is a good choice for applications that are singly homed and depend on public proxies for user locality. _varyRequestHeaders.Add("Accept-Encoding"); // caches the ignored urls to prevent a query to the settings _ignoredUrls = _cacheManager.Get("CacheSettingsPart.IgnoredUrls", context => { context.Monitor(_signals.When(CacheSettingsPart.CacheKey)); return(_workContext.CurrentSite.As <CacheSettingsPart>().IgnoredUrls); } ); // caches the culture setting _applyCulture = _cacheManager.Get("CacheSettingsPart.ApplyCulture", context => { context.Monitor(_signals.When(CacheSettingsPart.CacheKey)); return(_workContext.CurrentSite.As <CacheSettingsPart>().ApplyCulture); } ); // caches the debug mode _debugMode = _cacheManager.Get("CacheSettingsPart.DebugMode", context => { context.Monitor(_signals.When(CacheSettingsPart.CacheKey)); return(_workContext.CurrentSite.As <CacheSettingsPart>().DebugMode); } ); // don't cache ignored url ? if (IsIgnoredUrl(filterContext.RequestContext.HttpContext.Request.AppRelativeCurrentExecutionFilePath, _ignoredUrls)) { return; } var queryString = filterContext.RequestContext.HttpContext.Request.QueryString; var requestHeaders = filterContext.RequestContext.HttpContext.Request.Headers; var parameters = new Dictionary <string, object>(filterContext.ActionParameters); foreach (var key in queryString.AllKeys) { if (key == null) { continue; } parameters[key] = queryString[key]; } foreach (var varyByRequestHeader in _varyRequestHeaders) { if (requestHeaders.AllKeys.Contains(varyByRequestHeader)) { parameters["HEADER:" + varyByRequestHeader] = requestHeaders[varyByRequestHeader]; } } // compute the cache key _cacheKey = ComputeCacheKey(filterContext, parameters); // create a tag which doesn't care about querystring _invariantCacheKey = ComputeCacheKey(filterContext, null); // don't retrieve cache content if refused // in this case the result of the action will update the current cached version if (filterContext.RequestContext.HttpContext.Request.Headers["Cache-Control"] != "no-cache") { // fetch cached data _cacheItem = _cacheStorageProvider.GetCacheItem(_cacheKey); if (_cacheItem == null) { Logger.Debug("Cached version not found"); } } else { Logger.Debug("Cache-Control = no-cache requested"); } var response = filterContext.HttpContext.Response; // render cached content if (_cacheItem != null) { Logger.Debug("Cache item found, expires on " + _cacheItem.ValidUntilUtc); var output = _cacheItem.Output; // adds some caching information to the output if requested if (_debugMode) { response.AddHeader("X-Cached-On", _cacheItem.CachedOnUtc.ToString("r")); response.AddHeader("X-Cached-Until", _cacheItem.ValidUntilUtc.ToString("r")); } // shorcut action execution filterContext.Result = new ContentResult { Content = output, ContentType = _cacheItem.ContentType }; response.StatusCode = _cacheItem.StatusCode; ApplyCacheControl(_cacheItem, response); return; } _cacheItem = new CacheItem(); // get contents ApplyCacheControl(_cacheItem, response); // no cache content available, intercept the execution results for caching _previousFilter = response.Filter; response.Filter = _filter = new CapturingResponseFilter(response.Filter); }
public void OnResultExecuting(ResultExecutingContext filterContext) { // layers and widgets should only run on a full view rendering result var viewResult = filterContext.Result as ViewResult; if (viewResult == null) { return; } var workContext = _workContextAccessor.GetContext(filterContext); if (workContext == null || workContext.Layout == null || workContext.CurrentSite == null || AdminFilter.IsApplied(filterContext.RequestContext) || !ThemeFilter.IsApplied(filterContext.RequestContext)) { return; } // Once the Rule Engine is done: // Get Layers and filter by zone and rule var activeLayers = _orchardServices.ContentManager.Query <LayerPart, LayerPartRecord>().List(); var activeLayerIds = new List <int>(); foreach (var activeLayer in activeLayers) { // ignore the rule if it fails to execute try { if (_conditionManager.Matches(activeLayer.Record.LayerRule)) { activeLayerIds.Add(activeLayer.ContentItem.Id); } } catch (Exception e) { Logger.Warning(e, T("An error occured during layer evaluation on: {0}", activeLayer.Name).Text); } } var widgetParts = _widgetsService.GetWidgets(layerIds: activeLayerIds.ToArray()); // Build and add shape to zone. var zones = workContext.Layout.Zones; var defaultCulture = workContext.CurrentSite.As <SiteSettingsPart>().SiteCulture; var currentCulture = workContext.CurrentCulture; foreach (var widgetPart in widgetParts) { var commonPart = widgetPart.As <ICommonPart>(); if (commonPart == null || commonPart.Container == null) { Logger.Warning("The widget '{0}' is has no assigned layer or the layer does not exist.", widgetPart.Title); continue; } // ignore widget for different cultures var localizablePart = widgetPart.As <ILocalizableAspect>(); if (localizablePart != null) { // if localized culture is null then show if current culture is the default // this allows a user to show a content item for the default culture only if (localizablePart.Culture == null && defaultCulture != currentCulture) { continue; } // if culture is set, show only if current culture is the same if (localizablePart.Culture != null && localizablePart.Culture != currentCulture) { continue; } } // check permissions if (!_orchardServices.Authorizer.Authorize(Orchard.Core.Contents.Permissions.ViewContent, widgetPart)) { continue; } var useCache = UseCache(widgetPart, filterContext); var widgetShape = useCache ? BuildCachedWidgetShape(widgetPart, filterContext) : BuildWidgetShape(widgetPart); zones[widgetPart.Record.Zone].Add(widgetShape, widgetPart.Record.Position); } }
public CultureDetailsViewModel GetCultureDetailsViewModel(string culture) { var model = new CultureDetailsViewModel { Culture = culture }; var wc = _wca.GetContext(); { var _sessionLocator = wc.Resolve <ISessionLocator>(); using (var session = _sessionLocator.For(typeof(LocalizableStringRecord))) { var query = session.CreateQuery(string.Format(@" select s from {0}Q42.DbTranslations.Models.LocalizableStringRecord as s fetch all properties order by s.Path", DataTablePrefix())); var currentPath = ""; var group = default(CultureDetailsViewModel.TranslationGroupViewModel); foreach (LocalizableStringRecord s in query.Enumerable()) { if (s.Path != currentPath) { group = new CultureDetailsViewModel.TranslationGroupViewModel { Path = String.Format(s.Path, culture) }; if (!group.Path.Contains(culture)) { throw new Exception("Something went wrong: the culture is not included in the path."); } model.Groups.Add(group); currentPath = s.Path; } if (group != null) { var translation = s.Translations.Where(t => t.Culture == culture).FirstOrDefault(); group.Translations.Add(new CultureDetailsViewModel.TranslationViewModel { Context = s.Context, Key = s.StringKey, OriginalString = s.OriginalLanguageString, LocalString = translation != null ? translation.Value : null }); } } } return(model); } }
public IEnumerable <OwinMiddlewareRegistration> GetOwinMiddlewares() => new[] { // Although we only construct a single OwinMiddlewareRegistration here, you could return multiple ones of // course. new OwinMiddlewareRegistration { // The priority value decides the order of OwinMiddlewareRegistrations. I.e. "0" will run before // "10", but registrations without a priority value will run before the ones that have it set. Note // that this priority notation is the same as the one for shape placement (so you can e.g. use // ":before"). Priority = "50", // This is the delegate that sets up middlewares. Configure = app => // This delegate is the actual middleware. Make sure to add using Owin; otherwise you won't get // why the following line won't compile. The context is the Owin context, something similar to // HttpContext; the next delegate is the next middleware in the pipeline. Note that you could // write multiple configuration steps here, not just this one. app.Use(async(context, next) => { // Note that although your IOwinMiddlewareProvider behaves like an ordinary Orchard // dependency, the middleware delegate lives on its own and will run detached from the // provider! Because of this you'll need to either access the Work Context as we do here, or // inject your dependencies as Work<TDependency> objects. If you build multiple middlewares // with many dependencies here, doing the following is a better choice. var workContext = _wca.GetContext(); // But this would be an alternative: var siteSettings = _siteServiceWork.Value.GetSiteSettings(); var clock = workContext.Resolve <IClock>(); var requestStart = clock.UtcNow; // We let the next middleware run, but this is not mandatory: if this middleware would return // a cached page for example then we could just leave this out. await next.Invoke(); // Think twice when wrapping this call into a try-catch: here you'd catch all exceptions that // would normally result in a 404 or an 503, so it's maybe better to always let them bubble // up. But keep in mind that any uncaught exception here in your code will result in a YSOD. var requestDuration = clock.UtcNow - requestStart; // No need to use the ugly HttpContext, because we have OwinContext! var url = context.Request.Uri; // OK, but what if we _really_ need something from HttpContext? // This is Orchard, so should be true... if (context.Environment.ContainsKey("System.Web.HttpContextBase")) { var httpContext = context.Environment["System.Web.HttpContextBase"] as HttpContextBase; if (httpContext != null) { // Voila, we have the ugly HttpContext again! Like RouteData: var routeDataValues = httpContext.Request.RequestContext.RouteData.Values; // ...you know what to do. } } Logger.Information( "The request to " + url + " on the site " + siteSettings.SiteName + " had taken " + requestDuration + "time."); // You see, we've done something useful! // NEXT STATION: let's add some tokens of our own! Head over to UtcNowTokens. }) } };