private void LoadPropertiesInContainer(LoaderProperties loaderProperty, string moduleName, string configFile) { string cacheKeyImplementation = moduleName + loaderProperty.ImplementationAsString; string cacheKeyInterface = moduleName + loaderProperty.InterfaceAsString; loaderProperty.ImplementationAsType = _CachingService.Get <Type>(cacheKeyImplementation); if (loaderProperty.ImplementationAsType == null) { loaderProperty.ImplementationAsType = Type.GetType(loaderProperty.ImplementationAsString, true); _CachingService.Insert(cacheKeyImplementation, loaderProperty.ImplementationAsType); } loaderProperty.InterfaceAsType = _CachingService.Get <Type>(cacheKeyInterface); if (loaderProperty.InterfaceAsType == null) { loaderProperty.InterfaceAsType = Type.GetType(loaderProperty.InterfaceAsString); _CachingService.Insert(cacheKeyInterface, loaderProperty.InterfaceAsType); } TypeInfo typeInfo = loaderProperty.ImplementationAsType.GetTypeInfo(); if (typeInfo.ImplementedInterfaces.Contains(loaderProperty.InterfaceAsType)) { _DependencyInjectionContainer.Add(loaderProperty.ImplementationAsType, loaderProperty.InterfaceAsType, cacheKeyImplementation); } else { throw new Exception($"Type: {loaderProperty.ImplementationAsString} doesn't implement {loaderProperty.InterfaceAsString} in {configFile}"); } }
public string GetUserFullName(int id) { var arrData = ((IEnumerable <User>)_cachingService.Get(typeof(User).ToString())).ToArray(); if (arrData.FirstOrDefault(x => x.Id == id) != null) { return(arrData.First(x => x.Id == id).FullName); } return(string.Empty); }
public async Task <AccountEvolutionModel> GetAccountEvolution(int accountId) { if (cachingService.Exists($"{nameof(GetAccountEvolution)}{accountId}")) { return(cachingService.Get <AccountEvolutionModel>($"{nameof(GetAccountEvolution)}{accountId}")); } var result = await accountMetricsServiceClient.GetAccountEvolution(accountId); cachingService.StoreOrUpdate($"{nameof(GetAccountEvolution)}{accountId}", result); return(result); }
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { ICachingService cachingService = context.HttpContext.RequestServices.GetRequiredService <ICachingService>(); string key = context.HttpContext.Request.Path; object cachedData = cachingService.Get(key); if (cachedData != null) { ContentResult contentResult = new ContentResult { Content = JsonSerializer.Serialize(cachedData), StatusCode = 200, ContentType = "application/json" }; context.Result = contentResult; return; } ActionExecutedContext executedContext = await next(); if (executedContext.Result is OkObjectResult okObjectResult) { cachingService.Put(key, okObjectResult.Value, TimeSpan.FromSeconds(_timeToLiveInSeconds)); } }
public async Task <IProcessingContext> ExecuteAsync(LoadedNodeSet loaderContext, IProcessingContext processingContext, IPluginServiceManager pluginServiceManager, IPluginsSynchronizeContextScoped contextScoped, INode currentNode) { if (currentNode is View view) { string cacheKey = processingContext.InputModel.Module + processingContext.InputModel.NodeSet + processingContext.InputModel.Nodepath + view.BindingKey + "_View"; ICachingService cachingService = pluginServiceManager.GetService <ICachingService>(typeof(ICachingService)); string cachedView = cachingService.Get <string>(cacheKey); if (cachedView == null) { string directoryPath = Path.Combine( processingContext.InputModel.KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolder, processingContext.InputModel.Module, "Views"); PhysicalFileProvider fileProvider = new PhysicalFileProvider(directoryPath); cachedView = File.ReadAllText(Path.Combine(directoryPath, view.Settings.Path)); cachingService.Insert(cacheKey, cachedView, fileProvider.Watch(view.Settings.Path)); } IResourceModel resourceModel = new ResourceModel(); resourceModel.Content = cachedView; resourceModel.SId = $"node/view/{processingContext.InputModel.Module}/{processingContext.InputModel.NodeSet}/{processingContext.InputModel.Nodepath}/{view.BindingKey}"; processingContext.ReturnModel.Views.Add(view.BindingKey, resourceModel); } else { processingContext.ReturnModel.Status.StatusResults.Add(new StatusResult { StatusResultType = EStatusResult.StatusResultError, Message = "Current node is null or not OfType(View)" }); throw new InvalidDataException("HtmlViewSynchronizeContextLocalImp.CurrentNode is null or not OfType(View)"); } return(await Task.FromResult(processingContext)); }
public async Task <AirportResponse> GetAllAirports(string iso = null) { AirportResponse airportResponse = new AirportResponse(); IEnumerable <AirportData.Models.AirportDetails> airports; if (_cache.IsCacheExists(cacheKey)) { airportResponse.SourceFrom = "from-Cache"; airports = _cache.Get <IEnumerable <AirportData.Models.AirportDetails> >(cacheKey); } else { airportResponse.SourceFrom = "from-Database"; airports = await _airportRepository.GetAsync(); _cache.Put(cacheKey, airports, CacheExpiryTime.FiveMinutes); } if (string.IsNullOrEmpty(iso)) { airportResponse.Airports = airports; } else { airportResponse.Airports = airports.Where(x => x.Iso == iso).ToList(); } return(airportResponse); }
public IEnumerable <RssItemDto> GetRssItems(int pageIndex, int pageSize) { int homeId = Services.ContentService.GetRootContent().Single(c => c.Name == "Home").Id; int start = pageIndex * pageSize; int end = Math.Min(start + pageSize, Services.ContentService.CountChildren(homeId)); if (end < start) { return(Enumerable.Empty <RssItemDto>()); } _cachingService.CacheProvider = ApplicationContext.ApplicationCache.RuntimeCache; // Check if all the items requested are cached first. If any are missing, then stop using the cache and get the whole page from Umbraco. if (_cachingService.Get(Enumerable.Range(start, end - start).Select(i => i.ToString()), out IEnumerable <RssItemDto> cachedItems)) { return(cachedItems); } RssItemDto[] rssItems = _rssItemMappingService.Map(Services.ContentService.GetPagedChildren(homeId, pageIndex, pageSize, out long totalRecords).Select(c => new RssItemViewModel { Title = c.GetValue <string>("title"), Description = c.GetValue <string>("description"), Categories = c.GetValue <string>("categories"), Date = c.GetValue <string>("date"), Link = c.GetValue <string>("link") })).ToArray(); // Cache the retrieved items. _cachingService.Insert(Enumerable.Range(start, Math.Min(pageSize, Convert.ToInt32(totalRecords) - start)).ToDictionary(i => i.ToString(), i => rssItems[i - start])); return(rssItems); }
public Task <T> ExecuteCachedAsync <T>(Func <T> cachedItem, string key) { return(Task.Factory.StartNew(() => { if (_cachingService.Get(key) == null) { var result = cachedItem(); //TODO: will be decided how to define methods for wider usage with Emre _cachingService.Set(key, _serializer.Serialize(result)); return result; } else { return _serializer.Deserialize <T>(_cachingService.Get(key)); } })); }
protected override List <Dictionary <string, object> > Read(IDataLoaderReadContext execContext) { Node node = (Node)execContext.CurrentNode; string directoryPath = Path.Combine( execContext.ProcessingContext.InputModel.KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolder(execContext.ProcessingContext.InputModel.Module), execContext.ProcessingContext.InputModel.Module, "Public"); var filename = execContext.Evaluate("rawfilename"); if (filename.Value == null) { PhysicalFileProvider fileProvider = new PhysicalFileProvider(directoryPath); return(new List <Dictionary <string, object> >() { new Dictionary <string, object>() { { "files", Directory.GetFiles(directoryPath) } } }); } string fileName = filename.Value.ToString(); string filePath = Path.Combine(directoryPath, fileName); string cacheKey = $"{filePath}_Raw"; ICachingService cachingService = execContext.PluginServiceManager.GetService <ICachingService>(typeof(ICachingService)); string cachedRaw = cachingService.Get <string>(cacheKey); if (cachedRaw == null) { PhysicalFileProvider fileProvider = new PhysicalFileProvider(directoryPath); try { cachedRaw = File.ReadAllText(filePath); } catch (Exception ex) { execContext.ProcessingContext.ReturnModel.Status.StatusResults.Add(new StatusResult { StatusResultType = EStatusResult.StatusResultError, Message = ex.Message }); throw; } cachingService.Insert(cacheKey, cachedRaw, fileProvider.Watch(fileName)); } return(new List <Dictionary <string, object> >() { new Dictionary <string, object>() { { "filename", fileName }, { "content", cachedRaw }, { "length", cachedRaw.Length } } }); }
protected override List <Dictionary <string, object> > Read(IDataLoaderReadContext execContext) { Node node = (Node)execContext.CurrentNode; Dictionary <string, object> currentResult = null; JsonDataSynchronizeContextScopedImp jsonDataSynchronizeContextScopedImp = execContext.OwnContextScoped as JsonDataSynchronizeContextScopedImp; if (jsonDataSynchronizeContextScopedImp == null) { throw new NullReferenceException("The contextScoped is not JsonSyncronizeContextScopedImp"); } /* * string directoryPath = contextScoped.CustomSettings[START_FOLDER_PATH_JSON_DATA] * .Replace("@wwwroot@", processingContext.InputModel.EnvironmentSettings.WebRootPath) * .Replace("@treenodename@", loaderContext.NodeSet.Name); */ string directoryPath = Path.Combine( execContext.ProcessingContext.InputModel.KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolder(execContext.ProcessingContext.InputModel.Module), execContext.ProcessingContext.InputModel.Module, "Data"); if (node?.Read?.Select?.HasFile() == true) { string filePath = Path.Combine(directoryPath, node.Read.Select.File); string cacheKey = $"{execContext.ProcessingContext.InputModel.NodeSet}{execContext.ProcessingContext.InputModel.Nodepath}{node.NodeKey}_Json"; ICachingService cachingService = execContext.PluginServiceManager.GetService <ICachingService>(typeof(ICachingService)); string cachedJson = cachingService.Get <string>(cacheKey); if (cachedJson == null) { PhysicalFileProvider fileProvider = new PhysicalFileProvider(directoryPath); try { cachedJson = File.ReadAllText(filePath); } catch (Exception ex) { execContext.ProcessingContext.ReturnModel.Status.StatusResults.Add(new StatusResult { StatusResultType = EStatusResult.StatusResultError, Message = ex.Message }); throw; } cachingService.Insert(cacheKey, cachedJson, fileProvider.Watch(node.Read.Select.File)); } currentResult = new Dictionary <string, object>(JsonConvert.DeserializeObject <Dictionary <string, object> >(cachedJson, new DictionaryConverter())); } return(new List <Dictionary <string, object> >() { currentResult }); }
public async Task <IEnumerable <Sample> > GetAll() { if (cachingService.Exists(CacheKey.Samples)) { return(cachingService.Get <IEnumerable <Sample> >(CacheKey.Samples)); } var list = await repository.GetAllAsync(x => x.StatusId != StatusType.Deleted.ToInt32()); AddItemsToCache(list); return(list); }
public async Task <IEnumerable <NotificationModel> > GetNotifications() { if (cachingService.Exists(nameof(NotificationManager.GetNotifications))) { return(cachingService.Get <IEnumerable <NotificationModel> >(nameof(NotificationManager.GetNotifications))); } var notifications = await notificationServiceClient.GetNotifications(); cachingService.Store(nameof(NotificationManager.GetNotifications), notifications); return(notifications); }
public async Task <IEnumerable <Transaction> > GetAutoComplete() { if (cachingService.Exists(nameof(GetAutoComplete))) { return(cachingService.Get <IEnumerable <Transaction> >(nameof(GetAutoComplete))); } var results = await transactionServiceClient.GetAutoComplete(); var transactions = MapToEntities(results); cachingService.Store(nameof(GetAutoComplete), transactions); return(transactions); }
public string Get() { var cachingKey = new CachingKey(CachingKeys.VERSION_NUMBER_KEY); var version = cachingService.Get(cachingKey); if (version != null) { return(version.ToString()); } var result = System.IO.File.ReadAllText(Path.Combine(this.hostingEnvironment.WebRootPath, "version.txt")); cachingService.Put(cachingKey, result); return(result); }
public async Task <AnimalExcludedReason> GetExcludedReasonByCode(AnimalContext animalContext, string exclusionReason) { var excludedReason = await _cachingService.Get($"exclusion-{exclusionReason}", TimeSpan.FromHours(24), () => { return(animalContext.Set <AnimalExcludedReason>() .FirstOrDefaultAsync(x => x.Description.Equals(exclusionReason, StringComparison.InvariantCultureIgnoreCase))); }); if (excludedReason == null) { throw new BadRequestException($"Invalid exclusion reason code '{exclusionReason}' provided"); } return(excludedReason); }
public async Task <string> GetWeekStatus() { if (_cache.Get("istu_week_status") is string cachedStatus) { return(cachedStatus); } var weekStatus = await TryGetIstuWeekStatusFromIstuWithBrowserEmulation(ISTU_URL); if (weekStatus != null && !string.IsNullOrEmpty(weekStatus)) { _ = CacheUntillNextMonday("istu_week_status", weekStatus); return(weekStatus); } return("Неделя не может быть определена"); }
public LoadedNodeSet LoadNodeSet(string module, string treeNodesName, string nodeName) { LoadedNodeSet loaderContext = new LoadedNodeSet(); //find the node definition in the directory specified //load the definition //parse the definition and populate into the models NodeSetModel nodeSet = null; string NODESET_DIRNAME = "NodeSets"; string cacheKey = $"NodeSet_{module}_{treeNodesName}"; nodeSet = _CachingService.Get <NodeSetModel>(cacheKey); if (nodeSet == null) { nodeSet = new NodeSetModel(); string nodeSetDir = Path.Combine(_KraftGlobalConfigurationSettings.GeneralSettings.ModulesRootFolder(module), module, NODESET_DIRNAME, treeNodesName); string nodeSetFile = Path.Combine(nodeSetDir, "Definition.json"); if (!File.Exists(nodeSetFile)) { throw new FileNotFoundException($"The requested file: {nodeSetFile} was not found"); } PhysicalFileProvider fileProvider = new PhysicalFileProvider(nodeSetDir); using (StreamReader file = File.OpenText(nodeSetFile)) { JsonSerializer serializer = new JsonSerializer(); RootObject result = (RootObject)serializer.Deserialize(file, typeof(RootObject)); nodeSet = result.NodeSet; }; nodeSet.Name = treeNodesName; ProcessNodes(nodeSet.Root, nodeSetFile, nodeSet); _CachingService.Insert(cacheKey, nodeSet, fileProvider.Watch("**/*.*")); } loaderContext.NodeSet = nodeSet; loaderContext.StartNode = (!string.IsNullOrEmpty(nodeName)) ? FindNode(nodeSet.Root.Children, ParseNodePath(nodeName), n => n.Children, n => n.NodeKey.Trim()) : nodeSet.Root; return(loaderContext); }
/// <summary> /// Gets the specified key. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="key">The key.</param> /// <returns>T.</returns> public static T Get <T>(string key) { return(cacheService.Get <T>(key)); }
public Task <List <Cinema> > GetCurrentCinemas() => _cinemaCache.Get();
public Task <List <FullFilm> > GetLocalFilms() => _filmCache.Get(FilmCacheFile);