コード例 #1
0
ファイル: SchemaTable.cs プロジェクト: LeeWangyeol/Scut
 /// <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>();
 }
コード例 #2
0
ファイル: CacheSettings.cs プロジェクト: DBailey635/C1-CMS
        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
        }
コード例 #3
0
ファイル: ProductPool.cs プロジェクト: jimji2008/ProcutVS
        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
                                                                });
            }
        }
コード例 #4
0
ファイル: CacheManager.cs プロジェクト: rongcheng/benz
        /// <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());
        }
コード例 #5
0
        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;
            }
        }
コード例 #6
0
ファイル: CacheItem..cs プロジェクト: onesimoh/Andamio
 public CachedItem(object value, CacheType cacheType, TimeSpan increment)
 {
     Value = value;
     CacheType = cacheType;
     Increment = increment;
     if (cacheType.IsDefined())
     { Expiration = DateTime.Now.Add(increment); }
 }
コード例 #7
0
		/// <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);
			}
		}
コード例 #8
0
		/// <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);
			}
		}
コード例 #9
0
 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;
 }
コード例 #10
0
 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");
     }
 }
コード例 #11
0
 /// <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");
     }
 }
コード例 #12
0
ファイル: CacheSettings.cs プロジェクト: yuanfei05/vita
 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;
       }
 }
コード例 #13
0
        /// <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);
            }

        }
コード例 #14
0
ファイル: cache.cs プロジェクト: Exclr8/CloudCore
        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);
        }
コード例 #15
0
ファイル: ProductPool.cs プロジェクト: jimji2008/ProcutVS
        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;
        }
コード例 #16
0
ファイル: Cache.UT.cs プロジェクト: juliolins/interview
        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]);
        }
コード例 #17
0
ファイル: ProductPool.cs プロジェクト: jimji2008/ProcutVS
        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;
        }
コード例 #18
0
ファイル: Cache.UT.cs プロジェクト: juliolins/interview
        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));
        }
コード例 #19
0
		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;
		}
コード例 #20
0
 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));
 }
コード例 #21
0
 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;
 }
コード例 #22
0
 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;
 }
コード例 #23
0
		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);
		}
コード例 #24
0
		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);
        }
コード例 #25
0
        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);
            }
        }
コード例 #26
0
 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();
     }
 }
コード例 #27
0
        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 "";
            }
        }
コード例 #28
0
 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;
     }
 }
コード例 #29
0
        /// <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();
        }
コード例 #30
0
        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 "";
            }
        }
コード例 #31
0
ファイル: Assistant.cs プロジェクト: dreamsql/Outter
 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);
         }
     }
 }
コード例 #32
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);
        }
コード例 #33
0
        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();
            }
        }
コード例 #34
0
        /// <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));
        }
コード例 #35
0
        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);
        }
コード例 #36
0
        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);
        }
コード例 #37
0
        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);
        }
コード例 #38
0
        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);
        }
コード例 #39
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());
            }
        }
コード例 #40
0
        /// <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);
            }
        }
コード例 #41
0
        /// <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;
            }
        }
コード例 #42
0
        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);
            }
        }
コード例 #43
0
        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));
        }
コード例 #44
0
        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)));
        }
コード例 #45
0
ファイル: AppCache.cs プロジェクト: yanyizzZ/Origin
 /// <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);
 }
コード例 #46
0
        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;
                }
            }
        }
コード例 #47
0
        /// <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);
        }
コード例 #48
0
ファイル: CacheRegister.cs プロジェクト: doriswang/Test
        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;
            }
        }
コード例 #49
0
ファイル: InMemoryCache.cs プロジェクト: radtek/sqlwristband
        } // 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
コード例 #50
0
            /// <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);
            }
コード例 #51
0
        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;
                }
            }
        }
コード例 #52
0
        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);
        }
コード例 #53
0
ファイル: GameLoader.cs プロジェクト: pixar2016/Assets
        /// <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);
            }
        }
コード例 #54
0
        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);
        }
コード例 #55
0
        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;
                }
            }
        }
コード例 #56
0
        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));
            }
        }
コード例 #57
0
        /// <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);
        }
コード例 #58
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);
            }
        }
コード例 #59
0
ファイル: Repository.cs プロジェクト: lin5/Unity
        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);
            }
        }
コード例 #60
0
        /// <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;
            }
        }