public void TestUsage() { _provider.Add("test", "value", DateTimeOffset.MaxValue, "region"); Assert.That(_provider.Contains("test", "region"), Is.True); Assert.That(_provider.Get("test", "region"), Is.EqualTo("value")); }
public void InsertData(IProcessManagerData data) { Type typeParameterType = data.GetType(); MethodInfo md = GetType().GetTypeInfo().GetMethods().First(m => m.Name == "GetMemoryData" && m.GetParameters()[0].Name == "data"); //MethodInfo genericMd = md.MakeGenericMethod(typeParameterType); MethodInfo genericMd = md.MakeGenericMethod(typeof(IProcessManagerData)); lock (_memoryCacheLock) { var memoryData = genericMd.Invoke(this, new object[] { data }); string key = data.CorrelationId.ToString(); //if (!Cache.Contains(key)) //{ // Cache.Set(key, memoryData, _policy); //} //else //{ // throw new ArgumentException(string.Format("ProcessManagerData with CorrelationId {0} already exists in the cache.", key)); //} if (!_provider.Contains(key)) { _provider.Add(key, memoryData, _absoluteExpiry); } else { throw new ArgumentException(string.Format("ProcessManagerData with CorrelationId {0} already exists in the cache.", key)); } } }
public async Task <OAuthUser> GenerateTokenCredential(Dictionary <string, object> parameters) { OAuthUser oAuthUser = new OAuthUser() { IsSucceed = false }; string result = null; var payload = await _serviceProxyProvider.Invoke <object>(parameters, AppConfig.AuthorizationRoutePath, AppConfig.AuthorizationServiceKey); if (payload != null && !payload.Equals("null")) { oAuthUser = JsonConvert.DeserializeObject <OAuthUser>(payload.ToString()); if (oAuthUser.IsSucceed) { var jwtHeader = JsonConvert.SerializeObject(new JWTSecureDataHeader() { TimeStamp = DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") }); var base64Payload = ConverBase64String(JsonConvert.SerializeObject(payload)); var encodedString = $"{ConverBase64String(jwtHeader)}.{base64Payload}"; var route = await _serviceRouteProvider.GetRouteByPath(AppConfig.AuthorizationRoutePath); var signature = HMACSHA256(encodedString, route.ServiceDescriptor.Token); result = $"{encodedString}.{signature}"; oAuthUser.AccessToken = result; oAuthUser.ExpireTime = AppConfig.AccessTokenExpireTimeSpan.TotalSeconds; _cacheProvider.Add(base64Payload, result, AppConfig.AccessTokenExpireTimeSpan); } } return(oAuthUser); }
/// <summary> /// This method retrieves token string for a specific <paramref name="siteId" />. /// Token is retrieved from cache if it exists there and is valid, otherwise provided by the remote API /// </summary> /// <returns> /// Token string for Consultix authorization /// </returns> /// <param name="siteId">Site Id Guid associated to the token</param> /// <seealso cref="GetClientId(Guid)"/> /// <seealso cref="RefreshToken(string)"/> public string GetToken(Guid siteId) { var clientId = GetClientId(siteId); // Cache key is related to client Id. Client Id is related to site Id var cacheKey = "{{ClientId_CacheKey}}"; // Get from remote API if not existing in cache if (!_cacheProvider.ContainsKey(cacheKey)) { var bearer = RefreshToken(clientId); _cacheProvider.Add(cacheKey, bearer, bearer.ExpiryStamp); return(bearer?.AccessToken); } else { var bearer = _cacheProvider.Get <BearerToken>(cacheKey); // Check token validity if from cache, otherwise get from remote if (AuthenticationHelper.IsValidToken(bearer)) { return(bearer.AccessToken); } else { var newBearer = RefreshToken(clientId); _cacheProvider.Add(cacheKey, newBearer, newBearer.ExpiryStamp); return(bearer?.AccessToken); } } }
private void AndCacheIsPopulated() { _cache.Add("A", "1"); _cache.Add("B", "2"); _cache.Add("C", "3"); _cache.Add("D", "4"); }
private static T Get <T>(this ICacheProvider cacheManager, string key, string valKey, TimeSpan?slidingExpiration, DateTime?absoluteExpiration, Func <T> acquire) { if (cacheManager.Exists(key)) { return(cacheManager.Get <T>(key, valKey)); } else { var result = acquire(); if (slidingExpiration.HasValue) { cacheManager.Add(key, valKey, result, slidingExpiration.Value); } else if (absoluteExpiration.HasValue) { cacheManager.Add(key, valKey, result, absoluteExpiration.Value); } else { cacheManager.Add(key, valKey, result); } return(result); } }
/// <summary>The retrieve items.</summary> /// <param name="typesToRequest">The types to request.</param> /// <param name="includeRegions">The include regions.</param> /// <param name="systemId">The system id.</param> /// <param name="minQuantity">The min quantity.</param> /// <param name="cacheKey">The cache key.</param> /// <returns>The <see cref="IEnumerable" />.</returns> private IEnumerable <ItemOrderStats> RetrieveItems( List <int> typesToRequest, IEnumerable <int> includeRegions, int systemId, int minQuantity, string cacheKey) { var resultItems = new List <ItemOrderStats>(); // make the request for the types we don't have valid caches for NameValueCollection requestParameters = CreateMarketRequestParameters( typesToRequest, includeRegions, systemId, minQuantity); Task <HttpResponseMessage> requestTask = _requestProvider.PostAsync(new Uri(EveCentralBaseUrl + MarketStatApi), requestParameters); requestTask.Wait(); // wait for the completion (we're in a background task anyways) if (requestTask.IsCompleted && requestTask.Result != null && !requestTask.IsCanceled && !requestTask.IsFaulted && requestTask.Exception == null) { Task <Stream> contentStreamTask = requestTask.Result.Content.ReadAsStreamAsync(); contentStreamTask.Wait(); using (Stream stream = contentStreamTask.Result) { try { // process result IEnumerable <ItemOrderStats> retrievedItems = GetOrderStatsFromXml(stream); // cache it. foreach (ItemOrderStats item in retrievedItems) { _regionDataCache.Add( ItemKeyFormat.FormatInvariant(item.ItemTypeId, cacheKey), item, DateTimeOffset.Now.Add(_cacheTtl)); resultItems.Add(item); _regionDataCache.Add( ItemKeyFormat.FormatInvariant(item.ItemTypeId, cacheKey), item, DateTimeOffset.Now.Add(_cacheTtl)); resultItems.Add(item); } } catch (Exception ex) { Trace.TraceError(ex.FormatException()); throw; } } } return(resultItems); }
public void Add_GivenKeyAndValueAndExpiration_ShouldCallAddOnIoAdapter() { var expectedValue = "value".ToJson(); _localStorageCacheProvider.Add(_key, "value", default(TimeSpan)); _mockIoAdapter.Verify(e => e.Add(BasePath, _key, expectedValue), Times.Once); }
private void DownloadLatestData(int marketLocation) { bool retry = false; lock (DownloadLock) { try { string lastDownloadKey = LastDownloadTs.FormatInvariant(marketLocation); CacheItem <DateTimeOffset> lastDownload = _priceCache.Get <DateTimeOffset>(lastDownloadKey); // check to see if there is newer data available. MarketLocationData marketDataInfo = LastMarketUpdate(marketLocation); if (lastDownload == null || (lastDownload.IsDirty && lastDownload.Data < marketDataInfo.Freshness)) { IEnumerable <ItemOrderStats> locationData = DownloadData(marketLocation); _priceCache.Add( ItemKeyFormat.FormatInvariant(marketLocation), locationData, DateTimeOffset.Now.Add(_cacheTtl)); Trace.TraceInformation(Resources.NewMarketData); //// MessageBox.Show(Resources.NewMarketData, string.Empty, MessageBoxButtons.OK, MessageBoxIcon.Information); _priceCache.Add(lastDownloadKey, DateTimeOffset.Now, DateTimeOffset.Now.Add(_cacheTtl)); } downloadError = false; } catch (Exception e) { // log it. Trace.TraceError(e.FormatException()); if (!downloadError && MessageBox.Show( Resources.ErrorDownloadingData, Resources.ErrorCaption, MessageBoxButtons.YesNo, MessageBoxIcon.Error) == DialogResult.Yes) { retry = true; } else { string lastDownloadKey = LastDownloadTs.FormatInvariant(marketLocation); _priceCache.Add(lastDownloadKey, DateTimeOffset.Now, DateTimeOffset.Now.AddMinutes(30)); } downloadError = true; } } if (retry) { DownloadLatestData(marketLocation); } }
public void Should_Add_AndRetrieveSuccessfull_InLocalMemoryCacher() { const string key = "ShouldAddAndRetrieveSuccessfullyKey"; const string value = "ShouldAddAndRetrieveSuccessfullyValue"; _cacheProvider.Add(key, value, TimeSpan.FromSeconds(1)); _cacheProvider .Retrieve <string>(key) .Should() .Be(value); }
public static void Update(this ICacheProvider cacheProvider, string key, string jsonValue, long?storeTime = null) { if (storeTime.HasValue) { cacheProvider.Remove(key); cacheProvider.Add(key, jsonValue, storeTime.Value); } else { cacheProvider.Remove(key); cacheProvider.Add(key, jsonValue); } }
private static void SetCache(ICacheProvider cacheProvider, string key, object value, long?numOfMinutes) { if (numOfMinutes.HasValue) { cacheProvider.Remove(key); cacheProvider.Add(key, value, numOfMinutes.Value); } else { cacheProvider.Remove(key); cacheProvider.Add(key, value); } }
public T Get <T>(string cacheID, Func <T> func) where T : class { T item = cacheProvider.Get <T>(cacheID); if (item == null) { item = func(); if (item != null) { cacheProvider.Add <T>(item, cacheID); } } return(item); }
/// <summary> /// 添加过期时间 /// </summary> /// <param name="cacheProvider"></param> /// <param name="key"></param> /// <param name="valKey"></param> /// <param name="value"></param> private void AddCache(ICacheProvider cacheProvider, string key, string valKey, object value) { if (_expiration == ExpirationType.AbsoluteTime) { cacheProvider.Add(key, valKey, value, DateTime.Now.Add(_expireTime)); } else if (_expiration == ExpirationType.SlidingTime) { cacheProvider.Add(key, valKey, value, _expireTime); } else { cacheProvider.Add(key, valKey, value); } }
void _invalidator_AddNewKeyEvent(object sender, AddKeyEventArgs e) { _logger.DebugFormat("Received add cache key {0} custom data {1}", new object[] { e.Key, e.CustomRemoteData }); //add directly to cache if no custom data and has some data if (e.CustomRemoteData.IsNullOrEmpty() && e.Data != null) { _logger.DebugFormat("Added data from remote cache key {0} custom data {1}", new object[] { e.Key, e.CustomRemoteData }); _provider.Add(e.Key, e.Data, e.AbsoluteTimeout, e.SlidingTimeout, e.Category, e.Priority); } //if have custom data or dont have data, raise event for managers to process data else if (RemoteCacheItemAdded != null) { RemoteCacheItemAdded.Invoke(this, e); } }
/// <summary> /// 添加缓存 /// </summary> /// <param name="input">调用拦截目标时的输入信息。</param> /// <param name="getNext">通过行为链来获取下一个拦截行为的委托。</param> /// <returns>返回信息</returns> private IMethodReturn CreateMethodReturnForGet(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext) { //取拦截目标的方法名称 //根据实现类与方法,构造key var key = CreateKey(input); //根据方法的输入参数值构造valKey var valKey = CreateValueKey(input); //是否已存在该方法的缓存,不存在则调用方法,并将结果写入缓存 try { if (_cache.Exists(key, valKey)) { var obj = _cache.Get(key, valKey); var arguments = new object[input.Arguments.Count]; input.Arguments.CopyTo(arguments, 0); return(new VirtualMethodReturn(input, obj, arguments)); } else { var methodReturn = getNext().Invoke(input, getNext); if (methodReturn.ReturnValue != null) { _cache.Add(key, valKey, methodReturn.ReturnValue); } return(methodReturn); } } catch (Exception ex) { return(new VirtualMethodReturn(input, ex)); } }
public IEnumerable <Event> GetEvents(List <int> serverIds, string baseUrl, string searchKey, DateTime startDate, DateTime endDate, bool cutEvents = true) { List <Event> allEvents = new List <Event>(); //Get Cache duration int cacheDuration = _options.Value.CacheEventsDurationInSeconds; Uri u = new Uri(baseUrl); foreach (int serverId in serverIds) { //Set CacheKey string cacheKey = $"{_options.Value.CacheEventsKey}_{u.Host}_{serverId}_{startDate.ToString("yyyyMMdd")}"; IEnumerable <Event> events; if (!_cacheProvider.TryGetValue <IEnumerable <Event> >(cacheKey, out events)) { //Get Events From Repo events = _eventsRepository.GetEvents(serverId, baseUrl, startDate, endDate, cutEvents); if (events != null) {//Set Cache _cacheProvider.Add(cacheKey, events, cacheDuration); } else { events = new List <Event>(); } } //Add to news collection allEvents.AddRange(searchKey == "" ? events : events.Where(e => e.Name.Contains(searchKey))); } return(allEvents.OrderBy(x => x.StartTime)); }
public IEnumerable <News> GetNews(List <int> serverIds, string baseUrl, string searchKey) { List <News> allNews = new List <News>(); int cacheDuration = _options.Value.CacheNewsDurationInSeconds; Uri u = new Uri(baseUrl); foreach (int serverId in serverIds) { //Set Cache Key string cacheKey = $"{_options.Value.CacheNewsKey}_{u.Host}_{serverId}"; IEnumerable <News> news; if (!_cacheProvider.TryGetValue <IEnumerable <News> >(cacheKey, out news)) { //Get News From Repo news = _newsRepository.GetNews(serverId, baseUrl); //Add to cache _cacheProvider.Add(cacheKey, news, cacheDuration); } //Add to news collection allNews.AddRange(string.IsNullOrEmpty(searchKey) ? news : news.Where(n => n.Title.ToLower().Contains(searchKey) || n.Summary.ToLower().Contains(searchKey) || n.Body.ToLower().Contains(searchKey))); } return(allNews.OrderByDescending(x => x.PublishedDate)); }
public static IEnumerable <T> ToCache <T>(this IEnumerable <T> query) { ICacheProvider provider = Config.Cache.DefaultProvider; provider.Add(query, new CacheItemPolicy()); return(query); }
public override IEnumerable <T> Find(System.Linq.Expressions.Expression <Func <T, bool> > where, params System.Linq.Expressions.Expression <Func <T, object> >[] includeProperties) { IEnumerable <T> query = _surrogate.Find(where, includeProperties).AsQueryable(); if (!_cacheProvider.Contains(query)) { CacheItemPolicy policy = WrapPolicy(); _cacheProvider.Add(query, policy); } else { query = _cacheProvider.Get(query); } return(query); }
public async Task <ServiceResult <IEnumerable <Movie> > > GetAsync(string title) { var result = _cacheProvider.Get(title); if (!result.Any()) { using (var client = new HttpClient()) { client.BaseAddress = new Uri(RESOURCE_LOCATION); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(DATA_TYPE)); var path = String.Format(RESOURCE_PARAMS, title); var response = await client.GetAsync(path); if (response.IsSuccessStatusCode) { var data = await response.Content.ReadAsStringAsync(); result = JsonConvert.DeserializeObject <IEnumerable <Movie> >(data); } } _cacheProvider.Add(title, result); } return(new ServiceResult <IEnumerable <Movie> >(result)); }
public static IHtmlString CacheWidget <T>(this HtmlHelper html, string key, int cacheSeconds, string url, WidgetBag <T> bag, bool isSessionCache = false) where T : class { #if !DEBUG var cacheManager = WebHelper.GetService <ICacheManager>(); ICacheProvider cache = null; if (isSessionCache) { cache = cacheManager.CreateCacheProvider(CacheScope.WorkUnit); } else { cache = cacheManager.CreateCacheProvider(CacheScope.Global); } if (cacheSeconds > 0 && !string.IsNullOrWhiteSpace(key) && cache != null) { IHtmlString content = null; content = cache.GetData(key) as IHtmlString; if (content != null) { return(content); } content = html.Widget <T>(url, bag); cache.Add(key, content, null, new TimeSpan(0, 0, cacheSeconds), DateTime.MaxValue); return(content); } #endif return(html.Widget <T>(url, bag)); }
public static IHtmlString CachePartial(this HtmlHelper html, string key, int cacheSeconds, string partialName, object model = null, ViewDataDictionary viewData = null, bool isSessionCache = false) { #if !DEBUG var cacheManager = WebHelper.GetService <ICacheManager>(); ICacheProvider cache = null; if (isSessionCache) { cache = cacheManager.CreateCacheProvider(CacheScope.WorkUnit); } else { cache = cacheManager.CreateCacheProvider(CacheScope.Global); } if (cacheSeconds > 0 && !string.IsNullOrWhiteSpace(key) && cache != null) { IHtmlString content = null; content = cache.GetData(key) as IHtmlString; if (content != null) { return(content); } content = html.Partial(partialName, model, viewData); cache.Add(key, content, null, new TimeSpan(0, 0, cacheSeconds), DateTime.MaxValue); return(content); } #endif return(html.Partial(partialName, model, viewData)); }
public async ValueTask <T> GetOrSet <T>(string key, Func <ValueTask <T> > acquireAsync, int cacheTime, CancellationToken cancellationToken = default) { var normalizedKey = _cacheKeyNormalizer.NormalizeKey(key); var isSet = await _cacheProvider.IsSet(normalizedKey, cancellationToken).ConfigureAwait(false); if (isSet) { var result = await _cacheProvider.Get <T>(normalizedKey, cancellationToken).ConfigureAwait(false); _logger.Trace($"Cache hit. key={key} valueType={result}"); return(result); } else { var result = await acquireAsync(); _logger.Trace($"Attempting to add a new entry to the cache. key={key} valueType={result}."); await _cacheProvider.Add(normalizedKey, result, cacheTime, cancellationToken).ConfigureAwait(false); return(result); } }
private async Task AddToCache(HttpRequestMessage request, HttpResponseMessage response) { var primaryKey = new CacheKey(request.RequestUri); var entry = await CacheEntry.Create(response).ConfigureAwait(false); await _cache.Add(primaryKey, entry).ConfigureAwait(false); }
public object Invoke(object instance, object[] inputs, out object[] outputs) { object o = null; string key = GenerateCachekey(); if (provider.Contains(key)) { outputs = new object[] { }; WebOperationContext.Current.OutgoingResponse.Headers.Add("X-Cache-Lookup", "NetHttpService Cache Extension v1.0 "); CacheEntry entry = provider.GetData <CacheEntry>(key); WebOperationContext.Current.OutgoingResponse.ContentType = entry.ContentType; o = new MemoryStream(entry.Response); } else { o = innerInvoker.Invoke(instance, inputs, out outputs); byte[] bytes = GetBytes((Stream)o); WebOperationContext.Current.OutgoingResponse.Headers.Add("X-Cache", "MISS from NetHttpService Cache Extension v1.0 "); CacheEntry entry = new CacheEntry() { ContentType = WebOperationContext.Current.OutgoingResponse.ContentType, Response = bytes }; provider.Add(key, entry); } return(o); }
public static IHtmlString CacheAction(this HtmlHelper html, string key, int cacheSeconds, string action, string controller = null, object routes = null, bool isSessionCache = false) { #if !DEBUG var cacheManager = WebHelper.GetService <ICacheManager>(); ICacheProvider cache = null; if (isSessionCache) { cache = cacheManager.CreateCacheProvider(CacheScope.WorkUnit); } else { cache = cacheManager.CreateCacheProvider(CacheScope.Global); } if (cacheSeconds > 0 && !string.IsNullOrWhiteSpace(key) && cache != null) { IHtmlString content = null; content = cache.GetData(key) as IHtmlString; if (content != null) { return(content); } content = html.Action(action, controller, routes); cache.Add(key, content, null, new TimeSpan(0, 0, cacheSeconds), DateTime.MaxValue); return(content); } #endif return(html.Action(action, controller, routes)); }
private static void ProceedResult <T>(ICacheProvider cache, string key, CachedResultLock cachedResultLock, CachableResult <T> cachableResult) { object result = null; if (cachableResult != null) { // if cachableResult.Result is null, it's still a result. So we need to cache it as EmptyResult object // so the next time we didn't get null from cache and had to go create result // once again. But we can do it only if dependency keys are null/empty, or they don't include // cachableResult data, because otherwise will be caching EmptyResult object // with dependeny key calculated for null object which is incorrect behavior. result = cachableResult.Result; if (result == null) { result = EmptyResult; } cache.Add(key, result, cachableResult.Parameters); } cachedResultLock.Result = result; cachedResultLock.IsExecuted = true; }
public async Task <IContent> GetNewFile(string path, CancellationToken token) { if (_cache.Get(path) is IContent cachedContent) { var newFileIsAdded = _history.Add(path); if (_history.Count != 1 && newFileIsAdded) { _history.CurrentIndex++; } return(cachedContent); } var content = await _baseModel.GetNewFile(path, token); _cache.Add(path, content); return(content); }
private static void SetCachedIncludesFor(string filename, IncludesCacheModel value, IEnumerable <FileInfo> files) { // Create a depdency on all of the files var dependencies = RejuicerEngine.IsPassThroughEnabled ? null : files.Where(f => f != null); cacheProvider.Add(GetCacheKeyFor(filename), value, dependencies); }
public OutputContent GetContent(ICacheProvider cacheProvider, Mode mode) { var upgraded = false; _lock.EnterUpgradeableReadLock(); try { // check the cache first var returnValue = cacheProvider.Get<OutputContent>(GetCacheKeyFor(VirtualPath, mode)); if (returnValue == null) { Log.WriteLine("Generating Content For '{0}'", VirtualPath); _lock.EnterWriteLock(); upgraded = true; byte[] rejuicedValue = null; var file = new FileInfo(PhysicalPath); // clear existing dependencies _dependencies.Clear(); var minificationProvider = MinificationRegistry.Get(ResourceType); var notFound = false; try { var fileBytes = File.ReadAllBytes(PhysicalPath); rejuicedValue = FileTransformationPipeline.TransformInputFile(this, fileBytes); } catch (IOException) { } // Combined value var combinedValue = new OutputContent { Content = rejuicedValue, ContentHash = rejuicedValue.HashArray(), AllowClientCaching = false, ContentType = ResourceType == ResourceType.Css ? "text/css" : "text/javascript", LastModifiedDate = file.LastWriteTimeUtc }; var dependencies = GetDependencies(); cacheProvider.Add(GetCacheKeyFor(VirtualPath, Mode.Combine), combinedValue, dependencies); returnValue = combinedValue; if (Mode == Mode.Minify && !notFound) { Log.WriteLine("Minifying Content For '{0}'", VirtualPath); // Minified value byte[] minifiedContent = null; try { minifiedContent = minificationProvider.Minify(rejuicedValue); } catch (Exception e) { // Yes, catching Exception is bad. However, anyone can plug in their own minification provider // and throw any exception they want. We want to make sure that exceptions thrown by rejuicer // have the filename inside them. So we just wrap the exception here & throw the wrapped exception. throw new InvalidOperationException(string.Format("Encountered exception trying minify invalid JavaScript for file '{0}'.", VirtualPath), e); } var minifiedValue = new OutputContent { Content = minifiedContent, ContentHash = minifiedContent.HashArray(), AllowClientCaching = false, ContentType = ResourceType == ResourceType.Css ? "text/css" : "text/javascript", LastModifiedDate = file.LastWriteTimeUtc }; cacheProvider.Add(GetCacheKeyFor(VirtualPath, mode), minifiedValue, dependencies); returnValue = minifiedValue; } } return returnValue; } finally { if (upgraded) { _lock.ExitWriteLock(); } _lock.ExitUpgradeableReadLock(); } }