/// <summary> /// Gets an object from cache or delegates creating one. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="builder"></param> /// <param name="cacheKey"></param> /// <returns></returns> private static T GetFromCacheOrCreate <T>(Func <T> builder, string cacheKey) where T : class { if (Cache.Contains(cacheKey)) { return((T)Cache[cacheKey]); } Log.Debug("Creating cached object: {0}.", cacheKey); T obj; try { obj = builder.Invoke(); lock (obj) // add object to cache { Cache.Add(cacheKey, obj, new CacheItemPolicy()); } } catch (Exception ex) // just log and rethrow { Log.Error("Error creating {0}: {1}.", cacheKey, ex); throw; } return(obj); }
/// <summary> /// Insert value into the cache using /// appropriate name/value pairs /// </summary> /// <typeparam name="T">Type of cached item</typeparam> /// <param name="objectToCache">Item to be cached</param> /// <param name="key">Name of item</param> /// <param name="cacheTimeFrame">Time Frame</param> /// <param name="cacheTime">Time</param> public static void Add <T>(T objectToCache, string key, EnumCacheTimeFrame cacheTimeFrame = EnumCacheTimeFrame.AddDays, double cacheTime = 1) where T : class { var cacheDateTime = DateTime.Now; switch (cacheTimeFrame) { case EnumCacheTimeFrame.AddSeconds: cacheDateTime = DateTime.Now.AddSeconds(cacheTime); break; case EnumCacheTimeFrame.AddMinutes: cacheDateTime = DateTime.Now.AddMinutes(cacheTime); break; case EnumCacheTimeFrame.AddHours: cacheDateTime = DateTime.Now.AddHours(cacheTime); break; case EnumCacheTimeFrame.AddDays: cacheDateTime = DateTime.Now.AddDays(cacheTime); break; } Cache.Add(key, objectToCache, cacheDateTime); }
//public QueueMonitorOptionProvider(IQueueMonitorOption option) //{ // _option = option; //} //public QueueMonitorOptionProvider():this(new LocalJsonQueueMonitorOption()) //{ //} /// <summary> /// 获取监控配置 /// </summary> /// <param name="queueName"></param> /// <returns></returns> public static QueueMonitorOption GetOption(string queueName) { lock (lockObj) { try { queueName = queueName.Substring(queueName.LastIndexOf("\\") + 1); Dictionary <string, QueueMonitorOption> dics = new Dictionary <string, QueueMonitorOption>(); if (!cache.Contains(cacheKey)) //内存字典没值或缓存没有 { //缓存处理 dics = _option.LoadOption(); if (dics.Count > 0) { cache.Add(cacheKey, dics, DateTimeOffset.Now.AddSeconds(int.Parse(ConfigurationManager.AppSettings["OptionCacheInterval"]))); } } else { dics = (Dictionary <string, QueueMonitorOption>)cache[cacheKey]; } if (dics.ContainsKey(queueName)) { return(dics[queueName]); } return(GetDefault(queueName)); } catch (Exception ex) { log.Error("获取队列监控配置异常(" + queueName + "):" + ex.Message, ex); return(GetDefault(queueName)); } } }
private void btn_login_Click(object sender, EventArgs e) { using (var ctx = new db_dataEntities()) { var username = this.txtusername.Text; var password = this.txtpassword.Text; var getUser = ctx.tbl_user.Where(o => o.username == username && o.password == password).FirstOrDefault(); if (getUser != null) { ObjectCache cache = MemoryCache.Default; CacheItemPolicy cacheItemPolicy = new CacheItemPolicy(); cache.Add("userLogin", getUser, cacheItemPolicy); this.Hide(); menu_admin frm2 = new menu_admin(); frm2.Show(); } else { MessageBox.Show("please check username and password"); this.txtusername.Text = ""; this.txtpassword.Text = ""; } } }
/// <summary> /// Adds an item. /// </summary> /// <param name="key"></param> /// <param name="data"></param> /// <param name="timeout"></param> /// <returns></returns> public bool AddItem(string key, object data, int timeout = 30) { if (key is null) { throw new ArgumentNullException(nameof(key)); } if (data is null) { throw new ArgumentNullException(nameof(data)); } bool result; if (string.IsNullOrWhiteSpace(key)) { result = false; } else if (string.IsNullOrWhiteSpace(data.ToString())) { result = false; } else { var cip = new CacheItemPolicy { AbsoluteExpiration = DateTime.Now.AddMinutes(timeout) }; result = _data.Add(new CacheItem(key, data), cip); } return(result); }
private async Task <IEnumerable <Topendata> > RetriveHotSpotData(string cacheName) { string targetURI = "https://gis.taiwan.net.tw/XMLReleaseALL_public/activity_C_f.json"; HttpClient client = new HttpClient(); client.MaxResponseContentBufferSize = Int32.MaxValue; var response = await client.GetStringAsync(targetURI); JavaScriptSerializer serializer = new JavaScriptSerializer(); Topendata_T json = serializer.Deserialize <Topendata_T>(response); Topendata[] collection = json.XML_Head.Infos.Info; //var collection = JsonConvert.DeserializeObject<IEnumerable<Topendata>>(response); CacheItemPolicy policy = new CacheItemPolicy(); policy.AbsoluteExpiration = DateTime.Now.AddMinutes(10); ObjectCache cacheItem = MemoryCache.Default; cacheItem.Add(cacheName, collection, policy); return(collection); }
protected override bool AreDeepEqual(object a, object b) { ObjectCache.Add(a, b); var properties = PropertyCache.GetPropertyInfos(a.GetType(), DeepComparisonOptions.PropertyComparison); return(properties.All(property => { var valueA = property.GetValue(a); var valueB = property.GetValue(b); var isACircular = CircularReferenceMonitor.AddReference(a, valueA); var isBCircular = CircularReferenceMonitor.AddReference(b, valueB); if (isACircular && isBCircular) { return ObjectCache.TryGet(valueA, out var originalB) && ReferenceEquals(originalB, valueB); } if (isACircular || isBCircular) { return false; } return DeepComparisonService.AreDeepEqual(valueA, valueB, DeepComparisonOptions); })); }
public EnumDef Find(Guid id) { var cached = EnumDefCache.Find(id); if (cached != null) { return(Clone(cached.CachedObject)); } var dbEnumDef = DataContext.GetEntityDataContext().Entities.Object_Defs.OfType <Enum_Def>().FirstOrDefault(e => e.Id == id); if (dbEnumDef == null) { return(null); } var enumDef = new EnumDef { Id = dbEnumDef.Id, Caption = dbEnumDef.Full_Name, Description = dbEnumDef.Description, Name = dbEnumDef.Name, EnumItems = new List <EnumValue>(LoadEnumItems(id)) }; EnumDefCache.Add(enumDef, id); return(Clone(enumDef)); }
public bool Add(string key, IEnumerable <T> value) { CacheItemPolicy policy = new CacheItemPolicy(); policy.AbsoluteExpiration = DateTimeOffset.Now.Add(cacheDuration); return(cache.Add(key, value, policy)); }
public IEnumerable <IAsset> Process(IEnumerable <IAsset> assets) { var key = string.Join("_", assets.Select(a => a.GetHashCode().ToString(CultureInfo.InvariantCulture))); if (_cache.Contains(key)) { return(_cache[key] as IEnumerable <IAsset>); } var results = assets.Where(a => !a.IsProcessable).ToList(); foreach (IAsset asset in assets.Where(a => a.IsProcessable)) { string newContent = asset.Reader.Content; if (asset is CssAsset && string.IsNullOrEmpty(newContent) == false) { newContent = Yahoo.Yui.Compressor.CssCompressor.Compress(newContent); } else { newContent = Yahoo.Yui.Compressor.JavaScriptCompressor.Compress(newContent, true, true, false, false, -1, Encoding, CultureInfo); } asset.Reader = new MemoryAssetReader(asset.Reader.AssociatedFilePaths, newContent); results.Add(asset); } _cache.Add(key, results, new DateTimeOffset(DateTime.Now.AddDays(1))); return(results); }
public void Add(string key, object itemToCache, int cacheTime) { if (itemToCache != null) { _cache.Add(key, itemToCache, DateTime.Now.AddMinutes(cacheTime)); } }
public ImageResult SearchImages(ImageSearchParams param) { ObjectCache cache = MemoryCache.Default; string key = $"{param.Query}.{param.Offset}.{param.OffsetGroups}"; var cacheImages = cache.Get(key) as ImageResult; if (cacheImages == null) { var qualityImages = _pixabayApi.SearchImages(param); CacheItemPolicy policy = new CacheItemPolicy() { SlidingExpiration = TimeSpan.FromMinutes(30) }; if (qualityImages?.TotalCount > 500) { cache.Add(key, qualityImages, policy); return(qualityImages); } else { var vkImages = _vkApi.SearchImages(param); while (vkImages == null) { param.OffsetGroups += 4; IncrementGroupOffset(param.OffsetGroups); vkImages = _vkApi.SearchImages(param); } return(VkImages(param.OffsetGroups, cache, key, policy, vkImages)); } } return(cacheImages); }
/// <summary> /// Almacena un objeto en caché especificando una duración en segundos /// </summary> /// <param name="nombreCache"></param> /// <param name="datos"></param> /// <param name="segundos"></param> /// <returns></returns> public static bool Add(string nombreCache, object datos, long segundos) { bool sw = false; try { ObjectCache cache = MemoryCache.Default; if (cache.Contains(nombreCache)) { // La caché ya existe, la eliminamos primero ILogger log = LogFactory.GetLogger(typeof(CacheData)); log.Warning("Add({0}, obj, {1}). Esta caché ya existía. Reemplazando.", nombreCache, segundos); cache.Remove(nombreCache); } var politicaDuracion = new CacheItemPolicy(); politicaDuracion.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(segundos)); if (datos != null) { sw = cache.Add(nombreCache, datos, politicaDuracion); } } catch (Exception e) { ILogger log = LogFactory.GetLogger(typeof(CacheData)); log.Error("Add()", e); } return(sw); }
public HttpResponseMessage GetCandidates() { using (CandidateProfileDBContext candidateProfileDBContext = new CandidateProfileDBContext()) { //var candidates = candidateProfileDBContext.Candidates.ToList(); //return candidates; ObjectCache cache = MemoryCache.Default; //caching enabled for fast data access if (cache.Contains(Cache_Key_Candidates)) { return(Request.CreateResponse(HttpStatusCode.OK, cache.Get(Cache_Key_Candidates))); } else { var candidates = candidateProfileDBContext.Candidates.Select(c => new { c.CandidateId, c.FullName, c.DOB, c.Domain, c.ProfileDocument.DocumentName }).OrderBy(c => c.FullName).ToList(); // Store data in the cache CacheItemPolicy cacheItemPolicy = new CacheItemPolicy(); cacheItemPolicy.AbsoluteExpiration = DateTime.Now.AddHours(2.0); cache.Add(Cache_Key_Candidates, candidates, cacheItemPolicy); return(Request.CreateResponse(HttpStatusCode.OK, candidates)); } } }
public IEnumerable GetAvailableProducts(string currentUser) { try { ObjectCache cache = MemoryCache.Default; if (cache.Contains(cacheKey)) { return((IEnumerable)cache.Get(cacheKey)); } else { IProduct productBO = new ProductBO(currentUser); IEnumerable availableStocks = productBO.GetAllProducts();// this.GetDefaultStocks(); // Store data in the cache CacheItemPolicy cacheItemPolicy = new CacheItemPolicy(); cacheItemPolicy.AbsoluteExpiration = DateTime.Now.AddHours(6); cache.Add(cacheKey, availableStocks, cacheItemPolicy); return(availableStocks); } } catch (Exception ex) { throw new Exception(ex.Message); } }
/// <summary> /// Sets the cache /// </summary> /// <param name="name">key to lookup value in the future</param> /// <param name="value">value to remember</param> /// <param name="minutesFromNow">Number of minutes to cache the value</param> public static void Set(string name, object value, double minutesFromNow = 10) { CacheItemPolicy policy = new CacheItemPolicy(); policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(minutesFromNow); cache.Add(name, value, policy); }
/// <summary> /// 取得可以被Cache的資料(注意:非Thread-Safe) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">Cache保存號碼牌</param> /// <param name="callback">傳回查詢資料的函數</param> /// <param name="cacheMins"></param> /// <param name="forceRefresh">是否清除Cache,重新查詢</param> /// <returns></returns> public static T GetCachableData <T>(string key, Func <T> callback, int cacheMins, bool forceRefresh = false) where T : class { ObjectCache cache = MemoryCache.Default; string cacheKey = key; T res = cache[cacheKey] as T; //是否清除Cache,強制重查 if (res != null && forceRefresh) { cache.Remove(cacheKey); res = null; } if (res == null) { res = callback(); cache.Add(cacheKey, res, new CacheItemPolicy() { SlidingExpiration = new TimeSpan(0, cacheMins, 0) }); } return(res); }
internal SelectList GetSelectList(bool refresh = false) { ObjectCache cache = MemoryCache.Default; var list = (SelectList)cache["PvgMemberSelectList"]; if (refresh || list == null) { var items = Search("") .Select(s => new { Text = s.FirstName + " " + s.LastName, Value = s.Id }) .ToList(); list = new SelectList(items, "Value", "Text"); if (refresh) { cache.Remove("PvgMemberSelectList"); } cache.Add("PvgMemberSelectList", list, new CacheItemPolicy { Priority = CacheItemPriority.NotRemovable }); } return(list); }
public void RefreshCache(string city) { if (!cache.Contains(city)) { WebRequest request = WebRequest.Create( "https://api.jcdecaux.com/vls/v1/stations?contract=" + city + "&apiKey=133d203b9097bbbd95dd05214669a8219913166f"); WebResponse response = request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); string responseFromServer = reader.ReadToEnd(); reader.Close(); response.Close(); stations = JsonConvert.DeserializeObject <Station[]>(responseFromServer); CacheItemPolicy policy = new CacheItemPolicy(); policy.AbsoluteExpiration = DateTimeOffset.Now.AddSeconds(cache_timer); CacheItem item = new CacheItem(city, stations); cache.Add(item, policy); numb_request++; } else { stations = (Station[])cache.Get(city); numb_cache_request++; } }
public override CacheModificationResult AddOrChange <T>(CacheKey key, CacheValueOf <T> cacheObject) { using (new WriteLockDisposable(ThreadLocker)) { var exists = _memoryCache.GetCacheItem(key) != null; var cacheItemPolicy = cacheObject.Policy.ToCacheItemPolicy(); var entryDate = DateTime.Now; var policyExpiry = cacheItemPolicy.AbsoluteExpiration.Subtract(entryDate); cacheItemPolicy.RemovedCallback += arguments => LogHelper.TraceIfEnabled( GetType(), "Item was removed from cache ({0}). Policy had {1}s to run when entered at {2}. Key: {3}", () => arguments.RemovedReason.ToString(), () => policyExpiry.TotalSeconds.ToString(), () => entryDate.ToString(), () => key); _keyTracker.AddOrUpdate(key, key, (existingKey, existingValue) => key); if (exists) { LogHelper.TraceIfEnabled(GetType(), "Updating item with {0} left to run", () => policyExpiry.TotalSeconds.ToString()); _memoryCache.Set(key, cacheObject, cacheItemPolicy); return(new CacheModificationResult(true, false)); } var diff = cacheObject.Policy.GetExpiryDate().Subtract(DateTimeOffset.Now); LogHelper.TraceIfEnabled(GetType(), "Adding item with {0} left to run", () => policyExpiry.TotalSeconds.ToString()); _memoryCache.Add(key, cacheObject, cacheItemPolicy); } return(new CacheModificationResult(false, true)); }
public static UserViewModel getCanvasUser() { ObjectCache objCache = MemoryCache.Default; if (objCache.Contains(UserViewModel.CACHE_CANVAS_USER)) { return((UserViewModel)objCache.Get(UserViewModel.CACHE_CANVAS_USER)); } UserViewModel canvasUserVM = new UserViewModel(UserViewModel.MODE_CANVAS); UserView userView = new UserView(); userView.DataContext = canvasUserVM; bool?userResult = userView.ShowDialog(); //RT - The box may have been cancelled if (userResult != true) { return(null); } //Add the item to the cache. We don't know if the username and password are correct. CacheItemPolicy policy = new CacheItemPolicy(); policy.AbsoluteExpiration = DateTimeOffset.Now.AddMinutes(5); objCache.Add(UserViewModel.CACHE_CANVAS_USER, canvasUserVM, policy); return(canvasUserVM); }
/// <summary> /// Gets the label contents. /// </summary> /// <param name="labelFile">The label file.</param> /// <returns></returns> private string GetLabelContents(string labelFile) { string labelContents = string.Empty; if (cache.Contains(labelFile)) { //get an item from the cache labelContents = cache.Get(labelFile).ToString(); } else { // get label from site using (WebClient client = new WebClient()) { labelContents = client.DownloadString(labelFile); } var rockConfig = RockConfig.Load(); CacheItemPolicy cachePolicy = new CacheItemPolicy(); cachePolicy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddSeconds(rockConfig.CacheLabelDuration)); //add an item to the cache cache.Add(labelFile, labelContents, cachePolicy); } return(labelContents); }
private async Task <IEnumerable <ShulinParkingLotVM> > RetriveShulinParkingLotData(string cacheName) { string targetURI = "http://data.ntpc.gov.tw/api/v1/rest/datastore/382000000A-G00218-002"; HttpClient client = new HttpClient(); client.MaxResponseContentBufferSize = Int32.MaxValue; var response = await client.GetStringAsync(targetURI); JObject resultJO = JObject.Parse(response); // get JSON result objects into a list string results = resultJO["result"]["records"].ToString(); IEnumerable <ShulinParkingLotVM> collection = JsonConvert.DeserializeObject <IEnumerable <ShulinParkingLotVM> >(results); CacheItemPolicy policy = new CacheItemPolicy(); policy.AbsoluteExpiration = DateTime.Now.AddMinutes(30); ObjectCache cacheItem = MemoryCache.Default; cacheItem.Add(cacheName, collection, policy); return(collection); }
public static LatLong PlaceOrZipToLatLong(string placeOrZip) { ObjectCache cache = MemoryCache.Default; string url = "http://ws.geonames.org/postalCodeSearch?{0}={1}&maxRows=1&style=SHORT"; url = String.Format(url, placeOrZip.IsNumeric() ? "postalcode" : "placename", placeOrZip); var result = cache[placeOrZip] as XDocument; if (result == null) { result = XDocument.Load(url); cache.Add(placeOrZip, result, new CacheItemPolicy() { SlidingExpiration = TimeSpan.FromDays(1) }); } if (result.Descendants("code").Any()) { var ll = (from x in result.Descendants("code") select new LatLong { Lat = (float)x.Element("lat"), Long = (float)x.Element("lng") }) .First(); return(ll); } return(null); }
public bool AddOnlineUser(string email) { try { ObjectCache cache = MemoryCache.Default; List <string> users = cache["users"] as List <string>; if (users == null) { users = new List <string>(); } if (!users.Contains(email)) { users.Add(email); } cache.Add("users", users, DateTime.Now.AddHours(1)); return(true); } catch { return(false); } }
/// <summary> /// 取得可以被Cache的資料(注意:非Thread-Safe) /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">Cache保存號碼牌</param> /// <param name="callback">傳回查詢資料的函數</param> /// <param name="absExpire">有效期限</param> /// <param name="forceRefresh">是否清除Cache,重新查詢</param> /// <returns></returns> public static T GetCachableData <T>(string key, Func <T> callback, DateTimeOffset absExpire, bool forceRefresh = false) where T : class { ObjectCache cache = MemoryCache.Default; string cacheKey = key; //取得每個Key專屬的鎖定對象 lock (GetAsyncLock(key)) { T res = cache[cacheKey] as T; //是否清除Cache,強制重查 if (res != null && forceRefresh) { cache.Remove(cacheKey); res = null; } if (res == null) { res = callback(); cache.Add(cacheKey, res, new CacheItemPolicy() { AbsoluteExpiration = absExpire }); } return(res); } }
public T this[string name] { get { //Get the default MemoryCache to cache objects in memory ObjectCache cache = MemoryCache.Default; object data = cache.Get(name); if (data != null) { return((T)data); } return(default(T)); } set { //Get the default MemoryCache to cache objects in memory ObjectCache cache = MemoryCache.Default; //Create a custom Timeout of 10 seconds CacheItemPolicy policy = new CacheItemPolicy(); policy.AbsoluteExpiration = DateTimeOffset.MaxValue; //Get data from the database and write them to the result //add the object to the cache cache.Add(name, value, policy); } }
public void Add(string key, LazyLock item, ICacheDetails cacheDetails) { var policy = new CacheItemPolicy(); // Set timeout policy.Priority = CacheItemPriority.NotRemovable; if (IsTimespanSet(cacheDetails.AbsoluteCacheExpiration)) { policy.AbsoluteExpiration = DateTimeOffset.Now.Add(cacheDetails.AbsoluteCacheExpiration); } else if (IsTimespanSet(cacheDetails.SlidingCacheExpiration)) { policy.SlidingExpiration = cacheDetails.SlidingCacheExpiration; } // Add dependencies var dependencies = (IList <ChangeMonitor>)cacheDetails.CacheDependency.Dependency; if (dependencies != null) { foreach (var dependency in dependencies) { policy.ChangeMonitors.Add(dependency); } } // Setting priority to not removable ensures an // app pool recycle doesn't unload the item, but a timeout will. policy.Priority = CacheItemPriority.NotRemovable; // Setup callback policy.RemovedCallback = CacheItemRemoved; cache.Add(key, item, policy); }
public Task <bool> AddNewPlayer(Player player) { try { List <Player> players = new List <Player>(); CacheItemPolicy policy = new CacheItemPolicy { AbsoluteExpiration = DateTime.Now.AddDays(30) }; if (_cache.Contains(_cacheKey)) { players = (List <Player>)_cache.Get(_cacheKey); players.Add(player); _cache.Set(_cacheKey, players, policy); return(Task.FromResult(true)); } else { players.Add(player); _cache.Add(_cacheKey, players, policy); return(Task.FromResult(true)); } } catch (Exception e) { return(Task.FromResult(false)); } }
public virtual void AddData(string key, object data) { if (!_cache.Contains(key)) { _cache.Add(key, data, ExpirationPolicy); } }
public void AddTest() { ObjectCache target = new ObjectCache(_DOFactory); var tempSale = new SaleDO { rowID = 1 }; Assert.Equal(true, target.Add(tempSale, ObjectCache.AddBehavior.DONT_OVERWRITE)); tempSale = new SaleDO { rowID = 1 }; Assert.Equal(false, target.Add(tempSale, ObjectCache.AddBehavior.DONT_OVERWRITE)); tempSale = new SaleDO { rowID = 1 }; Assert.Equal(true, target.Add(tempSale, ObjectCache.AddBehavior.OVERWRITE)); tempSale = new SaleDO { rowID = 1 }; try { target.Add(tempSale, ObjectCache.AddBehavior.THROWEXCEPTION); Assert.True(false); } catch (Exception e) { //TODO proper exception type not defined, for AddBehavior.THROW_EXCEPTION } }
public void CountTest() { DataObjectFactory DOFactory = new DataObjectFactory(_DAL); ObjectCache target = new ObjectCache(DOFactory); target.GetByID<SaleDO>(1); Assert.Equal(1, target.Count); var tempSale = new SaleDO { rowID = 2 }; target.Add( tempSale, ObjectCache.AddBehavior.THROWEXCEPTION); Assert.Equal(2, target.Count); target.Remove(tempSale); Assert.Equal(1, target.Count); //target.Clear(); //Assert.AreEqual(0, target.Count); }
private void SetCache(ObjectCache cache, string key, object value, CacheItemPolicy policy) { cache.Add(key, value, policy); CurrentCacheKeys.Add(key); }