public void ExceptionThrownDuringAddIntoIsolatedStorageAllowsItemToBeReaddedLater() { using (IsolatedStorageBackingStore backingStore = new IsolatedStorageBackingStore("foo", null)) { ICachingInstrumentationProvider instrumentationProvider = new NullCachingInstrumentationProvider(); Cache cache = new Cache(backingStore, instrumentationProvider); try { try { cache.Add("my", new NonSerializableClass()); Assert.Fail("Should have thrown exception internally to Cache.Add"); } catch (Exception) { cache.Add("my", new SerializableClass()); Assert.IsTrue(cache.Contains("my")); } } finally { backingStore.Flush(); } } }
public void Add_ShouldUpdateIfPresent_Test() { Cache cache = new Cache(); var otherValue = "otherValue"; cache.Add(TestKey, TestValue, new TimeSpan(0, 0, 1)); Assert.AreEqual(TestValue, cache.Get<string, string>(TestKey)); cache.Add(TestKey, otherValue, new TimeSpan(0, 0, 1)); Assert.AreEqual(otherValue, cache.Get<string, string>(TestKey)); }
public void AddGet_DateTime_ShouldAdd_Test() { Cache cache = new Cache(); cache.Add(TestKey, TestValue, DateTime.Now + new TimeSpan(0, 5, 0)); Assert.AreEqual(TestValue, cache.Get<string, string>(TestKey)); }
public void AddGet_TimeSpan_ShouldAddToTheCache_Test() { Cache cache = new Cache(); cache.Add(TestKey, TestValue, new TimeSpan(0, 5, 0)); Assert.AreEqual(TestValue, cache.Get<string, string>(TestKey)); }
public void ItemAddedPreviousToFailedAddIsRemovedCompletelyIfSecondAddFails() { using (IsolatedStorageBackingStore backingStore = new IsolatedStorageBackingStore("foo", null)) { ICachingInstrumentationProvider instrumentationProvider = new NullCachingInstrumentationProvider(); Cache cache = new Cache(backingStore, instrumentationProvider); cache.Add("my", new SerializableClass()); try { try { cache.Add("my", new NonSerializableClass()); Assert.Fail("Should have thrown exception internally to Cache.Add"); } catch (Exception) { Assert.IsFalse(cache.Contains("my")); Assert.AreEqual(0, backingStore.Count); Hashtable isolatedStorageContents = backingStore.Load(); Assert.AreEqual(0, isolatedStorageContents.Count); } } finally { backingStore.Flush(); } } }
public void TestCacheAllItemsAccessedJustBeforeGC() { Cache cache = new Cache(); for (int i = 0; i < 4; i++) { cache.Add(i, new DummyClass { Name = i.ToString(), Value = new byte[1024] }); } var value0 = cache[0]; var value1 = cache[1]; var value2 = cache[2]; var value3 = cache[3]; Assert.AreEqual(4, cache.Count); Assert.AreEqual(4, cache.ActiveCount); Assert.AreEqual("0", (cache[0] as DummyClass).Name); Assert.AreEqual("1", (cache[1] as DummyClass).Name); Assert.AreEqual("2", (cache[2] as DummyClass).Name); Assert.AreEqual("3", (cache[3] as DummyClass).Name); GC.Collect(); Assert.AreEqual(4, cache.Count); Assert.AreEqual(4, cache.ActiveCount); Assert.AreEqual("0", (cache[0] as DummyClass).Name); Assert.AreEqual("1", (cache[1] as DummyClass).Name); Assert.AreEqual("2", (cache[2] as DummyClass).Name); Assert.AreEqual("3", (cache[3] as DummyClass).Name); }
private Cache<int, string> CreateCacheContainingFirstThousandCountingNumbers() { Cache<int, string> c = new Cache<int, string>(); foreach (KeyValuePair<int, string> entry in Enumerable.Range(1, 1000).Select(i => new KeyValuePair<int, string>(i, i.ToString()))) c.Add(entry); return c; }
public void TestByKey() { var cache = new Cache(); cache.Add("TestKey", 1); Assert.IsTrue(Equals(cache["TestKey"], 1)); }
public void Cache_Get_Item_Key_Should_Return_Item() { Cache<string, int> cache = new Cache<string, int>(); int EXPECTED = 1; cache.Add("1", 1); Assert.AreEqual(EXPECTED, cache.Get("1")); }
public void BasicCaching() { var cache = new Cache<string, int>(2); cache.Add("A", 1); cache.Add("B", 2); Assert.AreEqual<int>(2, cache.Count, "The count is incorrect."); cache.Add("C", 3); Assert.AreEqual<int>(2, cache.Count, "The count is incorrect."); var keys = new List<string>(cache.Keys); CollectionAssert.DoesNotContain(keys, "A", "The cache contained 'A'."); CollectionAssert.Contains(keys, "B", "The cache did not contain 'B'."); CollectionAssert.Contains(keys, "C", "The cache did not contain 'C'."); }
public void TestCacheSomeItemsAccessedJustBeforeGC() { Cache cache = new Cache(); for (int i = 0; i < 5; i++) { cache.Add(i, new byte[1024]); } var value1 = cache[1]; var value3 = cache[3]; Assert.AreEqual(5, cache.Count); Assert.AreEqual(5, cache.ActiveCount); Assert.IsNotNull(cache[0]); Assert.IsNotNull(cache[1]); Assert.IsNotNull(cache[2]); Assert.IsNotNull(cache[3]); Assert.IsNotNull(cache[4]); GC.Collect(); Assert.AreEqual(5, cache.Count); Assert.AreEqual(2, cache.ActiveCount); Assert.IsNull(cache[0]); Assert.IsNotNull(cache[1]); Assert.IsNull(cache[2]); Assert.IsNotNull(cache[3]); Assert.IsNull(cache[4]); }
public void TestCacheNoItemsAccessedBeforeGC() { Cache cache = new Cache(); for (int i = 0; i < 5; i++) { cache.Add(i, i.ToString()); } Assert.AreEqual(5, cache.Count); Assert.AreEqual(5, cache.ActiveCount); Assert.AreEqual("0", cache[0]); Assert.AreEqual("1", cache[1]); Assert.AreEqual("2", cache[2]); Assert.AreEqual("3", cache[3]); Assert.AreEqual("4", cache[4]); GC.Collect(); Assert.AreEqual(5, cache.Count); Assert.AreEqual(0, cache.ActiveCount); Assert.IsNull(cache[0]); Assert.IsNull(cache[1]); Assert.IsNull(cache[2]); Assert.IsNull(cache[3]); Assert.IsNull(cache[4]); }
public void ItemAddedPreviousToFailedAddIsRemovedCompletelyIfSecondAddFails() { TestConfigurationContext context = new TestConfigurationContext(); using (IsolatedStorageBackingStore backingStore = new IsolatedStorageBackingStore("foo")) { CacheCapacityScavengingPolicy scavengingPolicy = new CacheCapacityScavengingPolicy("test", new CachingConfigurationView(context)); Cache cache = new Cache(backingStore, scavengingPolicy); cache.Initialize(this); cache.Add("my", new SerializableClass()); try { cache.Add("my", new NonSerializableClass()); Assert.Fail("Should have thrown exception internally to Cache.Add"); } catch (Exception) { Assert.IsFalse(cache.Contains("my")); Assert.AreEqual(0, backingStore.Count); Hashtable isolatedStorageContents = backingStore.Load(); Assert.AreEqual(0, isolatedStorageContents.Count); } } }
public void Remove_ShouldDoNothingIfNull_Test() { Cache cache = new Cache(); cache.Add(TestKey, TestValue, new TimeSpan(0, 0, 1)); Assert.AreEqual(TestValue, cache.Get<string, string>(TestKey)); cache.Remove<string>(null); Assert.AreEqual(TestValue, cache.Get<string, string>(TestKey)); }
public void AddGet_DateTime_ShouldAddAndExpire_Test() { Cache cache = new Cache(); cache.Add(TestKey, TestValue, DateTime.Now + new TimeSpan(0, 0, 1)); Assert.AreEqual(TestValue, cache.Get<string, string>(TestKey)); Thread.Sleep(2000); Assert.IsNull(cache.Get<string, string>(TestKey)); }
static void Main(string[] args) { var storage = new PiStorage(); var datetime = new ChangeableTime(); var cache = new Cache<int, string>(2, 1000, 10000, storage, datetime); cache.Add(1, "One"); datetime.AddTime(400); cache.Add(2, "Two"); datetime.AddTime(400); cache.Add(3, "Three"); Console.WriteLine("Pi" + cache[1]); //Indexer and Get will add deleted data from storage datetime.AddTime(0); Console.WriteLine("Pi" + cache.Get(2)); datetime.AddTime(0); Console.WriteLine("Pi" + cache[3]); Console.ReadKey(); }
public void Cache_Remove_Item_Key_Should_Remove_Item() { Cache<string, int> cache = new Cache<string, int>(); bool EXPECTED = true; cache.Add("1", 1); Assert.AreEqual(EXPECTED, cache.Remove("1")); int EXPECTEDCOUNT = 0; Assert.AreEqual(EXPECTEDCOUNT, cache.Count); EXPECTED = false; Assert.AreEqual(EXPECTED, cache.Contains("1")); }
public void Contains_ValueIsReferenceType_ChecksForReferenceEquality() { ICache<string, SampleValue> cache = new Cache<string, SampleValue>(_timerInterval); SampleValue value = new SampleValue(); ICacheItem<SampleValue> cacheItem = new NonExpiringCacheItem<SampleValue>(value); KeyValuePair<string, SampleValue> keyValuePair = new KeyValuePair<string, SampleValue>(_key, value); cache.Add(_key, cacheItem); bool result = cache.Contains(keyValuePair); Assert.True(result); }
public void ExceptionThrownDuringAddIntoIsolatedStorageAllowsItemToBeReaddedLater() { TestConfigurationContext context = new TestConfigurationContext(); using (IsolatedStorageBackingStore backingStore = new IsolatedStorageBackingStore("foo")) { CacheCapacityScavengingPolicy scavengingPolicy = new CacheCapacityScavengingPolicy("test", new CachingConfigurationView(context)); Cache cache = new Cache(backingStore, scavengingPolicy); cache.Initialize(this); try { cache.Add("my", new NonSerializableClass()); Assert.Fail("Should have thrown exception internally to Cache.Add"); } catch (Exception) { cache.Add("my", new SerializableClass()); Assert.IsTrue(cache.Contains("my")); } } }
public void ExceptionThrownDuringAddIntoIsolatedStorageAllowsItemToBeReaddedLater() { using (IsolatedStorageBackingStore backingStore = new IsolatedStorageBackingStore("foo", null)) { CacheCapacityScavengingPolicy scavengingPolicy = new CacheCapacityScavengingPolicy(10); CachingInstrumentationProvider instrumentationProvider = new CachingInstrumentationProvider(); Cache cache = new Cache(backingStore, scavengingPolicy, instrumentationProvider); cache.Initialize(this); try { cache.Add("my", new NonSerializableClass()); Assert.Fail("Should have thrown exception internally to Cache.Add"); } catch (Exception) { cache.Add("my", new SerializableClass()); Assert.IsTrue(cache.Contains("my")); } } }
public void ConditionalCaching() { var cache = new Cache<string, int>(2); int value; if (!cache.TryGetValue("A", out value)) { value = 1; cache.Add("A", value); } Assert.AreEqual<int>(1, cache.Count, "The count is incorrect."); Assert.IsTrue(cache.TryGetValue("A", out value), "The cache did not contain 'A'."); Assert.AreEqual<int>(1, value, "The cached value is incorrect."); }
public void ExceptionThrownDuringAddResultsInObjectBeingRemovedFromCacheCompletely() { MockBackingStore backingStore = new MockBackingStore(); ICachingInstrumentationProvider instrumentationProvider = new NullCachingInstrumentationProvider(); Cache cache = new Cache(backingStore, instrumentationProvider); try { cache.Add("foo", "bar"); Assert.Fail("Should have thrown exception thrown internally to Cache.Add"); } catch (Exception) { Assert.IsFalse(cache.Contains("foo")); Assert.AreEqual(1, backingStore.removalCount); } }
public void ExceptionThrownDuringAddResultsInObjectBeingRemovedFromCacheCompletely() { TestConfigurationContext context = new TestConfigurationContext(); MockBackingStore backingStore = new MockBackingStore(); CacheCapacityScavengingPolicy scavengingPolicy = new CacheCapacityScavengingPolicy("test", new CachingConfigurationView(context)); Cache cache = new Cache(backingStore, scavengingPolicy); cache.Initialize(this); try { cache.Add("foo", "bar"); Assert.Fail("Should have thrown exception thrown internally to Cache.Add"); } catch (Exception) { Assert.IsFalse(cache.Contains("foo")); Assert.AreEqual(1, backingStore.removalCount); } }
public UserProfile GetByUserName(string userName) { UserProfile entity; var cachedEntity = Cache?.Get($"{SingleCacheKeyPrefix}:{userName}"); if (string.IsNullOrEmpty(cachedEntity)) { entity = Db.Set <UserProfile>().Include(e => e.AppUser) .FirstOrDefault(e => e.AppUser.UserName == userName); Cache?.Add($"{SingleCacheKeyPrefix}:{userName}", JsonConvert.SerializeObject(entity)); } else { entity = JsonConvert.DeserializeObject <UserProfile>(cachedEntity); } return(entity); }
public static DeviceAtlasData GetDeviceAtlasData(Cache objCache, FileLog objEventLog, ExceptionLog objExceptionEventLog) { DeviceAtlasData objDeviceAtlasData = null; lock (DeviceAtlasData.CacheLock) { if (objCache["DeviceAtlasData"] != null) { objDeviceAtlasData = (DeviceAtlasData)objCache["DeviceAtlasData"]; } else { objDeviceAtlasData = new DeviceAtlasData(objEventLog, objExceptionEventLog); objCache.Add("DeviceAtlasData", objDeviceAtlasData, null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.NotRemovable, null); } } return objDeviceAtlasData; }
private void LoadQuestions(TaskScheduler uiScheduler) { if (Cache.Contains(Constants.CacheNames.QuoteSlipSchedules)) { Questions = ((List <IQuestionClass>) Cache.Get(Constants.CacheNames.QuoteSlipSchedules)); } else { Questions = LoadQuestionsFromSharePoint(Settings.Default.SharePointContextUrl, Settings.Default.PolicySchedulesListName); Cache.Add(Constants.CacheNames.QuoteSlipSchedules, Questions, new CacheItemPolicy()); } Task.Factory.StartNew(() => { clbQuestions.DataSource = Questions; clbQuestions.DisplayMember = "Title"; clbQuestions.ValueMember = "Id"; }, CancellationToken.None, TaskCreationOptions.None, uiScheduler); }
private Object GetAsset(string assetPath) { if (assetCache == null) { assetCache = new Cache <Object>(); } Object asset = null; if (assetCache.HasCache(assetPath)) { asset = assetCache.Get(assetPath); } else { asset = AssetDatabase.LoadMainAssetAtPath(assetPath); assetCache.Add(assetPath, asset); } return(asset); }
private void DataBind() { PatientDataTier aDatatier = new PatientDataTier(); ViewState["vpatid"] = txtPatientID.Text.Trim(); DataSet aDataSet = new DataSet(); aDataSet = aDatatier.GetPatient(Convert.ToString(ViewState["vpatid"])); grdPatient.DataSource = aDataSet.Tables[0]; // Cache for a while if (Cache["PatientData"] == null) { Cache.Add("PatientData", new DataView(aDataSet.Tables[0]), null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(10), System.Web.Caching.CacheItemPriority.Default, null); } grdPatient.DataBind(); }
private List <IInsurer> GetInsurers(string type) { List <IInsurer> returnItems; if (Cache.Contains(type)) { returnItems = (List <IInsurer>)Cache.Get(type); } else { var list = new SharePointList(Settings.Default.SharePointContextUrl, Settings.Default.ApprovedInsurersListName, Constants.SharePointQueries.AllItemsSortByTitle); var presenter = new SharePointListPresenter(list, this); returnItems = presenter.GetInsurers(); if (!type.Equals(Constants.CacheNames.NoCache)) { Cache.Add(type, returnItems, new CacheItemPolicy()); } } return(returnItems); }
public List <SelectListItem> GetCountryList(string keyword) { if (Cache.Get("CountryList") != null) { return(Cache.Get("CountryList") as List <SelectListItem>); } else { var list = new List <SelectListItem> { new SelectListItem { Value = "", Text = "" } }; _countryService.GetCountryList(keyword).ForEach(c => list.Add(new SelectListItem { Value = c.CountryCode, Text = string.Format("{0}|{1}", c.CountryCode, c.ChineseName) })); Cache.Add("CountryList", list); return(list); } }
protected void Button3_Click(object sender, EventArgs e) { con = new SqlConnection("Data Source=DESKTOP-9MJ1CJ8;Initial Catalog=StudentDB;Integrated Security=True;Pooling=False"); adp = new SqlDataAdapter("Select * from StudentInfo", con); if (Cache["data2"] == null) { ds = new DataSet(); adp.Fill(ds, "StudentInfo"); CacheDependency cd = new CacheDependency(@"c:\FILES\Data.txt"); Cache.Add("data2", ds, cd, DateTime.MaxValue, TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, null); Label1.Text = "From db"; } else { ds = (DataSet)Cache["data2"]; Label1.Text = "From cache"; } GridView1.DataSource = ds.Tables[0]; GridView1.DataBind(); }
/// <summary> /// 从缓存中获取运输方式支持的国家 /// </summary> private List <ShippingMethodCountryModel> GetShippingMethodCountriesFromCache(int shippingMethodId) { object inCache = Cache.Get(shippingMethodId.ToString()); if (inCache != null) { var listShippingMethodCountryModel = inCache as List <ShippingMethodCountryModel>; if (listShippingMethodCountryModel != null) { return(listShippingMethodCountryModel); } } var listShippingMethodCountryModelNewest = _freightService.GetCountryArea(shippingMethodId); if (listShippingMethodCountryModelNewest != null) { Cache.Add(shippingMethodId.ToString(), listShippingMethodCountryModelNewest, 5); } return(listShippingMethodCountryModelNewest); }
/// <summary> /// 获取指定IP所在地理位置 /// </summary> /// <param name="strIP">IP地址</param> /// <returns></returns> private IPLocation GetIPLocation(string strIP) { _ip = IPToLong(strIP); if (cache[cache_key] == null) { string path = HttpContext.Current.Server.MapPath(IPDataPath); FileStream fs = new FileStream(path, System.IO.FileMode.Open, System.IO.FileAccess.Read); byte[] buff = new byte[fs.Length]; fs.Read(buff, 0, (int)fs.Length); CacheDependency cDep = new CacheDependency(path); cache.Add(cache_key, buff, cDep, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null); } _ipFile = new MemoryStream((byte[])cache[cache_key]); long[] ipArray = BlockToArray(ReadIPBlock()); long offset = SearchIP(ipArray, 0, ipArray.Length - 1) * 7 + 4; _ipFile.Position += offset; //跳过起始IP _ipFile.Position = ReadLongX(3) + 4; //跳过结束IP IPLocation loc = new IPLocation(); int flag = _ipFile.ReadByte(); //读取标志 if (flag == 1) //表示国家和地区被转向 { _ipFile.Position = ReadLongX(3); flag = _ipFile.ReadByte();//再读标志 } long countryOffset = _ipFile.Position; loc.Country = ReadString(flag); if (flag == 2) { _ipFile.Position = countryOffset + 3; } flag = _ipFile.ReadByte(); loc.Area = ReadString(flag); _ipFile.Close(); _ipFile = null; return(loc); }
public static List <UserEntity> GetUserAll() { List <UserEntity> all = new List <UserEntity>(); UserRepository mr = new UserRepository(); List <UserInfo> miList = Cache.Get <List <UserInfo> >("UserALL"); if (miList.IsEmpty()) { miList = mr.GetAllUser(); Cache.Add("UserALL", miList); } if (!miList.IsEmpty()) { foreach (UserInfo mInfo in miList) { UserEntity userEntity = TranslateUserEntity(mInfo); all.Add(userEntity); } } return(all); }
private void BindData() { PhysicianDataTier aDatatier = new PhysicianDataTier(); string phyID = Convert.ToString(Session["vPhyID"]); string fname = Convert.ToString(Session["vFName"]); string lname = Convert.ToString(Session["vLName"]); txtPhysicianID.Text = phyID; txtFName.Text = fname; txtLName.Text = lname; if ((phyID.Length > 0) || (fname.Length > 0) || (lname.Length > 0)) { DataSet aDataset = new DataSet(); aDataset = aDatatier.GetAllPhysicians(phyID, fname, lname); if (aDataset.Tables[0].Rows.Count > 0) { grdStudent.Visible = true; grdStudent.DataSource = aDataset.Tables[0]; if (Cache["StudentData"] == null) { Cache.Add("StudentData", new DataView(aDataset.Tables[0]), null, System.Web.Caching.Cache.NoAbsoluteExpiration, System.TimeSpan.FromMinutes(10), System.Web.Caching.CacheItemPriority.Default, null); grdStudent.DataBind(); } } else { grdStudent.Visible = false; } } else { grdStudent.Visible = false; } }
public void CacheCRUDTest_forIHubProxy() { var startTime = new DateTime(2017, 1, 1, 1, 1, 30); //freez time var timeProviderStub = new Mock <TimeProvider>(); timeProviderStub .SetupGet(tp => tp.Now) .Returns(startTime); TimeProvider.Current = timeProviderStub.Object; int cacheTimeOut = 1; var cache = new Cache <long, IHubProxy>(10, cacheTimeOut); //add long id = 1; var hubProxyStub = new Mock <IHubProxy>(); var expected = hubProxyStub.Object; cache.Add(id, expected); IHubProxy actual; var res = cache.TryGet(id, out actual); Assert.Equal(res, true); Assert.True(ReferenceEquals(expected, actual)); //delete cache.Delete(id); res = cache.TryGet(id, out actual); Assert.Equal(res, false); }
public JsonResult InventoryDataImport() { List <ImportInventoryEntity> list = new List <ImportInventoryEntity>(); try { LogHelper.WriteTextLog("InventoryDataImport", "库存数据导入"); DataSet ds = new DataSet(); if (Request.Files.Count == 0) { throw new Exception("请选择导入文件!"); } String token = Request["token"]; Cache.Remove(token); // 保存文件到UploadFiles文件夹 for (int i = 0; i < Request.Files.Count; i++) { HttpPostedFileBase file = Request.Files[i]; var fileName = file.FileName; var filePath = Server.MapPath(string.Format("~/{0}", "UploadFiles")); string path = Path.Combine(filePath, fileName); file.SaveAs(path); LogHelper.WriteTextLog("InventoryDataImport", path); ds = ExcelHelper.ImportExceltoDt_New(path); list = InventoryService.GetInventoryImportList(ds); LogHelper.WriteTextLog("InventoryDataImport", JsonHelper.ToJson(list)); //存入缓存 Cache.Add(token, list); } } catch (Exception ex) { LogHelper.WriteTextLog("InventoryDataImport", ex.ToString()); } return(Json(list)); }
public override void AssociateDependentKeysToParent(string parentKey, IEnumerable <string> dependentCacheKeys, CacheDependencyAction actionToPerform = CacheDependencyAction.ClearDependentItems) { Logger.WriteInfoMessage(string.Format("Associating list of cache keys to parent key:[{0}]", parentKey)); var cacheKeyForDependency = GetParentItemCacheKey(parentKey); var currentEntry = Cache.Get <DependencyItem[]>(cacheKeyForDependency); var tempList = new List <DependencyItem>(); if (currentEntry != null && currentEntry.Length > 0) { Logger.WriteInfoMessage(string.Format("Creating new associated dependency list for parent key:[{0}]", parentKey)); tempList.AddRange(currentEntry); } else { RegisterParentDependencyDefinition(parentKey, actionToPerform); var items = Cache.Get <DependencyItem[]>(cacheKeyForDependency); if (items != null) { tempList.AddRange(items); } } var keysList = new List <string>(dependentCacheKeys); keysList.ForEach(d => { if (!tempList.Any(c => c.CacheKey == d)) { tempList.Add(new DependencyItem { CacheKey = d, Action = actionToPerform }); } }); Cache.InvalidateCacheItem(cacheKeyForDependency); Cache.Add(cacheKeyForDependency, GetMaxAge(), tempList.ToArray()); }
public override void Execute() { lock (typeof(GetUrlItem)) { PageCacheItem page = new PageCacheItem(); mRequest = (HttpWebRequest)WebRequest.Create(URL); mResponse = (HttpWebResponse)mRequest.GetResponse(); int length = 0; foreach (string key in mResponse.Headers.Keys) { page.Headers.Add(new HeaderItem { Name = key, Value = mResponse.Headers[key] }); if (key == "Content-Length") { int.TryParse(mResponse.Headers[key], out length); } } page.Data = new Byte[length]; int offset = 0; int count; using (System.IO.Stream stream = mResponse.GetResponseStream()) { count = stream.Read(page.Data, offset, page.Data.Length - offset); offset += count; while (count > 0) { count = stream.Read(page.Data, offset, page.Data.Length - offset); offset += count; } } if (Cache != null) { Cache.Remove(Key); Cache.Add(Key, page, null, DateTime.Now.AddMinutes(Item.Expiry), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null); } } }
public override void Process(HttpRequestArgs args) { Item item = Context.Item; if (Context.Database == null || item == null) { return; } if (Context.PageMode.IsExperienceEditor || Context.PageMode.IsPreview) { return; } string itemId = item.ID.ToString(); Redirect resolvedMapping = this.GetResolvedMapping(itemId); bool flag = resolvedMapping != null; if (resolvedMapping == null) { resolvedMapping = this.FindMapping(itemId); } if (resolvedMapping != null && !flag) { Dictionary <string, Redirect> dictionaryitem = HttpRuntime.Cache[this.ResolvedRedirectPrefix] as Dictionary <string, Redirect> ?? new Dictionary <string, Redirect>(); dictionaryitem[itemId] = resolvedMapping; Cache cache = HttpRuntime.Cache; string resolvedMappingsPrefix = this.ResolvedRedirectPrefix; DateTime utcNow = DateTime.UtcNow; cache.Add(resolvedMappingsPrefix, dictionaryitem, null, utcNow.AddMinutes((double)this.CacheExpiration), TimeSpan.Zero, CacheItemPriority.Normal, null); } if (resolvedMapping != null && HttpContext.Current != null) { if (!resolvedMapping.RedirectUrl.IsNullOrEmpty()) { HttpContext.Current.Response.Redirect(resolvedMapping.RedirectUrl, true); args.AbortPipeline(); } } }
public string GetResourceByCultureAndKey(CultureInfo culture, string resourceKey) { if (culture == null || culture.Name.Length == 0) { culture = new CultureInfo(this.m_defaultResourceCulture); } //Cache query var key = resourceKey + "_" + culture.Name; var resourceValue = _cache[key] as string; if (resourceValue == null) { try { resourceValue = (from r in _db.Resources where r.cultureCode == culture.Name && r.resourceKey == resourceKey select r.resourceValue).SingleOrDefault(); } catch (EntityCommandExecutionException) { resourceValue = null; } if (resourceValue != null) { _cache.Add(key, resourceValue); System.Console.WriteLine("caching: " + key + " value: " + resourceValue); } } if (resourceValue == null) { resourceValue = resourceKey; } return(resourceValue); }
private SessionStateStoreData FetchCachedStoreData(HttpContext context, string id, out bool locked, out TimeSpan lockAge, out object lockId, out SessionStateActions actions, bool exclusive) { // 1-2 remote calls locked = false; lockAge = TimeSpan.Zero; lockId = null; actions = SessionStateActions.None; // check for existing session byte[] bytes = Cache.Get <byte[]>(GetCacheKey(id)); if (bytes == null) { return(null); } SessionStoreDataContext data = SessionStoreDataContext.Deserialize(bytes, context); locked = data.IsLocked; if (locked) { lockAge = DateTime.Now.Subtract(data.LockDate.Value); lockId = data.LockDate; // specs require null to be returned return(null); } //todo: rewrite with real locking when available // as of a few microseconds ago, this session was unlocked, so proceed if (exclusive) { data.LockDate = DateTime.Now; // not perfectly thread safe as there can be race conditions between // clustered servers, but this is the best we've got Cache.Add(GetCacheKey(id), (object)SessionStoreDataContext.Serialize(data), DateTime.Now.AddMinutes(data.Data.Timeout)); } return(data.Data); }
protected override void InsertTiles() { var bm = new byte[TileSizeX * TileSizeY * BitsPerPixel]; Cache.Connection.Open(); var trans = Cache.Connection.BeginTransaction(); var count = 0; for (byte level = 0; level < MaxLevel; level++) { var numberOfTiles = Math.Pow(2, level); for (byte i = 0; i < numberOfTiles; i++) { for (byte j = 0; j < numberOfTiles; j++) { bm[0] = i; bm[1] = j; bm[2] = level; Cache.Add(new TileIndex(i, j, level.ToString(CultureInfo.InvariantCulture)), bm); count++; } } } trans.Commit(); Cache.Connection.Close(); using (var cn = (SQLiteConnection)Cache.Connection.Clone()) { cn.Open(); SQLiteCommand cmd = cn.CreateCommand(); cmd.CommandText = "SELECT count(*) FROM cache"; Assert.AreEqual(count, Convert.ToInt32(cmd.ExecuteScalar())); } Console.WriteLine($"{count} dummy tiles inserted."); }
bool ProcessHealthMessage([NotNull] HealthStatusMessage msg) { WriteLineInColor("Received Health Status Message", ConsoleColor.Yellow); RILogManager.Default?.SendInformation("Received Health Status Message"); if (msg.message.ToString().ToUpper() != "OK" && ((MSStatus)msg.status) != MSStatus.Healthy) { WriteLineInColor("Health Warning", ConsoleColor.Red); RILogManager.Default?.SendInformation("Health Warning"); } RILogManager.Default?.SendInformation(msg.serviceName); RILogManager.Default?.SendInformation(msg.status.ToString()); RILogManager.Default?.SendInformation(ToBytes(msg.memoryUsed)); RILogManager.Default?.SendInformation(msg.CPU.ToString()); RILogManager.Default?.SendInformation(msg.message); WriteLineInColor("Service: " + msg.serviceName, ConsoleColor.Yellow); WriteLineInColor("Status: " + msg.status.ToString(), ConsoleColor.Yellow); WriteLineInColor("Memory Used: " + ToBytes(msg.memoryUsed), ConsoleColor.Yellow); WriteLineInColor("CPU Used: " + msg.CPU.ToString(), ConsoleColor.Yellow); WriteLineInColor("Message: " + msg.message, ConsoleColor.Yellow); Cache?.Add("MicroServiceID_" + msg.ID + "_" + msg.date + "_Status", (msg.status == 1 ? "Healthy" : "Unhealthy"), "MicroServiceStatus"); Cache?.Add("MicroServiceID_" + msg.ID + "_" + msg.date + "_Memory", msg.memoryUsed, "MicroServiceStatus"); Cache?.Add("MicroServiceID_" + msg.ID + "_" + msg.date + "_CPU", msg.CPU, "MicroServiceStatus"); msg.ID = new Random().Next(8000001, 9000000).ToString(); using (var _db = new LiteDatabase(connectionString)) { Thread.Sleep(5); _db.Shrink(); var collection = _db.GetCollection <HealthStatusMessage>(); collection.EnsureIndex(x => x.ID); collection.Insert(msg); } return(true); }
public async Task <List <modelAQI> > AQIs() { List <modelAQI> _AQIs = new List <modelAQI>(); Cache _cache = new Cache(); string cachename = "AQI" + DateTime.UtcNow.Hour.ToString(); bool getSuccess = false; if (_cache [cachename] != null) { try { _AQIs = (List <modelAQI>)_cache.Get(cachename); getSuccess = true; } catch (Exception) { } } if (_cache [cachename] == null || getSuccess == false) { string responseBody = string.Empty; using (HttpClient client = new HttpClient()) { string url = "http://opendata2.epa.gov.tw/AQI.json"; HttpResponseMessage response = await client.GetAsync(url); if (response.IsSuccessStatusCode) { } responseBody = await response.Content.ReadAsStringAsync(); } _AQIs = JsonConvert.DeserializeObject <List <modelAQI> >(responseBody); _cache.Remove(cachename); _cache.Add(cachename, _AQIs, null, DateTime.Now.AddMinutes(60), Cache.NoSlidingExpiration, CacheItemPriority.Default, null); } return(_AQIs); }
/// <summary> /// Determines whether the User has the given permission. /// </summary> /// <param name="u">The u.</param> /// <param name="permissionname">The permissionname.</param> /// <param name="cache">The cache.</param> /// <param name="context">The context.</param> /// <returns></returns> public static bool IsInRole(this User u, string permissionname, Cache cache, Entities context) { List <Role> permissions; if (!cache.Contains("permissions")) { permissions = context.Roles.ToList(); cache.Add <List <Role> >("permissions", permissions); } else { permissions = cache.Get <List <Role> >("permissions"); } if (!permissions.Any(x => x.Name == permissionname)) { throw new PermissionNotFoundException(); } int id = permissions.Where(x => x.Name == permissionname).First().Id; return(context.UserRoles.Any(x => x.UserId == u.Id && x.PermissionId == id)); }
private Cache <string, List <DataRepository> > observedDataNodesGroupedByFolder(IEnumerable <ITreeNode> treeNodes) { var observedDataWithFolderAddressCache = new Cache <string, List <DataRepository> >(); treeNodes.Each(treeNode => { var classificationNode = getClassificationNodeFrom(treeNode); classificationNode.AllLeafNodes.OfType <ObservedDataNode>().Each(observedDataNode => { if (observedDataWithFolderAddressCache.Contains(observedDataNode.ParentNode.Id)) { observedDataWithFolderAddressCache[observedDataNode.ParentNode.Id].Add(observedDataNode.Tag.Subject); } else { observedDataWithFolderAddressCache.Add(observedDataNode.ParentNode.Id, new List <DataRepository> { observedDataNode.Tag.Subject }); } }); }); return(observedDataWithFolderAddressCache); }
public void NavigateToType(Type value) { if (value == null || !typeof(PageViewModel).IsAssignableFrom(value)) { return; } if (_existingViewModels.TryGetValue(value, out var viewModel) && _existingViews.TryGetValue(value, out var view)) { ActivePage = view; ActivateItem(viewModel); } else { var vm = _resolver.Resolve <PageViewModel>(value); ActivePage = (PageView)ViewLocator.LocateForModel(vm, null, null); ViewModelBinder.Bind(vm, ActivePage, null); ActivateItem(vm); _existingViewModels.Add(value, vm); _existingViews.Add(value, ActivePage); } }
public void TestStoreModel() { var model = new TestModel { Name = "weitaolee", Sex = "male", Age = 25 }; var key = Guid.NewGuid().Shrink(); Cache.Add <TestModel>(key, model, TimeSpan.FromSeconds(30)); var cacheModel = Cache.Get <TestModel>(key); Assert.NotEqual(cacheModel, null); Assert.Equal(cacheModel.Name, model.Name); Assert.Equal(cacheModel.Sex, model.Sex); Assert.Equal(cacheModel.Age, model.Age); Cache.Remove(key); cacheModel = Cache.Get <TestModel>(key); Assert.Equal(cacheModel, null); }
protected T ReadFromCache <T>(string key, Func <T> setFunc, int?timeout = null) { if (Cache.TryGetValue(key, out T rv) == false) { T data = setFunc(); if (timeout == null) { Cache.Add(key, data); } else { Cache.Add(key, data, new DistributedCacheEntryOptions() { SlidingExpiration = new TimeSpan(0, 0, timeout.Value) }); } return(data); } else { return(rv); } }
protected void LoadSearchItems() { if (Cache["SearchCache"] == null) { MainDataContext db = ((AdminPage)Page).DataContext; searchJSON = new JSON( from p in SearchItems orderby p.Name select new { name = p.Name, url = p.Url }).JSONValue; Cache.Add("SearchCache", searchJSON, null, DateTime.UtcNow.AddHours(6), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, null); } else { searchJSON = Cache["SearchCache"].ToString(); } }
private StringLocalizer() { var assembly = Assembly.GetAssembly(typeof(StringLocalizer)) ?? Assembly.GetExecutingAssembly(); var resourceManager = new ResourceManager("BuildNotifications.Core.Text.Texts", assembly) { IgnoreCase = true }; foreach (var culture in LocalizedCultures()) { var resourceSet = resourceManager.GetResourceSet(culture, true, true); if (resourceSet != null) { var resourceDictionary = resourceSet.Cast <DictionaryEntry>() .Where(r => !string.IsNullOrEmpty(r.Value?.ToString())) .ToDictionary(r => r.Key.ToString() !, r => r.Value?.ToString() ?? string.Empty); Cache.Add(culture, resourceDictionary); } } _defaultDictionary = Cache[DefaultCulture]; }
public static List <MenuEntity> GetMenuAll() { List <MenuEntity> all = new List <MenuEntity>(); MenuRepository mr = new MenuRepository(); List <MenuInfo> miList = Cache.Get <List <MenuInfo> >("MenuALL"); if (miList.IsEmpty()) { miList = mr.GetAllMenu(); Cache.Add("MenuALL", miList); } if (!miList.IsEmpty()) { foreach (MenuInfo mInfo in miList) { MenuEntity menuEntity = TranslateMenuEntity(mInfo); all.Add(menuEntity); } } return(all); }
/// <summary> /// Populates the cache. /// </summary> /// <param name="cache">The cache.</param> protected static void PopulateCache(Cache cache) { Item dictionaryItem = ManagerFactory.BlogManagerInstance.GetDictionaryItem(); _cacheRootID = dictionaryItem.ID; if (dictionaryItem == null) { Log.Error("No dictionary configured for blog " + ManagerFactory.BlogManagerInstance.GetCurrentBlog().SafeGet(x => x.Name), typeof(Translator)); return; } IEnumerable <Item> entries = dictionaryItem.Axes.GetDescendants(); entries = entries.Where(entry => entry.TemplateID == Settings.DictionaryEntryTemplateID); foreach (Item entry in entries) { string key = entry[KEY].Trim(); if (!cache.ContainsKey(key)) { cache.Add(key, entry.ID); } } }
public void Run() { long percentComplete = 0; _exhuastiveCache = new Cache(10, 0.0); if ((_fitnessCrit == FitnessCriteria.R2) || (_fitnessCrit == FitnessCriteria.AdjustedR2)) { _exhuastiveCache.Comparer = new DescendSort(); } else if ((_fitnessCrit == FitnessCriteria.Sensitivity) || (_fitnessCrit == FitnessCriteria.Specificity) || (_fitnessCrit == FitnessCriteria.Accuracy)) { _exhuastiveCache.Comparer = new DescendSort(); } else { _exhuastiveCache.Comparer = new AscendSort(); } IIndividual indiv = null; List<short> combList = new List<short>(); short tmp = 0; ; for (int i = 0; i < _numVars; i++) { //ListItem li = (ListItem)lbIndVariables.Items[i]; tmp = (short)(i + 1); //tmp += Convert.ToInt16(li.ValueItem); combList.Add(tmp); } long totalComb = 0; long totalComplete = 0; Combinations<short> combinations = null; List<Combinations<short>> listAllComb = new List<Combinations<short>>(); for (short i = 1; i <= _maxVarsInModel; i++) { combinations = new Combinations<short>(combList.ToArray(), i, GenerateOption.WithoutRepetition); listAllComb.Add(combinations); totalComb += combinations.Count; } for (short i = 1; i <= _maxVarsInModel; i++) { if (Cancel) break; //combinations = new Combinations<short>(combList.ToArray(), i, GenerateOption.WithoutRepetition); combinations = listAllComb[i - 1]; foreach (IList<short> comb in combinations) { if ((!Double.IsNaN(_decisionThreshold)) && (!Double.IsNaN(_mandateThreshold)) && (_maxVIF != Int32.MaxValue)) indiv = new MLRIndividual(i, i, _fitnessCrit, _maxVIF, _decisionThreshold, _mandateThreshold); else if (_maxVIF != Int32.MaxValue) indiv = new MLRIndividual(i, i, _fitnessCrit, _maxVIF); else indiv = new MLRIndividual(i, i, _fitnessCrit); for (int j = 0; j < comb.Count; j++) indiv.Chromosome[j] = comb[j]; if (Cancel) break; indiv.Evaluate(); if (indiv.IsViable()) { //_exhuastiveCache.SortCache(); //_exhuastiveCache.ReplaceMinimum(indiv); _exhuastiveCache.Add(indiv); } //else //throw new Exception("Invalid individual."); totalComplete++; if ((totalComplete % 10) == 0) { percentComplete = totalComplete * 100 / totalComb; ESProgress(percentComplete, _exhuastiveCache.MaximumFitness); //VBLogger.getLogger().logEvent(percentComplete.ToString(), VBLogger.messageIntent.UserOnly, VBLogger.targetSStrip.ProgressBar); //lblProgress.Text = "Progress: " + (Convert.ToDouble(totalComplete) / Convert.ToDouble(totalComb)) * 100; //Console.WriteLine("Progress: " + (Convert.ToDouble(totalComplete) / Convert.ToDouble(totalComb)) * 100); //lblProgress.Refresh(); //Application.DoEvents(); } } } _exhuastiveCache.Sort(); //list = _exhuastiveCache.CacheList; //lbModels.Items.Clear(); //UpdateFitnessListBox(); ESComplete(this); }
public void Cache_Add_Null_Key_Should_Throw_Exception() { Cache<string, int> cache = new Cache<string, int>(); cache.Add(null, 0); }
public void UpdateCache() { var cache = new Cache<string, int>(2); cache.Add("A", 1); int value; Assert.IsTrue(cache.TryGetValue("A", out value), "The cache did not contain 'A'."); Assert.AreEqual<int>(1, value, "The cached value is incorrect."); cache.Add("A", 2); Assert.IsTrue(cache.TryGetValue("A", out value), "The cache did not contain 'A'."); Assert.AreEqual<int>(2, value, "The cached value is incorrect."); }
public void Cache_Add_Item_Key_Should_Return_True() { Cache<string, int> cache = new Cache<string, int>(); bool EXPECTED = true; Assert.AreEqual(EXPECTED, cache.Add("1", 1)); }
/// <summary> /// Return a list of all the ensembles. /// </summary> /// <returns>List of all the ensembles in the file.</returns> public Cache<long, DataSet.Ensemble> GetAllEnsembles() { Cache<long, DataSet.Ensemble> list = new Cache<long, DataSet.Ensemble>((uint)_ensembleList.Count); // Populate the cache with all the ensembles for (int x = 0; x < _ensembleList.Count; x++ ) { list.Add(x, _ensembleList[x].Ensemble); } return list; }
static void RunTest(DateTime time, MemoryCache internalCache, ClassWithComplexClassList @object) { var cache = new Cache(new CacheConfiguration(internalCache)); cache.Add(@object, time); var cacheItem = cache.Get<ClassWithComplexClassList>(item => item.Id == 1); cache.RemoveAllGraphs<ClassWithComplexClassList>(); }