/// <summary> /// /// </summary> /// <param name="accessLevel">访问级别</param> /// <param name="cacheType">缓存的类型</param> /// <param name="isStoreInDb">是否存储到DB</param> public SchemaTable(AccessLevel accessLevel, CacheType cacheType, bool isStoreInDb) { AccessLevel = accessLevel; CacheType = cacheType; Keys = new string[0]; _columns = new ConcurrentDictionary<string, SchemaColumn>(); }
public TimeSpan SlidingExpritationPeriod { get; set; } // Has sense for AspNet/Mixed cache public CacheSettings(CacheType cacheType) { CacheType = cacheType; SlidingExpritationPeriod = TimeSpan.Zero; DefaultPriority = CachePriority.Default; Size = -1; // Unlimited }
public static void Cache(Product product, CacheType cacheType) { if (!string.IsNullOrEmpty(product.UPC) && !upcProductDic.ContainsKey(product.UPC)) { upcProductDic.Add(product.UPC, new ProductWraper() { CacheType = cacheType, Product = product, LastUsedTime = DateTime.Now }); } if (!string.IsNullOrEmpty(product.AmazonASIN) && !amazonAsinProductDic.ContainsKey(product.AmazonASIN)) { amazonAsinProductDic.Add(product.AmazonASIN, new ProductWraper() { CacheType = cacheType, Product = product, LastUsedTime = DateTime.Now }); } if (!string.IsNullOrEmpty(product.BestBuySKU) && !bestBuySkuProductDic.ContainsKey(product.BestBuySKU)) { bestBuySkuProductDic.Add(product.BestBuySKU, new ProductWraper() { CacheType = cacheType, Product = product, LastUsedTime = DateTime.Now }); } }
/// <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 async Task<bool> SaveCache(string stringToStore, CacheType type) { var fileName = type.GetFileNameFromCacheType(); try { StorageFile file; // Check if file exist in local folder and if it does replace it // C:\Users\three\AppData\Local\Packages\c49b095b-93a9-472f-a151-0629a4c64267_a9ekxv88vhe1y\LocalState if (type == CacheType.SettingsData) { file = await LocalRoamingFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); } else { file = await LocalCacheFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting); } // Write file to folder await FileIO.WriteTextAsync(file, stringToStore); return true; } catch { return false; } }
public CachedItem(object value, CacheType cacheType, TimeSpan increment) { Value = value; CacheType = cacheType; Increment = increment; if (cacheType.IsDefined()) { Expiration = DateTime.Now.Add(increment); } }
/// <summary> /// Invalidate the image corresponding to given parameters from given caches. /// </summary> /// <param name="parameters">Image parameters.</param> /// <param name="cacheType">Cache type.</param> public static void Invalidate(this TaskParameter parameters, CacheType cacheType) { using (var task = CreateTask(parameters, null)) { var key = task.GetKey(); ImageService.Invalidate(key, cacheType); } }
/// <summary> /// Invalidate the image corresponding to given parameters from given caches. /// </summary> /// <param name="parameters">Image parameters.</param> /// <param name="cacheType">Cache type.</param> public static async Task InvalidateAsync(this TaskParameter parameters, CacheType cacheType) { var target = new Target<WriteableBitmap, ImageLoaderTask>(); using (var task = CreateTask(parameters, target)) { var key = task.GetKey(); await ImageService.Instance.InvalidateCacheEntryAsync(key, cacheType).ConfigureAwait(false); } }
public CacheCommandLogEntry(OperationContext context, string commandName, object[] args, DateTime dateTime, long executionTime, int rowCount, CacheType cacheType) : base(LogEntryType.Command, context, dateTime) { _commandName = commandName; _args = args; _dateTime = dateTime; _executionTime = executionTime; _rowCount = rowCount; _cacheType = cacheType; }
public static ICacheService CacheInstance(CacheType cacheType) { switch (cacheType) { case CacheType.LocalMemory: return new LocalMemoryCacheService(); default: throw new ArgumentException("Invalid cache type or cache type does not have implementation"); } }
/// <summary> /// Returns a caching map for the given input map. /// </summary> internal static IZoneIntervalMap CacheMap([NotNull] IZoneIntervalMap map, CacheType type) { switch (type) { case CacheType.Hashtable: return new HashArrayCache(map); default: throw new ArgumentException("The type parameter is invalid", "type"); } }
public void AddCachedTypes(CacheType cacheType, params Type[] entities) { if(entities == null || entities.Length == 0) return; switch(cacheType) { case CacheType.None: break; case CacheType.LocalSparse: this.LocalSparseCacheTypes.UnionWith(entities); break; case CacheType.Sparse: this.SparseCacheTypes.UnionWith(entities); break; case CacheType.FullSet: this.FullSetCacheTypes.UnionWith(entities); break; } }
/// <summary> /// /// </summary> /// <param name="cacheItemType"></param> /// <param name="periodTime"></param> /// <param name="isReadOnly"></param> public CacheItemSet(CacheType cacheItemType, int periodTime, bool isReadOnly) { LoadingStatus = LoadingStatus.None; _cacheItemType = cacheItemType; _isReadOnly = isReadOnly; if (periodTime > 0) { _period = new CachePeriod(periodTime); } }
public static void Put(CacheType typeOfCache, Object cacheItem) { TimeSpan expiry; switch (typeOfCache) // handle the expiry according to the type of cache { default: expiry = new TimeSpan(12, 0, 0); break; } Put(KeyName(typeOfCache), cacheItem, expiry); }
public static Product GetByAmazonASIN(string ASIN, CacheType cacheType) { Product product = null; if (!amazonAsinProductDic.ContainsKey(ASIN) || (cacheType == CacheType.Full && amazonAsinProductDic[ASIN].CacheType == CacheType.Simple)) product = GetAFilledProductByAmazonASIN(ASIN, cacheType); else product = amazonAsinProductDic[ASIN].Product; return product; }
public void Basic(CacheType cacheType) { var cache = GetCache(cacheType, 3); cache[1] = 10; cache[2] = 20; cache[3] = 30; Assert.AreEqual(10, cache[1]); Assert.AreEqual(20, cache[2]); Assert.AreEqual(30, cache[3]); }
public static Product GetByAmazonASIN(string ASIN, CacheType cacheType) { ProductWrapper cachedProductWrapper = (ProductWrapper)HttpRuntime.Cache.Get(GetCacheKeyForAmazonASIN(ASIN)); if (cachedProductWrapper == null || cacheType > cachedProductWrapper.CacheType) { cachedProductWrapper = Cache(GetAFilledProductByAmazonASIN(ASIN, cacheType), cacheType); } return cachedProductWrapper.Product; }
public void Extensions(CacheType cacheType) { var cache = GetCache(cacheType, 3); cache.Add(1, 10); cache.Add(2, 20); cache.Add(3, 30); Assert.AreEqual(10, cache.Get(1)); Assert.AreEqual(20, cache.Get(2)); Assert.AreEqual(30, cache.Get(3)); }
private async Task<byte[]> DownloadBytesAndCacheAsync(string url, string filename, string filepath, CancellationToken token, TimeSpan? duration, CacheType? cacheType) { var responseBytes = await DownloadAsync(url, filename, token).ConfigureAwait(false); if (responseBytes == null) return null; var allowDiskCaching = AllowDiskCaching(cacheType); if (allowDiskCaching) { await _diskCache.AddToSavingQueueIfNotExistsAsync(filename, responseBytes, duration ?? new TimeSpan(30, 0, 0, 0)); // by default we cache data 30 days) } return responseBytes; }
public BrokeredMessage CreateMessage(string body, string queue, string messageType, CacheType cacheType, string filename) { var location = FullFilename(messageType, queue, filename); var sasUri = TokenGenerator.GetBlobSasUri(_container, location); CloudBlockBlob blockBlob = SaveToStorage(body, location); LargeMessage myRefMsg = new LargeMessage { Uri = blockBlob.Uri, BodyLocation = blockBlob.Name, CacheType = CacheType.Storage, SasUri = new Uri(sasUri) }; return new BrokeredMessage(SerializationHelper.SerializeToJsonString(myRefMsg)); }
public RunWorkPlan( DataSet dataSet, Cardinality cardinality, IndexType indexType, ReservationBufferSize reservationBufferSize, CacheSize cacheSize, Drive drive, CacheType cacheType, WorkPlan workPlan) : base(dataSet, cardinality, indexType, reservationBufferSize, cacheType, cacheSize) { Drive = drive; WorkPlan = workPlan; }
public Experiment( DataSet dataSet, Cardinality cardinality, IndexType indexType, ReservationBufferSize reservationBufferSize, CacheType cacheType, CacheSize cacheSize) { DataSet = dataSet; Cardinality = cardinality; IndexType = indexType; ReservationBufferSize = reservationBufferSize; CacheType = cacheType; CacheSize = cacheSize; }
public async Task<CacheStream> GetStreamAsync(string url, CancellationToken token, TimeSpan? duration = null, string key = null, CacheType? cacheType = null) { string filename = string.IsNullOrWhiteSpace(key) ? _md5Helper.MD5(url) : _md5Helper.MD5(key); var allowDiskCaching = AllowDiskCaching(cacheType); string filepath = allowDiskCaching == false ? null : await _diskCache.GetFilePathAsync(filename); if (allowDiskCaching) { var diskStream = await _diskCache.TryGetStreamAsync(filename).ConfigureAwait(false); if (diskStream != null) return new CacheStream(diskStream, true); } var memoryStream = await DownloadStreamAndCacheAsync(url, filename, filepath, token, duration, cacheType).ConfigureAwait(false); return new CacheStream(memoryStream, false); }
public async Task<DownloadedData> GetAsync(string url, CancellationToken token, TimeSpan? duration = null, string key = null, CacheType? cacheType = null) { string filename = string.IsNullOrWhiteSpace(key) ? _md5Helper.MD5(url) : _md5Helper.MD5(key); var allowDiskCaching = AllowDiskCaching(cacheType); string filepath = allowDiskCaching == false ? null : await _diskCache.GetFilePathAsync(filename); if (allowDiskCaching) { byte[] data = await _diskCache.TryGetAsync(filename, token).ConfigureAwait(false); if (data != null) return new DownloadedData(filepath, data) { RetrievedFromDiskCache = true }; } var bytes = await DownloadBytesAndCacheAsync(url, filename, filepath, token, duration, cacheType).ConfigureAwait(false); return new DownloadedData(filepath, bytes); }
public Task<bool> SaveCache(string objectToStore, CacheType type) { var fileName = FileNameFromCacheType(type); try { var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); var filePath = Path.Combine(documentsPath, fileName); File.WriteAllText(filePath, objectToStore); return Task.FromResult(true); } catch (Exception) { return Task.FromResult(false); } }
public string LoadCache(CacheType type) { var fileName = FileNameFromCacheType(type); try { var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); var filePath = Path.Combine(documentsPath, fileName); return File.Exists(filePath) ? Task.FromResult(File.ReadAllText(filePath)).GetAwaiter().GetResult() : Task.FromResult("").GetAwaiter().GetResult(); } catch (Exception) { return Task.FromResult("").GetAwaiter().GetResult(); } }
public string LoadSettings(CacheType type) { var fileName = FileNameFromCacheType(type); try { var documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); var filePath = Path.Combine(documentsPath, fileName); return File.Exists(filePath) ? File.ReadAllText(filePath) : ""; } catch (Exception) { return ""; } }
public Texture2D this[CacheType type, GraphicsDevice device] { get { Texture2D tex = null; Bitmap img = null; lock (this) { if (!_textures.TryGetValue(type, out tex) && _images.TryGetValue(type, out img)) { // generate texture from image tex = ImageGenerator.BitmapToTexture(img, device); _textures[type] = tex; } } return tex; } }
/// <summary> /// Initializes a new instance of the CaptchaControl class. Sets all properties and fields to defaults. /// </summary> public CaptchaControl() { this.errorMessage = string.Empty; this.userValidated = true; this.optionalUICulture = string.Empty; Resources.Culture = null; this.layoutStyle = Layout.Horizontal; this.cacheStrategy = CacheType.HttpRuntime; this.timeoutSecondsMin = 3; this.timeoutSecondsMax = 90; this.font = string.Empty; this.captchaInputID = "CaptchaInput"; this.captcha = new CaptchaImage(); }
public string LoadCache(CacheType type) { var fileName = type.GetFileNameFromCacheType(); try { // Check if file exist and read from it var file = type == CacheType.SettingsData ? LocalRoamingFolder.GetFileAsync(fileName).GetAwaiter().GetResult() : LocalCacheFolder.GetFileAsync(fileName).GetAwaiter().GetResult(); return FileIO.ReadTextAsync(file).GetAwaiter().GetResult(); } catch (FileNotFoundException) { return ""; } }
public void Add(Account account, string rawData, CacheType cacheType) { lock (_lock) { CacheData cacheData = this.CreateCacheData(account, rawData, cacheType); if (cacheType == CacheType.Transaciton || cacheType == CacheType.HistoryOrder) { _recordManager.Persistent(cacheData); CacheFileManager.Copy(cacheData.FilePath); this.AddForTradingData(cacheData); } else if (cacheType == CacheType.Reset) { _recordManager.Persistent(cacheData); CacheFileManager.Move(cacheData.FilePath); _resetSaver.Add(cacheData); } } }
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); }
public void Init(BaseConfig config = null) { lock (_lock) { if (config != null) { cacheConfig = (CacheConfig)config; } else { LibrariesConfig librariesConfig = ConfigurationManager.GetSection("LibrariesConfig") as LibrariesConfig; if (librariesConfig != null) { cacheConfig = librariesConfig.GetObjByXml <CacheConfig>("CacheConfig"); if (cacheConfig == null) { throw new Exception("缺少缓存配置CacheConfig"); } } } if (cacheConfig == null) { throw new Exception("缺少缓存配置CacheConfig"); } switch ((CacheType)Enum.Parse(typeof(CacheType), cacheConfig.Provider)) { case CacheType.Memcached: _cacheClient = new MemcacheManager(); break; case CacheType.Redis: _cacheClient = new RedisManager(); break; default: _cacheClient = new MemoryCacheManager(); break; } _cacheType = _cacheClient.Type; _cacheClient.SetConfig(cacheConfig); _cacheClient.Init(); } }
/// <summary> /// Exports current items in the cache /// </summary> /// <param name="cacheType">Specifies what type of cache items will be exported</param> /// <returns>Collection of <see cref="ExportableCI"/> containing all the items currently in the cache</returns> public async Task <IEnumerable <ExportableCI> > CacheExportAsync(CacheType cacheType) { var tasks = new List <Task <IEnumerable <ExportableCI> > >(); if (cacheType.HasFlag(CacheType.SportData)) { tasks.Add(_sportDataCache.ExportAsync()); } if (cacheType.HasFlag(CacheType.SportEvent)) { tasks.Add(_sportEventCache.ExportAsync()); } if (cacheType.HasFlag(CacheType.Profile)) { tasks.Add(_profileCache.ExportAsync()); } tasks.ForEach(t => t.ConfigureAwait(false)); return((await Task.WhenAll(tasks)).SelectMany(e => e)); }
public static ICache Get(CacheType cacheType) { ICache cache = new NullCache(); try { var caches = Container.GetAll <ICache>(); cache = (from c in caches where c.CacheType == cacheType select c).Last(); cache.Initialise(); } catch (Exception ex) { Log.Warn("Failed to instantiate cache of type: {0}, using null cache. Exception: {1}", cacheType, ex); cache = new NullCache(); } return(cache); }
protected override bool ItemExists <T>(string cacheKey, T key, CacheType type) { var found = false; if (ItemExists(cacheKey)) { var value = _cache[cacheKey]; switch (type) { case CacheType.Dictionary: found = value.Convert <IDictionary, object>().Contains(key); break; case CacheType.Set: found = value.Convert <ISet <T>, object>().Contains(key); break; } } return(found); }
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); }
public static IServiceCollection AddCache(this IServiceCollection services, CacheType type) { CacheProvider provider = null; switch (type) { case CacheType.RuntimeCache: provider = new CacheProvider(new RuntimeCache()); break; case CacheType.InMemoryCache: provider = new CacheProvider(new InMemoryCache()); break; default: throw new NotImplementedException(); } return(services); }
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()); } }
/// <summary> /// Invalidates the cache for given key. /// </summary> /// <returns>The async.</returns> /// <param name="key">Concerns images with this key.</param> /// <param name="cacheType">Memory cache, Disk cache or both</param> /// <param name="removeSimilar">If similar keys should be removed, ie: typically keys with extra transformations</param> public async Task InvalidateCacheEntryAsync(string key, CacheType cacheType, bool removeSimilar = false) { InitializeIfNeeded(); if (cacheType == CacheType.All || cacheType == CacheType.Memory) { ImageCache.Instance.Remove(key); if (removeSimilar) { ImageCache.Instance.RemoveSimilar(key); } } if (cacheType == CacheType.All || cacheType == CacheType.Disk) { string hash = _md5Helper.MD5(key); await Config.DiskCache.RemoveAsync(hash).ConfigureAwait(false); } }
/// <summary> /// Clears image cache /// </summary> /// <param name="cacheType">Cache type to invalidate</param> public static async Task ClearCacheAsync(CacheType cacheType) { switch (cacheType) { case CacheType.Memory: ImageService.Instance.InvalidateMemoryCache(); break; case CacheType.Disk: await ImageService.Instance.InvalidateDiskCacheAsync().ConfigureAwait(false); break; case CacheType.All: ImageService.Instance.InvalidateMemoryCache(); await ImageService.Instance.InvalidateDiskCacheAsync().ConfigureAwait(false); break; } }
internal bool SaveResetContent(CacheType cacheType, out string content) { content = string.Empty; try { content = this.SaveCommon(cacheType); #if NOBROADCAST #else Broadcaster.Default.Add(_account.Id, content); #endif _account.AcceptChanges(); return(true); } catch (Exception ex) { Logger.Error(ex); _account.RejectChanges(); return(false); } }
protected override V GetItem <K, V>(string cacheKey, K key, CacheType type) { cacheKey = StandardizeCacheKey(cacheKey); if (ItemExists(cacheKey)) { var value = _cache[cacheKey]; switch (type) { case CacheType.Dictionary: return((V)(value.Convert <IDictionary, object>())[key]); break; default: throw new ArgumentException(String.Format("Cache item {0} is not a supported type", cacheKey)); } } return(default(V)); }
public static ISimpleCache GetCache(string keyPrefix = null, TimeSpan?duration = null) { duration = duration ?? TimeSpan.FromHours(1); switch (cacheType) { case CacheType.Azure: try { var cache = dataCacheFactory.GetDefaultCache(); return(new SimpleCacheAzure(cache, keyPrefix)); } catch (Exception ex) { // If we've got one error, let's bail on trying to use Azure, and just default to the simple cache. cacheType = CacheType.Simple; logger.Error("Unable to instantiate Azure cache; returning simple cache. Error = " + ex); return(new SimpleCache(duration.Value)); } case CacheType.Redis: try { return(new SimpleCacheRedis(redisCs, keyPrefix, null, duration)); } catch (Exception ex) { // If we've got one error, let's bail on trying to use Azure, and just default to the simple cache. cacheType = CacheType.Simple; logger.Error("Unable to instantiate Redis cache; returning simple cache. Error = " + ex); return(new SimpleCache(duration.Value)); } case CacheType.PassThrough: return(new SimpleCachePassThroughProd()); } // Return a short timespan because this will almost always just be used in testing return(new SimpleCache(TimeSpan.FromMinutes(5))); }
/// <summary> /// 获取缓存 /// </summary> /// <param name="type">类型</param> /// <param name="key">标识key</param> /// <returns></returns> public ObjCache GetCache(CacheType type, string key) { if (mainCache.ContainsKey(type)) { foreach (KeyValuePair <CacheType, Dictionary <string, ObjCache> > mainKvp in mainCache) { if (mainKvp.Key == type && mainKvp.Value.ContainsKey(key)) { foreach (KeyValuePair <string, ObjCache> contentKvp in mainKvp.Value) { if (contentKvp.Key == key) { return(contentKvp.Value); } } break; } } } return(null); }
protected override void DeleteItem <T>(string cacheKey, T key, CacheType type) { if (ItemExists(cacheKey)) { var value = _cache[cacheKey]; switch (type) { case CacheType.Dictionary: value.Convert <IDictionary, object>().Remove(key); break; case CacheType.Set: value.Convert <ISet <T>, object>().Remove(key); break; default: throw new ArgumentException(String.Format("Operation on type {0} not supported", type)); break; } } }
/// <summary> /// 设置object格式集合类型队列 /// </summary> /// <param name="cacheType"></param> /// <param name="key"></param> /// <param name="data"></param> /// <param name="expire"></param> public static void SetObjectCollect <T>(CacheType cacheType, string key, List <T> data) { key = GetIdentifier(cacheType, key); List <string> execData = new List <string>(); //1.转换object为json字符串 foreach (var item in data) { string strJson = JsonData.JavaScriptSerialize(item); execData.Add(strJson); } //插入key execData.Insert(0, key); //插入命令 execData.Insert(0, "SADD"); List <string> lstOutput = new List <string>(); string location = command.Exec(execData, lstOutput); SetKeyTimeout(cacheType, key, true); }
public static void Register(IList <string> connectionNames, CacheType cacheType) { switch (cacheType) { case CacheType.InProcess: InProcessRegister(connectionNames); break; case CacheType.Redis: RedisRegister(connectionNames); break; case CacheType.Memcache: MemcacheRegister(connectionNames); break; default: InProcessRegister(connectionNames); break; } }
} // end of CreateCacheTableSingleRowRealtime /// <summary> Returns cache key name /// For single-row metric cache is common for all targets (table name only, no schema) /// Multi-row metrics each have its own cache </summary> /// <param name="targetId">target id or -1 for single row metrics</param> /// <param name="metricGroup">metric group</param> /// <param name="CacheType">data/dictionary</param> public static string GetCacheKey(int targetId, MetricGroup metricGroup, CacheType cacheType = CacheType.Data) { switch (cacheType) { case CacheType.Data: if (metricGroup.isMultiRow) { return(SqlServerProbe.DataTableName(targetId, metricGroup)); } else { return(metricGroup.dataTableName); } case CacheType.Dictionary: return(SqlServerProbe.DictTableName(targetId, metricGroup)); default: throw new Exception("Unsupported cache type"); } } // end of GetCacheKey method
/// <summary> /// Get the string identifier for the specified cache type /// </summary> /// <param name="t"></param> /// <returns>string identifier for cache type, or null if not defined</returns> public static string FromType(CacheType t) { switch (t) { case CacheType.Campaign: return(kCampaign); case CacheType.Multiplayer: return(kMultiplayer); case CacheType.MainMenu: return(kMainMenu); case CacheType.Shared: return(kShared); case CacheType.SharedCampaign: return(kSharedCampaign); case CacheType.Unknown5: return(kUnknown5); case CacheType.Unknown6: return(kUnknown6); } return(null); }
protected override void SetItem <K, V>(string cacheKey, K key, V item, CacheType type) { if (ItemExists(cacheKey)) { var value = _cache[cacheKey]; switch (type) { case CacheType.Dictionary: value.Convert <IDictionary, object>()[key] = item; break; case CacheType.Set: var set = value.Convert <ISet <K>, object>(); if (!set.Contains(key)) { set.Add(key); } break; } } }
public async Task <IEnumerable <T> > GetOrSet <T>(CacheType cacheType, string cacheKeyName, Func <CancellationToken, Task <IEnumerable <T> > > getValue, bool append = false, CancellationToken cancellationToken = default) { var value = await Get <IEnumerable <T> >(cacheType, cacheKeyName, cancellationToken); async Task <IEnumerable <T> > getDataFromSource() { value = await Set(cacheType, cacheKeyName, async (cancellationToken) => await getValue(cancellationToken)); return(value); }; if (value == null || !value.Any()) { return(await getDataFromSource()); } return(value); }
/// <summary> /// 异步缓存资源 /// </summary> /// <param name="cacheType">缓存类型,场景,全局</param> /// <param name="assetPaths">资源列表</param> /// <param name="finishCallback">完成回调</param> /// <param name="processCallBack">分步回调</param> public void CacheAssetASync(CacheType cacheType, string[] assetPaths, Action finishCallback = null, Action processCallBack = null) { CheckScenePool(); List <string> disList = assetPaths.Distinct().ToList(); int resCount = disList.Count; int loadCount = 0; Action loadOkAction = () => { loadCount++; if (processCallBack != null) { processCallBack(); } if (loadCount >= resCount) { UnloadBundles(); if (finishCallback != null) { finishCallback(); } } }; if (resCount <= 0) { loadOkAction(); return; } SpawnPool cachePool = m_ScenePool; if (cacheType == CacheType.GlobalCache) { cachePool = m_GlobalPool; } for (int i = 0; i < resCount; i++) { // Debug.Log("AsyncCacheSceneAsset: " + assetPaths[i]); CacheAsync(disList[i], loadOkAction, cachePool); } }
public string GetContent(string url, CacheType type, TimeSpan stayInCache) { string ret = null; try { ConvertToHash(ref url); if (cache == null) { return(ret); } 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); }
protected override void SetItem <K, V>(string cacheKey, K key, V item, CacheType type) { cacheKey = StandardizeCacheKey(cacheKey); if (GetDatabase(ConnectionType.Exists).KeyExists(cacheKey)) { switch (type) { case CacheType.Dictionary: GetDatabase(ConnectionType.Write).HashSet(cacheKey, new HashEntry[] { new HashEntry(key.ToString(), Serialize(item)) }); break; case CacheType.Set: GetDatabase(ConnectionType.Write).SetAdd(cacheKey, Serialize(key)); break; case CacheType.List: GetDatabase(ConnectionType.Write).ListRightPush(cacheKey, Serialize(key)); break; } } }
public static T Get <T>(CacheType type, string id) { switch (type) { case CacheType.WebtoonSection: if (File.Exists(GlobalVar.CACHE_DIRECTORY + "\\cache__" + id + ".dat")) { XmlSerializer xmlSerializer = new XmlSerializer(typeof(WebtoonSectionCacheStruct)); using (StreamReader streamReader = new StreamReader(GlobalVar.CACHE_DIRECTORY + "\\cache__" + id + ".dat")) { return(( T )xmlSerializer.Deserialize(streamReader)); } } else { return(default(T)); } default: return(default(T)); } }
/// <summary> /// 覆盖插入 带过期设置 /// </summary> /// <param name="key"></param> /// <param name="value"></param> public static void Insert(string key, object value, CacheType type) { int m; int s; switch ((int)type) { case 1: m = ConfigurationManager.AppSettings["tokenExpiresM"].ToInt(); s = ConfigurationManager.AppSettings["tokenExpiresS"].ToInt(); break; default: m = ConfigurationManager.AppSettings["tokenExpiresM"].ToInt(); s = ConfigurationManager.AppSettings["tokenExpiresS"].ToInt(); break; } TimeSpan span = new TimeSpan(0, m, s); HttpRuntime.Cache.Insert(key, value, null, Cache.NoAbsoluteExpiration, span); }
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); } }
private void CacheContainer_OnCacheUpdated(CacheType cacheType, DateTimeOffset offset) { var cacheUpdateEvent = new CacheUpdateEvent { UpdatedTime = offset }; switch (cacheType) { case CacheType.BranchCache: HandleBranchCacheUpdatedEvent(cacheUpdateEvent); break; case CacheType.GitLogCache: HandleGitLogCacheUpdatedEvent(cacheUpdateEvent); break; case CacheType.GitTrackingStatusCache: HandleGitTrackingStatusCacheUpdatedEvent(cacheUpdateEvent); break; case CacheType.GitLocksCache: HandleGitLocksCacheUpdatedEvent(cacheUpdateEvent); break; case CacheType.GitUserCache: break; case CacheType.RepositoryInfoCache: HandleRepositoryInfoCacheUpdatedEvent(cacheUpdateEvent); break; case CacheType.GitStatusEntriesCache: HandleGitStatusEntriesCacheUpdatedEvent(cacheUpdateEvent); break; default: throw new ArgumentOutOfRangeException(nameof(cacheType), cacheType, null); } }
/// <summary> /// Initializes a new instance of the <see cref="DapperApps.Phone.Collections.MultiLevelCache<T>"/> /// class that is empty, has the specified initial capacity, and uses the specified /// <see cref="System.Collections.Generic.IEqualityComparer<string>"/>. /// </summary> /// <param name="capacity">The initial number of elements that the <see cref="DapperApps.Phone.Collections.MultiLevelCache<T>"/> /// can contain.</param> /// <param name="comparer">The <see cref="System.Collections.Generic.IEqualityComparer<string>"/> implementation to use /// when comparing keys, or null to use the default <see cref="System.Collections.Generic.EqualityComparer<string>"/> /// for the type of the key.</param> /// <param name="cacheDir">The on-disk directory where objects are cached.</param> /// <param name="cachingType">How/when items are cached/uncached.</param> /// <exception cref="System.ArgumentOutOfRangeException">capacity is less than 0.</exception> public MultiLevelCache( int capacity, IEqualityComparer <string> comparer, string cacheDir = DEFAULT_DISK_CACHE_DIR, CacheInitOption cacheCreationOption = DEFAULT_CACHE_CREATION_OPTION, CacheType cachingType = DEFAULT_CACHING_TYPE) { try { _dictionary = new Dictionary <string, T>(capacity, comparer); _items = new Dictionary <string, CacheItem <T> >(capacity, comparer); CachingType = cachingType; //TODO exceptions Storage_Init(cacheDir, cacheCreationOption); } catch { throw; } }