public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

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

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            Connect();

            var creationTime = DateTimeOffset.UtcNow;

            var absoluteExpiration = GetAbsoluteExpiration(creationTime, options);

            var result = _cache.ScriptEvaluate(SetScript, new RedisKey[] { _instance + key },
                new RedisValue[]
                {
                    absoluteExpiration?.Ticks ?? NotPresent,
                    options.SlidingExpiration?.Ticks ?? NotPresent,
                    GetExpirationInSeconds(creationTime, absoluteExpiration, options) ?? NotPresent,
                    value
                });
        }
        /// <summary>
        /// Tries to get the value from the cache, and only calls the delegating handler on cache misses.
        /// </summary>
        /// <returns>The HttpResponseMessage from cache, or a newly invoked one.</returns>
        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            string key = request.RequestUri.ToString();
            // gets the data from cache, and returns the data if it's a cache hit
            if (request.Method == HttpMethod.Get)
            {
                var data = await responseCache.TryGetAsync(key);
                if (data != null)
                {
                    HttpResponseMessage cachedResponse = PrepareCachedEntry(request, data);
                    StatsProvider.ReportCacheHit(cachedResponse.StatusCode);
                    return cachedResponse;
                }
            }

            // cache misses need to ask the inner handler for an actual response
            HttpResponseMessage response = await base.SendAsync(request, cancellationToken);

            // puts the retrieved response into the cache and returns the cached entry
            if (request.Method == HttpMethod.Get)
            {
                byte[] entry = await response.ToCacheEntry();
                var options = new DistributedCacheEntryOptions {AbsoluteExpirationRelativeToNow = response.StatusCode.GetAbsoluteExpirationRelativeToNow(cacheExpirationPerHttpResponseCode)};
                await responseCache.TrySetAsync(key, entry, options);
                HttpResponseMessage cachedResponse = PrepareCachedEntry(request, entry);
                StatsProvider.ReportCacheMiss(cachedResponse.StatusCode);
                return cachedResponse;
            }

            // returns the original response
            return response;
        }
Exemple #3
0
        public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            Set(key, value, options);
            return CompletedTask;
        }
 /// <summary>
 /// Tries to set a new value to the cache, that is, ignoring all exceptions.
 /// </summary>
 /// <param name="cache">The distributed cache.</param>
 /// <param name="key">The key for this cache entry.</param>
 /// <param name="value">The value of this cache entry.</param>
 /// <param name="options">Cache options for the entry.</param>
 /// <returns>A task, when completed, has tried to put the entry into the cache.</returns>
 public static async Task TrySetAsync(this IDistributedCache cache, string key, byte[] value, DistributedCacheEntryOptions options)
 {
     try
     {
         await cache.SetAsync(key, value, options);
     }
     catch (Exception)
     {
         // ignoer all exceptions
     }
 }
        /// <inheritdoc />
        public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

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

            return _distributedCache.SetAsync(key, value, options);
        }
Exemple #6
0
        public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            var memoryCacheEntryOptions = new MemoryCacheEntryOptions();
            memoryCacheEntryOptions.AbsoluteExpiration = options.AbsoluteExpiration;
            memoryCacheEntryOptions.AbsoluteExpirationRelativeToNow = options.AbsoluteExpirationRelativeToNow;
            memoryCacheEntryOptions.SlidingExpiration = options.SlidingExpiration;

            _memCache.Set(key, value, memoryCacheEntryOptions);
        }
 public static async Task SetUsingBytesAsync<T>(this IDistributedCache distributedCache, string key, T value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken)) => await distributedCache.SetAsync(key, value.ToByteArray(), options, token);
 public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options)
 {
     return _distributedCache.SetAsync(key, value, options);
 }
Exemple #9
0
        public virtual async Task SetCacheItemAsync(string key, byte[] value, DistributedCacheEntryOptions options)
        {
            var utcNow = SystemClock.UtcNow;

            var absoluteExpiration = GetAbsoluteExpiration(utcNow, options);
            ValidateOptions(options.SlidingExpiration, absoluteExpiration);

            using (var connection = new SqlConnection(ConnectionString))
            {
                var upsertCommand = new SqlCommand(SqlQueries.SetCacheItem, connection);
                upsertCommand.Parameters
                    .AddCacheItemId(key)
                    .AddCacheItemValue(value)
                    .AddSlidingExpirationInSeconds(options.SlidingExpiration)
                    .AddAbsoluteExpiration(absoluteExpiration)
                    .AddWithValue("UtcNow", SqlDbType.DateTimeOffset, utcNow);

                await connection.OpenAsync();

                try
                {
                    await upsertCommand.ExecuteNonQueryAsync();
                }
                catch (SqlException ex)
                {
                    if (IsDuplicateKeyException(ex))
                    {
                        // There is a possibility that multiple requests can try to add the same item to the cache, in
                        // which case we receive a 'duplicate key' exception on the primary key column.
                    }
                    else
                    {
                        throw;
                    }
                }
            }
        }
 public DistributedCacheRegistration(string name, DistributedCacheEntryOptions entryOptions, DistributedCacheItemBuilderAsync builder, Func <object, object[], string[]> cacheTags)
     : this(new StackTrace(), name, entryOptions, null, builder, cacheTags)
 {
 }
 private static long? GetExpirationInSeconds(DateTimeOffset creationTime, DateTimeOffset? absoluteExpiration, DistributedCacheEntryOptions options)
 {
     if (absoluteExpiration.HasValue && options.SlidingExpiration.HasValue)
     {
         return (long)Math.Min(
             (absoluteExpiration.Value - creationTime).TotalSeconds,
             options.SlidingExpiration.Value.TotalSeconds);
     }
     else if (absoluteExpiration.HasValue)
     {
         return (long)(absoluteExpiration.Value - creationTime).TotalSeconds;
     }
     else if (options.SlidingExpiration.HasValue)
     {
         return (long)options.SlidingExpiration.Value.TotalSeconds;
     }
     return null;
 }
Exemple #12
0
        public static void Set <T>(this IDistributedCache cache, string key, T value, DistributedCacheEntryOptions options)
            where T : class, new ()
        {
            byte[] data = Serialize(value);

            cache.Set(key, data, options);
        }
 public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
 {
     base.Set(key, value, new DistributedCacheEntryOptions());
 }
 public static async Task SetUsingJsonAsync<T>(this IDistributedCache distributedCache, string key, T value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken)) => await distributedCache.SetStringAsync(key, JsonConvert.SerializeObject(value), options, token);
 public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options)
 {
     throw new NotImplementedException();
 }
 public static async Task SetUsingJsonAsync<T>(this IDistributedCache distributedCache, T value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken)) => await distributedCache.SetUsingJsonAsync(typeof(T).FullName, value, options, token);
 public static void SetUsingJson<T>(this IDistributedCache distributedCache, string key, T value, DistributedCacheEntryOptions options) => distributedCache.SetString(key, JsonConvert.SerializeObject(value), options);
 public static void SetUsingJson<T>(this IDistributedCache distributedCache, T value, DistributedCacheEntryOptions options) => distributedCache.SetUsingJson(typeof(T).FullName, value, options);
 public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
 {
     base.Set(key, value, new Microsoft.Framework.Caching.Distributed.DistributedCacheEntryOptions());
 }
Exemple #20
0
        public async static Task SetAsync <T>(this IDistributedCache cache, string key, T value, DistributedCacheEntryOptions options, CancellationToken token = default(CancellationToken))
            where T : class, new()
        {
            byte[] data = Serialize(value);

            await cache.SetAsync(key, data, options, token);
        }
 public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options)
 {
     return base.SetAsync(key, value, new Microsoft.Framework.Caching.Distributed.DistributedCacheEntryOptions());
 }
Exemple #22
0
        public async Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            await ConnectAsync();

            var creationTime = DateTimeOffset.UtcNow;

            await _cache.ScriptEvaluateAsync(SetScript, new RedisKey[] { _instance + key },
                new RedisValue[]
                {
                        options.AbsoluteExpiration?.Ticks ?? NotPresent,
                        options.SlidingExpiration?.Ticks ?? NotPresent,
                        GetExpirationInSeconds(creationTime, options) ?? NotPresent,
                        value
                });
        }
 public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options)
 {
     return base.SetAsync(key, value, new DistributedCacheEntryOptions());
 }
Exemple #24
0
        private static long? GetExpirationInSeconds(DateTimeOffset creationTime, DistributedCacheEntryOptions options)
        {
            // Calculate absolute expiration time
            DateTimeOffset? absoluteExpiration = null;
            if (options.AbsoluteExpirationRelativeToNow.HasValue)
            {
                absoluteExpiration = creationTime + options.AbsoluteExpirationRelativeToNow;
            }
            else if (options.AbsoluteExpiration.HasValue)
            {
                if (options.AbsoluteExpiration <= creationTime)
                {
                    throw new ArgumentOutOfRangeException(
                        nameof(DistributedCacheEntryOptions.AbsoluteExpiration),
                        options.AbsoluteExpiration.Value,
                        "The absolute expiration value must be in the future.");
                }
                absoluteExpiration = options.AbsoluteExpiration;
            }

            if (absoluteExpiration.HasValue && options.SlidingExpiration.HasValue)
            {
                return (long)Math.Min(
                    (absoluteExpiration.Value - creationTime).TotalSeconds,
                    options.SlidingExpiration.Value.TotalSeconds);
            }
            else if (absoluteExpiration.HasValue)
            {
                return (long)(absoluteExpiration.Value - creationTime).TotalSeconds;
            }
            else if (options.SlidingExpiration.HasValue)
            {
                return (long)options.SlidingExpiration.Value.TotalSeconds;
            }
            return null;
        }
 public void Set(string key, byte[] value, DistributedCacheEntryOptions options)
 {
     this.SetAsync(key, value, options).Wait();
 }
        // Internal for unit testing
        internal DistributedCacheEntryOptions GetDistributedCacheEntryOptions()
        {
            var options = new DistributedCacheEntryOptions();
            if (ExpiresOn != null)
            {
                options.SetAbsoluteExpiration(ExpiresOn.Value);
            }

            if (ExpiresAfter != null)
            {
                options.SetAbsoluteExpiration(ExpiresAfter.Value);
            }

            if (ExpiresSliding != null)
            {
                options.SetSlidingExpiration(ExpiresSliding.Value);
            }

            return options;
        }
        private static DateTimeOffset? GetAbsoluteExpiration(DateTimeOffset creationTime, DistributedCacheEntryOptions options)
        {
            if (options.AbsoluteExpiration.HasValue && options.AbsoluteExpiration <= creationTime)
            {
                throw new ArgumentOutOfRangeException(
                    nameof(DistributedCacheEntryOptions.AbsoluteExpiration),
                    options.AbsoluteExpiration.Value,
                    "The absolute expiration value must be in the future.");
            }
            var absoluteExpiration = options.AbsoluteExpiration;
            if (options.AbsoluteExpirationRelativeToNow.HasValue)
            {
                absoluteExpiration = creationTime + options.AbsoluteExpirationRelativeToNow;
            }

            return absoluteExpiration;
        }
 public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options)
 {
     throw new NotImplementedException();
 }
Exemple #29
0
        public async Task SetAsync(
            string key,
            byte[] value,
            DistributedCacheEntryOptions options)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

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

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            await _dbOperations.SetCacheItemAsync(key, value, options);

            ScanForExpiredItemsIfRequired();
        }
 public DistributedCacheRegistration(string name, DistributedCacheEntryOptions entryOptions, DistributedCacheItemBuilderAsync builder, params string[] cacheTags)
     : this(new StackTrace(), name, entryOptions, null, builder, cacheTags != null && cacheTags.Length > 0 ? (a, b) => cacheTags : (Func <object, object[], string[]>)null)
 {
 }
Exemple #31
0
        protected DateTimeOffset? GetAbsoluteExpiration(DateTimeOffset utcNow, DistributedCacheEntryOptions options)
        {
            // calculate absolute expiration
            DateTimeOffset? absoluteExpiration = null;
            if (options.AbsoluteExpirationRelativeToNow.HasValue)
            {
                absoluteExpiration = utcNow.Add(options.AbsoluteExpirationRelativeToNow.Value);
            }
            else if (options.AbsoluteExpiration.HasValue)
            {
                if (options.AbsoluteExpiration.Value <= utcNow)
                {
                    throw new InvalidOperationException("The absolute expiration value must be in the future.");
                }

                absoluteExpiration = options.AbsoluteExpiration.Value;
            }
            return absoluteExpiration;
        }
 public Task SetAsync(string key, byte[] value, DistributedCacheEntryOptions options)
 {
     DateTimeOffset? absoluteExpiration = null;
     var currentTime = DateTimeOffset.UtcNow;
     if (options.AbsoluteExpirationRelativeToNow.HasValue)
     {
         absoluteExpiration = currentTime.Add(options.AbsoluteExpirationRelativeToNow.Value);
     }
     else if (options.AbsoluteExpiration.HasValue)
     {
         if (options.AbsoluteExpiration.Value <= currentTime)
         {
             throw new ArgumentOutOfRangeException(
                nameof(options.AbsoluteExpiration),
                options.AbsoluteExpiration.Value,
                "The absolute expiration value must be in the future.");
         }
         absoluteExpiration = options.AbsoluteExpiration;
     }
     var item = new CachedItem(partitionKey, key, value) { LastAccessTime = currentTime };
     if (absoluteExpiration.HasValue)
     {
         item.AbsolutExperiation = absoluteExpiration;
     }
     if (options.SlidingExpiration.HasValue)
     {
         item.SlidingExperiation = options.SlidingExpiration;
     }
     var op = TableOperation.InsertOrReplace(item);
     return this.azuretable.ExecuteAsync(op);
 }
        internal static Task SetAsync(
            [NotNull] this IDistributedCache cache, [NotNull] string key,
            [NotNull] Func<DistributedCacheEntryOptions, byte[]> factory) {
            var options = new DistributedCacheEntryOptions();
            var buffer = factory(options);

            return cache.SetAsync(key, buffer, options);
        }
 public static void SetUsingBytes<T>(this IDistributedCache distributedCache, string key, T value, DistributedCacheEntryOptions options) => distributedCache.Set(key, value.ToByteArray(), options);
        public void Displayed(ShapeDisplayedContext context)
        {
            // TODO: Configure duration of sliding expiration

            var cacheContext = context.ShapeMetadata.Cache();

            // If the shape is not cached, evaluate the ESIs
            if(cacheContext == null)
            {
                string content;
                using (var sw = new StringWriter())
                {
                    context.ChildContent.WriteTo(sw, HtmlEncoder.Default);
                    content = sw.ToString();
                }

                ProcessESIs(ref content, GetDistributedCache);
                context.ChildContent = new HtmlString(content);
            }
            else if (!_cached.Contains(cacheContext) && context.ChildContent != null)
            {
                var cacheEntries = GetCacheEntries(cacheContext).ToList();
                string cacheKey = GetCacheKey(cacheContext.CacheId, cacheEntries);

                using (var sw = new StringWriter())
                {
                    context.ChildContent.WriteTo(sw, HtmlEncoder.Default);
                    var content = sw.ToString();

                    _cached.Add(cacheContext);
                    _cache[cacheKey] = content;
                    var contexts = String.Join(ContextSeparator.ToString(), cacheContext.Contexts.ToArray());
                    context.ChildContent = new HtmlString($"[[cache id='{cacheContext.CacheId}' contexts='{contexts}']]");

                    var bytes = Encoding.UTF8.GetBytes(content);

                    // Default duration is sliding expiration (permanent as long as it's used)
                    DistributedCacheEntryOptions options = new DistributedCacheEntryOptions
                    {
                        SlidingExpiration = new TimeSpan(0, 1, 0)
                    };

                    // If a custom duration is specified, replace the default options
                    if (cacheContext.Duration.HasValue)
                    {
                        options = new DistributedCacheEntryOptions
                        {
                            AbsoluteExpirationRelativeToNow = cacheContext.Duration
                        };
                    }

                    _dynamicCache.SetAsync(cacheKey, bytes, options).Wait();
                    _tagCache.Tag(cacheKey, cacheContext.Tags.ToArray());
                }
            }

        }
Exemple #36
0
 public static async Task SetAsync <T>(this IDistributedCache cache, string key, T value, DistributedCacheEntryOptions options) where T : class
 {
     var json = JsonConvert.SerializeObject(value);
     await cache.SetStringAsync(key, json, options);
 }