private void ContentCacheUpdateCallback(CacheEntryUpdateArguments arguments)
        {
            if (arguments.RemovedReason == CacheEntryRemovedReason.Expired)
            {
                var expiredCacheItem = MemoryCache.Default.GetCacheItem(arguments.Key);

                if (expiredCacheItem != null)
                {
                    String url = expiredCacheItem.Key;
                    Logger.Trace(String.Format("Return From ContentCacheUpdateCallback {0}", url));
                    var ret = GetJsonFromCacheOrWebservice(url);

                    expiredCacheItem.Value = ret;

                    arguments.UpdatedCacheItem = expiredCacheItem;

                    var policy = new CacheItemPolicy();
                    policy.Priority = CacheItemPriority.Default;

                    _callbackU                = new CacheEntryUpdateCallback(ContentCacheUpdateCallback);
                    policy.UpdateCallback     = _callbackU;
                    policy.AbsoluteExpiration = DateTime.Now.AddMinutes(_cacheMinute);


                    arguments.UpdatedCacheItemPolicy = policy;
                }
                else
                {
                    arguments.UpdatedCacheItem = null;
                }
            }
        }
Exemple #2
0
 /// <summary>
 /// 定义在从缓存中即将移除某个缓存项时触发
 /// </summary>
 /// <param name="args">有关将从缓存中移除的缓存项的信息</param>
 protected virtual void OnUpdateCallback(CacheEntryUpdateArguments args)
 {
     if (_UpdateCallback != null)
     {
         _UpdateCallback(args);
     }
 }
Exemple #3
0
        /// <summary>
        /// Updates a cached request when the item has expired.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="arguments"></param>
        public void CacheUpdated <T>(CacheEntryUpdateArguments arguments) where T : new()
        {
            if (arguments.RemovedReason == CacheEntryRemovedReason.Expired)
            {
                CachedRequestResponse <T> cachedItem = arguments.Source[arguments.Key] as CachedRequestResponse <T>;

                log.DebugFormat("Cache item expired and being updated for request: {0}", GetRequestUrl(cachedItem.Request));

                CachedRequestResponse <T> newCachedItem = new CachedRequestResponse <T>();
                newCachedItem.Request     = cachedItem.Request;
                newCachedItem.Data        = this.ExecuteRestRequest <T>(cachedItem.Request);
                newCachedItem.LastCached  = DateTime.Now;
                newCachedItem.Duration    = cachedItem.Duration;
                newCachedItem.KeepCurrent = true;


                CacheItemPolicy policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = DateTimeOffset.Now.Add(cachedItem.Duration);
                policy.UpdateCallback     = CacheUpdated <T>;

                arguments.UpdatedCacheItem       = new CacheItem(arguments.Key, newCachedItem);
                arguments.UpdatedCacheItemPolicy = policy;


                //MemoryCache cache = MemoryCache.Default;


                log.Debug("Request automatically recached.");
            }
        }
Exemple #4
0
        public static void DefaultExpiredBehavior(CacheEntryUpdateArguments args)
        {
            const char SEPARATOR = '-';

            var split = args.Key.Split(SEPARATOR);

            var key  = split.First();
            var type = split.Last();
        }
Exemple #5
0
 private void CacheItemRemoved(CacheEntryUpdateArguments args)
 {
     if (args.RemovedReason == CacheEntryRemovedReason.Expired || args.RemovedReason == CacheEntryRemovedReason.Removed)
     {
         var key = args.Key;
         args.UpdatedCacheItem       = new CacheItem(key, updateCacheFunc(key));
         args.UpdatedCacheItemPolicy = GetPolicy();
     }
 }
Exemple #6
0
        private void UpdateCallback(CacheEntryUpdateArguments arguments)
        {
            var expired = arguments.RemovedReason == CacheEntryRemovedReason.Expired;

            if (!expired)
            {
                logger.TraceError(
                    $"Temp cache: Can't refresh cache since remove reason is {arguments.RemovedReason}. Key:{arguments.Key}");
                return;
            }
            var oldItem = (DocItemCache)memCache?[arguments.Key];

            if (oldItem == null)
            {
                // If memcache was disposed don't error out
                if (memCache != null)
                {
                    logger.TraceError(
                        $"Temp cache: Can't refresh cache since item is not in the cache. Key:{arguments.Key}");
                }

                return;
            }
            var hits = oldItem.Hits;
            var lowerHitsThreshold = LatestCacheConfiguration.LowerHitsThreshold;

            if (hits < lowerHitsThreshold)
            {
                logger.TraceInfo(
                    $"Temp cache: Will not refresh cache item with {hits} hits. LowerHitsThreshold: {lowerHitsThreshold}. Key: {arguments.Key}");
                return;
            }
            logger.TraceInfo(
                $"Temp cache: Refreshing cache. Hits: {hits} higher than {lowerHitsThreshold}. Key: {arguments.Key}");

            var reader = storeReader;

            try
            {
                var     oldKey       = oldItem.Item.Key;
                DocItem freshDocItem = reader.ReadFromStore(oldKey).GetAwaiter().GetResult();
                freshDocItem = freshDocItem ?? EmptyDocItem.Create(oldKey);
                var docItemCache = new DocItemCache(freshDocItem);
                var cacheItem    = new CacheItem(oldKey.ToString(), docItemCache);
                arguments.UpdatedCacheItem       = cacheItem;
                arguments.UpdatedCacheItemPolicy = GetPolicy();

                logger.TraceInfo(
                    $"Temp cache: Cache refreshed! Key: {arguments.Key}");
            }
            catch (Exception e)
            {
                logger.TraceError(
                    $"Temp cache: Failed to refresh cache. Key:{arguments.Key}. Error: {e}");
            }
        }
Exemple #7
0
 private void CacheItemRemoved(CacheEntryUpdateArguments args)
 {
     if (args.RemovedReason == CacheEntryRemovedReason.Expired || args.RemovedReason == CacheEntryRemovedReason.Removed)
     {
         var id            = args.Key;
         var updatedEntity = _baseRepository.GetById(id);
         args.UpdatedCacheItem       = new CacheItem(id, updatedEntity);
         args.UpdatedCacheItemPolicy = GetPolicy();
     }
 }
Exemple #8
0
        private void CachedItemUpdateCallback(CacheEntryUpdateArguments arguments)
        {
            // Log these values from arguments list
            String strLog = String.Concat("Reason: ",
                                          arguments.RemovedReason.ToString(),
                                          " | Key-Name: ",
                                          arguments.UpdatedCacheItem.Key,
                                          " | Value-Object: ",
                                          arguments.UpdatedCacheItem.Value.ToString());

            Debug.WriteLine(strLog);
        }
Exemple #9
0
        private void RefetchItem(CacheEntryUpdateArguments args)
        {
            var cacheKey     = args.Key;
            var meta         = _meta[cacheKey];
            int refreshLimit = meta.MaxCount;
            int refreshCount = meta.CurrentCount + 1;

            if (refreshLimit == 0 || refreshCount <= refreshLimit)
            {
                string msg = String.Format("Refetching cache ({0}) - #{1}", cacheKey, refreshCount);
                EventLogger.Instance.Log(new LogInformation()
                {
                    Type = LogType.Debug, Category = "Cache", Message = msg, Origin = Configuration.Settings.Origin.ToString()
                });
                Debug.Print(msg);

                //_meta[cacheKey] = new Tuple<Func<object>, TimeSpan, int, int>(meta.Item1, meta.Item2, meta.Item3, refreshCount);
                _meta[cacheKey] = meta;
                //new Tuple<Func<object>, TimeSpan, int, int>(meta.Item1, meta.Item2, meta.Item3, refreshCount);

                args.UpdatedCacheItem = new CacheItem(cacheKey, new object());

                args.UpdatedCacheItemPolicy = new CacheItemPolicy()
                {
                    AbsoluteExpiration = Repository.CurrentDate.Add(meta.CacheTime),
                    UpdateCallback     = new CacheEntryUpdateCallback(RefetchItem)
                };

                try
                {
                    //throw new NotImplementedException("This needs implementing");
                    var data = RefetchData(meta);
                    SetItem(cacheKey, data, meta.CacheTime);
                }
                catch (Exception ex)
                {
                    EventLogger.Log(ex, Domain.Models.Origin.Unknown);
                }
            }
            else
            {
                string msg = String.Format("Expiring cache ({0}) - #{1}", cacheKey, refreshCount);
                EventLogger.Instance.Log(new LogInformation()
                {
                    Type = LogType.Debug, Category = "Cache", Message = msg, Origin = Configuration.Settings.Origin.ToString()
                });
                Debug.Print(msg);
                Remove(cacheKey, true);
            }
        }
Exemple #10
0
        private void UpdateCallback(CacheEntryUpdateArguments args)
        {
            if (args.RemovedReason == CacheEntryRemovedReason.Expired)
            {
                NotifyExpired(args.Key);
                CacheItem updatedCacheItem = CreateCacheItem(args.Key);

                if (updatedCacheItem != null)
                {
                    args.UpdatedCacheItem       = updatedCacheItem;
                    args.UpdatedCacheItemPolicy = CreateCachePolicy();
                }
            }
        }
Exemple #11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="args"></param>
        private void CacheEntryUpdate(CacheEntryUpdateArguments args)
        {
            var cacheItem = MemCache.GetCacheItem(args.Key);
            var cacheObj  = cacheItem.Value;

            cacheItem.Value       = cacheObj;
            args.UpdatedCacheItem = cacheItem;
            var policy = new CacheItemPolicy
            {
                UpdateCallback     = new CacheEntryUpdateCallback(CacheEntryUpdate),
                AbsoluteExpiration = DateTimeOffset.UtcNow.AddMinutes(RefreshInterval)
            };

            args.UpdatedCacheItemPolicy = policy;
        }
        public void CacheItemRemoved(CacheEntryUpdateArguments args)
        {
            if (args.RemovedReason == CacheEntryRemovedReason.ChangeMonitorChanged)
            {
                //var id = args.Key;
                //var updatedEntity = "MYMODIFIEDVALUE";
                //args.UpdatedCacheItem = new CacheItem(id, updatedEntity);

                //var policy = new CacheItemPolicy();
                //policy.AbsoluteExpiration = DateTimeOffset.MaxValue;
                //policy.ChangeMonitors.Add(new HostFileChangeMonitor(new List<string> { "D:\\Websites\\Myfile.txt" }));
                //policy.UpdateCallback = CacheItemRemoved;
                //args.UpdatedCacheItemPolicy = policy;
            }
        }
        /// <summary>
        /// Updates the workout state stored in cache
        /// </summary>
        /// <param name="args">The update arguments</param>
        private void UpdateWorkoutState(CacheEntryUpdateArguments args)
        {
            string serialNumber = args.Key;

            if (!_activePolls.ContainsKey(serialNumber))
            {
                // This device is no longer connected, so do not refresh the state
                return;
            }

            if (args?.UpdatedCacheItem == null)
            {
                return;
            }

            args.UpdatedCacheItem.Value = GetWorkoutState(serialNumber);
        }
Exemple #14
0
        private static void CacheUpdateHandler(CacheEntryUpdateArguments args)
        {
            ProcessStaticCacheBusterManifest();
            var cacheItem = Cache.GetCacheItem(args.Key);

            if (cacheItem != null)
            {
                cacheItem.Value = String.Empty;
            }
            else
            {
                cacheItem = new CacheItem("cacheItem", String.Empty);
            }

            args.UpdatedCacheItem       = cacheItem;
            args.UpdatedCacheItemPolicy = GetCachePolicy();
        }
Exemple #15
0
        private static void CacheUpdateHandler(CacheEntryUpdateArguments args)
        {
            CacheAllAffiliates();
            var cacheItem = Cache.GetCacheItem(args.Key);

            if (cacheItem != null)
            {
                cacheItem.Value = String.Empty;
            }
            else
            {
                cacheItem = new CacheItem("cacheItem", String.Empty);
            }

            args.UpdatedCacheItem       = cacheItem;
            args.UpdatedCacheItemPolicy = GetCachePolicy();
        }
        /// <summary>
        /// Calls when data in the cache was updated.
        /// </summary>
        /// <param name="arguments">The entity that responsible for displaying updated cache entry.</param>
        private void UpdateCallback(CacheEntryUpdateArguments arguments)
        {
            if (_monitor != null)
            {
                _monitor.Dispose();
            }

            _dependency.OnChange -= DependencyOnOnChange;

            if (_hasDataChanged)
            {
                CacheItemPolicy policy;

                arguments.UpdatedCacheItem       = new CacheItem(arguments.Key, LoadEntities(out policy));
                arguments.UpdatedCacheItemPolicy = policy;
                _hasDataChanged = false;

                ApplicationLogger.LogMessage(LogMessageType.Info, $"Data related to the {arguments.Key} ithe cache was updated and reloaded.");
            }
        }
Exemple #17
0
 public void UpdateCacheAgain(CacheEntryUpdateArguments cacheInfo)
 {
     try
     {
         cacheInfo.UpdatedCacheItem       = new CacheItem(this.cacheKey, base.GetDataFromContentFunction());
         cacheInfo.UpdatedCacheItemPolicy = new CacheItemPolicy()
         {
             UpdateCallback = UpdateCacheAgain, AbsoluteExpiration = DateTime.UtcNow.Add(this.contentInfo.ExpiresInterval)
         };
     }
     catch
     {
         cacheInfo.UpdatedCacheItem       = new CacheItem(this.cacheKey, this.Get());
         cacheInfo.UpdatedCacheItemPolicy = new CacheItemPolicy()
         {
             UpdateCallback = UpdateCacheAgain, AbsoluteExpiration = DateTime.UtcNow.Add(this.contentInfo.ExpiresInterval)
         };
     }
     //this.
     //expensiveObject = base.GetDataFromContentFunction();
     //dependency = null;
     //absoluteExpiration = DateTime.UtcNow.Add(this.contentInfo.ExpiresInterval);
     //slidingExpiration = System.Web.Caching.Cache.NoSlidingExpiration;
 }
Exemple #18
0
 private void UpdateCallback(CacheEntryUpdateArguments arguments)
 {
 }
Exemple #19
0
 private static void UpdateCallback(CacheEntryUpdateArguments arguments)
 {
     Console.WriteLine("UP =>" + arguments.UpdatedCacheItem.Key);
     Console.WriteLine("UP Data=>" + arguments.UpdatedCacheItem.Value);
 }
Exemple #20
0
 /// <summary>
 ///     Override to modify the cache behaviour when an item is about to be removed, make sure to configure
 ///     ActivateUpdateCallback / ActivateRemovedCallback
 /// </summary>
 /// <param name="cacheEntryUpdateArguments">CacheEntryUpdateArguments</param>
 protected virtual void UpdateCallback(CacheEntryUpdateArguments cacheEntryUpdateArguments)
 {
     _log.Verbose().WriteLine("Update request for {0} due to {1}.", cacheEntryUpdateArguments.Key, cacheEntryUpdateArguments.RemovedReason);
 }
Exemple #21
0
 public abstract void CacheRemoveCallBack(CacheEntryUpdateArguments arg);