Пример #1
0
 public Bitmap this[ScannedImage scannedImage]
 {
     get
     {
         var newState = scannedImage.GetThumbnailState();
         if (cache.ContainsKey(scannedImage))
         {
             // Cache hit
             var item = cache[scannedImage];
             if (item.State != newState)
             {
                 // Invalidated
                 item.Thumbnail.Dispose();
                 item.Thumbnail = scannedImage.GetThumbnail(userConfigManager.Config.ThumbnailSize);
                 item.State = newState;
             }
             return item.Thumbnail;
         }
         else
         {
             // Cache miss
             var item = new CacheItem
             {
                 Thumbnail = scannedImage.GetThumbnail(userConfigManager.Config.ThumbnailSize),
                 State = newState
             };
             return item.Thumbnail;
         }
     }
 }
        /// <summary>
        /// Initializes a new instance of the ImageListViewCacheManager class.
        /// </summary>
        /// <param name="owner">The owner control.</param>
        public ImageListViewCacheManager(ImageListView owner)
        {
            lockObject = new object();

            mImageListView = owner;
            mCacheMode = CacheMode.OnDemand;
            mCacheLimitAsItemCount = 0;
            mCacheLimitAsMemory = 20 * 1024 * 1024;
            mRetryOnError = owner.RetryOnError;

            toCache = new Stack<CacheItem>();
            thumbCache = new Dictionary<Guid, CacheItem>();
            editCache = new Dictionary<Guid, Image>();

            rendererToCache = new Stack<CacheItem>();
            rendererGuid = new Guid();
            rendererItem = null;

            memoryUsed = 0;
            memoryUsedByRemoved = 0;
            removedItems = new List<Guid>();

            mThread = new Thread(new ThreadStart(DoWork));
            mThread.IsBackground = true;

            stopping = false;
            stopped = false;
            disposed = false;

            mThread.Start();
            while (!mThread.IsAlive) ;
        }
Пример #3
0
 public StoreOperation(StoreMode mode, string key, CacheItem value, uint expires)
     : base(key)
 {
     this.mode = mode;
     this.value = value;
     this.expires = expires;
 }
Пример #4
0
        public void CanScavengeInBackground()
        {
            CacheItem item1 = new CacheItem("key1", "value1", CacheItemPriority.Low, null);
            CacheItem item2 = new CacheItem("key2", "value2", CacheItemPriority.Normal, null);
            CacheItem item3 = new CacheItem("key3", "value3", CacheItemPriority.High, null);

            AddCacheItem("key1", item1);
            AddCacheItem("key2", item2);
            AddCacheItem("key3", item3);

            TestConfigurationContext context = new TestConfigurationContext();
            CachingConfigurationView view = new CachingConfigurationView(context);
            view.GetCacheManagerSettings().CacheManagers["test"].MaximumElementsInCacheBeforeScavenging = 2;
            view.GetCacheManagerSettings().CacheManagers["test"].NumberToRemoveWhenScavenging = 1;

            CacheCapacityScavengingPolicy scavengingPolicy = new CacheCapacityScavengingPolicy("test", view);
            ScavengerTask scavenger = new ScavengerTask("test", view, scavengingPolicy, this);
            BackgroundScheduler scheduler = new BackgroundScheduler(null, scavenger);
            scheduler.Start();

            Thread.Sleep(500);
            scheduler.StartScavenging();
            Thread.Sleep(250);

            scheduler.Stop();
            Thread.Sleep(250);

            Assert.AreEqual("key1", scavengedKeys);
        }
 public void CallbackReasonScavengedIsGivenToCallbackMethod()
 {
     CacheItem emptyCacheItem = new CacheItem("key", null, CacheItemPriority.Low, new MockRefreshAction());
     RefreshActionInvoker.InvokeRefreshAction(emptyCacheItem, CacheItemRemovedReason.Scavenged, instrumentationProvider);
     Thread.Sleep(100);
     Assert.AreEqual(CacheItemRemovedReason.Scavenged, callbackReason);
 }
 public void RemovedValueCanBeNullDuringCallback()
 {
     CacheItem emptyCacheItem = new CacheItem("key", null, CacheItemPriority.Low, new MockRefreshAction());
     RefreshActionInvoker.InvokeRefreshAction(emptyCacheItem, CacheItemRemovedReason.Expired, instrumentationProvider);
     Thread.Sleep(100);
     Assert.IsNull(removedValue);
 }
 public void RemovedValueIsGivenToCallbackMethod()
 {
     CacheItem emptyCacheItem = new CacheItem("key", "value", CacheItemPriority.Low, new MockRefreshAction());
     RefreshActionInvoker.InvokeRefreshAction(emptyCacheItem, CacheItemRemovedReason.Expired, instrumentationProvider);
     Thread.Sleep(100);
     Assert.AreEqual("value", removedValue);
 }
        /// <summary>
        /// Adds new item to persistence store
        /// </summary>
        /// <param name="storageKey">Unique key for storage item.</param>
        /// <param name="newItem">Item to be added to cache. May not be null.</param>
        protected override void AddNewItem(int storageKey,
                                           CacheItem newItem)
        {
            string key = newItem.Key;
            byte[] valueBytes = SerializationUtility.ToBytes(newItem.Value);
            if (encryptionProvider != null)
            {
                valueBytes = encryptionProvider.Encrypt(valueBytes);
            }

            byte[] expirationBytes = SerializationUtility.ToBytes(newItem.GetExpirations());
            byte[] refreshActionBytes = SerializationUtility.ToBytes(newItem.RefreshAction);
            CacheItemPriority scavengingPriority = newItem.ScavengingPriority;
            DateTime lastAccessedTime = newItem.LastAccessedTime;

            DbCommand insertCommand = database.GetStoredProcCommand("AddItem");
            database.AddInParameter(insertCommand, "@partitionName", DbType.String, partitionName);
            database.AddInParameter(insertCommand, "@storageKey", DbType.Int32, storageKey);
            database.AddInParameter(insertCommand, "@key", DbType.String, key);
            database.AddInParameter(insertCommand, "@value", DbType.Binary, valueBytes);
            database.AddInParameter(insertCommand, "@expirations", DbType.Binary, expirationBytes);
            database.AddInParameter(insertCommand, "@refreshAction", DbType.Binary, refreshActionBytes);
            database.AddInParameter(insertCommand, "@scavengingPriority", DbType.Int32, scavengingPriority);
            database.AddInParameter(insertCommand, "@lastAccessedTime", DbType.DateTime, lastAccessedTime);

            database.ExecuteNonQuery(insertCommand);
        }
Пример #9
0
        public void Memcached_KeySizeLimit_WithRegion()
        {
            // arrange
            var longKey = string.Join(string.Empty, Enumerable.Repeat("a", 300));

            var item = new CacheItem<string>(longKey, "someRegion", "something");
            var cache = CacheFactory.Build<string>(settings =>
            {
                settings.WithUpdateMode(CacheUpdateMode.Full)
                    .WithMemcachedCacheHandle("default")
                    .WithExpiration(ExpirationMode.Absolute, TimeSpan.FromMinutes(1));
            });

            // act
            using (cache)
            {
                cache.Remove(item.Key, item.Region);
                Func<bool> act = () => cache.Add(item);
                Func<string> act2 = () => cache[item.Key, item.Region];

                // assert
                act().Should().BeTrue();
                act2().Should().Be(item.Value);
            }
        }
        public void Should_dispose_existing_phoenix()
        {
            var key = "theCacheKey" + Guid.NewGuid();
            // Arrange
            var objCacheItem = new CacheItem
            {
                MaxAge = 5,
                StaleWhileRevalidate = 5,
                StoreId = 1000,
                CreatedTime = DateTime.UtcNow.AddSeconds(-5).AddMilliseconds(-1),
                Key = key
            };

            var existingPhoenix = Substitute.For<Phoenix>(Substitute.For<_IInvocation>(), objCacheItem);

            var att = new OutputCacheAttributeWithPublicMethods { Duration = 5, CacheStoreId = 1000, StaleWhileRevalidate = 5 };

            Global.Cache.PhoenixFireCage[key] = existingPhoenix;

            // Action
            att.CreatePhoenixPublic(Substitute.For<_IInvocation>(), objCacheItem);

            // Assert
            Assert.That(Global.Cache.PhoenixFireCage[key] is Phoenix);
            existingPhoenix.Received(1).Dispose();
        }
Пример #11
0
 public void KeyIsGivenToCallbackMethod()
 {
     CacheItem emptyCacheItem = new CacheItem("key", null, CacheItemPriority.Low, new MockRefreshAction());
     RefreshActionInvoker.InvokeRefreshAction(emptyCacheItem, CacheItemRemovedReason.Scavenged);
     Thread.Sleep(100);
     Assert.AreEqual("key", removedKey);
 }
Пример #12
0
 private byte[] GetThumbnailInternal(string key, object item,
                                     DlnaMediaTypes type, ref int width,
                                     ref int height)
 {
   var thumbnailers = thumbers[type];
   var rw = width;
   var rh = height;
   foreach (var thumber in thumbnailers) {
     try {
       using (var i = thumber.GetThumbnail(item, ref width, ref height)) {
         var rv = i.ToArray();
         lock (cache) {
           cache[key] = new CacheItem(rv, rw, rh);
         }
         return rv;
       }
     }
     catch (Exception ex) {
       Debug(String.Format(
         "{0} failed to thumbnail a resource", thumber.GetType()), ex);
       continue;
     }
   }
   throw new ArgumentException("Not a supported resource");
 }
 public void CallbackDoesHappenIfRefreshActionIsSet()
 {
     CacheItem emptyCacheItem = new CacheItem("key", "value", CacheItemPriority.Low, new MockRefreshAction());
     RefreshActionInvoker.InvokeRefreshAction(emptyCacheItem, CacheItemRemovedReason.Expired, instrumentationProvider);
     Thread.Sleep(100);
     Assert.IsTrue(callbackHappened);
 }
        public static ICacheExpiration[] GetCacheExpirations(CacheItem item)
        {
            lastTimeAccessed = item.LastAccessedTime;
            var expirations = new List<ICacheExpiration>();

            switch (item.GetCacheItemType())
            {
                case CacheItemType.Object:
                    expirations.AddRange(GetTimeExpirations(true, true));

                    break;

                case CacheItemType.Page:
                    expirations.AddRange(GetTimeExpirations(true, true));

                    break;

                case CacheItemType.Collection:
                    expirations.AddRange(GetTimeExpirations(true, true));

                    break;
            }

            return expirations.ToArray();
        }
Пример #15
0
		IStoreOperation IOperationFactory.Store(StoreMode mode, string key, CacheItem value, uint expires, ulong cas)
		{
			if (cas == 0)
				return new StoreOperation(mode, key, value, expires);

			return new CasOperation(key, value, expires, (uint)cas);
		}
        public void SizeNotZeroWhenOneItemInserted()
        {
            CacheItem itemToStore = new CacheItem("key", "value", CacheItemPriority.NotRemovable, null);

            backingStore.Add(itemToStore);
            Assert.AreEqual(1, backingStore.Count, "Inserted item should be in Isolated Storage");
        }
 /// <summary>
 ///     Retrieves the binary data of the image from the cache.
 /// </summary>
 /// <param name="item">
 ///     The record that identifies the image in the cache.
 /// </param>
 /// <returns>
 ///     The binary data of the image.
 /// </returns>
 protected override Task<byte[]> GetCacheDataAsync(CacheItem item)
 {
     lock (this.cache)
     {
         return Task.FromResult(this.cache[item]);
     }
 }
Пример #18
0
        public void CanAddMinimalCacheItemToStoreWithItemNotPresent()
        {
            CacheItem cacheItem = new CacheItem("key", new SerializableClass(13), CacheItemPriority.Low, null);
            backingStore.Add(cacheItem);

            Assert.AreEqual(1, backingStore.Count);
        }
Пример #19
0
        protected override IOperationResult ProcessResponse(BinaryResponse response)
        {
            var status = response.StatusCode;
            var result = new BinaryOperationResult();

            this.StatusCode = status;

            if (status == 0)
            {
                int flags = BinaryConverter.DecodeInt32(response.Extra, 0);
                this.result = new CacheItem((ushort)flags, response.Data);
                this.Cas = response.CAS;

            #if EVEN_MORE_LOGGING
                if (log.IsDebugEnabled)
                    log.DebugFormat("Get succeeded for key '{0}'.", this.Key);
            #endif

                return result.Pass();
            }

            this.Cas = 0;

            #if EVEN_MORE_LOGGING
            if (log.IsDebugEnabled)
                log.DebugFormat("Get failed for key '{0}'. Reason: {1}", this.Key, Encoding.ASCII.GetString(response.Data.Array, response.Data.Offset, response.Data.Count));
            #endif

            var message = ResultHelper.ProcessResponseData(response.Data);
            return result.Fail(message);
        }
Пример #20
0
        protected override bool ProcessResponse(BinaryResponse response)
        {
            if (response.StatusCode == 0)
            {
                int flags = BinaryConverter.DecodeInt32(response.Extra, 0);
                this.result = new CacheItem((ushort)flags, response.Data);
                this.Cas = response.CAS;

            #if EVEN_MORE_LOGGING
                if (log.IsDebugEnabled)
                    log.DebugFormat("Get succeeded for key '{0}'.", this.Key);
            #endif

                return true;
            }

            this.Cas = 0;

            #if EVEN_MORE_LOGGING
            if (log.IsDebugEnabled)
                log.DebugFormat("Get failed for key '{0}'. Reason: {1}", this.Key, Encoding.ASCII.GetString(response.Data.Array, response.Data.Offset, response.Data.Count));
            #endif

            return false;
        }
Пример #21
0
        public void CanAddWithNullValue()
        {
            CacheItem cacheItem = new CacheItem("key", null, CacheItemPriority.Low, null);
            backingStore.Add(cacheItem);

            Assert.AreEqual(1, backingStore.Count);
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="ImageListViewCacheThumbnail"/> class.
        /// </summary>
        /// <param name="owner">The owner control.</param>
        public ImageListViewCacheThumbnail(ImageListView owner)
        {
            context = null;
            bw = new QueuedBackgroundWorker();
            bw.ProcessingMode = ProcessingMode.LIFO;
            bw.IsBackground = true;
            bw.DoWork += bw_DoWork;
            bw.RunWorkerCompleted += bw_RunWorkerCompleted;

            checkProcessingCallback = new SendOrPostCallback(CanContinueProcessing);

            mImageListView = owner;
            CacheMode = CacheMode.OnDemand;
            CacheLimitAsItemCount = 0;
            CacheLimitAsMemory = 20 * 1024 * 1024;
            RetryOnError = false;

            thumbCache = new Dictionary<Guid, CacheItem>();
            editCache = new Dictionary<Guid, bool>();
            processing = new Dictionary<Guid, bool>();
            processingRendererItem = Guid.Empty;
            processingGalleryItem = Guid.Empty;

            rendererItem = null;
            galleryItem = null;

            MemoryUsed = 0;
            MemoryUsedByRemoved = 0;
            removedItems = new List<Guid>();

            disposed = false;
        }
Пример #23
0
        public GetResponse(string key, ushort flags, ulong casValue, byte[] data, int offset, int count)
        {
            this.Key = key;
            this.CasValue = casValue;

            this.Item = new CacheItem(flags, new ArraySegment<byte>(data, offset, count));
        }
        public void WillSortByPriorityWithSameDate()
        {
            CacheItem firstItem = new CacheItem("key", "value", CacheItemPriority.High, null);
            CacheItem secondItem = new CacheItem("key2", "value2", CacheItemPriority.NotRemovable, null);
            CacheItem thirdItem = new CacheItem("key3", "value3", CacheItemPriority.Low, null);
            CacheItem fourthItem = new CacheItem("key4", "value4", CacheItemPriority.Normal, null);

            DateTime currentTime = DateTime.Now;
            firstItem.SetLastAccessedTime(currentTime);
            secondItem.SetLastAccessedTime(currentTime);
            thirdItem.SetLastAccessedTime(currentTime);
            fourthItem.SetLastAccessedTime(currentTime);

            AddCacheItem("key", firstItem);
            AddCacheItem("key2", secondItem);
            AddCacheItem("key3", thirdItem);
            AddCacheItem("key4", fourthItem);

            SortedList itemsToBeScavenged = new SortedList(inMemoryCache, new PriorityDateComparer(inMemoryCache));

            Assert.AreEqual("key3", GetCacheKey(itemsToBeScavenged, 0));
            Assert.AreEqual("key4", GetCacheKey(itemsToBeScavenged, 1));
            Assert.AreEqual("key", GetCacheKey(itemsToBeScavenged, 2));
            Assert.AreEqual("key2", GetCacheKey(itemsToBeScavenged, 3));
        }
Пример #25
0
        public GetCommand(CacheItem item, bool fetchUniqueID)
        {
            Condition.Requires(item).IsNotNull(
                "When getting item, item should be specified.");

            _item = item;
            _fetchUniqueID = fetchUniqueID;
        }
        public void SingleExpirationIsNotifiedWhenCacheItemUpdated()
        {
            RecordingExpiration recordingExpiration = new RecordingExpiration();
            CacheItem cacheItem = new CacheItem("key", "value", CacheItemPriority.Normal, null, recordingExpiration);
            cacheItem.TouchedByUserAction(true);

            Assert.IsTrue(recordingExpiration.wasNotified);
        }
        public void ReadCacheItemWithNullValue()
        {
            CacheItem itemToStore = new CacheItem("key", null, CacheItemPriority.Normal, null);
            CacheItem readItem = DoCacheItemRoundTripToStorage(itemToStore, false);

            Assert.IsNull(readItem.Value);
            Assert.AreEqual(itemToStore.Key, readItem.Key);
        }
Пример #28
0
 public CacheIndex Add(string indexKey, CacheItem item)
 {
     var k = string.Format(CultureInfo.InvariantCulture, "{0}|{1}", IndexKey, item.Key);
     if (!Keys.Contains(k))
         Keys.Add(k);
     UpdatedAt = DateTimeOffset.UtcNow;
     return this;
 }
 internal StoreOperationBase(StoreCommand mode, string key, CacheItem value, uint expires, ulong cas)
     : base(key)
 {
     this.command = mode;
     this.value = value;
     this.expires = expires;
     this.cas = cas;
 }
Пример #30
0
 public int AddItem(string key, string value)
 {
     var cacheItem = new CacheItem ();
     cacheItem.Stamp = DateTime.UtcNow;
     cacheItem.Id = key;
     cacheItem.Value = value;
     return database.Insert (cacheItem);
 }
Пример #31
0
 internal CasOperation(string key, CacheItem value, uint expires, ulong cas)
     : base(StoreCommand.CheckAndSet, key, value, expires, cas)
 {
 }
Пример #32
0
 internal string GenerateDirectory(CacheItem item) => GenerateDirectory(item.Key);
Пример #33
0
 protected virtual void OnItemDisposing(CacheItem <TValue> cacheItem)
 {
 }
#pragma warning restore CS1591 // Missing XML comment for publicly visible type or member
#pragma warning restore SA1600

        /// <summary>
        /// Puts the <paramref name="item"/> into the cache. If the item exists it will get updated
        /// with the new value. If the item doesn't exist, the item will be added to the cache.
        /// </summary>
        /// <param name="item">The <c>CacheItem</c> to be added to the cache.</param>
        protected override void PutInternal(CacheItem <TCacheValue> item)
        => base.PutInternal(item);
 /// <summary>
 /// Puts the <paramref name="item"/> into the cache. If the item exists it will get updated
 /// with the new value. If the item doesn't exist, the item will be added to the cache.
 /// </summary>
 /// <param name="item">The <c>CacheItem</c> to be added to the cache.</param>
 protected override void PutInternalPrepared(CacheItem <TCacheValue> item) => this.Store(StoreMode.Set, item);
Пример #36
0
 private static void UpdateCacheValueInfoForHit(CacheItem cacheItem)
 {
     cacheItem.TheTime = DateTime.Now;
 }
Пример #37
0
        public void Set <T>(string key, T value)
        {
            var cacheItem = new CacheItem(key, value);

            Client.Set(cacheItem, null);
        }
        private static async Task <ResponseHandlerResult> WriteResponseInCacheAsync(HttpResponseBase httpResponse, CacheItem cacheItem)
        {
            await cacheItem.Response.WriteResponseAsync(httpResponse);

            httpResponse.Headers.Set("Last-Modified", cacheItem.CachedUtcTimestamp.ToHttpDate());

            return(ResponseHandlerResult.ResponseWritten());
        }
        public async Task <ResponseHandlerResult> HandleResponseAsync(HttpContextBase context, IResponse suggestedResponse, ICache cache, string cacheKey)
        {
            context.ThrowIfNull("context");
            suggestedResponse.ThrowIfNull("suggestedResponse");

            if (!suggestedResponse.CachePolicy.HasPolicy || cache == null || cacheKey == null)
            {
                return(ResponseHandlerResult.ResponseNotHandled());
            }

            CacheItem cacheItem = await cache.GetAsync(cacheKey);

            string responseETag = suggestedResponse.CachePolicy.ETag;

            #region If-Match precondition header

            IfMatchHeader[] ifMatchHeaders = IfMatchHeader.ParseMany(context.Request.Headers["If-Match"]).ToArray();

            // Only consider If-Match headers if response status code is 2xx or 412
            if (ifMatchHeaders.Any() && ((suggestedResponse.StatusCode.StatusCode >= 200 && suggestedResponse.StatusCode.StatusCode <= 299) || suggestedResponse.StatusCode.StatusCode == 412))
            {
                // Return 412 if no If-Match header matches the response ETag
                // Return 412 if an "If-Match: *" header is present and the response has no ETag
                if (ifMatchHeaders.All(arg => arg.EntityTag.Value != responseETag) ||
                    (responseETag == null && ifMatchHeaders.Any(arg => arg.EntityTag.Value == "*")))
                {
                    return(await WriteResponseAsync(context.Response, new Response().PreconditionFailed()));
                }
            }

            #endregion

            #region If-None-Match precondition header

            IfNoneMatchHeader[] ifNoneMatchHeaders = IfNoneMatchHeader.ParseMany(context.Request.Headers["If-None-Match"]).ToArray();

            if (ifNoneMatchHeaders.Any())
            {
                // Return 304 if an If-None-Match header matches the response ETag and the request method was GET or HEAD
                // Return 304 if an "If-None-Match: *" header is present, the response has an ETag and the request method was GET or HEAD
                // Return 412 if an "If-None-Match: *" header is present, the response has an ETag and the request method was not GET or HEAD
                if (ifNoneMatchHeaders.Any(arg => arg.EntityTag.Value == responseETag) ||
                    (ifNoneMatchHeaders.Any(arg => arg.EntityTag.Value == "*") && responseETag != null))
                {
                    if (String.Equals(context.Request.HttpMethod, "GET", StringComparison.OrdinalIgnoreCase) || String.Equals(context.Request.HttpMethod, "HEAD", StringComparison.OrdinalIgnoreCase))
                    {
                        if (cacheItem != null)
                        {
                            cacheItem.Response.CachePolicy.Apply(context.Response.Cache);
                        }
                        else
                        {
                            suggestedResponse.CachePolicy.Apply(context.Response.Cache);
                        }

                        return(await WriteResponseAsync(context.Response, new Response().NotModified()));
                    }

                    return(await WriteResponseAsync(context.Response, new Response().PreconditionFailed()));
                }
            }

            #endregion

            #region If-Modified-Since precondition header

            IfModifiedSinceHeader ifModifiedSinceHeader = IfModifiedSinceHeader.Parse(context.Request.Headers["If-Modified-Since"]);
            bool validIfModifiedSinceHttpDate           = ifModifiedSinceHeader != null && ifModifiedSinceHeader.HttpDate <= _systemClock.UtcDateTime;

            // Only consider an If-Modified-Since header if response status code is 200 and the HTTP-date is valid
            if (suggestedResponse.StatusCode.ParsedStatusCode == HttpStatusCode.OK && validIfModifiedSinceHttpDate)
            {
                // Return 304 if the response was cached before the HTTP-date
                if (cacheItem != null && cacheItem.CachedUtcTimestamp < ifModifiedSinceHeader.HttpDate)
                {
                    return(await WriteResponseAsync(context.Response, new Response().NotModified()));
                }
            }

            #endregion

            #region If-Unmodified-Since precondition header

            IfUnmodifiedSinceHeader ifUnmodifiedSinceHeader = IfUnmodifiedSinceHeader.Parse(context.Request.Headers["If-Unmodified-Since"]);
            bool validIfUnmodifiedSinceHttpDate             = ifUnmodifiedSinceHeader != null && ifUnmodifiedSinceHeader.HttpDate <= _systemClock.UtcDateTime;

            // Only consider an If-Unmodified-Since header if response status code is 2xx or 412 and the HTTP-date is valid
            if (((suggestedResponse.StatusCode.StatusCode >= 200 && suggestedResponse.StatusCode.StatusCode <= 299) || suggestedResponse.StatusCode.StatusCode == 412) && validIfUnmodifiedSinceHttpDate)
            {
                // Return 412 if the previous response was removed from the cache or was cached again at a later time
                if (cacheItem == null || cacheItem.CachedUtcTimestamp >= ifUnmodifiedSinceHeader.HttpDate)
                {
                    return(await WriteResponseAsync(context.Response, new Response().PreconditionFailed()));
                }
            }

            #endregion

            #region No server caching

            // Do not cache the response when the response sends a non-cacheable status code, or when an Authorization header is present
            if (!_cacheableStatusCodes.Contains(suggestedResponse.StatusCode) || context.Request.Headers["Authorization"] != null)
            {
                return(await WriteResponseAsync(context.Response, suggestedResponse));
            }

            CacheControlHeader cacheControlHeader = CacheControlHeader.Parse(context.Request.Headers["Cache-Control"]);

            // Do not cache the response if a "Cache-Control: no-cache" or "Cache-Control: no-store" header is present
            if (cacheControlHeader != null && (cacheControlHeader.NoCache || cacheControlHeader.NoStore))
            {
                return(await WriteResponseAsync(context.Response, suggestedResponse));
            }

            IEnumerable <PragmaHeader> pragmaHeader = PragmaHeader.ParseMany(context.Request.Headers["Pragma"]);

            // Do not cache the response if a "Pragma: no-cache" header is present
            if (pragmaHeader.Any(arg => String.Equals(arg.Name, "no-cache", StringComparison.OrdinalIgnoreCase)))
            {
                return(await WriteResponseAsync(context.Response, suggestedResponse));
            }

            #endregion

            // Return 504 if the response has not been cached but the client is requesting to receive only a cached response
            if (cacheItem == null && cacheControlHeader != null && cacheControlHeader.OnlyIfCached)
            {
                return(await WriteResponseAsync(context.Response, new Response().GatewayTimeout()));
            }

            if (cacheItem != null)
            {
                // Write the cached response if no Cache-Control header is present
                // Write the cached response if a "Cache-Control: max-age" header is validated
                // Write the cached response if a "Cache-Control: max-stale" header is validated
                // Write the cached response if a "Cache-Control: min-fresh" header is validated
                if (cacheControlHeader == null ||
                    _systemClock.UtcDateTime - cacheItem.CachedUtcTimestamp <= cacheControlHeader.MaxAge ||
                    cacheControlHeader.OnlyIfCached ||
                    cacheItem.ExpiresUtcTimestamp == null ||
                    _systemClock.UtcDateTime - cacheItem.ExpiresUtcTimestamp.Value <= cacheControlHeader.MaxStale ||
                    cacheItem.ExpiresUtcTimestamp.Value - _systemClock.UtcDateTime < cacheControlHeader.MinFresh)
                {
                    return(await WriteResponseInCacheAsync(context.Response, cacheItem));
                }
            }

            bool cacheOnServer = suggestedResponse.CachePolicy.AllowsServerCaching;
            var  cacheResponse = new CacheResponse(suggestedResponse);

            if (cacheOnServer)
            {
                DateTime expirationUtcTimestamp = suggestedResponse.CachePolicy.ServerCacheExpirationUtcTimestamp != null
                                        ? suggestedResponse.CachePolicy.ServerCacheExpirationUtcTimestamp.Value
                                        : _systemClock.UtcDateTime + suggestedResponse.CachePolicy.ServerCacheMaxAge.Value;

                await cache.AddAsync(cacheKey, cacheResponse, expirationUtcTimestamp);
            }

            return(await WriteResponseAsync(context.Response, cacheResponse));
        }
Пример #40
0
 private void AddCacheItem(string key, CacheItem itemToAdd)
 {
     inMemoryCache.Add(key, itemToAdd);
 }
Пример #41
0
 public void Set(string key, T value, TimeSpan?lifetime = null)
 {
     Ensure.That(key, () => key).IsNotNullOrWhiteSpace();
     _store[key] = new CacheItem(value, lifetime);
 }
 /// <summary>
 /// Adds a value to the cache.
 /// </summary>
 /// <param name="item">The <c>CacheItem</c> to be added to the cache.</param>
 /// <returns>
 /// <c>true</c> if the key was not already added to the cache, <c>false</c> otherwise.
 /// </returns>
 protected override bool AddInternalPrepared(CacheItem <TCacheValue> item) =>
 this.Store(StoreMode.Add, item).Success;
        public override async Task <FetchCoinsResponse> FetchCoinsAsync(uint256[] txIds)
        {
            Guard.NotNull(txIds, nameof(txIds));

            FetchCoinsResponse result         = null;
            uint256            innerBlockHash = null;

            UnspentOutputs[] outputs     = new UnspentOutputs[txIds.Length];
            List <int>       miss        = new List <int>();
            List <uint256>   missedTxIds = new List <uint256>();

            using (_Lock.LockRead())
            {
                WaitOngoingTasks();
                for (int i = 0; i < txIds.Length; i++)
                {
                    CacheItem cache;
                    if (!_Unspents.TryGetValue(txIds[i], out cache))
                    {
                        miss.Add(i);
                        missedTxIds.Add(txIds[i]);
                    }
                    else
                    {
                        outputs[i] = cache.UnspentOutputs == null ? null :
                                     cache.UnspentOutputs.IsPrunable ? null :
                                     cache.UnspentOutputs.Clone();
                    }
                }
                PerformanceCounter.AddMissCount(miss.Count);
                PerformanceCounter.AddHitCount(txIds.Length - miss.Count);
            }
            var fetchedCoins = await Inner.FetchCoinsAsync(missedTxIds.ToArray()).ConfigureAwait(false);

            using (_Lock.LockWrite())
            {
                _Flushing.Wait();
                innerBlockHash = fetchedCoins.BlockHash;
                if (_BlockHash == null)
                {
                    Debug.Assert(_Unspents.Count == 0);
                    _InnerBlockHash = innerBlockHash;
                    _BlockHash      = innerBlockHash;
                }
                for (int i = 0; i < miss.Count; i++)
                {
                    var index   = miss[i];
                    var unspent = fetchedCoins.UnspentOutputs[i];
                    outputs[index] = unspent;
                    CacheItem cache = new CacheItem();
                    cache.ExistInInner    = unspent != null;
                    cache.IsDirty         = false;
                    cache.UnspentOutputs  = unspent;
                    cache.OriginalOutputs = unspent?._Outputs.ToArray();
                    _Unspents.TryAdd(txIds[index], cache);
                }
                result = new FetchCoinsResponse(outputs, _BlockHash);
            }

            if (CacheEntryCount > MaxItems)
            {
                Evict();
                if (CacheEntryCount > MaxItems)
                {
                    await FlushAsync().ConfigureAwait(false);

                    Evict();
                }
            }

            return(result);
        }
Пример #44
0
 /// <summary>
 /// Adds or gets an existing cache region.
 /// </summary>
 /// <param name="item">The cache item.</param>
 /// <returns></returns>
 private Dictionary <string, CacheEntryItem> AddOrGetExistingCacheRegion(CacheItem item)
 {
     return(this.AddOrGetExistingCacheRegion(item.RegionName));
 }
Пример #45
0
 protected abstract void OnAccess(CacheItem item);
Пример #46
0
        /// <summary>
        /// Merges the provided descriptions with those found in cache
        /// </summary>
        /// <param name="culture">A <see cref="CultureInfo"/> specifying the language of the <code>descriptions</code></param>
        /// <param name="descriptions">A <see cref="IEnumerable{MarketDescriptionDTO}"/> containing market descriptions in specified language</param>
        private void Merge(CultureInfo culture, IEnumerable <MarketDescriptionDTO> descriptions)
        {
            Contract.Requires(culture != null);
            Contract.Requires(descriptions != null && descriptions.Any());

            var descriptionList = descriptions as List <MarketDescriptionDTO> ?? descriptions.ToList();

            try
            {
                _semaphoreCacheMerge.Wait();
                foreach (var marketDescription in descriptionList)
                {
                    try
                    {
                        var cachedItem = _cache.GetCacheItem(marketDescription.Id.ToString());
                        if (cachedItem == null)
                        {
                            cachedItem = new CacheItem(marketDescription.Id.ToString(), MarketDescriptionCacheItem.Build(marketDescription, _mappingValidatorFactory, culture, CacheName));
                            _cache.Add(cachedItem, _cacheItemPolicy);
                        }
                        else
                        {
                            ((MarketDescriptionCacheItem)cachedItem.Value).Merge(marketDescription, culture);
                        }
                    }
                    catch (Exception e)
                    {
                        if (!(e is InvalidOperationException))
                        {
                            throw;
                        }

                        ExecutionLog.Warn($"Mapping validation for MarketDescriptionCacheItem failed. Id={marketDescription.Id}", e);
                    }
                }
                _fetchedLanguages.Add(culture);
            }
            finally
            {
                if (!_isDisposed)
                {
                    _semaphoreCacheMerge.Release();
                }
            }

            //var c = _cache.Count();
            //ExecutionLog.Debug($"InvariantMarketDescriptionCache count: {c}.");
            //foreach (var keyValue in _cache.Where(s=>s.Key != null))
            //{
            //    var ci = (MarketDescriptionCacheItem)keyValue.Value;
            //    if (ci.Mappings != null)
            //    {
            //        foreach (var mapping in ci.Mappings)
            //        {
            //            if (mapping.OutcomeMappings != null)
            //            {
            //                foreach (var outcomeMapping in mapping.OutcomeMappings)
            //                {
            //                    if (outcomeMapping.ProducerOutcomeNames.Count != ci.FetchedLanguages.Count)
            //                    {
            //                        ExecutionLog.Error($"Market {ci.Id}: problem with outcome mapping {outcomeMapping.OutcomeId} and mapped marketId {outcomeMapping.MarketId}");
            //                    }
            //                }
            //            }
            //        }
            //    }
            //}
            //var cacheItem = _cache.First();
        }
Пример #47
0
        public void OnResultExecuted(ResultExecutedContext filterContext)
        {
            // This filter is not reentrant (multiple executions within the same request are
            // not supported) so child actions are ignored completely.
            if (filterContext.IsChildAction)
            {
                return;
            }

            var captureHandlerIsAttached = false;

            try {
                if (!_isCachingRequest)
                {
                    return;
                }

                Logger.Debug("Item '{0}' was rendered.", _cacheKey);


                if (!ResponseIsCacheable(filterContext))
                {
                    filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    filterContext.HttpContext.Response.Cache.SetNoStore();
                    filterContext.HttpContext.Response.Cache.SetMaxAge(new TimeSpan(0));
                    return;
                }

                // Determine duration and grace time.
                var cacheDuration  = _cacheRouteConfig != null && _cacheRouteConfig.Duration.HasValue ? _cacheRouteConfig.Duration.Value : CacheSettings.DefaultCacheDuration;
                var cacheGraceTime = _cacheRouteConfig != null && _cacheRouteConfig.GraceTime.HasValue ? _cacheRouteConfig.GraceTime.Value : CacheSettings.DefaultCacheGraceTime;

                // Include each content item ID as tags for the cache entry.
                var contentItemIds = _displayedContentItemHandler.GetDisplayed().Select(x => x.ToString(CultureInfo.InvariantCulture)).ToArray();

                // Capture the response output using a custom filter stream.
                var response      = filterContext.HttpContext.Response;
                var captureStream = new CaptureStream(response.Filter);
                response.Filter = captureStream;

                // Add ETag header for the newly created item
                var etag = Guid.NewGuid().ToString("n");
                if (HttpRuntime.UsingIntegratedPipeline)
                {
                    if (response.Headers.Get("ETag") == null)
                    {
                        response.Headers["ETag"] = etag;
                    }
                }

                captureStream.Captured += (output) => {
                    try {
                        // Since this is a callback any call to injected dependencies can result in an Autofac exception: "Instances
                        // cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed."
                        // To prevent access to the original lifetime scope a new work context scope should be created here and dependencies
                        // should be resolved from it.

                        // Recheck the response status code incase it was modified before the callback.
                        if (response.StatusCode != 200)
                        {
                            Logger.Debug("Response for item '{0}' will not be cached because status code was set to {1} during rendering.", _cacheKey, response.StatusCode);
                            return;
                        }

                        using (var scope = _workContextAccessor.CreateWorkContextScope()) {
                            var cacheItem = new CacheItem()
                            {
                                CachedOnUtc       = _now,
                                Duration          = cacheDuration,
                                GraceTime         = cacheGraceTime,
                                Output            = output,
                                ContentType       = response.ContentType,
                                QueryString       = filterContext.HttpContext.Request.Url.Query,
                                CacheKey          = _cacheKey,
                                InvariantCacheKey = _invariantCacheKey,
                                Url        = filterContext.HttpContext.Request.Url.AbsolutePath,
                                Tenant     = scope.Resolve <ShellSettings>().Name,
                                StatusCode = response.StatusCode,
                                Tags       = new[] { _invariantCacheKey }.Union(contentItemIds).ToArray(),
                                ETag       = etag
                            };

                            // Write the rendered item to the cache.
                            var cacheStorageProvider = scope.Resolve <IOutputCacheStorageProvider>();
                            cacheStorageProvider.Set(_cacheKey, cacheItem);

                            Logger.Debug("Item '{0}' was written to cache.", _cacheKey);

                            // Also add the item tags to the tag cache.
                            var tagCache = scope.Resolve <ITagCache>();
                            foreach (var tag in cacheItem.Tags)
                            {
                                tagCache.Tag(tag, _cacheKey);
                            }
                        }
                    }
                    finally {
                        // Always release the cache key lock when the request ends.
                        ReleaseCacheKeyLock();
                    }
                };

                captureHandlerIsAttached = true;
            }
            finally {
                // If the response filter stream capture handler was attached then we'll trust
                // it to release the cache key lock at some point in the future when the stream
                // is flushed; otherwise we'll make sure we'll release it here.
                if (!captureHandlerIsAttached)
                {
                    ReleaseCacheKeyLock();
                }
            }
        }
        private bool Set(CacheItem <TCacheValue> item, When when, bool sync = false)
        {
            if (!_isLuaAllowed)
            {
                return(SetNoScript(item, when, sync));
            }

            var fullKey = GetKey(item.Key, item.Region);
            var value   = ToRedisValue(item.Value);

            var flags = sync ? CommandFlags.None : CommandFlags.FireAndForget;

            // ARGV [1]: value, [2]: type, [3]: expirationMode, [4]: expirationTimeout(millis), [5]: created(ticks)
            var parameters = new RedisValue[]
            {
                value,
                item.ValueType.AssemblyQualifiedName,
                (int)item.ExpirationMode,
                (long)item.ExpirationTimeout.TotalMilliseconds,
                item.CreatedUtc.Ticks,
                item.UsesExpirationDefaults
            };

            RedisResult result;

            if (when == When.NotExists)
            {
                result = Eval(ScriptType.Add, fullKey, parameters, flags);
            }
            else
            {
                result = Eval(ScriptType.Put, fullKey, parameters, flags);
            }

            if (result == null)
            {
                if (flags.HasFlag(CommandFlags.FireAndForget))
                {
                    if (!string.IsNullOrWhiteSpace(item.Region))
                    {
                        // setting region lookup key if region is being used
                        _connection.Database.HashSet(item.Region, fullKey, "regionKey", When.Always, CommandFlags.FireAndForget);
                    }

                    // put runs via fire and forget, so we don't get a result back
                    return(true);
                }

                // should never happen, something went wrong with the script
                throw new InvalidOperationException("Something went wrong adding an item, result must not be null.");
            }
            else
            {
                if (result.IsNull && when == When.NotExists)
                {
                    // add failed because element exists already
                    if (Logger.IsEnabled(LogLevel.Information))
                    {
                        Logger.LogInfo("DB {0} | Failed to add item [{1}] because it exists.", _connection.Database.Database, item.ToString());
                    }

                    return(false);
                }

                var resultValue = (RedisValue)result;

                if (resultValue.HasValue && resultValue.ToString().Equals("OK", StringComparison.OrdinalIgnoreCase))
                {
                    // Added successfully:
                    if (!string.IsNullOrWhiteSpace(item.Region))
                    {
                        // setting region lookup key if region is being used
                        // we cannot do that within the lua because the region could be on another cluster node!
                        _connection.Database.HashSet(item.Region, fullKey, "regionKey", When.Always, CommandFlags.FireAndForget);
                    }

                    return(true);
                }

                Logger.LogWarn("DB {0} | Failed to set item [{1}]: {2}.", _connection.Database.Database, item.ToString(), resultValue.ToString());
                return(false);
            }
        }
Пример #49
0
 public override void Set(CacheItem item, CacheItemPolicy policy)
 {
     Set(item.Key, item.Value, policy, item.RegionName);
 }
        public void OnActionExecuting(ActionExecutingContext filterContext)
        {
            // apply OutputCacheAttribute logic if defined
            var actionAttributes     = filterContext.ActionDescriptor.GetCustomAttributes(typeof(OutputCacheAttribute), true);
            var controllerAttributes = filterContext.ActionDescriptor.ControllerDescriptor.GetCustomAttributes(typeof(OutputCacheAttribute), true);
            var outputCacheAttribute = actionAttributes.Concat(controllerAttributes).Cast <OutputCacheAttribute>().FirstOrDefault();

            if (outputCacheAttribute != null)
            {
                if (outputCacheAttribute.Duration <= 0 || outputCacheAttribute.NoStore)
                {
                    Logger.Debug("Request ignored based on OutputCache attribute");
                    return;
                }
            }

            // saving the current datetime
            _now = _clock.UtcNow;

            // before executing an action, we check if a valid cached result is already
            // existing for this context (url, theme, culture, tenant)

            Logger.Debug("Request on: " + filterContext.RequestContext.HttpContext.Request.RawUrl);

            // don't cache POST requests
            if (filterContext.HttpContext.Request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
            {
                Logger.Debug("Request ignored on POST");
                return;
            }

            // don't cache the admin
            if (AdminFilter.IsApplied(new RequestContext(filterContext.HttpContext, new RouteData())))
            {
                Logger.Debug("Request ignored on Admin section");
                return;
            }

            // ignore child actions, e.g. HomeController is using RenderAction()
            if (filterContext.IsChildAction)
            {
                Logger.Debug("Request ignored on Child actions");
                return;
            }

            _workContext = _workContextAccessor.GetContext();

            // don't return any cached content, or cache any content, if the user is authenticated
            if (_workContext.CurrentUser != null)
            {
                Logger.Debug("Request ignored on Authenticated user");
                return;
            }


            // caches the default cache duration to prevent a query to the settings
            _cacheDuration = _cacheManager.Get("CacheSettingsPart.Duration",
                                               context => {
                context.Monitor(_signals.When(CacheSettingsPart.CacheKey));
                return(_workContext.CurrentSite.As <CacheSettingsPart>().DefaultCacheDuration);
            }
                                               );

            // caches the default max age duration to prevent a query to the settings
            _maxAge = _cacheManager.Get("CacheSettingsPart.MaxAge",
                                        context => {
                context.Monitor(_signals.When(CacheSettingsPart.CacheKey));
                return(_workContext.CurrentSite.As <CacheSettingsPart>().DefaultMaxAge);
            }
                                        );

            _varyQueryStringParameters = _cacheManager.Get("CacheSettingsPart.VaryQueryStringParameters",
                                                           context => {
                context.Monitor(_signals.When(CacheSettingsPart.CacheKey));
                var varyQueryStringParameters = _workContext.CurrentSite.As <CacheSettingsPart>().VaryQueryStringParameters;

                return(string.IsNullOrWhiteSpace(varyQueryStringParameters) ? null
                        : varyQueryStringParameters.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray());
            }
                                                           );

            var varyRequestHeadersFromSettings = _cacheManager.Get("CacheSettingsPart.VaryRequestHeaders",
                                                                   context => {
                context.Monitor(_signals.When(CacheSettingsPart.CacheKey));
                var varyRequestHeaders = _workContext.CurrentSite.As <CacheSettingsPart>().VaryRequestHeaders;

                return(string.IsNullOrWhiteSpace(varyRequestHeaders) ? null
                        : varyRequestHeaders.Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray());
            }
                                                                   );

            _varyRequestHeaders = (varyRequestHeadersFromSettings == null) ? new HashSet <string>() : new HashSet <string>(varyRequestHeadersFromSettings);

            // different tenants with the same urls have different entries
            _varyRequestHeaders.Add("HOST");

            // Set the Vary: Accept-Encoding response header.
            // This instructs the proxies to cache two versions of the resource: one compressed, and one uncompressed.
            // The correct version of the resource is delivered based on the client request header.
            // This is a good choice for applications that are singly homed and depend on public proxies for user locality.
            _varyRequestHeaders.Add("Accept-Encoding");

            // caches the ignored urls to prevent a query to the settings
            _ignoredUrls = _cacheManager.Get("CacheSettingsPart.IgnoredUrls",
                                             context => {
                context.Monitor(_signals.When(CacheSettingsPart.CacheKey));
                return(_workContext.CurrentSite.As <CacheSettingsPart>().IgnoredUrls);
            }
                                             );

            // caches the culture setting
            _applyCulture = _cacheManager.Get("CacheSettingsPart.ApplyCulture",
                                              context => {
                context.Monitor(_signals.When(CacheSettingsPart.CacheKey));
                return(_workContext.CurrentSite.As <CacheSettingsPart>().ApplyCulture);
            }
                                              );

            // caches the debug mode
            _debugMode = _cacheManager.Get("CacheSettingsPart.DebugMode",
                                           context => {
                context.Monitor(_signals.When(CacheSettingsPart.CacheKey));
                return(_workContext.CurrentSite.As <CacheSettingsPart>().DebugMode);
            }
                                           );

            // don't cache ignored url ?
            if (IsIgnoredUrl(filterContext.RequestContext.HttpContext.Request.AppRelativeCurrentExecutionFilePath, _ignoredUrls))
            {
                return;
            }

            var queryString    = filterContext.RequestContext.HttpContext.Request.QueryString;
            var requestHeaders = filterContext.RequestContext.HttpContext.Request.Headers;
            var parameters     = new Dictionary <string, object>(filterContext.ActionParameters);

            foreach (var key in queryString.AllKeys)
            {
                if (key == null)
                {
                    continue;
                }

                parameters[key] = queryString[key];
            }

            foreach (var varyByRequestHeader in _varyRequestHeaders)
            {
                if (requestHeaders.AllKeys.Contains(varyByRequestHeader))
                {
                    parameters["HEADER:" + varyByRequestHeader] = requestHeaders[varyByRequestHeader];
                }
            }

            // compute the cache key
            _cacheKey = ComputeCacheKey(filterContext, parameters);

            // create a tag which doesn't care about querystring
            _invariantCacheKey = ComputeCacheKey(filterContext, null);

            // don't retrieve cache content if refused
            // in this case the result of the action will update the current cached version
            if (filterContext.RequestContext.HttpContext.Request.Headers["Cache-Control"] != "no-cache")
            {
                // fetch cached data
                _cacheItem = _cacheStorageProvider.GetCacheItem(_cacheKey);

                if (_cacheItem == null)
                {
                    Logger.Debug("Cached version not found");
                }
            }
            else
            {
                Logger.Debug("Cache-Control = no-cache requested");
            }

            var response = filterContext.HttpContext.Response;

            // render cached content
            if (_cacheItem != null)
            {
                Logger.Debug("Cache item found, expires on " + _cacheItem.ValidUntilUtc);

                var output = _cacheItem.Output;

                // adds some caching information to the output if requested
                if (_debugMode)
                {
                    response.AddHeader("X-Cached-On", _cacheItem.CachedOnUtc.ToString("r"));
                    response.AddHeader("X-Cached-Until", _cacheItem.ValidUntilUtc.ToString("r"));
                }

                // shorcut action execution
                filterContext.Result = new ContentResult {
                    Content     = output,
                    ContentType = _cacheItem.ContentType
                };

                response.StatusCode = _cacheItem.StatusCode;

                ApplyCacheControl(_cacheItem, response);

                return;
            }

            _cacheItem = new CacheItem();

            // get contents
            ApplyCacheControl(_cacheItem, response);

            // no cache content available, intercept the execution results for caching
            _previousFilter = response.Filter;
            response.Filter = _filter = new CapturingResponseFilter();
        }
Пример #51
0
        public void Add(string key, object data, int cacheTime, string region)
        {
            var cachItem = new CacheItem <object>(key, region, data, ExpirationMode.Absolute, TimeSpan.FromMinutes(cacheTime));

            Cache.Add(cachItem);
        }
Пример #52
0
 internal StoreOperation(StoreMode mode, string key, CacheItem value, uint expires)
     : base((StoreCommand)mode, key, value, expires, 0)
 {
     this.mode = mode;
 }
 /// <summary>
 /// Puts the <paramref name="item"/> into the cache. If the item exists it will get updated
 /// with the new value. If the item doesn't exist, the item will be added to the cache.
 /// </summary>
 /// <param name="item">The <c>CacheItem</c> to be added to the cache.</param>
 protected override void PutInternalPrepared(CacheItem <TCacheValue> item) =>
 Retry(() => Set(item, When.Always, false));
Пример #54
0
 public override object CreateMemento()
 {
     //no state to remember, but we do want to remove the reference to the 'real lut'.  It will be recreated later.
     _cacheItem = null;
     return(base.CreateMemento());
 }
#pragma warning restore CS1591
#pragma warning restore SA1600

        /// <summary>
        /// Adds a value to the cache.
        /// <para>
        /// Add call is synced, so might be slower than put which is fire and forget but we want to
        /// return true|false if the operation was successfully or not. And always returning true
        /// could be misleading if the item already exists
        /// </para>
        /// </summary>
        /// <param name="item">The <c>CacheItem</c> to be added to the cache.</param>
        /// <returns>
        /// <c>true</c> if the key was not already added to the cache, <c>false</c> otherwise.
        /// </returns>
        protected override bool AddInternalPrepared(CacheItem <TCacheValue> item) =>
        Retry(() => Set(item, When.NotExists, true));
Пример #56
0
        public void OnResultExecuted(ResultExecutedContext filterContext)
        {
            var captureHandlerIsAttached = false;

            try {
                // This filter is not reentrant (multiple executions within the same request are
                // not supported) so child actions are ignored completely.
                if (filterContext.IsChildAction || !_isCachingRequest)
                {
                    return;
                }

                Logger.Debug("Item '{0}' was rendered.", _cacheKey);

                // Obtain individual route configuration, if any.
                CacheRouteConfig configuration = null;
                var configurations             = _cacheService.GetRouteConfigs();
                if (configurations.Any())
                {
                    var route = filterContext.Controller.ControllerContext.RouteData.Route;
                    var key   = _cacheService.GetRouteDescriptorKey(filterContext.HttpContext, route);
                    configuration = configurations.FirstOrDefault(c => c.RouteKey == key);
                }

                if (!ResponseIsCacheable(filterContext, configuration))
                {
                    filterContext.HttpContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    filterContext.HttpContext.Response.Cache.SetNoStore();
                    filterContext.HttpContext.Response.Cache.SetMaxAge(new TimeSpan(0));
                    return;
                }

                // Determine duration and grace time.
                var cacheDuration  = configuration != null && configuration.Duration.HasValue ? configuration.Duration.Value : CacheSettings.DefaultCacheDuration;
                var cacheGraceTime = configuration != null && configuration.GraceTime.HasValue ? configuration.GraceTime.Value : CacheSettings.DefaultCacheGraceTime;

                // Include each content item ID as tags for the cache entry.
                var contentItemIds = _displayedContentItemHandler.GetDisplayed().Select(x => x.ToString(CultureInfo.InvariantCulture)).ToArray();

                // Capture the response output using a custom filter stream.
                var response      = filterContext.HttpContext.Response;
                var captureStream = new CaptureStream(response.Filter);
                response.Filter         = captureStream;
                captureStream.Captured += (output) => {
                    try {
                        // Since this is a callback any call to injected dependencies can result in an Autofac exception: "Instances
                        // cannot be resolved and nested lifetimes cannot be created from this LifetimeScope as it has already been disposed."
                        // To prevent access to the original lifetime scope a new work context scope should be created here and dependencies
                        // should be resolved from it.

                        using (var scope = _workContextAccessor.CreateWorkContextScope()) {
                            var cacheItem = new CacheItem()
                            {
                                CachedOnUtc       = _now,
                                Duration          = cacheDuration,
                                GraceTime         = cacheGraceTime,
                                Output            = output,
                                ContentType       = response.ContentType,
                                QueryString       = filterContext.HttpContext.Request.Url.Query,
                                CacheKey          = _cacheKey,
                                InvariantCacheKey = _invariantCacheKey,
                                Url        = filterContext.HttpContext.Request.Url.AbsolutePath,
                                Tenant     = scope.Resolve <ShellSettings>().Name,
                                StatusCode = response.StatusCode,
                                Tags       = new[] { _invariantCacheKey }.Union(contentItemIds).ToArray()
                            };

                            // Write the rendered item to the cache.
                            var cacheStorageProvider = scope.Resolve <IOutputCacheStorageProvider>();
                            cacheStorageProvider.Remove(_cacheKey);
                            cacheStorageProvider.Set(_cacheKey, cacheItem);

                            Logger.Debug("Item '{0}' was written to cache.", _cacheKey);

                            // Also add the item tags to the tag cache.
                            var tagCache = scope.Resolve <ITagCache>();
                            foreach (var tag in cacheItem.Tags)
                            {
                                tagCache.Tag(tag, _cacheKey);
                            }
                        }
                    }
                    finally {
                        // Always release the cache key lock when the request ends.
                        ReleaseCacheKeyLock();
                    }
                };

                captureHandlerIsAttached = true;
            }
            finally {
                // If the response filter stream capture handler was attached then we'll trust
                // it to release the cache key lock at some point in the future when the stream
                // is flushed; otherwise we'll make sure we'll release it here.
                if (!captureHandlerIsAttached)
                {
                    ReleaseCacheKeyLock();
                }
            }
        }
Пример #57
0
 public void Add(CacheItem item, bool moveItem = true) => AddAndGet(item, moveItem);
 public void Add(CacheItem newCacheItem)
 {
     throw new Exception();
 }
Пример #59
0
 public LinearDirectMemoryCache(IMemoryProvider <Word> backingMemoryProvider, int cacheSize)
     : base(backingMemoryProvider)
 {
     Cache = new CacheItem <Word> [cacheSize];
 }
 public VBStore(VBucketNodeLocator locator, StoreMode mode, string key, CacheItem value, uint expires)
     : base(mode, key, value, expires)
 {
     this.locator = locator;
 }