예제 #1
0
        protected override Exceptional<ObjectLocator> StoreObjectLocator_protected(ObjectLocator myObjectLocator, CachePriority myCachePriority = CachePriority.LOW)
        {
            if (_ObjectLocatorLRUList.ULongCount() >= _Capacity)
            {

                // Remove oldest LinkedListNode from LRUList and add new ObjectLocator to the ObjectCache
                OnItemDiscarded(new DiscardEventArgs(myObjectLocator.ObjectLocation));

                //_ObjectLocatorCache.Remove(_ObjectLocatorLRUList.First.Value.ObjectLocation);

                var __ObjectLocation = _ObjectLocatorLRUList.First.Value.ObjectLocation;

                if (__ObjectLocation == ObjectLocation.Root)
                {
                    var _ObjectLocatorNode = _ObjectLocatorLRUList.First();
                    _ObjectLocatorLRUList.RemoveFirst();
                    _ObjectLocatorLRUList.AddLast(_ObjectLocatorNode);
                }

                __ObjectLocation = _ObjectLocatorLRUList.First.Value.ObjectLocation;
                RemoveObjectLocation(__ObjectLocation);

            }

            return new Exceptional<ObjectLocator>(myObjectLocator);
        }
        IPageDefinition IPageDefinition.Cache(string cacheCategory, CachePriority cachePriority)
        {
            _page.CacheCategory = cacheCategory;
            _page.CachePriority = cachePriority;

            return(this);
        }
예제 #3
0
        /// <summary>
        /// Implemented in derived classes to add a new entry to the cache
        /// </summary>
        /// <param name="key">The key for the new entry</param>
        /// <param name="data">The data for the new entry</param>
        /// <param name="cachePriority">The entry priority</param>
        /// <returns>The newly created cache entry</returns>
        protected override AbstractCacheEntry AddEntry(string key, byte[] data, CachePriority cachePriority)
        {
            var entry = new MemoryCacheEntry(key, data, cachePriority);

            _cache.AddOrUpdate(key, entry, (k, e) => entry);
            return(entry);
        }
예제 #4
0
        /// <summary>
        /// Cache item with given Func&lt;object>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="cacheFunction"></param>
        /// <param name="interval"></param>
        /// <param name="dependencies"></param>
        /// <param name="priority"></param>
        /// <param name="removalCallback"></param>
        /// <param name="settings"></param>
        /// <returns></returns>
        public virtual T CacheItem <T>(string key, Func <object> cacheFunction, double interval = 30, ICacheDependency dependencies = null,
                                       CachePriority priority = CachePriority.Default, Action <string, object, CacheRemovalReason> removalCallback = null, ICacheSettings settings = null)
        {
            if (cacheFunction == null)
            {
                return(default(T));
            }

            settings = settings ?? Settings;
            bool cacheEnabled = settings.Enabled;

            // Handle Structs
            if (_ReflectionHelper.IsValueType(typeof(T)))
            {
                // Boxing needed to avoid nullable checks on structs
                object o           = GetCrossPlatformCacheData(key);
                T      cachedValue = default(T);

                if (o != null)
                {
                    cachedValue = (T)o;
                }

                // !EnableCache allows previewing to disable per user
                if (!cacheEnabled || o == null)
                {
                    cachedValue = (T)cacheFunction();

                    if (cacheEnabled && interval > 0)
                    {
                        SetCrossPlatformCache(key, cachedValue, interval, dependencies, priority, removalCallback);
                    }
                }

                return(cachedValue);
            }

            // Handle Classes
            var cachedData = GetCrossPlatformCacheData(key);

            // !EnableCache allows previewing to disable per user
            if (!cacheEnabled || cachedData == null)
            {
                cachedData = cacheFunction();

                // If cached data is bad, store for a minute.
                if (cachedData == null)
                {
                    interval   = 60;
                    cachedData = new NullData();
                }

                if (cacheEnabled && interval > 0)
                {
                    SetCrossPlatformCache(key, cachedData, interval, dependencies, priority, removalCallback);
                }
            }

            return((cachedData is NullData) ? default(T) : (T)cachedData);
        }
예제 #5
0
 public MemoryCacheEntry(string key, byte[] data, CachePriority priority)
 {
     Key      = key;
     Size     = data.Length;
     Priority = priority;
     _bytes   = data;
 }
예제 #6
0
        /// <summary>
        /// Adds an object to the cache
        /// </summary>
        /// <param name="key">The cache key for the object</param>
        /// <param name="o">The object to be stored. Must be serializable.</param>
        /// <param name="cachePriority">The priority of the item in the cache</param>
        public void Insert(string key, object o, CachePriority cachePriority)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            if (o == null)
            {
                throw new ArgumentNullException("o");
            }
            byte[] buff;
            if (o is IBinarySerializable)
            {
                using (var ms = new MemoryStream())
                {
                    (o as IBinarySerializable).Save(ms);
                    ms.Close();
                    buff = ms.GetBuffer();
                }
            }
            else
            {
                buff = Serialize(o);
            }

            if (buff != null)
            {
                Insert(key, buff, cachePriority);
            }
        }
예제 #7
0
 public MemoryCacheEntry(string key, byte[] data, CachePriority priority)
 {
     Key = key;
     Size = data.Length;
     Priority = priority;
     _bytes = data;
 }
예제 #8
0
        public AssetCache(float lasttime, Object ob, CachePriority priority)
        {
            lastUseTime   = lasttime;
            obj           = ob;
            cachePriority = priority;
            switch (priority)
            {
            case CachePriority.NoCache:
                cacheDelayTime = 0;
                break;

            case CachePriority.ShortTime:
                cacheDelayTime = 30;
                break;

            case CachePriority.MiddleTime:
                cacheDelayTime = 100;
                break;

            case CachePriority.LongTime:
                cacheDelayTime = 200;
                break;

            case CachePriority.Persistent:
                cacheDelayTime = 0;
                break;
            }
        }
예제 #9
0
        public void Add <T>(string key, T value, CachePriority priority, int timeout, bool slidingExpiration, bool addRefreshDependency)
        {
            if (Equals(value, default(T)))
            {
                return;
            }

            CacheItemPriority cacheItemPriority = TranslateCachePriority(priority);

            DateTime absoluteExpiration;
            TimeSpan slidingExpirationTimeSpan;

            if (slidingExpiration)
            {
                absoluteExpiration        = Cache.NoAbsoluteExpiration;
                slidingExpirationTimeSpan = new TimeSpan(0, timeout, 0);
            }
            else
            {
                absoluteExpiration        = DateTime.Now.AddMinutes(timeout);
                slidingExpirationTimeSpan = Cache.NoSlidingExpiration;
            }

            CacheDependency dependency = null;

            if (addRefreshDependency)
            {
                dependency = new WebCacheRefreshDependency();
            }

            HttpContext.Current.Cache.Insert(key, value, dependency, absoluteExpiration, slidingExpirationTimeSpan, cacheItemPriority, null);
        }
예제 #10
0
        /// <summary>
        /// 对缓存优先级做一个默认的转换
        /// </summary>
        /// <param name="priority">原始的优先级</param>
        /// <returns>目标优先级</returns>
        private CacheItemPriority CacheItemPriorityConvert(CachePriority priority)
        {
            var p = CacheItemPriority.Default;

            switch (priority)
            {
            case CachePriority.Low:
            {
                p = CacheItemPriority.Low;
                break;
            }

            case CachePriority.Normal:
            {
                p = CacheItemPriority.Normal;
                break;
            }

            case CachePriority.High:
            {
                p = CacheItemPriority.High;
                break;
            }

            case CachePriority.NotRemovable:
            {
                p = CacheItemPriority.NotRemovable;
                break;
            }
            }
            return(p);
        }
예제 #11
0
 public DirectoryCacheEntry(FileInfo fileInfo, CachePriority priority)
 {
     _fileInfo = fileInfo;
     Key       = fileInfo.Name;
     Priority  = priority;
     Size      = fileInfo.Length;
 }
예제 #12
0
        public static void ConfirmCachePriority(XmlElement xmlElem,
                                                string name, CachePriority priority, bool compulsory)
        {
            XmlNode xmlNode;

            xmlNode = XMLReader.GetNode(xmlElem, name);
            if (xmlNode == null && compulsory == true)
            {
                throw new ConfigNotFoundException(name);
            }
            else if (xmlNode != null)
            {
                if (xmlNode.InnerText == "DEFAULT")
                {
                    Assert.AreEqual(CachePriority.DEFAULT, priority);
                }
                else if (xmlNode.InnerText == "HIGH")
                {
                    Assert.AreEqual(CachePriority.HIGH, priority);
                }
                else if (xmlNode.InnerText == "LOW")
                {
                    Assert.AreEqual(CachePriority.LOW, priority);
                }
                else if (xmlNode.InnerText == "VERY_HIGH")
                {
                    Assert.AreEqual(CachePriority.VERY_HIGH, priority);
                }
                else if (xmlNode.InnerText == "VERY_LOW")
                {
                    Assert.AreEqual(CachePriority.VERY_LOW, priority);
                }
            }
        }
예제 #13
0
        public void SetCachePriority(CachePriority priority)
        {
            cachePriority = priority;
            switch (priority)
            {
            case CachePriority.NoCache:
                cacheDelayTime = 0;
                break;

            case CachePriority.ShortTime:
                cacheDelayTime = 30;
                break;

            case CachePriority.MiddleTime:
                cacheDelayTime = 100;
                break;

            case CachePriority.LongTime:
                cacheDelayTime = 200;
                break;

            case CachePriority.Persistent:
                cacheDelayTime = 0;
                break;
            }
        }
예제 #14
0
 public DirectoryCacheEntry(FileInfo fileInfo, CachePriority priority)
 {
     _fileInfo = fileInfo;
     Key = fileInfo.Name;
     Priority = priority;
     Size = fileInfo.Length;
 }
예제 #15
0
        /// <summary>
        /// Adds a new item to the cache
        /// </summary>
        /// <param name="key">The cache key for the item. Must not be null</param>
        /// <param name="data">The data to be stored as a byte array. Must not be null</param>
        /// <param name="cachePriority">The priority of the item in the cache</param>
        public void Insert(string key, byte[] data, CachePriority cachePriority)
        {
            if (key == null)
            {
                throw new ArgumentNullException("key");
            }
            if (data == null)
            {
                throw new ArgumentNullException("data");
            }
            Remove(key);
            if (CacheSize + data.Length > _highwaterMark)
            {
                CacheEvictionPolicy.Run(this, CacheSize - _lowwaterMark);
                if (CacheSize + data.Length > _cacheMaxSize)
                {
                    // If even after cache eviction there is not enough space, return without caching the object
                    return;
                }
            }
            var newEntry = AddEntry(key, data, cachePriority);

            if (newEntry != null)
            {
                CacheEvictionPolicy.NotifyInsert(key, data.Length, cachePriority);
                lock (_cacheLock)
                {
                    CacheSize += newEntry.Size;
                }
            }
        }
예제 #16
0
 /// <summary>
 /// 添加缓存
 /// </summary>
 /// <param name="key">关键字</param>
 /// <param name="value">缓存值</param>
 /// <param name="priority">优先级</param>
 /// <param name="absoluteExpiration">过期时间</param>
 public void Add <T>(string key, T value, CachePriority priority, DateTime absoluteExpiration)
 {
     if (this._enable)
     {
         HttpRuntime.Cache.Insert(key, value, null, absoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriorityConvert(priority), null);
     }
     return;
 }
예제 #17
0
        /// <summary>
        /// Adding an item to memcached
        /// </summary>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        /// <param name="duration"></param>
        /// <param name="priority"></param>
        /// <returns></returns>
        public Response <T> AddToCache(string key, T obj, int duration, CachePriority priority)
        {
            try
            {
                var newPolicy = new CacheItemPolicy();

                logger.Info("Add key : " + RegionName + key);
                logger.Info("Total keys : " + MemoryCache.Default.GetCount(null));
                logger.Info("Physical limits : " + MemoryCache.Default.PhysicalMemoryLimit);
                //logger.Info("Polling interval : " + MemoryCache.Default.PollingInterval);
                //logger.Info("Cache mem limit : " + MemoryCache.Default.CacheMemoryLimit);
                //logger.Info("Default capacities: " + MemoryCache.Default.DefaultCacheCapabilities);
                //logger.Info("Default sliding: " + defaultPolicy.SlidingExpiration);

                //if (priority == CachePriority.Low)
                //{
                //    newPolicy.Priority = CacheItemPriority.Default;
                //}

                //if (priority == CachePriority.High)
                //{
                //    newPolicy.Priority = CacheItemPriority.NotRemovable;
                //}

                if (duration != 0)
                {
                    newPolicy.SlidingExpiration = new TimeSpan(10000000 * (long)duration);
                }

                if (MemoryCache.Default.Contains(RegionName + key))
                {
                    logger.Info("[Memcache] Key is already existed : key : " + RegionName + key);
                    MemoryCache.Default.Remove(RegionName + key, null);
                }


                var isSuccess = MemoryCache.Default.Add(RegionName + key, obj, newPolicy, null);

                if (isSuccess)
                {
                    logger.Info("Total keys after add : " + MemoryCache.Default.GetCount(null));
                    // logger.Info("Total keys after add : " + MemoryCache.Default.Get);
                    return(new Response <T>(1, "added", obj));
                }

                else
                {
                    return(new Response <T>(-1, "adding item failed", null));
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex);
            }


            return(new Response <T>(0, "item is exist", null));
        }
예제 #18
0
        public IEnumerable <T> GetAll <T>(String Key, Func <T[]> alternative, CachePriority priority = CachePriority.Default)
        {
            var cached = Get(Key);

            if (cached == null)
            {
                Set(Key, alternative.Invoke(), priority);
            }
            return(((T[])Get(Key)).ToList());
        }
예제 #19
0
        public MixedCache(string name, CacheSettings settings)
        {
            _weakReferenceCache    = new WeakRefCache <string, TValue>(name, settings.Size);
            _defaultPriority       = settings.DefaultPriority;
            _slidingExpirationTime = settings.SlidingExpritationPeriod;

            _aspNetCachePrefix = "MixedCache" + Name;

            _useAspNetCacheByDefault = _defaultPriority != CachePriority.WeakReference &&
                                       _defaultPriority != CachePriority.Undefined;
        }
예제 #20
0
        public CacheItemMetaData(CachePriority priority, long expire)
        {
            this.expire = expire;

            this.lastUpdated = DateTime.Now.Ticks;

            this.Hittimes = 0;

            this.priority = priority;

            this.discription = new Dictionary<string, string>();
        }
예제 #21
0
        public void AddToDataCache(String cacheKeyName, Object cacheItem, CachePriority cacheItemPriority, List <String> filePath)
        {
            removalCallback = new CacheEntryRemovedCallback(this.CacheItemRemovedCallback);
            policy          = new CacheItemPolicy();
            policy.Priority = (cacheItemPriority == CachePriority.Default) ? CacheItemPriority.Default : CacheItemPriority.NotRemovable;

            //policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(10.00);
            policy.RemovedCallback = removalCallback;
            policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePath));

            // Add the Item cache
            cache.Set(cacheKeyName, cacheItem, policy);
        }
예제 #22
0
 /// <summary>
 /// AddToCache
 /// T타입을 사용하기 위해서, 메소드 오버라이딩 추가함
 /// 2013.10.15 박정환
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="CacheKeyName"></param>
 /// <param name="value"></param>
 /// <param name="MyCacheItemPriority"></param>
 public void AddToCache <T>(string CacheKeyName, T value, CachePriority MyCacheItemPriority)
 {
     //Type type = typeof(T);
     callback = new CacheEntryRemovedCallback(this.CachedItemRemovedCallback);
     policy   = new CacheItemPolicy
     {
         Priority           = (MyCacheItemPriority == CachePriority.Default) ? CacheItemPriority.Default : CacheItemPriority.NotRemovable,
         AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(60.00),
         RemovedCallback    = callback
     };
     // Add inside cache
     cache.Set(CacheKeyName, value, policy);
 }
예제 #23
0
        public void AddToMyCache(String CacheKeyName, Object CacheItem, CachePriority CacheItemPriority, double CacheExpirationSeconds)
        {
            callbackWrapper = new CacheEntryRemovedCallback(this.CacheWrapperCallback);
            policy          = new CacheItemPolicy
            {
                Priority           = (System.Runtime.Caching.CacheItemPriority)CacheItemPriority,
                AbsoluteExpiration = DateTime.Now.AddSeconds(CacheExpirationSeconds),
                RemovedCallback    = callbackWrapper
            };
            //policy.ChangeMonitors.Add(new HostFileChangeMonitor(FilePath));

            cache.Set(CacheKeyName, CacheItem, policy);
        }
예제 #24
0
        private static CacheItemPriority TranslateCachePriority(CachePriority priority)
        {
            switch (priority)
            {
            case CachePriority.High:
                return(CacheItemPriority.High);

            case CachePriority.Medium:
                return(CacheItemPriority.Normal);

            default:
                return(CacheItemPriority.Low);
            }
        }
예제 #25
0
        /// <summary>
        /// Converts cache priority to implementations priority
        /// </summary>
        /// <param name="priority"></param>
        /// <returns></returns>
        protected virtual CacheItemPriority ConvertPriority(CachePriority priority)
        {
            switch (priority)
            {
            case CachePriority.NotRemovable:
                return(CacheItemPriority.NotRemovable);

            case CachePriority.Low:
            case CachePriority.High:
            case CachePriority.Default:
            default:
                return(CacheItemPriority.Default);
            }
        }
예제 #26
0
        /// <summary>
        /// 캐쉬를 파일에 쓰는 설정
        /// </summary>
        /// <param name="CacheKeyName"></param>
        /// <param name="CacheItem"></param>
        /// <param name="MyCacheItemPriority"></param>
        /// <param name="FilePath"></param>
        public void AddToCache(string CacheKeyName, object CacheItem, CachePriority MyCacheItemPriority, List <string> FilePath)
        {
            //
            callback = new CacheEntryRemovedCallback(this.CachedItemRemovedCallback);
            policy   = new CacheItemPolicy
            {
                Priority           = (MyCacheItemPriority == CachePriority.Default) ? CacheItemPriority.Default : CacheItemPriority.NotRemovable,
                AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(60.00),
                RemovedCallback    = callback
            };
            policy.ChangeMonitors.Add(new HostFileChangeMonitor(FilePath));

            // Add inside cache
            cache.Set(CacheKeyName, CacheItem, policy);
        }
예제 #27
0
        /// <summary>
        /// Cross platform cache set/add/insert
        /// </summary>
        /// <param name="key"></param>
        /// <param name="cachedValue"></param>
        /// <param name="interval"></param>
        /// <param name="dependencies"></param>
        /// <param name="priority"></param>
        /// <param name="removalCallback"></param>
        /// <param name="settings"></param>
        protected virtual void SetCrossPlatformCache(string key, object cachedValue, double interval = 30, ICacheDependency dependencies = null,
                                                     CachePriority priority = CachePriority.Default, Action <string, object, CacheRemovalReason> removalCallback = null, ICacheSettings settings = null)
        {
#if NET35
            HttpRuntime.Cache.Insert(key, cachedValue, ConvertDependency(dependencies), DateTime.UtcNow.AddSeconds(interval), Cache.NoSlidingExpiration,
                                     ConvertPriority(priority), (cKey, cData, reason) => removalCallback?.Invoke(cKey, cData, ConvertRemovedReason(reason)));
#elif NET40 || NET45
            CacheItemPolicy policy = new CacheItemPolicy();
            policy.Priority           = ConvertPriority(priority);
            policy.AbsoluteExpiration = DateTime.UtcNow.AddSeconds(interval);
            policy.RemovedCallback    = (args) => removalCallback?.Invoke(args.CacheItem?.Key, args?.CacheItem.Value, ConvertRemovedReason(args.RemovedReason));

            if (dependencies?.FileNames?.Any() == true)
            {
                policy.ChangeMonitors.Add(new HostFileChangeMonitor(dependencies?.FileNames.ToList()));
            }

            if (dependencies?.CacheKeys?.Any() == true)
            {
                policy.ChangeMonitors.Add(MemoryCache.Default.CreateCacheEntryChangeMonitor(dependencies?.CacheKeys.ToList()));
            }

            MemoryCache.Default.Set(key, cachedValue, policy);
#elif NETSTANDARD1_3
            // store in the cache
            _MemoryCache.Set
            (
                key,
                cachedValue,
                new MemoryCacheEntryOptions()
            {
                Priority           = ConvertPriority(priority),
                AbsoluteExpiration = DateTime.UtcNow.AddSeconds(interval)
            }
                .RegisterPostEvictionCallback((key2, value, reason, state) => PostEvictionDelegateWrapper(key2, value, reason, state, removalCallback))
            );

            //todo: how to handle cache dependencies?
            if (dependencies != null)
            {
                throw new NotSupportedException("ICacheDependencies not supported in netcore at this time!");
            }

            StandardCacheHelper.CacheKeys.TryAdd(key, key); // track independently of memory cache
#endif
        }
        /// <summary>
        /// Add an item to the cache with the designated cache priority
        /// </summary>
        /// <param name="cacheKeyName"></param>
        /// <param name="cacheItem"></param>
        /// <param name="cacheItemPriority"></param>
        /// <param name="filePath"></param>
        public void AddToCache(String cacheKeyName, Object cacheItem, CachePriority cacheItemPriority, List <String> filePath)
        {
            _callback = CachedItemRemovedCallback;
            _policy   = new CacheItemPolicy
            {
                Priority           = (cacheItemPriority == CachePriority.Default) ? CacheItemPriority.Default : CacheItemPriority.NotRemovable,
                AbsoluteExpiration = DateTimeOffset.Now.AddYears(1),
                RemovedCallback    = _callback
            };

            if (filePath != null && filePath.Any())
            {
                _policy.ChangeMonitors.Add(new HostFileChangeMonitor(filePath));
            }

            // Add inside cache
            Cache.Set(cacheKeyName, cacheItem, _policy);
        }
예제 #29
0
        public static bool ConfigCachePriority(XmlElement xmlElem,
                                               string name, ref CachePriority cachePriority, bool compulsory)
        {
            XmlNode xmlNode;
            string  priority;

            xmlNode = XMLReader.GetNode(xmlElem, name);
            if (xmlNode == null && compulsory == false)
            {
                return(false);
            }
            else if (xmlNode == null && compulsory == true)
            {
                throw new ConfigNotFoundException(name);
            }

            priority = xmlNode.InnerText;
            if (priority == "DEFAULT")
            {
                cachePriority = CachePriority.DEFAULT;
            }
            else if (priority == "HIGH")
            {
                cachePriority = CachePriority.HIGH;
            }
            else if (priority == "LOW")
            {
                cachePriority = CachePriority.LOW;
            }
            else if (priority == "VERY_HIGH")
            {
                cachePriority = CachePriority.VERY_HIGH;
            }
            else if (priority == "VERY_LOW")
            {
                cachePriority = CachePriority.VERY_LOW;
            }
            else
            {
                throw new InvalidConfigException(name);
            }

            return(true);
        }
        /// <summary>
        /// Tracks cache inserts
        /// </summary>
        /// <param name="insertedKey">The inserted key</param>
        /// <param name="size">The size (in bytes) of the inserted value</param>
        /// <param name="priority">The priority assigned to the inserted cache item</param>
        public void NotifyInsert(string insertedKey, long size, CachePriority priority)
        {
            ConcurrentDictionary <string, TimestampedCacheEntry> queue = null;

            switch (priority)
            {
            case CachePriority.Normal:
                queue = _normalPriorityEntries;
                break;

            case CachePriority.High:
                queue = _highPriorityEntries;
                break;
            }
            if (queue != null)
            {
                queue[insertedKey] = new TimestampedCacheEntry(insertedKey);
            }
        }
예제 #31
0
        public void Add(string key, TValue value, CachePriority cachePriority)
        {
            _weakReferenceCache.Add(key, value);

            if (cachePriority == CachePriority.WeakReference ||
                cachePriority == CachePriority.Undefined)
            {
                return;
            }

            CacheItemPriority aspNetCachePriority;

            switch (cachePriority)
            {
            case CachePriority.Low:
                aspNetCachePriority = CacheItemPriority.Low;
                break;

            case CachePriority.High:
                aspNetCachePriority = CacheItemPriority.High;
                break;

            case CachePriority.NeverExpires:
                aspNetCachePriority = CacheItemPriority.NotRemovable;
                break;

            default:
                aspNetCachePriority = CacheItemPriority.Default;
                break;
            }


            string aspNetKey = GetAspNetKey(key);

            HttpRuntime.Cache.Add(aspNetKey,
                                  value,
                                  null,
                                  DateTime.MaxValue,
                                  _slidingExpirationTime,
                                  aspNetCachePriority,
                                  null);
        }
예제 #32
0
 public void Add(IPersistable p, CachePriority priority = CachePriority.Normal)
 {
     //switch (priority)
     //{
     //    case CachePriority.Normal:
     //        _lowPriorityItems.Add(p);
     //        break;
     //    case CachePriority.High:
     //        _highPriorityItems.Add(p);
     //        break;
     //}
     try
     {
         _lowPriorityItems.Add(p);
     } catch(Exception ex)
     {
         Logging.LogWarning(BrightstarEventId.CachingError, "Encountered an error when adding object {0} to cache. Cause: {1}",
             p.ObjectId, ex);
     }
 }
예제 #33
0
 public void Add(IPersistable p, CachePriority priority = CachePriority.Normal)
 {
     //switch (priority)
     //{
     //    case CachePriority.Normal:
     //        _lowPriorityItems.Add(p);
     //        break;
     //    case CachePriority.High:
     //        _highPriorityItems.Add(p);
     //        break;
     //}
     try
     {
         _lowPriorityItems.Add(p);
     } catch (Exception ex)
     {
         Logging.LogWarning(BrightstarEventId.CachingError, "Encountered an error when adding object {0} to cache. Cause: {1}",
                            p.ObjectId, ex);
     }
 }
예제 #34
0
        public static void Add(string key, object value, CachePriority priority, DateTime?absoluteExpiration, TimeSpan?slidingExpiration)
        {
            CacheItemPriority p = (CacheItemPriority)Enum.Parse(typeof(CacheItemPriority), priority.ToString());

            if (absoluteExpiration != null & slidingExpiration != null)
            {
                CacheManagerInstance.Add(key, value, p, null, new AbsoluteTime(absoluteExpiration.Value), new SlidingTime(slidingExpiration.Value));
            }
            else if (absoluteExpiration != null)
            {
                CacheManagerInstance.Add(key, value, p, null, new AbsoluteTime(absoluteExpiration.Value));
            }
            else if (slidingExpiration != null)
            {
                CacheManagerInstance.Add(key, value, p, null, new SlidingTime(slidingExpiration.Value));
            }
            else
            {
                CacheManagerInstance.Add(key, value, p, null);
            }
        }
예제 #35
0
 public CacheItemPriority ConvertPriority(CachePriority p)
 {
     switch(p)
     {
     case CachePriority.AboveNormal:
         return CacheItemPriority.AboveNormal;
     case CachePriority.BelowNormal:
         return CacheItemPriority.BelowNormal;
     case CachePriority.Default:
         return CacheItemPriority.Default;
     case CachePriority.High:
         return CacheItemPriority.High;
     case CachePriority.Low:
         return CacheItemPriority.Low;
     case CachePriority.Normal:
         return CacheItemPriority.Normal;
     case CachePriority.NotRemovable:
         return CacheItemPriority.NotRemovable;
     default:
         return CacheItemPriority.Default;
     }
 }
예제 #36
0
        public void Set(String Key, Object Item, CachePriority cacheItemPriority, Action <CacheEntryRemovedArguments> callback = null, double Minutes = 10.00)
        {
            //
            var _Policy = new CacheItemPolicy {
                Priority = (cacheItemPriority == CachePriority.Default)
                    ? CacheItemPriority.Default
                    : CacheItemPriority.NotRemovable,
                AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(Minutes)
            };

            if (callback != null)
            {
                _Policy.RemovedCallback = new CacheEntryRemovedCallback(callback);
            }

            _Lock.EnterWriteLock();
            try {
                _Cache.Set(Key, Item, _Policy);
            }
            finally {
                _Lock.ExitWriteLock();
            }
        }
예제 #37
0
 /// <summary>
 /// Adds a key/value pair to the cache.
 /// </summary>
 /// <param name="key">The cache key.</param>
 /// <param name="value">The cached value.</param>
 /// <param name="priority">The cached item priority.</param>
 public void Add(string key, object value, CachePriority priority)
 {
     Add(key, value, Cache.NoAbsoluteExpiration, priority);
 }
예제 #38
0
        private static CacheItemPriority ConvertCachePriority(CachePriority priority)
        {
            CacheItemPriority cachedItemPriority;

            switch (priority)
            {
                case CachePriority.Low:
                    cachedItemPriority = CacheItemPriority.Low;
                    break;
                case CachePriority.High:
                    cachedItemPriority = CacheItemPriority.High;
                    break;
                default:
                    cachedItemPriority = CacheItemPriority.Normal;
                    break;
            }

            return cachedItemPriority;
        }
예제 #39
0
        /// <summary>
        /// Adds a key/value pair to the cache.
        /// </summary>
        /// <param name="key">The cache key.</param>
        /// <param name="value">The cached value.</param>
        /// <param name="slidingExpiration">A <see cref="TimeSpan"/> representing a sliding expiration time.</param>
        /// <param name="priority">The cached item priority.</param>
        public virtual void Add(string key, object value, TimeSpan slidingExpiration, CachePriority priority)
        {
            if (String.IsNullOrEmpty(key))
            {
                throw new ArgumentNullException("key");
            }

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

            m_cache.Add(key, value, null, Cache.NoAbsoluteExpiration, slidingExpiration, ConvertCachePriority(priority), null);
        }
예제 #40
0
 public CacheItemMetaData(CachePriority priority)
     : this(priority, long.MaxValue)
 {
 }
예제 #41
0
 /// <summary>
 /// Implemented in derived classes to add a new entry to the cache
 /// </summary>
 /// <param name="key">The key for the new entry</param>
 /// <param name="data">The data for the new entry</param>
 /// <param name="cachePriority">The entry priority</param>
 /// <returns>The newly created cache entry</returns>
 protected override AbstractCacheEntry AddEntry(string key, byte[] data, CachePriority cachePriority)
 {
     var entry = new MemoryCacheEntry(key, data, cachePriority);
     _cache.AddOrUpdate(key, entry, (k, e) => entry);
     return entry;
 }
예제 #42
0
        protected override Exceptional<AFSObject> StoreAFSObject_protected(AFSObject myAFSObject, CacheUUID myCacheUUID, CachePriority myCachePriority = CachePriority.LOW)
        {
            Debug.Assert(myCacheUUID                        != null);

            return new Exceptional<AFSObject>();
        }
예제 #43
0
        /// <summary>
        /// Implemented in derived classes to add a new entry to the cache
        /// </summary>
        /// <param name="key">The key for the new entry</param>
        /// <param name="data">The data for the new entry</param>
        /// <param name="cachePriority">The entry priority</param>
        /// <returns>The newly created cache entry</returns>
        protected override AbstractCacheEntry AddEntry(string key, byte[] data, CachePriority cachePriority)
        {
            try
            {
                var fileName = KeyToFileName(key);
                var dir = cachePriority == CachePriority.High ? _highDir : _normalDir;
                var cacheFilePath = Path.Combine(dir.FullName, fileName);
#if SILVERLIGHT
                using(var w = File.OpenWrite(cacheFilePath))
                {
                    w.Write(data, 0, data.Length);
                    w.Flush(true);
                    w.Close();
                }
#else
                File.WriteAllBytes(cacheFilePath, data);
#endif
                return new DirectoryCacheEntry(new FileInfo(cacheFilePath), cachePriority);
            }
            catch (Exception)
            {
                return null;
            }
        }
예제 #44
0
파일: CacheInfo.cs 프로젝트: Earlz/lucidmvc
 //provide a second overload so that people uninterested in priority don't have to specify CachePriorty.Default
 public CacheInfo(TimeSpan? absolute=null, TimeSpan? sliding=null, CachePriority priority=CachePriority.Default)
 {
     AbsoluteExpirationFromNow=absolute;
     SlidingExpiration=sliding;
     Priority=priority;
 }