public void GetReturnsCachedValue() { // Arrange var entry = new MockCacheEntry(); MockCacheEntry result; MockCacheEntry onCacheExpireResult() { return(entry); } MockCacheEntry onCacheExpireThrowException() { throw new Exception(); } using (var provider = new CacheProvider()) { // First call provider.Get( cacheKey, onCacheExpireResult, CacheDuration.Short); // Act result = provider.Get( cacheKey, onCacheExpireThrowException, CacheDuration.Short); } // Assert result.Id.ShouldBeEqualTo(entry.Id); }
public async Task CachProviderTest() { var index = 0; var interval = TimeSpan.FromSeconds(1); CacheProvider <AccountEventEntity> cache = new CacheProvider <AccountEventEntity>( interval, async(k, token) => { return(await Task.FromResult <AccountEventEntity>(this.GenerateTestRecord(index++))); }); string key = "testkey"; var entity1 = await cache.Get(key, CancellationToken.None); var entity2 = await cache.Get(key, CancellationToken.None); var entity3 = await cache.Get(key, CancellationToken.None); Assert.AreEqual(entity1, entity2); Assert.AreEqual(entity1, entity3); await Task.Delay(interval); var entity4 = await cache.Get(key, CancellationToken.None); Assert.IsTrue(entity4.CreatedTime > entity1.CreatedTime); }
static void Main(string[] args) { IVigilCache cache = new CacheProvider(CacheType.BlobStorageProvider); var ddd = cache.Get <List <KPIReport> >(Areas.KPIReport, "DetailReport", "1002|20191208|20191215|Weighted Exceptions|1|0412c9ee-a3af-40b7-85f8-74f8e161f519|True|False|0"); var empty = cache.Get <ComplexType>(Areas.General, "bad^key", "boy"); cache.Set(Areas.General, "dan", "dan", "expires soon", TimeSpan.FromSeconds(-1)); string expired = cache.Get(Areas.General, "dan", "dan"); ComplexType t = new ComplexType() { Date = DateTime.Now, Value = 489.9, Titles = new List <string>() { "President", "Operations" } }; cache.Set <ComplexType>(Areas.General, "test", "1", t); System.Threading.Thread.Sleep(1000); var x = cache.Get <ComplexType>(Areas.General, "test", "1"); System.Diagnostics.Debug.Assert(x != null); Console.WriteLine(x.Value); //cache.Delete(Areas.General, "test", "1"); Console.Read(); }
public void Okay_Get_Object() { var testObject = new tempObject() { id = 1231, name = "asdfa", time = DateTime.UtcNow }; _cacheProvider.Add("Seriable_Object_2", testObject, 10); var obj = _cacheProvider.Get("Seriable_Object_2"); Assert.NotNull(obj); }
public async Task <Company> Get(int id) { Company item = (Company)CacheProvider.Get("Company" + id); if (item != null) { return(item); } using (SqlConnection connection = SqlConnectionManager.GetConnection(DbConnectionString)) { IEnumerable <Company> ciudades = await connection.QueryAsync <Company>(@" SET NOCOUNT ON; SELECT Id, Name FROM Company WHERE Id = @Id", new { Id = id }).ConfigureAwait(false); item = ciudades.FirstOrDefault(); } CacheProvider .Insert("Company", "Company" + id, item); return(item); }
public async Task <IEnumerable <Company> > List() { IEnumerable <Company> items = (IEnumerable <Company>)CacheProvider.Get("CompanyList"); if (items != null) { return(items); } using (SqlConnection connection = SqlConnectionManager.GetConnection(DbConnectionString)) { items = await connection.QueryAsync <Company>(@" SET NOCOUNT ON; SELECT Id, Name FROM Company ORDER BY Name" ).ConfigureAwait(false); } CacheProvider .Insert("Company", "CompanyList", items); return(items); }
public static bool Update(int id, bool value) { if (id == 0) { return(true); } Dictionary <int, bool> obj = GetSetting(); if (obj.ContainsKey(id)) { obj[id] = value; } else { obj.Add(id, value); } if (SaveSetting(obj)) { object oCache = CacheProvider.Get(KeyCache.KeyPopup); if (oCache != null) { CacheProvider.Update(KeyCache.KeyPopup, obj); } return(true); } return(false); }
public DriverLicenseTypeResponse GetList(GetDriverLicenseCarTypeRequest request, IEnumerable <KeyValuePair <string, string> > pairs) { DriverLicenseTypeResponse response = new DriverLicenseTypeResponse(); //根据经纪人获取手机号 IBxAgent agentModel = GetAgentModelFactory(request.Agent); if (!agentModel.AgentCanUse()) { response.Status = HttpStatusCode.Forbidden; return(response); } //参数校验 if (!ValidateReqest(pairs, agentModel.SecretKey, request.SecCode)) { response.Status = HttpStatusCode.Forbidden; return(response); } var listskey = string.Format("gsc_driverlicense_cartype_key"); var list = CacheProvider.Get <List <bx_drivelicense_cartype> >(listskey); if (list == null) { list = _typeRepository.FindList(); CacheProvider.Set(listskey, list, 86400); } response.List = list; return(response); }
public Task <T> GetAsync <T>(string key) { ValidateKey(key); var item = CacheProvider.Get(key); return(GetValueFromAsyncLazy <T>(item)); }
/// <summary> /// 读取数据 /// </summary> /// <returns></returns> private ReMsg ReadData(string ulImgKey) { var cacheKey = CacheProvider.Get <ReMsg>(ulImgKey); logInfo.Info("消息首次返回:" + cacheKey.ToJson()); if (cacheKey.ErrCode != 1 && cacheKey.ErrCode != -1) { return(cacheKey); } else { System.Threading.Thread.Sleep(1000); for (int i = 0; i < 200; i++) { cacheKey = new ReMsg(); cacheKey = CacheProvider.Get <ReMsg>(ulImgKey); logInfo.Info("消息第" + (i + 1) + "次返回:" + cacheKey.ToJson()); if (cacheKey.ErrCode != 1 && cacheKey.ErrCode != -1) { return(cacheKey); } else { System.Threading.Thread.Sleep(1000); } } } return(null); }
public async Task <Event> GetByIdAsync(long id, string appKey) { var app = ApplicationBusiness.GetByAppKeyAsync(appKey); if (app == null) { throw new ArgumentException("The given application key is invalid."); } string cacheKey = Util.GetEventCacheKey(id); var foundEvent = CacheProvider.Get <Event>(cacheKey); if (foundEvent == null) { using (IUnitOfWork uow = DataAccessLayer.GetUnitOfWork()) { IRepository <Event> repos = DataAccessLayer.GetEventRepository(uow); foundEvent = await repos.GetByIdAsync(id); if (foundEvent.ApplicationId != app.Id) { throw new ArgumentException("The given event ID and application key do not match!"); } if (foundEvent != null) { await GetChildrenAsync(foundEvent); CacheProvider.Add(cacheKey, foundEvent, DateTimeOffset.Now.AddHours(Util.GetLogLifespanHours())); } } } return(foundEvent); }
private void BuildVm() { try { if (CacheProvider.Exist("Usuarios")) { Usuarios = (List <SelectListItem>)CacheProvider.Get("Usuarios"); } else { // TODO: Modify TEXT (SelectList) Usuarios = _serviceUsuario.GetAll(null, null).Select(x => new SelectListItem { Text = Convert.ToString(x.AccountName), Value = Convert.ToString(x.Id) }).ToList(); CacheProvider.Set("Usuarios", Usuarios); } if (CacheProvider.Exist("Passwords")) { Passwords = (List <SelectListItem>)CacheProvider.Get("Passwords"); } else { // TODO: Modify TEXT (SelectList) Passwords = _servicePassword.GetAll(null, null).Select(x => new SelectListItem { Text = Convert.ToString(x.Password1), Value = Convert.ToString(x.Id) }).ToList(); CacheProvider.Set("Passwords", Passwords); } } catch (Exception ex) { //LoggerFactory.CreateLog().Error(string.Format(CultureInfo.InvariantCulture, "Presentation Layer - InitializeVMUserPasswords ERROR"), ex); } }
public async Task LoadSession() { if (CacheProvider.IsSet(CacheKey.LoggedConsultant)) { consultant = CacheProvider.Get <Consultant> (CacheKey.LoggedConsultant); return; } ConsultantSession conSession = SessionFactory.ReadSession <ConsultantSession>(SessionKeys.LoggedConsultant); // may consultant session na, so kunin nalang natin ung info nya. if (conSession != null && conSession.IsSet) { consultant = await conService.GetConsultantByUsername(conSession.Username); } // i-load muna ung consultant session from account session ConsultantSessionLoader conLoader = new ConsultantSessionLoader(conService); bool isLoaded = await conLoader.LoadConsultantSession(); if (isLoaded) { consultant = conLoader.LoadedConsultant; CacheProvider.Set(CacheKey.LoggedConsultant, consultant); } }
public void SlidingExpiredItemIsRemoved() { var stringKey = CacheKey.Create <string>("hello"); var myObject1 = CacheProvider.GetOrCreate(stringKey, () => new CacheValueOf <TestCacheObject>(new TestCacheObject("hello-1"), new StaticCachePolicy(TimeSpan.FromSeconds(1)))); Assert.NotNull(myObject1); Assert.That(myObject1.AlreadyExisted, Is.False); Assert.That(myObject1.WasInserted, Is.True); Assert.NotNull(myObject1.Value); if (CacheIsAsync) { Thread.Sleep(500); } Assert.NotNull(CacheProvider.GetValue <TestCacheObject>(stringKey)); Assert.NotNull(CacheProvider.Get <TestCacheObject>(stringKey)); Thread.Sleep(TimeSpan.FromSeconds(1.2d)); Assert.Null(CacheProvider.Get <TestCacheObject>(stringKey)); }
private void BuildVm() { try { if (CacheProvider.Exist("Recetas")) { Recetas = (List <SelectListItem>)CacheProvider.Get("Recetas"); } else { // TODO: Modify TEXT (SelectList) Recetas = _serviceReceta.GetAll(null, null).Select(x => new SelectListItem { Text = Convert.ToString(x.Nombre), Value = Convert.ToString(x.Id) }).ToList(); CacheProvider.Set("Recetas", Recetas); } if (CacheProvider.Exist("Alims")) { Alims = (List <SelectListItem>)CacheProvider.Get("Alims"); } else { // TODO: Modify TEXT (SelectList) Alims = _serviceAlim.GetAll(null, null).Select(x => new SelectListItem { Text = Convert.ToString(x.Nombre), Value = Convert.ToString(x.Id) }).ToList(); CacheProvider.Set("Alims", Alims); } } catch (Exception ex) { //LoggerFactory.CreateLog().Error(string.Format(CultureInfo.InvariantCulture, "Presentation Layer - InitializeVMRecProd ERROR"), ex); } }
public async Task LoadLoggedClient() { // check kung may session na ung logged client. // pag wala, i-load natin then saka idisplay ung nav head details if (CacheProvider.IsSet(CacheKey.LoggedClient)) { loggedClient = CacheProvider.Get <Client>(CacheKey.LoggedClient); return; } cliSession = SessionFactory.ReadSession <ClientSession>(SessionKeys.LoggedClient); // may client session na, so kunin nalang natin ung info nya. if (cliSession != null && cliSession.IsSet) { loggedClient = await cliService.GetClientByUsername(cliSession.Username); } // i-load muna ung client session from account session ClientSessionLoader cliLoader = new ClientSessionLoader(cliService); bool isLoaded = await cliLoader.LoadClientSession(); if (isLoaded) { loggedClient = cliLoader.LoadedClient; CacheProvider.Set(CacheKey.LoggedClient, loggedClient); } }
/// <summary> /// /// </summary> /// <param name="command"></param> void SniffSprocParameters(SqlCommand command) { string cacheKey = command.CommandText; SqlParameter[] sprocParams = null; if (CacheProvider.Contains(cacheKey)) { sprocParams = CacheProvider.Get <SqlParameter[]>(cacheKey); } else { SqlCommandBuilder.DeriveParameters(command); sprocParams = new SqlParameter[command.Parameters.Count]; for (int i = 0; i < sprocParams.Length; ++i) { var param = command.Parameters[i] as SqlParameter; var paramClone = param as ICloneable; var clonedParam = paramClone.Clone(); sprocParams[i] = clonedParam as SqlParameter; } CacheProvider.Put(cacheKey, sprocParams, new Shinto.Cache.Modules.AbsoluteExpirationPolicy(cacheKey, sprocParams, DateTime.Now.AddHours(1))); return;//Command already has parameters, return to avoid adding, below } if (sprocParams != null && sprocParams.Length > 0) { //Add the params to the given command for (int i = 0; i < sprocParams.Length; ++i) { SqlParameter param = sprocParams[i]; var clonedParam = new SqlParameter(param.ParameterName, param.SqlDbType, param.Size, param.Direction, param.IsNullable, param.Precision, param.Scale, param.SourceColumn, param.SourceVersion, param.Value); command.Parameters.Add(clonedParam); } } }
/// <summary> /// 续保调用第三方接口传数据 /// </summary> /// <param name="agent"></param> /// <param name="viewModel"></param> public void PostThirdPart(int agent, ViewModels.GetReInfoViewModel viewModel) { //请求第三方Url string strUrl = string.Empty; //取缓存值 var cacheKey = string.Format("camera_url_{0}", agent); strUrl = CacheProvider.Get <string>(cacheKey); if (string.IsNullOrEmpty(strUrl)) { bx_config config = _configRepository.Find(agent.ToString(), 4); strUrl = config != null ? config.config_value : ""; CacheProvider.Set(cacheKey, strUrl, 10800); } //判断url是否为空 if (string.IsNullOrEmpty(strUrl)) { return; } IBxAgent agentModel = _getAgentInfoService.GetAgentModelFactory(agent); string secretKey = agentModel == null ? "" : agentModel.SecretKey; //执行post请求方法 Task.Factory.StartNew(() => SendPost(agent, secretKey, strUrl, viewModel)); }
public void CanAddAtLeast300ItemsPerSecond() { var watch = new Stopwatch(); TypedEntity[] itemsToAdd = new TypedEntity[500]; for (int i = 0; i < 300; i++) { var item = HiveModelCreationHelper.MockTypedEntity(true); itemsToAdd[i] = item; } watch.Start(); for (int i = 0; i < 300; i++) { CacheProvider.AddOrChangeValue(CacheKey.Create("Item " + i), itemsToAdd[i]); } watch.Stop(); var writeElapsed = watch.Elapsed; watch.Reset(); watch.Start(); for (int i = 0; i < 300; i++) { var cacheKey = CacheKey.Create("Item " + i); var item = CacheProvider.Get <TypedEntity>(cacheKey); Assert.That(item, Is.Not.Null); } watch.Stop(); var readElapsed = watch.Elapsed; LogHelper.TraceIfEnabled <AbstractCacheProviderFixture>("Write Took (s): " + writeElapsed.TotalSeconds); LogHelper.TraceIfEnabled <AbstractCacheProviderFixture>("Read Took (s): " + readElapsed.TotalSeconds); Assert.That(writeElapsed, Is.LessThan(TimeSpan.FromSeconds(1))); Assert.That(readElapsed, Is.LessThan(TimeSpan.FromSeconds(1))); }
public IEnumerable <T> Query <T>(string ruleName, object parameter, object state = null, Action <IEnumerable <T> > action = null) { IEnumerable <T> result; var rule = profile.Rules.First(r => r.Name == ruleName); var sqlStatement = profile.SqlStatements.First(s => s.Name == rule.SqlStatement); if (!IsNeedCache(rule.Expire)) { //从普通查询中获取 result = InternalQuery <T>(sqlStatement, parameter, state); } else { //尝试从缓存中获取 var key = HashParameters(ruleName, parameter, state); result = CacheProvider.Get <IEnumerable <T> >(key); if (result == null) { result = InternalQuery <T>(sqlStatement, parameter, state); SetResultToCache(key, result, rule.Expire); } } if (action != null) { //如果有事后处理函数,则执行 action(result); } return(result); }
public T Get <T>(string key) { ValidateKey(key); var item = CacheProvider.Get(key); return(GetValueFromLazy <T>(item)); }
private void BuildVm() { try { if (CacheProvider.Exist("Nt_Grp_Cants")) { Nt_Grp_Cants = (List <SelectListItem>)CacheProvider.Get("Nt_Grp_Cants"); } else { // TODO: Modify TEXT (SelectList) Nt_Grp_Cants = _serviceNt_Grp_Cant.GetAll(null, null).Select(x => new SelectListItem { Text = Convert.ToString(x.Nombre), Value = Convert.ToString(x.Id) }).ToList(); Nt_Grp_Cants.Insert(0, new SelectListItem { Text = string.Empty, Value = string.Empty }); CacheProvider.Set("Nt_Grp_Cants", Nt_Grp_Cants); } } catch (Exception ex) { //LoggerFactory.CreateLog().Error(string.Format(CultureInfo.InvariantCulture, "Presentation Layer - InitializeVMNt_Grp ERROR"), ex); } }
public bx_agent GetAgent(int agentid) { string CacheKey = string.Format("agent_key_cache_{0}", agentid); string CacheKeyWithNull = string.Format("agent_key_cache_null_{0}", agentid); var cacheValueWithNull = CacheProvider.Get <string>(CacheKeyWithNull); if (cacheValueWithNull == "1") { return(null); } var cacheValue = CacheProvider.Get <bx_agent>(CacheKey); if (cacheValue == null) { cacheValue = _agentRepository.GetAgent(agentid); if (cacheValue == null) { CacheProvider.Set(CacheKeyWithNull, 1, 600);//防止缓存渗透 } else { CacheProvider.Set(CacheKey, cacheValue, 12000); } } return(cacheValue); }
/// <summary> /// Get value from cache. /// </summary> /// <returns>Cache value.</returns> public object Get() { if (enableCache) { return(provider.Get(internalKey)); } return(null); }
public async Task UpdateClientHeightWeight(string heightStr, string weightStr) { // di pwede null bool isNull = heightStr == null || weightStr == null; // check natin kung valid float bool validHeight = float.TryParse(heightStr, out float height); bool validWeight = float.TryParse(weightStr, out float weight); // display invalid or error message if (isNull || !validHeight || !validWeight) { return; } /* Valid ung input so continue na. */ // kunin ung logged client, para sa kanya i-update ung height and weight ClientSession cliSession = SessionFactory.ReadSession <ClientSession> (SessionKeys.LoggedClient); if (cliSession == null || !cliSession.IsSet) { return; } // gawa tayo client model, client id lang kailangan i-send sa http Client client = new Client() { ClientId = cliSession.ClientId, Height = height, Weight = weight }; await cliService.UpdateHeightWeight(client); if (!CacheProvider.IsSet(CacheKey.LoggedClient)) { // get client info given session username cliSession = SessionFactory.ReadSession <ClientSession>(SessionKeys.LoggedClient); //TOdo show error, session has been lost login again if (cliSession == null || !cliSession.IsSet) { return; } client = await cliService.GetClientByUsername(cliSession.Username); } else { client = CacheProvider.Get <Client>(CacheKey.LoggedClient); } client.Height = height; client.Weight = weight; CacheProvider.Set(CacheKey.LoggedClient, client); }
private void BuildVm() { try { if (CacheProvider.Exist("UniMeds")) { UniMeds = (List <SelectListItem>)CacheProvider.Get("UniMeds"); } else { // TODO: Modify TEXT (SelectList) UniMeds = _serviceUniMed.GetAll(null, null).Select(x => new SelectListItem { Text = Convert.ToString(x.Descripcion), Value = Convert.ToString(x.Id) }).ToList(); UniMeds.Insert(0, new SelectListItem { Text = string.Empty, Value = string.Empty }); CacheProvider.Set("UniMeds", UniMeds); } if (CacheProvider.Exist("Alim_Grps")) { Alim_Grps = (List <SelectListItem>)CacheProvider.Get("Alim_Grps"); } else { // TODO: Modify TEXT (SelectList) Alim_Grps = _serviceAlim_Grp.GetAll(null, null).Select(x => new SelectListItem { Text = Convert.ToString(x.Nombre), Value = Convert.ToString(x.Id) }).ToList(); Alim_Grps.Insert(0, new SelectListItem { Text = string.Empty, Value = string.Empty }); CacheProvider.Set("Alim_Grps", Alim_Grps); } if (CacheProvider.Exist("Alim_Fuentes")) { Alim_Fuentes = (List <SelectListItem>)CacheProvider.Get("Alim_Fuentes"); } else { // TODO: Modify TEXT (SelectList) Alim_Fuentes = _serviceAlim_Fuente.GetAll(null, null).Select(x => new SelectListItem { Text = Convert.ToString(x.Nombre), Value = Convert.ToString(x.Id) }).ToList(); Alim_Fuentes.Insert(0, new SelectListItem { Text = string.Empty, Value = string.Empty }); CacheProvider.Set("Alim_Fuentes", Alim_Fuentes); } } catch (Exception ex) { //LoggerFactory.CreateLog().Error(string.Format(CultureInfo.InvariantCulture, "Presentation Layer - InitializeVMAlim ERROR"), ex); } }
public void TestItemExpiration() { using (var cacheProvider = new CacheProvider<string>((int)TimeSpan.FromMilliseconds(200).TotalMilliseconds)) { const int Key = 123; cacheProvider.Set(Key, "value"); Thread.Sleep(2000); var value = cacheProvider.Get(Key); Assert.IsNull(value, "item must be expired and removed from the cache"); } }
public void TestGet() { using (var cacheProvider = new CacheProvider<string>((int)TimeSpan.FromSeconds(60).TotalMilliseconds)) { const int Key = 123; const string ExpectedValue = "aValue1"; cacheProvider.Set(Key, ExpectedValue); var value = cacheProvider.Get(Key); Assert.AreEqual(ExpectedValue, value); } }
private void LoadClientSession() { if (sessionKeyToUse == null) { sessionKeyToUse = SessionKeys.LoggedClient; } cliSession = SessionFactory.ReadSession <ClientSession>(sessionKeyToUse); loggedClient = CacheProvider.Get <Client>(CacheKey.LoggedClient); }
public IEnumerable <Province> GetProvinces() { if (CacheProvider.Exist("GetProvinces")) { return(CacheProvider.Get("GetProvinces") as IEnumerable <Province>); } var estados = _service.GetProvinces(); CacheProvider.Set("GetProvinces", estados, 12000); return(estados); }
public IEnumerable <City> GetCities(string province) { if (CacheProvider.Exist("GetCities" + province)) { return(CacheProvider.Get("GetCities" + province) as IEnumerable <City>); } var cities = _service.GetCities(province); CacheProvider.Set("GetCities" + province, cities, 12000); return(cities); }
public List <int> GetConfigCityList(int agentId) { var agentCityKey = string.Format("agent_city_key_{0}", agentId); var listCity = CacheProvider.Get <List <int> >(agentCityKey); if (listCity == null) { listCity = _agentConfigRepository.GetConfigCityList(agentId).ToList(); CacheProvider.Set(agentCityKey, listCity, 10800); } return(listCity); }