Пример #1
0
        public static IObjectCache GetCache(CacheType cacheType, CacheIdentifiers cacheIdentifiers)
        {
            switch (cacheType)
            {
            case CacheType.InMemoryObjectCache:
                IObjectCache inMemoryObjectCache;
                if (!ObjectCaches.TryGetValue(cacheType.ToString() + cacheIdentifiers, out inMemoryObjectCache))
                {
                    inMemoryObjectCache = new InMemoryObjectCache(cacheIdentifiers);
                    ObjectCaches.Add(cacheType.ToString() + cacheIdentifiers, inMemoryObjectCache);
                    return(inMemoryObjectCache);
                }

                return(inMemoryObjectCache);

            case CacheType.RedisObjectCache:
                break;

            case CacheType.AzureRedisObjectCache:
                break;

            default:
                return(null);
            }

            return(null);
        }
Пример #2
0
        public static IThumbnailCache GetCache(CacheType t)
        {
            logger.Info("Creating instance of {cacheType}", t.ToString());
            switch (t)
            {
            case CacheType.FolderImages:
                return(ThumbnailCacheInFolder.Instance);

            default:
                throw new NotImplementedException($"Thumbnail Cache for {t.ToString()} is not implemented.");
            }
        }
Пример #3
0
        public void SaveContent(string url, CacheType type, string content)
        {
            try
            {
                ConvertToHash(ref url);

                string dir = Path.Combine(cache, type.ToString()) + Path.DirectorySeparatorChar;

                // precrete dir
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                string file = dir + url + ".txt";

                using (StreamWriter writer = new StreamWriter(file, false, Encoding.UTF8))
                {
                    writer.Write(content);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("SaveContent: " + ex);
            }
        }
Пример #4
0
        public string GetContent(string url, CacheType type, TimeSpan stayInCache)
        {
            string ret = null;

            try
            {
                ConvertToHash(ref url);

                string dir  = Path.Combine(cache, type.ToString()) + Path.DirectorySeparatorChar;
                string file = dir + url + ".txt";

                if (File.Exists(file))
                {
                    var writeTime = File.GetLastWriteTime(file);
                    if (DateTime.Now - writeTime < stayInCache)
                    {
                        using (StreamReader r = new StreamReader(file, Encoding.UTF8))
                        {
                            ret = r.ReadToEnd();
                        }
                    }
                    else
                    {
                        File.Delete(file);
                    }
                }
            }
            catch (Exception ex)
            {
                ret = null;
                Debug.WriteLine("GetContent: " + ex);
            }

            return(ret);
        }
        public async Task OnResourceExecutionAsync(ResourceExecutingContext context, ResourceExecutionDelegate next)
        {
            if (CacheLocation == CacheLocation.Client)
            {
                await next.Invoke();

                return;
            }

            var req  = context.HttpContext.Request;
            var resp = context.HttpContext.Response;

            _cacheKey = $"{req.Path}{ req.QueryString}";
            //get cached results
            var cachedResult = await CacheService.Get <string>(_cacheKey);

            var contentType = await
                              CacheService.Get <string>($"{_cacheKey}{ContentType}");

            var eTag = await CacheService.Get <string>($"{_cacheKey}_{HeaderNames.ETag}");

            //if we don't have cached output than return and execute the method
            //data will be store in the the cache later in the method OnResultExecuted
            if (cachedResult == null || string.IsNullOrEmpty(contentType) || string.IsNullOrEmpty(eTag))
            {
                await next.Invoke();

                return;
            }
            SetCacheHeaderForClientSideCaching(context.HttpContext.Response, eTag); //refresh cache lifetime on client side

            //we have to check the eTag, if the value is the same (which means that client already have the current version)
            if (req.Headers[HeaderNames.IfNoneMatch].Count != 0 && req.Headers[HeaderNames.IfNoneMatch] == context.HttpContext.Response.Headers[HeaderNames.ETag])
            {
                context.Result = new EmptyResult();
                context.HttpContext.Response.StatusCode = StatusCodes.Status304NotModified; // this will blank response
                SetCacheHeaderForClientSideCaching(context.HttpContext.Response, eTag);     //refresh cache lifetime on client side
                return;
            }
            context.Result   = new ContentResult();
            resp.ContentType = contentType;
            resp.StatusCode  = StatusCodes.Status200OK;//We add to cache only results with StatusCodes.Status200OK

            var responseStream = resp.Body;

            responseStream.Position = 0;
            if (responseStream.Length <= cachedResult.Length)
            {
                responseStream.SetLength(cachedResult.Length);
            }
            using (var writer = new StreamWriter(responseStream, Encoding.UTF8, 4096, true))
            {
                Debug.WriteLine("from cache");
                writer.Write(cachedResult);
                writer.Flush();
                responseStream.Flush();
            }
            context.HttpContext.Response.Headers.Add("CachingMechanism", CacheType.ToString());
        }
Пример #6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static Object GetItem(CacheType type)
        {
            switch (type)
            {
            case CacheType.TopCatalog:
                if (QJVRMSCache.Get(type.ToString()) == null)
                {
                    QJVRMSCache.Insert(type.ToString(), Catalog.GetTopCatalog());
                }
                break;

            case CacheType.AllCatalog:
                if (QJVRMSCache.Get(type.ToString()) == null)
                {
                    QJVRMSCache.Insert(type.ToString(), Catalog.GetAllCatalog());
                }
                break;

            case CacheType.Feature:
                break;

            case CacheType.ResouceType:
                if (QJVRMSCache.Get(type.ToString()) == null)
                {
                    QJVRMSCache.Insert(type.ToString(), ResourceTypeManager.GetTypeList());
                }
                break;

            default:
                break;
            }

            return(QJVRMSCache.Get(type.ToString()));
        }
Пример #7
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        public static Object GetItem(CacheType type)
        {

            switch (type)
            {
                case CacheType.TopCatalog:
                    if (QJVRMSCache.Get(type.ToString()) == null)
                    {
                        QJVRMSCache.Insert(type.ToString(), Catalog.GetTopCatalog());
                    }
                    break;
                case CacheType.AllCatalog:
                    if (QJVRMSCache.Get(type.ToString()) == null)
                    {
                        QJVRMSCache.Insert(type.ToString(), Catalog.GetAllCatalog());
                    }
                    break;
                case CacheType.Feature:
                    break;
                case CacheType.ResouceType:
                    if (QJVRMSCache.Get(type.ToString()) == null)
                    {
                        QJVRMSCache.Insert(type.ToString(), ResourceTypeManager.GetTypeList());
                    }
                    break;
                default:
                    break;
            }

            return QJVRMSCache.Get(type.ToString());
        }
        public static async void Invalidate(CacheType cacheType)
        {
            var file = await _tempFolder.GetFileAsync(cacheType.ToString());

            if (file != null)
            {
                await file.DeleteAsync();
            }
        }
Пример #9
0
        public string GetContent(string urlEnd, CacheType type, TimeSpan stayInCache)
        {
            string ret = null;

            try
            {
                Stuff.RemoveInvalidPathSymbols(ref urlEnd);

                string dir  = Path.Combine(cache, type.ToString()) + Path.DirectorySeparatorChar;
                string file = dir + urlEnd;

                switch (type)
                {
                case CacheType.GeocoderCache:
                    file += ".geo";
                    break;

                case CacheType.PlacemarkCache:
                    file += ".plc";
                    break;

                case CacheType.RouteCache:
                    file += ".dragdir";
                    break;

                case CacheType.UrlCache:
                    file += ".url";
                    break;

                default:
                    file += ".txt";
                    break;
                }

                if (File.Exists(file))
                {
                    var writeTime = File.GetLastWriteTime(file);
                    if (DateTime.Now - writeTime < stayInCache)
                    {
                        using (StreamReader r = new StreamReader(file, Encoding.UTF8))
                        {
                            ret = r.ReadToEnd();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                ret = null;
                Debug.WriteLine("GetContent: " + ex);
            }

            return(ret);
        }
Пример #10
0
        public async static Task Save(CacheType cacheType, object data)
        {
            var file = await _tempFolder.CreateFileAsync(cacheType.ToString(), CreationCollisionOption.ReplaceExisting);

            var cache = new CacheItem();

            cache.CreatedDate = DateTime.Now;

            cache.JsonData = JsonSerializerHelper.Serialize(data);
            var json = JsonSerializerHelper.Serialize(cache);
            await FileIO.WriteTextAsync(file, json);
        }
Пример #11
0
        public void SaveContent(string urlEnd, CacheType type, string content)
        {
            try
            {
                Stuff.RemoveInvalidPathSymbols(ref urlEnd);

                string dir = Path.Combine(cache, type.ToString()) + Path.DirectorySeparatorChar;

                // precrete dir
                if (!Directory.Exists(dir))
                {
                    Directory.CreateDirectory(dir);
                }

                string file = dir + urlEnd;

                switch (type)
                {
                case CacheType.GeocoderCache:
                    file += ".geo";
                    break;

                case CacheType.PlacemarkCache:
                    file += ".plc";
                    break;

                case CacheType.RouteCache:
                    file += ".dragdir";
                    break;

                case CacheType.UrlCache:
                    file += ".url";
                    break;

                case CacheType.DirectionsCache:
                    file += ".dir";
                    break;

                default:
                    file += ".txt";
                    break;
                }

                using (StreamWriter writer = new StreamWriter(file, false, Encoding.UTF8))
                {
                    writer.Write(content);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("SaveContent: " + ex);
            }
        }
Пример #12
0
        /// <summary>
        /// Hash key used by the cache system
        /// </summary>
        /// <returns>the key's hash</returns>
        public string KeyHash()
        {
            string typeName = ObjectType.Name;

            //Normalize interfaces versus classnames
            if (ObjectType.IsInterface)
            {
                typeName = typeName.Substring(1);
            }

            return(string.Format("{0}_{1}_{2}", CacheType.ToString(), typeName, BirthMark.ToString()));
        }
Пример #13
0
        /// <summary>
        /// 获取配置
        /// </summary>
        /// <param name="cacheType"><see cref="CacheType"/>枚举</param>
        /// <returns></returns>
        public static ItemConfig GetConfig(CacheType cacheType)
        {
            var name = cacheType.ToString();

            if (Configs.ContainsKey(name))
            {
                return(Configs[name]);
            }

            return(new ItemConfig {
                Level = 0, Minutes = 1
            });
        }
Пример #14
0
        private void CacheHasBeenInvalidated(CacheType cacheType)
        {
            if (repositoryManager == null)
            {
                if (!cacheInvalidationRequests.Contains(cacheType))
                {
                    cacheInvalidationRequests.Add(cacheType);
                }
                return;
            }

            Logger.Trace($"CacheInvalidated {cacheType.ToString()}");
            switch (cacheType)
            {
            case CacheType.Branches:
                repositoryManager?.UpdateBranches();
                break;

            case CacheType.GitLog:
                repositoryManager?.UpdateGitLog();
                break;

            case CacheType.GitAheadBehind:
                repositoryManager?.UpdateGitAheadBehindStatus();
                break;

            case CacheType.GitLocks:
                if (CurrentRemote != null)
                {
                    repositoryManager?.UpdateLocks();
                }
                break;

            case CacheType.GitUser:
                // user handles its own invalidation event
                break;

            case CacheType.RepositoryInfo:
                repositoryManager?.UpdateRepositoryInfo();
                break;

            case CacheType.GitStatus:
                repositoryManager?.UpdateGitStatus();
                break;

            default:
                throw new ArgumentOutOfRangeException(nameof(cacheType), cacheType, null);
            }
        }
Пример #15
0
        public static async void Invalidate(CacheType cacheType)
        {
            try
            {
                var file = await _tempFolder.GetFileAsync(cacheType.ToString());

                if (file != null)
                {
                    await file.DeleteAsync();
                }
            }
            catch (FileNotFoundException)
            {
            }
        }
Пример #16
0
        public async static Task <CacheItem> Load <T>(CacheType cacheType)
        {
            var file = await _tempFolder.CreateFileAsync(cacheType.ToString(), CreationCollisionOption.OpenIfExists);

            var fileContent = await FileIO.ReadTextAsync(file);

            if (string.IsNullOrEmpty(fileContent))
            {
                return(null);
            }

            CacheItem cache = JsonSerializerHelper.Deserialize <CacheItem>(fileContent);

            cache.Data = JsonSerializerHelper.Deserialize <T>(cache.JsonData);
            return(cache);
        }
Пример #17
0
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            var cacheSettings = context.HttpContext.RequestServices.GetRequiredService <RedisCacheSettings>();
            var logger        = context.HttpContext.RequestServices.GetRequiredService <ILogger <CachedAttribute> >();

            if (!cacheSettings.Enabled)
            {
                await next();

                return;
            }

            var key   = _getCacheKey(_itemType, _cacheType.ToString().ToLower(), context.HttpContext.Request);
            var cache = context.HttpContext.RequestServices.GetRequiredService <IResponseCacheService>();

            var cachedResponse = string.Empty;

            try {
                cachedResponse = await cache.GetCacheResponseAsync(key);
            } catch (RedisConnectionException) {
                await next();

                return;
            }

            if (!string.IsNullOrEmpty(cachedResponse))
            {
                logger.LogDebug($"Cache hit: {key}");
                var contentResult = new ContentResult {
                    ContentType = _contentType,
                    StatusCode  = 200,
                    Content     = cachedResponse
                };
                context.Result = contentResult;
                return;
            }

            logger.LogDebug($"Cache miss: {key}");
            var executedContext = await next();

            if (executedContext.Result is ContentResult result)
            {
                await cache.CacheResponseAsync(key, result.Content, TimeSpan.FromSeconds(_ttl));
            }
        }
Пример #18
0
        private string JoinKey(string cacheId, CacheType cacheType)
        {
            string cacheKeyPrefix;

            switch (cacheType)
            {
            case CacheType.User:
                cacheKeyPrefix = HttpContext.Current.Session.SessionID;
                break;

            case CacheType.Application:
                cacheKeyPrefix = cacheType.ToString();
                break;

            default:
                throw new ArgumentOutOfRangeException("cacheType");
            }
            return(cacheKeyPrefix + "." + cacheId);
        }
        private void ExecuteRestoreCacheDataJob()
        {
            var jobName  = CacheType.ToString() + "RestoreCacheDataJob";
            var jobGroup = "RestoreCacheDataGroup";

            var job = JobBuilder.Create <RestoreCacheDataJob>()
                      .WithIdentity(jobName, jobGroup)
                      .UsingJobData("CacheType", (int)CacheType)
                      .Build();

            var triggerName = CacheType.ToString() + "RestoreCacheDataTrigger";
            var trigger     = TriggerBuilder.Create()
                              .WithIdentity(triggerName, jobGroup)
                              .StartNow()
                              .Build();

            var jobManager = Container.Resolve <IJobManager>();

            jobManager.ScheduleJob(job, trigger);
        }
Пример #20
0
        private ICache <int, int> GetCache(CacheType cacheType, int capacity)
        {
            switch (cacheType)
            {
            case CacheType.LRU_ThreadSafe:
                return(CacheBuilder.LRU_ThreadSafe <int, int>(capacity));

            case CacheType.LRU_Non_ThreadSafe:
                return(CacheBuilder.LRU_NonThreadSafe <int, int>(capacity));

            case CacheType.MRU_ThreadSafe:
                return(CacheBuilder.MRU_ThreadSafe <int, int>(capacity));

            case CacheType.MRU_Non_ThreadSafe:
                return(CacheBuilder.MRU_NonThreadSafe <int, int>(capacity));

            default:
                throw new NotSupportedException(cacheType.ToString());
            }
        }
Пример #21
0
 /// <summary>
 /// Hash key used by the cache system
 /// </summary>
 /// <returns>the key's hash</returns>
 public string KeyHash()
 {
     //Not using type name right now, birthmarks are unique globally anyways
     return(string.Format("{0}_{1}", CacheType.ToString(), BirthMark));
 }
Пример #22
0
 private string GetCacheKey(HttpRequest req) =>
 _includeUrl
         ? $"{_cacheType}-{req.Path}"
         : _cacheType.ToString();
Пример #23
0
 public override string ToString()
 {
     return(type.ToString() + ":" + id.ToString());
 }
Пример #24
0
        public static IEnumerable <string> GetCacheEntries(CacheType cacheType)
        {
            var cacheDictionary    = GetCacheDictionary();
            var cacheItems         = new List <string>();
            var filteredCacheItems = cacheDictionary.Where(x => x.Key.ToString().Contains(cacheType.ToString())).ToList();

            foreach (var item in filteredCacheItems[0].Value)
            {
                cacheItems.Add(item);
            }
            cacheItems.Sort();
            return(cacheItems);
        }
Пример #25
0
 public string GetCacheKey(CacheType type) =>
 $"podcast|{this.AppUser.Slug}|{this.Slug}|{type.ToString()}";
Пример #26
0
 public static string GetCacheKey(CacheType cacheType, string key)
 {
     return("{0}_{1}".FormatTo(cacheType.ToString(), key));
 }
Пример #27
0
 private ICache<int, int> GetCache(CacheType cacheType, int capacity)
 {
     switch (cacheType)
     {
         case CacheType.LRU_ThreadSafe:
             return CacheBuilder.LRU_ThreadSafe<int, int>(capacity);
         case CacheType.LRU_Non_ThreadSafe:
             return CacheBuilder.LRU_NonThreadSafe<int, int>(capacity);
         case CacheType.MRU_ThreadSafe:
             return CacheBuilder.MRU_ThreadSafe<int, int>(capacity);
         case CacheType.MRU_Non_ThreadSafe:
             return CacheBuilder.MRU_NonThreadSafe<int, int>(capacity);
         default:
             throw new NotSupportedException(cacheType.ToString());
     }
 }