Exemplo n.º 1
0
        /// <summary>
        /// Changes the expiration <paramref name="mode" /> and <paramref name="timeout" /> for the
        /// given <paramref name="key" />.
        /// </summary>
        /// <param name="key">The cache key.</param>
        /// <param name="mode">The expiration mode.</param>
        /// <param name="timeout">The expiration timeout.</param>
        public override void Expire(string key, ExpirationMode mode, TimeSpan timeout)
        {
            this.CheckDisposed();
            var item = this.GetCacheItem(key);

            if (item == null)
            {
                this.Logger.LogTrace("Expire: item not found for key {0}", key);
                return;
            }

            if (mode == ExpirationMode.Absolute)
            {
                item = item.WithAbsoluteExpiration(timeout);
            }
            else if (mode == ExpirationMode.Sliding)
            {
                item = item.WithSlidingExpiration(timeout);
            }
            else if (mode == ExpirationMode.None)
            {
                item = item.WithNoExpiration();
            }
            else if (mode == ExpirationMode.Default)
            {
                item = item.WithDefaultExpiration();
            }

            item = GetItemExpiration(item);

            this.PutInternalPrepared(item);
        }
Exemplo n.º 2
0
        public async Task ExpireAsync(string key, ExpirationMode mode, TimeSpan timeout)
        {
            if (string.IsNullOrWhiteSpace(key))
            {
                throw new ArgumentNullException(nameof(key));
            }
            switch (mode)
            {
            case ExpirationMode.Absolute:
                await _cache.KeyExpireAsync(key, DateTime.Now.AddSeconds(timeout.TotalSeconds));

                break;

            case ExpirationMode.Default:
                await _cache.KeyExpireAsync(key, DateTime.Now.AddSeconds(timeout.TotalSeconds));

                break;

            case ExpirationMode.None:
                await _cache.KeyExpireAsync(key, DateTime.Now.AddDays(365));

                break;

            case ExpirationMode.Sliding:
                await _cache.KeyExpireAsync(key, timeout);

                break;
            }
        }
Exemplo n.º 3
0
        public void Put(string key, TCacheValue value, ExpiredMode mode, TimeSpan timespan)
        {
            ExpirationMode          expiretionMode = CacheUtility.ConvertFromCustomExpiredMode(mode);
            CacheItem <TCacheValue> item           = new CacheItem <TCacheValue>(key, value, expiretionMode, timespan);

            cacheManger.Put(item);
        }
Exemplo n.º 4
0
        private ICacheManager <T> GetCacheManager(string cacheName, ExpirationMode expirationMode, TimeSpan timeout)
        {
            lock (obj)
            {
                var cache = CacheFactory.Build <T>(cacheName,
                                                   settings =>
                {
                    settings
                    .WithSystemRuntimeCacheHandle(instanceName)
                    .EnableStatistics()
                    .EnablePerformanceCounters()
                    .WithExpiration(expirationMode, timeout);
                });

                if (!cacheManagerDict.Keys.Contains(cacheName))
                {
                    cacheManagerDict.Add(cacheName, cache);
                    return(cache);
                }
                else
                {
                    return(cacheManagerDict[cacheName]);
                }
            }
        }
Exemplo n.º 5
0
        public Task ExpireAsync <T>(string key, ExpirationMode expirationMode, TimeSpan timeout)
        {
            var cacheManager = GetCacheManager <T>();

            cacheManager.Expire(key, _region, expirationMode, timeout);

            return(Task.Run(() => { }));
        }
 public ExpirationCalculation(DateTimeOffset initail, TimeSpan slidingSize, DateTimeOffset maxExpireDate)
 {
     IsNegativeSlidingSize(slidingSize);
     createDate         = DateTimeOffset.Now;
     this.slidingSize   = slidingSize;
     this.initail       = initail;
     this.maxExpireDate = maxExpireDate;
     expireInfo         = new Effective(initail);
     mode = ExpirationMode.Sliding;
 }
 public ExpirationCalculation(DateTimeOffset initail)
 {
     maxCount      = 0;
     createDate    = DateTime.Now;
     slidingSize   = TimeSpan.Zero;
     this.initail  = initail;
     maxExpireDate = initail;
     expireInfo    = new Effective(initail);
     mode          = ExpirationMode.Absolute;
 }
Exemplo n.º 8
0
 public void Expire(string key, string region, ExpirationMode expirationMode, TimeSpan timeout)
 {
     try
     {
         cacheManager.Expire(key, region, expirationMode, timeout);
     }
     catch (Exception ex)
     {
         throw ex;
     }
 }
        /// <summary>
        /// Sets the expiration mode and timeout of the cache handle.
        /// </summary>
        /// <param name="expirationMode">The expiration mode.</param>
        /// <param name="timeout">The timeout.</param>
        /// <returns>The builder part.</returns>
        /// <exception cref="System.InvalidOperationException">
        /// If expiration mode is not set to 'None', timeout cannot be zero.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// Thrown if expiration mode is not 'None' and timeout is zero.
        /// </exception>
        /// <seealso cref="ExpirationMode"/>
        public ConfigurationBuilderCacheHandlePart WithExpiration(ExpirationMode expirationMode, TimeSpan timeout)
        {
            if (expirationMode != ExpirationMode.None && timeout == TimeSpan.Zero)
            {
                throw new InvalidOperationException("If expiration mode is not set to 'None', timeout cannot be zero.");
            }

            this.Configuration.ExpirationMode    = expirationMode;
            this.Configuration.ExpirationTimeout = timeout;
            return(this);
        }
 public ExpirationCalculation(DateTimeOffset initail, TimeSpan slidingSize, uint maxCount = 0)
 {
     IsNegativeSlidingSize(slidingSize);
     this.maxCount    = maxCount;
     createDate       = DateTime.Now;
     this.slidingSize = slidingSize;
     this.initail     = initail;
     maxExpireDate    = maxCount != 0 ? initail.Add(new TimeSpan(slidingSize.Ticks * maxCount)) : maxExpireDate;
     expireInfo       = new Effective(initail);
     mode             = ExpirationMode.Sliding;
 }
Exemplo n.º 11
0
        /// <summary>
        /// Sets the expiration mode and timeout of the cache handle.
        /// </summary>
        /// <param name="expirationMode">The expiration mode.</param>
        /// <param name="timeout">The timeout.</param>
        /// <returns>The builder part.</returns>
        /// <exception cref="System.InvalidOperationException">
        /// If expiration mode is not set to 'None', timeout cannot be zero.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// Thrown if expiration mode is not 'None' and timeout is zero.
        /// </exception>
        /// <seealso cref="ExpirationMode"/>
        public ConfigurationBuilderCacheHandlePart WithExpiration(ExpirationMode expirationMode, TimeSpan timeout)
        {
            // fixed #192 (was missing check for "Default" mode)
            if (expirationMode != ExpirationMode.None && expirationMode != ExpirationMode.Default && timeout == TimeSpan.Zero)
            {
                throw new InvalidOperationException("If expiration mode is not set to 'None', timeout cannot be zero.");
            }

            Configuration.ExpirationMode    = expirationMode;
            Configuration.ExpirationTimeout = timeout;
            return(this);
        }
Exemplo n.º 12
0
 public void Add(string key, TValue value, ExpirationMode expiration, TimeSpan timeout)
 {
     Remove(key);
     if (timeout != TimeSpan.Zero)
     {
         var cacheItem = new CacheItem <TValue>(key, value, expiration, timeout);
         _cacheManager.Add(cacheItem);
     }
     else
     {
         _cacheManager.Add(key, value);
     }
 }
Exemplo n.º 13
0
        /// <summary>
        /// Changes the expiration <paramref name="mode" /> and <paramref name="timeout" /> for the
        /// given <paramref name="key" />.
        /// </summary>
        /// <param name="key">The cache key.</param>
        /// <param name="region">The cache region.</param>
        /// <param name="mode">The expiration mode.</param>
        /// <param name="timeout">The expiration timeout.</param>
        public override void Expire(string key, string region, ExpirationMode mode, TimeSpan timeout)
        {
            this.CheckDisposed();
            var item = this.GetCacheItem(key, region);

            if (item == null)
            {
                this.Logger.LogTrace("Expire: item not found for key {0}:{1}", key, region);
                return;
            }

            this.PutInternalPrepared(item.WithExpiration(mode, timeout));
        }
        public static LazyCacheEntryOptions SetAbsoluteExpiration(this LazyCacheEntryOptions option, TimeSpan absoluteExpiration,
                                                                  ExpirationMode mode)
        {
            if (option == null)
            {
                throw new ArgumentNullException(nameof(option));
            }

            option.AbsoluteExpirationRelativeToNow = absoluteExpiration;
            option.ExpirationMode = mode;
            option.ImmediateAbsoluteExpirationRelativeToNow = absoluteExpiration;
            return(option);
        }
Exemplo n.º 15
0
        public void CacheItem_Ctor3_NullValue()
        {
            // arrange
            string         key     = "key";
            object         value   = null;
            ExpirationMode mode    = 0;
            TimeSpan       timeout = default(TimeSpan);

            // act
            Action act = () => new CacheItem <object>(key, value, mode, timeout);

            // assert
            act.ShouldThrow <ArgumentException>().WithMessage("*cannot be null.\r\nParameter name: value");
        }
Exemplo n.º 16
0
 public MemoryCacheImpl(string cacheName, ExpirationMode expirationMode, TimeSpan timeout)
 {
     if (MemoryCacheImpl <T> .cacheManagerDict != null)
     {
         if (cacheManagerDict.ContainsKey(cacheName))
         {
             cacheManager = cacheManagerDict[cacheName];
         }
         else
         {
             cacheManager = GetCacheManager(cacheName, expirationMode, timeout);
         }
     }
 }
Exemplo n.º 17
0
        public void CacheItemValidation_Ctor3_EmptyKey()
        {
            // arrange
            var            key     = string.Empty;
            object         value   = null;
            ExpirationMode mode    = 0;
            TimeSpan       timeout = default(TimeSpan);

            // act
            Action act = () => new CacheItem <object>(key, value, mode, timeout);

            // assert
            act.Should().Throw <ArgumentException>().WithMessage("*Parameter name: key");
        }
Exemplo n.º 18
0
        public void CacheItem_Ctor3_WhitespaceKey()
        {
            // arrange
            string         key     = "    ";
            object         value   = null;
            ExpirationMode mode    = 0;
            TimeSpan       timeout = default(TimeSpan);

            // act
            Action act = () => new CacheItem <object>(key, value, mode, timeout);

            // assert
            act.ShouldThrow <ArgumentException>().WithMessage("*Parameter name: key");
        }
Exemplo n.º 19
0
        public void CacheItem_Ctor4_EmptyKey()
        {
            // arrange
            var            key     = string.Empty;
            object         value   = null;
            string         region  = null;
            ExpirationMode mode    = ExpirationMode.None;
            TimeSpan       timeout = default(TimeSpan);

            // act
            Action act = () => new CacheItem <object>(key, value, region, mode, timeout);

            // assert
            act.ShouldThrow <ArgumentException>().WithMessage("*cannot be null.\r\nParameter name: key");
        }
        public void Set <T>(string key, T value, ExpirationMode expirationMode, int expiration)
        {
            MemoryCacheEntryOptions options = new MemoryCacheEntryOptions();
            TimeSpan expire = TimeSpan.FromSeconds(expiration);

            if (expirationMode == ExpirationMode.Sliding)
            {
                options.SlidingExpiration = expire;
            }
            else
            {
                options.AbsoluteExpirationRelativeToNow = expire;
            }
            MemoryCache.Set(key, value, options);
        }
        public static LazyCacheEntryOptions SetAbsoluteExpiration(this LazyCacheEntryOptions option, DateTimeOffset absoluteExpiration,
                                                                  ExpirationMode mode)
        {
            if (option == null)
            {
                throw new ArgumentNullException(nameof(option));
            }

            var delay = absoluteExpiration.Subtract(DateTimeOffset.UtcNow);

            option.AbsoluteExpiration = absoluteExpiration;
            option.ExpirationMode     = mode;
            option.ImmediateAbsoluteExpirationRelativeToNow = delay;
            return(option);
        }
Exemplo n.º 22
0
        public void CacheItem_Ctor4_NullValue()
        {
            // arrange
            string         key     = "key";
            object         value   = null;
            string         region  = null;
            ExpirationMode mode    = ExpirationMode.None;
            TimeSpan       timeout = default(TimeSpan);

            // act
            Action act = () => new CacheItem <object>(key, region, value, mode, timeout);

            // assert
            act.ShouldThrow <ArgumentNullException>().WithMessage("*Parameter name: value");
        }
Exemplo n.º 23
0
        public void CacheItem_Ctor4_WhitespaceRegion()
        {
            // arrange
            string         key     = "key";
            string         value   = "value";
            string         region  = "  ";
            ExpirationMode mode    = ExpirationMode.None;
            TimeSpan       timeout = default(TimeSpan);

            // act
            Action act = () => new CacheItem <object>(key, region, value, mode, timeout);

            // assert
            act.ShouldThrow <ArgumentException>()
            .WithMessage("*Parameter name: region");
        }
        public static void EnableOutputCaching(this HttpContext context,
                                               bool noCache,
                                               int sharedTimeSpan,
                                               int clientTimeSpan,
                                               int serverTimeSpan,
                                               bool excludeQueryStringFromCacheKey,
                                               bool mustRevalidate,
                                               bool anonymousOnly,
                                               Type cacheKeyGenerator,
                                               bool @private,
                                               Type customTimeSpanMethodClassType,
                                               string customTimeSpanMethodName,
                                               bool cachePerUser,
                                               ExpirationMode expirationMode,
                                               string apiName,
                                               bool logEnabled,
                                               string actionName,
                                               string controllerName)
        {
            var feature = context.Features.Get <ApiResponseCacheConfig>();

            if (feature == null)
            {
                feature = new ApiResponseCacheConfig();
                context.Features.Set(feature);
            }

            feature.AnonymousOnly  = anonymousOnly;
            feature.NoCache        = noCache;
            feature.SharedTimeSpan = sharedTimeSpan;
            feature.ClientTimeSpan = clientTimeSpan;
            feature.ServerTimeSpan = serverTimeSpan;
            feature.ExcludeQueryStringFromCacheKey = excludeQueryStringFromCacheKey;
            feature.MustRevalidate                = mustRevalidate;
            feature.CacheKeyGenerator             = cacheKeyGenerator;
            feature.Private                       = @private;
            feature.CustomTimeSpanMethodClassType = customTimeSpanMethodClassType;
            feature.CustomTimeSpanMethodName      = customTimeSpanMethodName;
            feature.CachePerUser                  = cachePerUser;
            feature.ExpirationMode                = expirationMode;
            feature.ApiName                       = apiName;
            feature.LogEnabled                    = logEnabled;
            feature.ActionName                    = actionName;
            feature.ControllerName                = controllerName;
        }
Exemplo n.º 25
0
        public static Task <T> GetOrAddAsync <T>(this IAppCache cache, string key, Func <Task <T> > addItemFactory,
                                                 DateTimeOffset expires, ExpirationMode mode)
        {
            if (cache == null)
            {
                throw new ArgumentNullException(nameof(cache));
            }

            switch (mode)
            {
            case ExpirationMode.LazyExpiration:
                return(cache.GetOrAddAsync(key, addItemFactory, new MemoryCacheEntryOptions {
                    AbsoluteExpiration = expires
                }));

            default:
                return(cache.GetOrAddAsync(key, addItemFactory, new LazyCacheEntryOptions().SetAbsoluteExpiration(expires, mode)));
            }
        }
Exemplo n.º 26
0
        public void CacheItem_Ctor3_ValidateCreatedResult()
        {
            // arrange
            string         key     = "key";
            object         value   = "value";
            ExpirationMode mode    = ExpirationMode.Sliding;
            TimeSpan       timeout = new TimeSpan(0, 23, 45);

            // act
            var act = new CacheItem <object>(key, value, mode, timeout);

            // assert
            act.Should()
            .Match <CacheItem <object> >(p => p.ExpirationMode == mode)
            .And.Match <CacheItem <object> >(p => p.ExpirationTimeout == timeout)
            .And.Match <CacheItem <object> >(p => p.Key == key)
            .And.Match <CacheItem <object> >(p => p.Value == value)
            .And.Match <CacheItem <object> >(p => p.Region == null);
        }
Exemplo n.º 27
0
        /// <inheritdoc />
        public void Expire(TKey key, ExpirationMode mode, TimeSpan timeout)
        {
            CheckDisposed();

            var item = GetCacheItemInternal(key);

            if (item == null)
            {
                Logger.LogTrace($"Expire: item not found for key {key}");
                return;
            }

            if (_logTrace)
            {
                Logger.LogTrace($"Expire [{item}] started.");
            }

            if (mode == ExpirationMode.Absolute)
            {
                item = item.WithAbsoluteExpiration(timeout);
            }
            else if (mode == ExpirationMode.Sliding)
            {
                item = item.WithSlidingExpiration(timeout);
            }
            else if (mode == ExpirationMode.None)
            {
                item = item.WithNoExpiration();
            }
            else if (mode == ExpirationMode.Default)
            {
                item = item.WithDefaultExpiration();
            }

            if (_logTrace)
            {
                Logger.LogTrace($"Expire - Expiration of [{item}] has been modified. Using put to store the item...");
            }

            PutInternal(item);
        }
        private void ExpireInternal(string key, string region, ExpirationMode mode, TimeSpan timeout)
        {
            CheckDisposed();

            var item = GetCacheItemInternal(key, region);

            if (item == null)
            {
                Logger.LogTrace("Expire: item not found for key {0}:{1}", key, region);
                return;
            }

            if (_logTrace)
            {
                Logger.LogTrace("Expire [{0}] started.", item);
            }

            if (mode == ExpirationMode.Absolute)
            {
                item = item.WithAbsoluteExpiration(timeout);
            }
            else if (mode == ExpirationMode.Sliding)
            {
                item = item.WithSlidingExpiration(timeout);
            }
            else if (mode == ExpirationMode.None)
            {
                item = item.WithNoExpiration();
            }
            else if (mode == ExpirationMode.Default)
            {
                item = item.WithDefaultExpiration();
            }

            if (_logTrace)
            {
                Logger.LogTrace("Expire - Expiration of [{0}] has been modified. Using put to store the item...", item);
            }

            PutInternal(item);
        }
        public static async Task <T> GetOrAddAsync <T>(
            this ICacheManager <T> cacheManager,
            string key,
            Func <string, Task <T> > valueFactory,
            ExpirationMode expirationMode,
            TimeSpan timeout)
        {
            T result;

            if (cacheManager.Exists(key))
            {
                result = cacheManager.Get <T>(key);
            }
            else
            {
                result = await valueFactory(key).ConfigureAwait(false);

                cacheManager.Add(new CacheItem <T>(key, result, expirationMode, timeout));
            }

            return(result);
        }
Exemplo n.º 30
0
 /// <summary>
 /// Changes the expiration <paramref name="mode"/> and <paramref name="timeout"/> for the
 /// given <paramref name="key"/> in <paramref name="region"/>.
 /// </summary>
 /// <param name="key">The cache key.</param>
 /// <param name="region">The cache region.</param>
 /// <param name="mode">The expiration mode.</param>
 /// <param name="timeout">The expiration timeout.</param>
 public abstract void Expire(string key, string region, ExpirationMode mode, TimeSpan timeout);
Exemplo n.º 31
0
        /// <summary>
        /// Sets the expiration mode and timeout of the cache handle.
        /// </summary>
        /// <param name="expirationMode">The expiration mode.</param>
        /// <param name="timeout">The timeout.</param>
        /// <returns>The builder part.</returns>
        /// <exception cref="System.InvalidOperationException">
        /// If expiration mode is not set to 'None', timeout cannot be zero.
        /// </exception>
        /// <exception cref="InvalidOperationException">
        /// Thrown if expiration mode is not 'None' and timeout is zero.
        /// </exception>
        /// <seealso cref="ExpirationMode"/>
        public ConfigurationBuilderCacheHandlePart WithExpiration(ExpirationMode expirationMode, TimeSpan timeout)
        {
            if (expirationMode != ExpirationMode.None && timeout == TimeSpan.Zero)
            {
                throw new InvalidOperationException("If expiration mode is not set to 'None', timeout cannot be zero.");
            }

            this.Configuration.ExpirationMode = expirationMode;
            this.Configuration.ExpirationTimeout = timeout;
            return this;
        }