public T this[string key] { get { lock (TempLock) { if (TemporaryStorage != null) { return TemporaryStorage; } } return CacheManager.Get(GetCacheKey(key)) as T; } set { lock (TempLock) { TemporaryStorage = this[key]; } Remove(key); var evictionPolicy = new CacheEvictionPolicy(_cacheDependencyKeys, _relativeExpiration, CacheTimeoutType.Absolute); CacheManager.Insert(GetCacheKey(key), value, evictionPolicy); lock (TempLock) { TemporaryStorage = null; } } }
private IEnumerable <SyndicationItem> GetFromCacheOrFactory(SyndicationItemFactory syndicationFactory, SyndicationFeedPageType currentPage, IEnumerable <Category> parsedCategories) { var cacheTime = currentPage.CacheFeedforSeconds; string categoryQuery = string.Empty; foreach (var category in parsedCategories) { categoryQuery += category.Name; } var cacheKey = string.Format("SyndicationFeedPageType_{0}_{1}", currentPage.ContentLink.ToString(), categoryQuery); var cachedItems = CacheManager.Get(cacheKey) as IEnumerable <SyndicationItem>; if (cachedItems == null) { cachedItems = syndicationFactory.GetSyndicationItems(); if (cacheTime > 0) { var cachePolicy = new CacheEvictionPolicy(new[] { DataFactoryCache.PageCommonCacheKey(currentPage.ContentLink) } , new TimeSpan(0, 0, cacheTime), CacheTimeoutType.Absolute); CacheManager.Insert(cacheKey, syndicationFactory.GetSyndicationItems(), cachePolicy); } } return(cachedItems); }
private void RetrieveGarages() { CacheEvictionPolicy policy = new CacheEvictionPolicy(TimeSpan.FromMinutes(4), CacheTimeoutType.Sliding); List <ParkingGarage> allGarages = CacheManager.Get(LocationsCacheKey) as List <ParkingGarage>; if (allGarages == null) { allGarages = new List <ParkingGarage>(); using (var client = new HttpClient()) { var json = client.GetStringAsync(_feedUrl); dynamic results = JsonConvert.DeserializeObject(json.Result); foreach (var item in results) { string jsonItem = item.ToString().Replace("\r\n", ""); ParkingGarage garage = JsonConvert.DeserializeObject <ParkingGarage>(jsonItem); allGarages.Add(garage); } } CacheManager.Insert(LocationsCacheKey, allGarages, policy); } Garages = allGarages; }
public void Insert(string key, object value, IEnumerable <Type> dependentTypes) { var timespan = new TimeSpan(0, 10, 0); var cacheEvictionPolicy = new CacheEvictionPolicy(timespan, CacheTimeoutType.Sliding, null, dependentTypes.Select(t => GetMasterKey(t))); _cache.Insert(key, value, cacheEvictionPolicy); }
/// <summary> /// Gets the personal product ids for the user. /// </summary> /// <returns>A list of object ids.</returns> private IEnumerable <int> GetPersonalProductIds() { Guid contactId = PrincipalInfo.CurrentPrincipal.GetContactId(); string userCacheKey = GetUserCacheKey(userGuid: contactId); CacheEvictionPolicy cacheEvictionPolicy = new CacheEvictionPolicy(new TimeSpan(0, 5, 0), timeoutType: CacheTimeoutType.Absolute); List <int> productIdList = this.synchronizedObjectInstanceCache.Get(key: userCacheKey) as List <int>; if (productIdList != null) { return(productIdList); } productIdList = new List <int>(); List <IPurchaseOrder> purchaseOrders = this.orderRepository.Load <IPurchaseOrder>(customerId: contactId).ToList(); productIdList.AddRange(this.GetLineItemIds(orderGroups: purchaseOrders)); if (productIdList.Any()) { this.synchronizedObjectInstanceCache.Insert(key: userCacheKey, productIdList.Distinct().ToList(), evictionPolicy: cacheEvictionPolicy); return(productIdList.Distinct()); } // If there are no orders yet, look in cart and wish-lists List <ICart> carts = this.orderRepository.Load <ICart>(customerId: contactId).ToList(); productIdList.AddRange(this.GetLineItemIds(orderGroups: carts)); this.synchronizedObjectInstanceCache.Insert(key: userCacheKey, productIdList.Distinct().ToList(), evictionPolicy: cacheEvictionPolicy); return(productIdList.Distinct()); }
protected virtual T CreateViewModel <T>(IContent currentContent, CommerceHomePage homePage, Customer.FoundationContact contact, bool isBookmarked) where T : CommerceHeaderViewModel, new() { var menuItems = new List <MenuItemViewModel>(); var menuCached = CacheManager.Get(homePage.ContentLink.ID + Constant.CacheKeys.MenuItems) as List <MenuItemViewModel>; if (menuCached != null) { menuItems = menuCached; } else { var menuItemBlocks = homePage.MainMenu?.FilteredItems.GetContentItems <MenuItemBlock>() ?? new List <MenuItemBlock>(); menuItems = menuItemBlocks? .Select(_ => new MenuItemViewModel { Name = _.Name, ButtonText = _.ButtonText, TeaserText = _.TeaserText, Uri = _.Link == null ? string.Empty : _urlResolver.GetUrl(new UrlBuilder(_.Link.ToString()), new UrlResolverArguments() { ContextMode = ContextMode.Default }), ImageUrl = !ContentReference.IsNullOrEmpty(_.MenuImage) ? _urlResolver.GetUrl(_.MenuImage) : "", ButtonLink = _.ButtonLink?.Host + _.ButtonLink?.PathAndQuery, ChildLinks = _.ChildItems?.ToList() ?? new List <GroupLinkCollection>() }).ToList() ?? new List <MenuItemViewModel>(); var keyDependency = new List <string>(); keyDependency.Add(_contentCacheKeyCreator.CreateCommonCacheKey(homePage.ContentLink)); // If The HomePage updates menu (remove MenuItems) foreach (var m in menuItemBlocks) { keyDependency.Add(_contentCacheKeyCreator.CreateCommonCacheKey((m as IContent).ContentLink)); } var eviction = new CacheEvictionPolicy(TimeSpan.FromDays(1), CacheTimeoutType.Sliding, keyDependency); CacheManager.Insert(homePage.ContentLink.ID + Constant.CacheKeys.MenuItems, menuItems, eviction); } return(new T { HomePage = homePage, CurrentContentLink = currentContent?.ContentLink, CurrentContentGuid = currentContent?.ContentGuid ?? Guid.Empty, UserLinks = new LinkItemCollection(), Name = contact?.FirstName ?? "", IsBookmarked = isBookmarked, MenuItems = menuItems, LoginViewModel = new LoginViewModel { ResetPasswordPage = homePage.ResetPasswordPage }, RegisterAccountViewModel = new RegisterAccountViewModel { Address = new AddressModel() }, MobileNavigation = homePage.MobileNavigationPages, }); }
public void Set <TObj>(string key, TObj obj, TimeSpan timeSpan, CacheDurationType cacheDuration) { if (obj != null && !string.IsNullOrEmpty(key)) { var cacheEvictionPolicy = new CacheEvictionPolicy(timeSpan, _typeConveter[cacheDuration]); _syncronizedObjectInstanceCache.Insert(key, obj, cacheEvictionPolicy); _keyCache.Set(key, DateTime.Now.Add(timeSpan), timeSpan, cacheDuration); } }
public void Insert(string key, object value, TimeSpan timeToLive) { if (String.IsNullOrWhiteSpace(key)) { return; } var evictionPolicy = new CacheEvictionPolicy(timeToLive, CacheTimeoutType.Absolute); _log.Debug(evictionPolicy, ep => $"Key: {key}, Item: {value}, CacheKeys: {ep?.CacheKeys}, Type: {ep?.TimeoutType}, Seconds: {ep?.Expiration.Duration().TotalSeconds}"); _cacheManager.Insert(key, value, evictionPolicy); }
public IEnumerable <string> GetLocations() { CacheEvictionPolicy policy = new CacheEvictionPolicy(TimeSpan.FromMinutes(2), CacheTimeoutType.Absolute); if (!(CacheManager.Get(LocationsCacheKey) is List <string> items)) { items = LocationsFromService(); CacheManager.Insert(LocationsCacheKey, items, policy); } return(items); }
public THeaderViewModel CreateHeaderViewModel <THeaderViewModel>(IContent currentContent, CmsHomePage homePage) where THeaderViewModel : HeaderViewModel, new() { var menuItems = new List <MenuItemViewModel>(); var menuCached = CacheManager.Get(homePage.ContentLink.ID + MenuCacheKey) as List <MenuItemViewModel>; if (menuCached != null) { menuItems = menuCached; } else { var menuItemBlocks = homePage.MainMenu?.FilteredItems.GetContentItems <MenuItemBlock>(); menuItems = menuItemBlocks? .Select(_ => new MenuItemViewModel { Name = _.Name, ButtonText = _.ButtonText, TeaserText = _.TeaserText, Uri = _.Link == null ? string.Empty : _urlResolver.GetUrl(new UrlBuilder(_.Link.ToString()), new UrlResolverArguments() { ContextMode = ContextMode.Default }), ImageUrl = !ContentReference.IsNullOrEmpty(_.MenuImage) ? _urlResolver.GetUrl(_.MenuImage) : "", ButtonLink = _.ButtonLink?.Host + _.ButtonLink?.PathAndQuery, ChildLinks = _.ChildItems?.ToList() ?? new List <GroupLinkCollection>() }).ToList() ?? new List <MenuItemViewModel>(); var keyDependency = new List <string>(); keyDependency.Add(_contentCacheKeyCreator.CreateCommonCacheKey(homePage.ContentLink)); // If The HomePage updates menu (remove MenuItems) foreach (var m in menuItemBlocks) { keyDependency.Add(_contentCacheKeyCreator.CreateCommonCacheKey((m as IContent).ContentLink)); } var eviction = new CacheEvictionPolicy(TimeSpan.FromDays(1), CacheTimeoutType.Sliding, keyDependency); CacheManager.Insert(homePage.ContentLink.ID + MenuCacheKey, menuItems, eviction); } return(new THeaderViewModel { HomePage = homePage, CurrentContentLink = currentContent?.ContentLink, CurrentContentGuid = currentContent?.ContentGuid ?? Guid.Empty, UserLinks = new LinkItemCollection(), Name = PrincipalInfo.Current.Name, MenuItems = menuItems, MobileNavigation = homePage.MobileNavigationPages, }); }
private bool GetSitemapData(SitemapData sitemapData) { int entryCount; string userAgent = Request.ServerVariables["USER_AGENT"]; var isGoogleBot = userAgent != null && userAgent.IndexOf("Googlebot", StringComparison.InvariantCultureIgnoreCase) > -1; string googleBotCacheKey = isGoogleBot ? "Google-" : string.Empty; if (SitemapSettings.Instance.EnableRealtimeSitemap) { string cacheKey = googleBotCacheKey + _sitemapRepository.GetSitemapUrl(sitemapData); var sitemapDataData = CacheManager.Get(cacheKey) as byte[]; if (sitemapDataData != null) { sitemapData.Data = sitemapDataData; return(true); } if (_sitemapXmlGeneratorFactory.GetSitemapXmlGenerator(sitemapData).Generate(sitemapData, false, out entryCount)) { if (SitemapSettings.Instance.EnableRealtimeCaching) { CacheEvictionPolicy cachePolicy; if (isGoogleBot) { cachePolicy = new CacheEvictionPolicy(null, new[] { DataFactoryCache.VersionKey }, null, Cache.NoSlidingExpiration, CacheTimeoutType.Sliding); } else { cachePolicy = null; } CacheManager.Insert(cacheKey, sitemapData.Data, cachePolicy); } return(true); } return(false); } return(_sitemapXmlGeneratorFactory.GetSitemapXmlGenerator(sitemapData).Generate(sitemapData, !SitemapSettings.Instance.EnableRealtimeSitemap, out entryCount)); }
/// <summary> /// <summary>Inserts an item in the cache.</summary> /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="expiration"></param> /// <param name="cacheKeys">The dependencies to other cached items, idetified by their keys.</param> /// <param name="masterKeys">The master keys that we depend upon. Master keys are used as markers to set up common dependencies without having to create the cache entries first. ///If you set up a master key dependency, there is no need for the corresponding entry to exist before adding ///something that depends on the master key. /// The concept of master keys could be regarded as similar to the cache region concept, but using master keys ///allows you to have more than one, where cache regions is restricted to one per cached item - you can only ///place the item in one region. /// </param> public void Insert(string key, object value, TimeSpan expiration, List <string> cacheKeys, List <string> masterKeys) { if (value == null) { return; } if (masterKeys == null) { masterKeys = new List <string>(); } if (cacheKeys == null) { cacheKeys = new List <string>(); } CacheEvictionPolicy cacheEvictionPolicy; if (!cacheKeys.Any() && !masterKeys.Any()) { cacheEvictionPolicy = new CacheEvictionPolicy(expiration, CacheTimeoutType.Absolute); } else if (masterKeys.Any() && !cacheKeys.Any()) { cacheEvictionPolicy = new CacheEvictionPolicy(expiration, CacheTimeoutType.Absolute, null, masterKeys.Select(k => $"{_keyPrefixDependency}{k}")); } else if (!masterKeys.Any() && cacheKeys.Any()) { cacheEvictionPolicy = new CacheEvictionPolicy(expiration, CacheTimeoutType.Absolute, cacheKeys.Select(k => $"{_keyPrefixDependency}{k}")); } else if (masterKeys.Any() && cacheKeys.Any()) { cacheEvictionPolicy = new CacheEvictionPolicy(expiration, CacheTimeoutType.Absolute, cacheKeys.Select(k => $"{_keyPrefixDependency}{k}"), masterKeys.Select(k => $"{_keyPrefixDependency}{k}")); } else { cacheEvictionPolicy = new CacheEvictionPolicy(expiration, CacheTimeoutType.Absolute); } var internalKey = _cacheKeyPrefix + key; _cacheManager.Insert(internalKey, value, cacheEvictionPolicy); }
private bool GetSitemapData(SitemapData sitemapData) { int entryCount; string userAgent = Request.ServerVariables["USER_AGENT"]; var isGoogleBot = userAgent != null && userAgent.IndexOf("Googlebot", StringComparison.InvariantCultureIgnoreCase) > -1; string googleBotCacheKey = isGoogleBot ? "Google-" : string.Empty; if (SitemapSettings.Instance.EnableRealtimeSitemap) { string cacheKey = googleBotCacheKey + _sitemapRepository.GetSitemapUrl(sitemapData); var sitemapDataData = CacheManager.Get(cacheKey) as byte[]; if (sitemapDataData != null) { sitemapData.Data = sitemapDataData; return true; } if (_sitemapXmlGeneratorFactory.GetSitemapXmlGenerator(sitemapData).Generate(sitemapData, false, out entryCount)) { if (SitemapSettings.Instance.EnableRealtimeCaching) { CacheEvictionPolicy cachePolicy; if (isGoogleBot) { cachePolicy = new CacheEvictionPolicy(null, new[] {DataFactoryCache.VersionKey}, null, Cache.NoSlidingExpiration, CacheTimeoutType.Sliding); } else { cachePolicy = null; } CacheManager.Insert(cacheKey, sitemapData.Data, cachePolicy); } return true; } return false; } return _sitemapXmlGeneratorFactory.GetSitemapXmlGenerator(sitemapData).Generate(sitemapData, !SitemapSettings.Instance.EnableRealtimeSitemap, out entryCount); }
/// <summary> /// Creates a new in-memory cache /// </summary> /// <param name="cacheSize">The maximum size of the cache in bytes</param> /// <param name="cacheEvictionPolicy">The eviction policy to use to maintain the cache size</param> /// <param name="highwaterMark">The cache size (in bytes) that will trigger the cache eviction policy to run</param> /// <param name="lowwaterMark">The cache size (in bytes) that the eviction policy will attempt to achieve when it is run</param> public MemoryCache(long cacheSize, ICacheEvictionPolicy cacheEvictionPolicy, long highwaterMark = 0, long lowwaterMark = 0) : base(cacheSize, cacheEvictionPolicy, highwaterMark, lowwaterMark) { _cache = new ConcurrentDictionary <string, MemoryCacheEntry>(); CacheEvictionPolicy.Initialize(this); }
/* * Each of the following simply returns the result of the default Episerver cache methods. * But illustrates how much can be overridden if, for example, you wanted to use a distributed cache provider. */ public void Insert(string key, object value, CacheEvictionPolicy evictionPolicy) => _defaultCache.Insert(key, value, evictionPolicy);
public THeaderViewModel CreateHeaderViewModel <THeaderViewModel>(IContent currentContent, CmsHomePage homePage) where THeaderViewModel : HeaderViewModel, new() { var menuItems = new List <MenuItemViewModel>(); var homeLanguage = homePage.Language.DisplayName; menuItems = homePage.MainMenu?.FilteredItems.Select(x => { var itemCached = CacheManager.Get(x.ContentLink.ID + homeLanguage + ":" + MenuCacheKey) as MenuItemViewModel; if (itemCached != null && !PageEditing.PageIsInEditMode) { return(itemCached); } else { var content = _contentLoader.Get <IContent>(x.ContentLink); MenuItemBlock _; MenuItemViewModel menuItem; if (content is MenuItemBlock) { _ = content as MenuItemBlock; menuItem = new MenuItemViewModel { Name = _.Name, ButtonText = _.ButtonText, TeaserText = _.TeaserText, Uri = _.Link == null ? string.Empty : _urlResolver.GetUrl(new UrlBuilder(_.Link.ToString()), new UrlResolverArguments() { ContextMode = ContextMode.Default }), ImageUrl = !ContentReference.IsNullOrEmpty(_.MenuImage) ? _urlResolver.GetUrl(_.MenuImage) : "", ButtonLink = _.ButtonLink?.Host + _.ButtonLink?.PathAndQuery, ChildLinks = _.ChildItems?.ToList() ?? new List <GroupLinkCollection>() }; } else { menuItem = new MenuItemViewModel { Name = content.Name, Uri = _urlResolver.GetUrl(content.ContentLink), ChildLinks = new List <GroupLinkCollection>() }; } if (!PageEditing.PageIsInEditMode) { var keyDependency = new List <string> { _contentCacheKeyCreator.CreateCommonCacheKey(homePage.ContentLink), // If The HomePage updates menu (remove MenuItems) _contentCacheKeyCreator.CreateCommonCacheKey(x.ContentLink) }; var eviction = new CacheEvictionPolicy(TimeSpan.FromDays(1), CacheTimeoutType.Sliding, keyDependency); CacheManager.Insert(x.ContentLink.ID + homeLanguage + ":" + MenuCacheKey, menuItem, eviction); } return(menuItem); } }).ToList(); return(new THeaderViewModel { HomePage = homePage, CurrentContentLink = currentContent?.ContentLink, CurrentContentGuid = currentContent?.ContentGuid ?? Guid.Empty, UserLinks = new LinkItemCollection(), Name = PrincipalInfo.Current.Name, MenuItems = menuItems, IsReadonlyMode = _databaseMode.DatabaseMode == DatabaseMode.ReadOnly }); }
protected virtual T CreateViewModel <T>(IContent currentContent, CommerceHomePage homePage, Customer.FoundationContact contact, bool isBookmarked) where T : CommerceHeaderViewModel, new() { var menuItems = new List <MenuItemViewModel>(); var homeLanguage = homePage.Language.DisplayName; menuItems = homePage.MainMenu?.FilteredItems.Select(x => { var itemCached = CacheManager.Get(x.ContentLink.ID + homeLanguage + ":" + Constant.CacheKeys.MenuItems) as MenuItemViewModel; if (itemCached != null && !PageEditing.PageIsInEditMode) { return(itemCached); } else { var content = _contentLoader.Get <IContent>(x.ContentLink); MenuItemBlock _; MenuItemViewModel menuItem; if (content is MenuItemBlock) { _ = content as MenuItemBlock; menuItem = new MenuItemViewModel { Name = _.Name, ButtonText = _.ButtonText, TeaserText = _.TeaserText, Uri = _.Link == null ? string.Empty : _urlResolver.GetUrl(new UrlBuilder(_.Link.ToString()), new UrlResolverArguments() { ContextMode = ContextMode.Default }), ImageUrl = !ContentReference.IsNullOrEmpty(_.MenuImage) ? _urlResolver.GetUrl(_.MenuImage) : "", ButtonLink = _.ButtonLink?.Host + _.ButtonLink?.PathAndQuery, ChildLinks = _.ChildItems?.ToList() ?? new List <GroupLinkCollection>() }; } else { menuItem = new MenuItemViewModel { Name = content.Name, Uri = _urlResolver.GetUrl(content.ContentLink), ChildLinks = new List <GroupLinkCollection>() }; } if (!PageEditing.PageIsInEditMode) { var keyDependency = new List <string>(); keyDependency.Add(_contentCacheKeyCreator.CreateCommonCacheKey(homePage.ContentLink)); // If The HomePage updates menu (remove MenuItems) keyDependency.Add(_contentCacheKeyCreator.CreateCommonCacheKey(x.ContentLink)); var eviction = new CacheEvictionPolicy(TimeSpan.FromDays(1), CacheTimeoutType.Sliding, keyDependency); CacheManager.Insert(x.ContentLink.ID + homeLanguage + ":" + Constant.CacheKeys.MenuItems, menuItem, eviction); } return(menuItem); } }).ToList(); return(new T { HomePage = homePage, CurrentContentLink = currentContent?.ContentLink, CurrentContentGuid = currentContent?.ContentGuid ?? Guid.Empty, UserLinks = new LinkItemCollection(), Name = contact?.FirstName ?? "", IsBookmarked = isBookmarked, IsReadonlyMode = _databaseMode.DatabaseMode == DatabaseMode.ReadOnly, MenuItems = menuItems ?? new List <MenuItemViewModel>(), LoginViewModel = new LoginViewModel { ResetPasswordPage = homePage.ResetPasswordPage }, RegisterAccountViewModel = new RegisterAccountViewModel { Address = new AddressModel() }, }); }