public object Get(string key, Type type) { ICacheItem item = GetCacheItem(key); if (item != null) { IPolicy policy = GetPolicy(type); if (policy != null && !policy.IsAvailable(item)) { item = null; } } if (item == null) { object data = DBManager.Get(key, type); if (data != null) { item = new implement.CacheItem { CreateTime = DateTime.Now, Data = data, Key = key }; } if (item != null) { mLevelCacheds[mLevelCacheds.Count - 1].Set(item); return(item.Data); } } return(null); }
public void CreateNewCacheItem_NewValue_ValueIsUpdated() { int newValue = _value + 7; ICacheItem <int> newCacheItem = _cacheItem.CreateNewCacheItem(newValue); Assert.AreEqual(newValue, newCacheItem.Value); }
public void Upgrade(ICacheItem item, ILevelCached levelcached) { if (levelcached.LevelValue > 0) { mLevelCacheds[levelcached.LevelValue - 1].Set(item); } }
private bool IsCurrent(ICacheItem <KursnaListaZaDan> item) { var today = DateTime.Now.Date; var datum = item.Value.Datum.Date; if (datum == today) { return(true); } if (today.DayOfWeek == DayOfWeek.Saturday && datum == today.AddDays(-1)) { return(true); } if (today.DayOfWeek == DayOfWeek.Sunday && datum == today.AddDays(-2)) { return(true); } if (DateTime.Now.Hour < 8 && datum == today.AddDays(-1)) { return(true); } return(false); }
public void UnRegister(ICacheItem item) { if (item != null && m_CacheItems.Contains(item)) { m_CacheItems.Remove(item); } }
/// <summary> /// Gets the item expiration. /// </summary> /// <param name="item">The item.</param> /// <returns>Returns the updated cache item.</returns> /// <exception cref="System.ArgumentNullException">If item is null.</exception> /// <exception cref="System.InvalidOperationException"> /// If expiration mode is defined without timeout. /// </exception> protected virtual ICacheItem <TKey, TValue> GetItemExpiration(ICacheItem <TKey, TValue> item) { NotNull(item, nameof(item)); // logic should be that the item setting overrules the handle setting if the item // doesn't define a mode (value is Default) it should use the handle's setting. if the // handle also doesn't define a mode (value is None|Default), we use None. var expirationMode = ExpirationMode.Default; var expirationTimeout = TimeSpan.Zero; var useItemExpiration = item.ExpirationMode != ExpirationMode.Default && !item.UsesExpirationDefaults; if (useItemExpiration) { expirationMode = item.ExpirationMode; expirationTimeout = item.ExpirationTimeout; } else if (Configuration.ExpirationMode != ExpirationMode.Default) { expirationMode = Configuration.ExpirationMode; expirationTimeout = Configuration.ExpirationTimeout; } if (expirationMode == ExpirationMode.Default || expirationMode == ExpirationMode.None) { expirationMode = ExpirationMode.None; expirationTimeout = TimeSpan.Zero; } else if (expirationTimeout == TimeSpan.Zero) { throw new InvalidOperationException("Expiration mode is defined without timeout."); } return(item.WithExpiration(expirationMode, expirationTimeout, !useItemExpiration)); }
void ICacheStorage.Set(int index, ICacheItem value) { if (this.RemotingIsReady()) { this.RemotingObject.Set(index, @value); } }
void ICacheStorage.Set(string key, ICacheItem value) { if (this.RemotingIsReady()) { this.RemotingObject.Set(key, @value); } }
private async Task <string> GetPageContent(string url) { IWebRequestHelper webRequestHelper = ServiceLocator.Current.GetInstance <IWebRequestHelper>(); IWebCache webCache = ServiceLocator.Current.GetInstance <IWebCache>(); ICacheItem cacheItem = await webCache.Get(url, TimeSpan.FromDays(CacheDurationDays), k => { return(webRequestHelper.GetDataAsync(url, null, null, 30000, null, new Dictionary <HttpRequestHeader, string> { { HttpRequestHeader.Accept, "application/json" } })); }); if (cacheItem == null) { return(null); } if (cacheItem.Data == null) { return(null); } return(cacheItem.GetUTF8()); }
private void OnConfigurableFileChanged(ICacheItem item, bool dirty) { if (dirty) { var fileCacheItem = item as IFileCacheItem; if (fileCacheItem == null) { return; } IInstanceInfo instanceInfo = null; IConfigurableFileInfo configurableFileInfo = null; foreach (var objectName in ObjectMappings.ToArray().Where(x => string.Equals(x.Value.Path, fileCacheItem.Path)).Select(x => x.Key)) { RegisterInstances.TryRemove(objectName, out instanceInfo); ObjectMappings.TryRemove(objectName, out configurableFileInfo); } if (configurableFileInfo != null) { RegisterConfigurableFile(configurableFileInfo); } } }
public void Set <T>(ICacheItem <T> item) { var serializedItem = new SerializedCacheItem <T>(item); _cache.Set(item.Key, serializedItem, DateTimeOffset.FromFileTime(item.ExpirationTime.ToFileTime())); _keys.Add(item.Key); }
public CacheItem(ICacheItem <T> entry) { Key = entry.Key; Value = entry.Value; Expiration = entry.Expiration; ExpirationTime = entry.ExpirationTime; }
private void AddToHandles(ICacheItem <TKey, TValue> item, int foundIndex) { if (_logTrace) { Logger.LogTrace($"Start updating handles with [{item}]."); } if (foundIndex == 0) { return; } // update all cache handles with lower order, up the list for (var handleIndex = 0; handleIndex < _cacheHandles.Length; handleIndex++) { if (handleIndex < foundIndex) { if (_logTrace) { Logger.LogTrace("Updating handles, added [{0}] to handle '{1}'.", item, _cacheHandles[handleIndex].Configuration.Name); } _cacheHandles[handleIndex].Add(item); } } }
private Dictionary <string, ICacheItem> Load(Stream s) { Dictionary <string, ICacheItem> table = new Dictionary <string, ICacheItem>(); int itemCount = UtilityMethods.ReadInt32(s); for (int i = 0; i < itemCount; i++) { try { string key = UtilityMethods.ReadString(s); ICacheItem val = persister.Read(s); if (val == null) // corrupt cache file { return(table); } table[key] = val; } catch (IOException) { return(table); } } return(table); }
/// <summary> /// Will raise the collection changed event. /// </summary> /// <param name="action">The action that is being performed.</param> /// <param name="newOrChangedItem">The new, changed or deleted item.</param> /// <param name="oldItem">If an item is being replaced, this is the original item.</param> protected void RaiseCollectionChangedEvent(System.Collections.Specialized.NotifyCollectionChangedAction action, ICacheItem <ICacheProcessorItem> newOrChangedItem, ICacheItem <ICacheProcessorItem> oldItem) { var handler = CollectionChanged; if (handler != null) { if (action == System.Collections.Specialized.NotifyCollectionChangedAction.Reset) { handler(this, new System.Collections.Specialized.NotifyCollectionChangedEventArgs(action)); } else if (action == System.Collections.Specialized.NotifyCollectionChangedAction.Replace) { handler(this, new System.Collections.Specialized.NotifyCollectionChangedEventArgs(action, newOrChangedItem, oldItem)); } else if (action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove) { handler(this, new System.Collections.Specialized.NotifyCollectionChangedEventArgs(action, oldItem)); } else { handler(this, new System.Collections.Specialized.NotifyCollectionChangedEventArgs(action, newOrChangedItem)); } } }
public static async Task <T> GetOrAdd <T>(this ICacheItem <T> self, ICacheItemLock lockObj, Func <Task <T> > getProc, bool continueOnCapturedContext = false) { var cacheValue = await self.Get().ConfigureAwait(continueOnCapturedContext); if (cacheValue.HasValue) { return(cacheValue.Value); } await lockObj.Acquire().ConfigureAwait(continueOnCapturedContext);; try { cacheValue = await self.Get().ConfigureAwait(continueOnCapturedContext); if (cacheValue.HasValue) { return(cacheValue.Value); } var value = await getProc().ConfigureAwait(continueOnCapturedContext); await self.Set(value).ConfigureAwait(continueOnCapturedContext); return(value); } finally { await lockObj.Release().ConfigureAwait(continueOnCapturedContext); } }
void ICache.Add(ICacheItem item) { Assert.IsTrue(item != null); Assert.IsTrue(item.Key != null); Assert.IsTrue(item.SlidingExpiration > TimeSpan.Zero); Assert.IsTrue(!this.keyIndex.ContainsKey(item.Key)); CacheEntry entry; lock (this.entries) { Assert.IsTrue(!this.keyIndex.ContainsKey(item.Key)); entry = new CacheEntry { CacheItem = item, AbsoluteExpiration = LocalTime2.Default.Now + item.SlidingExpiration }; this.entries.Add(entry); } object value = item.GetValue(); entry.Value = value; entry.Initialized = true; }
/// <summary> /// Tells if an object exists in cache /// </summary> /// <param name="keys">a string[] of keys</param> public static bool Contains(string mainKey, params string[] keys) { // create a new cache item object from factory based on expiration and keys ICacheItem item = CacheItemFactory.Item(mainKey, keys); return(MemoryCacheAccess.Current.Contains(item)); }
/// <summary> /// Retrieves a specified cache entry. /// </summary> /// <param name="key">The cache key used to reference the item.</param> /// <returns>The item retrieved from the cache. If the value of the key parameter is not found, returns null.</returns> public ICacheItem<T> this[string key] { get { if (string.IsNullOrWhiteSpace(key)) { throw new ArgumentNullException(nameof(key)); } ICacheItem<T> item = null; if (_InternalCache.ContainsKey(key)) { item = _InternalCache[key]; } return item; } set { if (string.IsNullOrWhiteSpace(key)) { throw new ArgumentNullException(nameof(key)); } if (!_InternalCache.ContainsKey(key)) { throw new IndexOutOfRangeException($"The specified key cannot be found. Key={key}"); } var oldValue = _InternalCache[key]; _InternalCache[key] = value; RaiseCollectionChangedEvent(System.Collections.Specialized.NotifyCollectionChangedAction.Replace, value, oldValue); } }
/// <summary> /// Gets the specified cache entry from the cache as a <see cref="Ptc.MediaHub.Cache.MethodCacheItem" /> instance. /// </summary> /// <param name="key">A unique identifier for the cache entry to get.</param> /// <returns> /// A reference to the cache entry that is identified by key, if the entry exists; otherwise, null. /// </returns> /// <exception cref="NotImplementedException"></exception> public ICacheItem Get(string key) { if (key == null) { throw new ArgumentNullException("key"); } try { if (IsCacheInitilized()) { ICacheItem cacheItem = this.cache.Get <ICacheItem>(key); if (cacheItem != null) { Trace.TraceInformation("Redis Cache Provider: Cache item retrieved (cache hit) for key {0}. Correlation Id = {1}", key, Trace.CorrelationManager.ActivityId); return(cacheItem); } else { Trace.TraceInformation("Redis Cache Provider: Cache item NULL (cache miss) for key {0}. Correlation Id = {1}", key, Trace.CorrelationManager.ActivityId); } } } catch (Exception ex) { Trace.TraceError("Redis Cache Provider: Error retrieving key {0}. Correlation Id = {1}\n Exception Message = {2} \n {3}", key, Trace.CorrelationManager.ActivityId, ex.Message, ex.StackTrace); } return(null); }
public static object ShowPropertyData( [ExcelArgument(Name = "ObjectHandle", Description = "Handle to an object.")] string h, [ExcelArgument(Name = "[Property]", Description = "Name of the property being retrieved.")] object p) { object res = ExcelError.ExcelErrorNA; if (_cache.ContainsKey(h)) { ICacheItem handle = _cache.Lookup(h) as CacheItem; if (!(p is ExcelMissing)) { res = handle.Get(p.ToString()); } else { res = handle.Get(); } if (handle.Exception != null) { res = handle.Exception.Message; } } return(res); }
public SerializedCacheItem(ICacheItem <T> entry) { Key = entry.Key; SerializedValue = JsonConvert.SerializeObject(entry.Value); Expiration = entry.Expiration; ExpirationTime = entry.ExpirationTime; }
public void Setup() { _now = new DateTime(2012, 8, 20); _dateTimeProviderMock = new Mock <IDateTimeProvider>(MockBehavior.Strict); _value = 7; _cacheItem = CreateCacheItem(); }
public void Set(ICacheItem data) { lock (this) { data.UpgradeValue = UpgradeValue; data.Reset(); data.LevelCached = Name; LinkedListNode <ICacheItem> item = null; mItemTable.TryGetValue(data.Key, out item); if (item != null) { item.Value = data; } else { if (mItemTable.Count >= Maximum) { LinkedListNode <ICacheItem> lastItem = mItemLink.Last; if (lastItem != null) { mItemLink.Remove(lastItem); mItemTable.Remove(lastItem.Value.Key); } } item = mItemLink.AddFirst(data); mItemTable[data.Key] = item; } } }
public ICacheItem Get(string key) { ICacheItem result = null; LinkedListNode <ICacheItem> item = null; mItemTable.TryGetValue(key, out item); if (item != null) { result = item.Value; result.Increment(); if (LevelValue > 0 && result.Upgrade() && UpgradeHandler != null) { OnUpgrade(item); } else { lock (this) { if (item.List == mItemLink) { mItemLink.Remove(item); mItemLink.AddFirst(item); } } } } return(result); }
private bool TryGetOrAddInternal(TKey key, TValue value, out ICacheItem <TKey, TValue> item) { ICacheItem <TKey, TValue> newItem = null; var tries = 0; do { tries++; item = GetCacheItemInternal(key); if (item != null) { return(true); } // changed logic to invoke the factory only once in case of retries if (newItem == null) { newItem = CreateCacheItem(key, value); } if (AddInternal(newItem)) { item = newItem; return(true); } }while (tries <= Configuration.MaxRetries); return(false); }
public void Set(ICacheItem data) { lock (this) { data.UpgradeValue = UpgradeValue; data.Reset(); data.LevelCached = Name; LinkedListNode<ICacheItem> item = null; mItemTable.TryGetValue(data.Key, out item); if (item != null) { item.Value = data; } else { if (mItemTable.Count >= Maximum) { LinkedListNode<ICacheItem> lastItem = mItemLink.Last; if (lastItem != null) { mItemLink.Remove(lastItem); mItemTable.Remove(lastItem.Value.Key); } } item = mItemLink.AddFirst(data); mItemTable[data.Key] = item; } } }
/// <summary> /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="absoluteExpiration"></param> /// <returns> /// <c>true</c> if insertion succeeded, or <c>false</c> if there is an already an entry in the cache that has the same key as key. /// </returns> /// <exception cref="NotImplementedException"></exception> public bool Add(string key, ICacheItem value, DateTimeOffset absoluteExpiration) { if (key == null) { throw new ArgumentNullException("key"); } try { if (IsCacheInitilized()) { TimeSpan expiration = absoluteExpiration.Subtract(DateTimeOffset.UtcNow); this.cache.SetAsync(key, value, expiration); double expirationInSeconds = Math.Ceiling(expiration.TotalSeconds); Trace.TraceInformation("Redis Cache Provider: Requested to add asyn key {0} for {1} secounds. Correlation Id = {2}", key, expirationInSeconds, Trace.CorrelationManager.ActivityId); return(true); } else { Trace.TraceWarning("Redis Cache Provider: Cache still not initilized when trying to add the key {0}. Correlation Id = {1}", key, Trace.CorrelationManager.ActivityId); } } catch (Exception ex) { Trace.TraceError("Redis Cache Provider: Error inserting cache item. Key={0}, Correlation Id = {2}.\n Exception Message {3}\n{4}", key, Trace.CorrelationManager.ActivityId, ex.Message, ex.StackTrace); } return(false); }
private Hashtable Load(Stream s) { Hashtable table = new Hashtable(); int itemCount = Utils.ReadInt32(s); for (int i = 0; i < itemCount; i++) { try { string key = Utils.ReadString(s); ICacheItem val = persister.Read(s); if (val == null) // corrupt cache file { return(table); } table[key] = val; } catch (IOException) { return(table); } } return(table); }
public void CacheHitTest() { if (Directory.Exists(Flickr.CacheLocation)) { Directory.Delete(Flickr.CacheLocation, true); } Flickr f = Instance; Flickr.FlushCache(); f.InstanceCacheDisabled = false; f.PeopleGetPublicPhotos(TestData.TestUserId); string lastUrl = f.LastRequest; ICacheItem item = Cache.Responses.Get(lastUrl, TimeSpan.MaxValue, false); Assert.IsNotNull(item, "Cache should now contain the item."); Assert.IsInstanceOf <ResponseCacheItem>(item); var response = item as ResponseCacheItem; Assert.IsNotNull(response.Url, "Url should not be null."); Assert.AreEqual(lastUrl, response.Url.AbsoluteUri, "Url should match the url requested from the cache."); }
public AppointmentMeasureGroup(Rect rect, Panel panel, ICacheItem <UIElement> expandButton) { Rect = rect; this.panel = panel; this.expandButton = expandButton; currentOffset = headerHeight; }
public override void Write(Stream outputStream, ICacheItem cacheItem) { ResponseCacheItem responseCacheItem = (ResponseCacheItem) cacheItem; StringBuilder stringBuilder = new StringBuilder(); stringBuilder.Append(responseCacheItem.Url.AbsoluteUri + "\n"); stringBuilder.Append(responseCacheItem.CreationTime.Ticks.ToString((IFormatProvider) NumberFormatInfo.InvariantInfo)); UtilityMethods.WriteString(outputStream, ((object) stringBuilder).ToString()); UtilityMethods.WriteString(outputStream, responseCacheItem.Response); }
/// <summary> /// 触发缓存改变事件。 /// </summary> /// <param name="type"></param> /// <param name="item"></param> protected void OnCacheChanged(CacheChangedType type, ICacheItem item) { CacheChangedEventArgs e = new CacheChangedEventArgs(); e.ChangedType = type; if (item != null) { e.Item = item; e.ItemKey = item.ItemKey; } this.OnCacheChanged(e); }
private ICacheItem InternalSet(string key, ICacheItem value) { if (key == null) throw new ArgumentNullException("key"); ICacheItem cacheItem = this.RemoveKey(key); if (value != null) this.dataTable[key] = value; this.dirty = this.dirty || !object.ReferenceEquals((object) cacheItem, (object) value); return cacheItem; }
public override void Write(Stream outputStream, ICacheItem cacheItem) { var item = (ResponseCacheItem)cacheItem; var result = new StringBuilder(); result.Append(item.Url.AbsoluteUri + "\n"); result.Append(item.CreationTime.Ticks.ToString(System.Globalization.NumberFormatInfo.InvariantInfo)); UtilityMethods.WriteString(outputStream, result.ToString()); UtilityMethods.WriteString(outputStream, item.Response); }
/// <returns>The old value associated with <c>key</c>, if any.</returns> private ICacheItem InternalSet(string key, ICacheItem value) { if (key == null) throw new ArgumentNullException("key"); ICacheItem flushedItem; flushedItem = RemoveKey(key); if (value != null) // don't ever let nulls get in dataTable[key] = value; dirty = dirty || !object.ReferenceEquals(flushedItem, value); return flushedItem; }
public override void Write(Stream outputStream, ICacheItem cacheItem) { ResponseCacheItem item = (ResponseCacheItem) cacheItem; StringBuilder result = new StringBuilder(); result.Append(item.Url + "\n"); result.Append(item.CreationTime.Ticks.ToString("0")); Utils.WriteString(outputStream, result.ToString()); Utils.WriteString(outputStream, item.Response); }
public override void Write(Stream outputStream, ICacheItem cacheItem) { PictureCacheItem pci = (PictureCacheItem) cacheItem; StringBuilder output = new StringBuilder(); output.Append(pci.url + "\n"); output.Append(pci.creationTime.Ticks + "\n"); output.Append(pci.filename + "\n"); output.Append(pci.fileSize + "\n"); Utils.WriteString(outputStream, output.ToString()); }
/// <summary> /// Adds the specified key. /// </summary> /// <param name="key">The key.</param> /// <param name="value">The value.</param> /// <param name="redisAbsoluteExpiration">The redis absolute expiration.</param> /// <param name="memoryAbsoluteExpiration">The memory absolute expiration.</param> /// <returns></returns> public bool Add(string key, ICacheItem value, DateTimeOffset redisAbsoluteExpiration, DateTimeOffset memoryAbsoluteExpiration) { //Ignore the memory expiration since we don't use memory cache in azure return Add(key, value, redisAbsoluteExpiration); }
/// <summary> /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="absoluteExpiration"></param> /// <returns> /// <c>true</c> if insertion succeeded, or <c>false</c> if there is an already an entry in the cache that has the same key as key. /// </returns> /// <exception cref="NotImplementedException"></exception> public bool Add(string key, ICacheItem value, DateTimeOffset absoluteExpiration) { if (key == null) throw new ArgumentNullException("key"); try { if (IsCacheInitilized()) { TimeSpan expiration = absoluteExpiration.Subtract(DateTimeOffset.UtcNow); this.cache.SetAsync(key, value, expiration); double expirationInSeconds = Math.Ceiling(expiration.TotalSeconds); Trace.TraceInformation("Redis Cache Provider: Requested to add asyn key {0} for {1} secounds. Correlation Id = {2}", key, expirationInSeconds, Trace.CorrelationManager.ActivityId); return true; } else { Trace.TraceWarning("Redis Cache Provider: Cache still not initilized when trying to add the key {0}. Correlation Id = {1}", key, Trace.CorrelationManager.ActivityId); } } catch (Exception ex) { Trace.TraceError("Redis Cache Provider: Error inserting cache item. Key={0}, Correlation Id = {2}.\n Exception Message {3}\n{4}", key, Trace.CorrelationManager.ActivityId, ex.Message, ex.StackTrace); } return false; }
public abstract void Write(Stream outputStream, ICacheItem cacheItem);
/// <summary> /// 添加一项到存储器中 /// </summary> /// <param name="key">存储项的健值</param> /// <param name="value">存储的对象</param> /// <remarks> /// 如果存在相同的健值,则更新存储的对象 /// </remarks> void ICacheStorage.Add(string key, ICacheItem value) { this.CacheStorage.Add(key, value); }
/// <summary> /// 添加缓存。 /// </summary> /// <param name="item">缓存项。</param> /// <returns>缓存键。</returns> public string AddCache(ICacheItem item) { if (item == null) { return null; } if (cache.ContainsKey(item.ItemKey)) { cache[item.ItemKey].RefreshItem(DateTime.Now); } else { cache[item.ItemKey] = item; item.CacheItemChanged += new CacheItemChangedEventHandler(delegate(CacheItemChangedEventArgs e) { if ((e.ChangedType == CacheChangedType.Access) && ItemQueue.Contains(e.CacheItemKey)) { int index = ItemQueue.IndexOf(e.CacheItemKey); SortHelper.MoveItemToEnd<string>(ItemQueue, index); this.OnCacheChanged(CacheChangedType.Access, cache[e.CacheItemKey]); } }); if (item.ItemSize > 0) { CurrentSize += item.ItemSize / 1024 / 1024; } if (CurrentSize >= CacheMaxSize) { startCheckWorker(); } this.OnCacheChanged(CacheChangedType.Added, item); } if (!ItemQueue.Contains(item.ItemKey)) { ItemQueue.Add(item.ItemKey); } return item.ItemKey; }
/// <summary> /// 设置存储项 /// </summary> /// <param name="index">存储项的索引值</param> /// <param name="value">存储的对象</param> /// <remarks> /// 仅针对存在存储项,若不存在,则不进行任何操作 /// </remarks> void ICacheStorage.Set(int index, ICacheItem value) { this.CacheStorage.Set(index, value); }