/// <summary> /// /// </summary> /// <param name="category"></param> /// <param name="sourceCulture"></param> /// <param name="sourceText"></param> /// <param name="targetCulture"></param> /// <param name="objParams"></param> /// <returns></returns> public string Translate(string category, CultureInfo sourceCulture, string sourceText, CultureInfo targetCulture, params object[] objParams) { string targetText = sourceText; if (targetCulture.Name != sourceCulture.Name && string.IsNullOrEmpty(category) == false) { ServiceDictionaryItemKey key = new ServiceDictionaryItemKey() { SourceText = sourceText, SourceCultureName = sourceCulture.Name, TargetCultureName = targetCulture.Name, Category = category }; if (ServiceDictionaryCache.Instance.TryGetValue(key, out targetText) == false) { string physicalFileName = GetCultureFilePath(category, targetCulture) + ".xml"; bool loaded = false; try { XmlDocument xmlDoc = XmlHelper.LoadDocument(physicalFileName); loaded = true; XmlElement item = FindMatchedItem(sourceText, xmlDoc.DocumentElement.SelectNodes("Item")); if (item != null) { targetText = item.GetAttribute("target"); } else { targetText = sourceText; } } catch (System.IO.FileNotFoundException) { targetText = sourceText; } catch (System.IO.DirectoryNotFoundException) { targetText = sourceText; } if (loaded) { FileCacheDependency dependency = new FileCacheDependency(physicalFileName); ServiceDictionaryCache.Instance.Add(key, targetText, dependency); } else { ServiceDictionaryCache.Instance.Add(key, targetText); } } } return(targetText); }
/// <summary> /// 获取meta配置中的 sourceMappings 节点 /// </summary> /// <param name="fileSettings">ConfigFilesSetting 类实例</param> /// <returns>meta配置中的 sourceMappings 节点</returns> private static MetaConfigurationSourceInstanceSection GetMetaSourceInstanceSection(ConfigFilesSetting fileSettings) { ConfigurationSection section; string cacheKey = ConfigurationBroker.CreateConfigurationCacheKey(fileSettings.MachineConfigurationFile, MetaConfigurationSourceInstanceSection.Name); if (ConfigurationSectionCache.Instance.TryGetValue(cacheKey, out section) == false) { ConfigurationBroker.GetMetaFileSettings(fileSettings); if (fileSettings.MetaFilePosition == MetaConfigurationPosition.LocalFile) { section = ConfigurationBroker.LoadMetaSourceInstanceSectionFromLocal(fileSettings); } else { section = ConfigurationBroker.LoadMetaSourceInstanceSectionFromMetaFile(fileSettings); } FileCacheDependency fileDependency = new FileCacheDependency( true, fileSettings.MachineConfigurationFile, fileSettings.LocalConfigurationFile, fileSettings.MetaConfigurationFile); SlidingTimeDependency timeDependency = new SlidingTimeDependency(ConfigurationBroker.SlidingTime); ConfigurationSectionCache.Instance.Add(cacheKey, section, new MixedDependency(fileDependency, timeDependency)); } return((MetaConfigurationSourceInstanceSection)section); }
/// <summary> /// /// </summary> /// <param name="category"></param> /// <param name="sourceCulture"></param> /// <param name="sourceText"></param> /// <param name="targetCulture"></param> /// <param name="objParams"></param> /// <returns></returns> public string Translate(string category, CultureInfo sourceCulture, string sourceText, CultureInfo targetCulture, params object[] objParams) { string targetText = sourceText; if (targetCulture.Name != sourceCulture.Name && string.IsNullOrEmpty(category) == false) { ServiceDictionaryItemKey key = new ServiceDictionaryItemKey() { SourceText = sourceText, SourceCultureName = sourceCulture.Name, TargetCultureName = targetCulture.Name, Category = category }; if (ServiceDictionaryCache.Instance.TryGetValue(key, out targetText) == false) { string physicalFileName = GetCultureFilePath(category, targetCulture) + ".xml"; bool loaded = false; try { XmlDocument xmlDoc = XmlHelper.LoadDocument(physicalFileName); loaded = true; XmlElement item = FindMatchedItem(sourceText, xmlDoc.DocumentElement.SelectNodes("Item")); if (item != null) targetText = item.GetAttribute("target"); else targetText = sourceText; } catch (System.IO.FileNotFoundException) { targetText = sourceText; } catch (System.IO.DirectoryNotFoundException) { targetText = sourceText; } if (loaded) { FileCacheDependency dependency = new FileCacheDependency(physicalFileName); ServiceDictionaryCache.Instance.Add(key, targetText, dependency); } else { ServiceDictionaryCache.Instance.Add(key, targetText); } } } return targetText; }
public void SetCache(string CacheKey, object objObject, string Scope = null, DateTimeOffset?AbsoluteExpiration = null, TimeSpan?SlidingExpiration = null, ProviderLevel level = ProviderLevel.Normal, FileCacheDependency objDependency = null, RemoveDelegate OnRemoveCallback = null) { if (objObject != null) { //if no OnRemoveCallback value is specified, use the default method if (OnRemoveCallback == null) { OnRemoveCallback = ItemRemovedCallback; } CachingProvider.Instance(level).Insert(CacheKey, objObject, Scope, AbsoluteExpiration, SlidingExpiration, objDependency, OnRemoveCallback); } }
/// <summary> /// 从缓存中加载数据, 或加载数据后并缓存 /// </summary> /// <returns></returns> public NavSiteMap GetCachedMap() { string cacheKey = _mapFile; NavSiteMap result = null; if (SiteMapCache.Instance.TryGetValue(cacheKey, out result) == false) { result = GetMap(); FileCacheDependency fd = new FileCacheDependency(false, _mapFile); SiteMapCache.Instance.Add(cacheKey, result, fd); } return(result); }
private static void ListenFileChanged(string cacheBinPath, PostEvictionDelegate callBackHandler) { //创建标识文件 if (!File.Exists(cacheBinPath)) { File.WriteAllText(cacheBinPath, DateTime.Now.ToString(), Encoding.UTF8); } FileCacheDependency dependency = new FileCacheDependency(cacheBinPath); string snapshotKey = string.Concat("plugin_listen:", cacheBinPath); var value = DateTime.Now; ConfigHelper.MonitorConfingSnapshot.Set(snapshotKey, value, dependency, callBackHandler); }
public MetaConfig GetAll() { var rule = _cache.Get <MetaConfig>(cacheKey); if (rule == null) { var json = FileConfigHelper.GetFileContent(filePath); if (json != "") { rule = NewtonJson.Deserialize <MetaConfig>(json); var dependency = new FileCacheDependency(fileName); _cache.Set(cacheKey, rule, dependency); } } return(rule); }
/// <summary> /// 从虚路径加载场景信息 /// </summary> /// <param name="virtualPath">场景文件的虚路径</param> /// <returns>幕的集合</returns> public static ActCollection GetActs(string virtualPath) { ActCollection result = null; string filePath = HttpContext.Current.Server.MapPath(virtualPath).ToLower(); if (ActCache.Instance.TryGetValue(filePath, out result) == false) { XmlDocument xmlDoc = XmlHelper.LoadDocument(filePath); result = LoadActs(xmlDoc); FileCacheDependency dependency = new FileCacheDependency(filePath); ActCache.Instance.Add(filePath, result, dependency); } return(result); }
public bool Set <T>(string key, T item, FileCacheDependency dependency) { try { if (item == null || string.IsNullOrEmpty(key)) { return(false); } var cacheEntryOptions = new MemoryCacheEntryOptions().AddExpirationToken(dependency.FileWatch); _cache.Set(key, item, cacheEntryOptions); return(true); } catch (Exception ex) { return(false); } }
private static async Task <TResult> GetContentFromVirtualPathAsync <TResult, TCache>(string virtualPath, TCache cache, Func <string, Task <TResult> > getContent) where TCache : CacheQueue <string, TResult> { ExceptionHelper.CheckStringIsNullOrEmpty(virtualPath, "virtualPath"); TResult result = default(TResult); HttpContext context = HttpContext.Current; string strPath = context.Server.MapPath(virtualPath).ToLower(); if (cache.TryGetValue(strPath, out result) == false) { result = await getContent(strPath); FileCacheDependency dependency = new FileCacheDependency(strPath); cache.Add(strPath, result, dependency); } return(result); }
/// <summary> /// 按节点名称从配置信息中取得节点,并将节点信息缓存,建立文件依赖 /// </summary> /// <param name="sectionName">节点名称</param> /// <returns>配置节点</returns> /// <remarks> /// 按名称获取配置节点信息。返回ConfigurationSection的派生类实体,实体类需由用户自定义。 /// <code source="..\Framework\TestProjects\Deluxeworks.Library.WebTest\Configuration\Default.aspx.cs" region="Using Broker" lang="cs" title="使用配置管理" /> /// </remarks> public static ConfigurationSection GetSection(string sectionName) { ConfigurationSection section; if (false == ConfigurationSectionCache.Instance.TryGetValue(sectionName, out section)) { ConfigFilesSetting settings = LoadFilesSetting(); System.Configuration.Configuration config = GetFinalConfiguration(settings); section = config.GetSection(sectionName); // 在Configuration对象中不能直接拿到Section对象时,遍历所有Group查找Section if (section == null || section is DefaultSection) { section = GetSectionFromGroups(sectionName, config.SectionGroups); } FileCacheDependency dependency = new FileCacheDependency( true, settings.MachineConfigurationFile, settings.LocalConfigurationFile, settings.MetaConfigurationFile, settings.GlobalConfigurationFile); ConfigurationSectionCache.Instance.Add(sectionName, section, dependency); #if DELUXEWORKSTEST // 测试使用 ConfigurationBroker.sectionReadFrom = ReadFrom.ReadFromFile; #endif } else { #if DELUXEWORKSTEST // 测试使用 ConfigurationBroker.sectionReadFrom = ReadFrom.ReadFromCache; #endif } return(section); }
/// <summary> /// 按节点名称从配置信息中取得节点,并将节点信息缓存,建立文件依赖 /// </summary> /// <param name="sectionName">节点名称</param> /// <param name="checkNullSection">如果返回null,是否抛出异常</param> /// <returns>配置节点</returns> /// <remarks> /// 按名称获取配置节点信息。返回ConfigurationSection的派生类实体,实体类需由用户自定义。 /// <code source="..\Framework\TestProjects\Deluxeworks.Library.WebTest\Configuration\Default.aspx.cs" region="Using Broker" lang="cs" title="使用配置管理" /> /// </remarks> public static ConfigurationSection GetSection(string sectionName, bool checkNullSection = false) { ConfigurationSection section; if (false == ConfigurationSectionCache.Instance.TryGetValue(sectionName, out section)) { ConfigFilesSetting settings = LoadFilesSetting(); System.Configuration.Configuration globalConfig = null; System.Configuration.Configuration config = GetFinalConfiguration(settings, out globalConfig); section = config.GetSectionRecursively(sectionName); List <string> dependentFiles = new List <string>(); dependentFiles.Add(settings.MachineConfigurationFile); dependentFiles.Add(settings.LocalConfigurationFile); dependentFiles.Add(settings.MetaConfigurationFile); dependentFiles.Add(settings.GlobalConfigurationFile); string configSourceFile = globalConfig.GetSectionRelativeFile(section); if (configSourceFile.IsNotEmpty()) { dependentFiles.Add(configSourceFile); } FileCacheDependency dependency = new FileCacheDependency(true, dependentFiles.ToArray()); ConfigurationSectionCache.Instance.Add(sectionName, section, dependency); } if (checkNullSection) { section.CheckSectionNotNull(sectionName); } return(section); }
/// <summary> /// Inserts the specified cache key. /// </summary> /// <param name="cacheKey">The cache key.</param> /// <param name="itemToCache">The value.</param> /// <param name="scope">The value in which scope.</param> /// <param name="absoluteExpiration">The absolute expiration.</param> /// <param name="slidingExpiration">The sliding expiration.</param> /// <param name="dependency">The dependency.</param> /// <param name="onRemoveCallback">The on remove callback.</param> public abstract void Insert(string cacheKey, object itemToCache, string scope = null, DateTimeOffset?absoluteExpiration = null, TimeSpan?slidingExpiration = null, FileCacheDependency dependency = null, RemoveDelegate onRemoveCallback = null);
public override void Insert(string cacheKey, object itemToCache, string scope = null, DateTimeOffset?absoluteExpiration = null, TimeSpan?slidingExpiration = null, FileCacheDependency dependency = null, RemoveDelegate onRemoveCallback = null) { var options = new MemoryCacheEntryOptions() { SlidingExpiration = slidingExpiration, AbsoluteExpiration = absoluteExpiration }; if (onRemoveCallback != null) { options.RegisterPostEvictionCallback((key, value, reason, state) => { onRemoveCallback(key, value, (RemoveReason)Enum.Parse(typeof(RemoveReason), reason.ToString()), state); }); } if (dependency != null) { options.AddExpirationToken(dependency.GetChangeToken()); } if (scope != null) { var ctsScope = UniqueObject.GetUniqueObject <CancellationTokenSource>(GetCacheKeyPrefix(scope)); options.AddExpirationToken(new CancellationChangeToken(ctsScope.Token)); } var ctsDefault = UniqueObject.GetUniqueObject <CancellationTokenSource>(GetCacheKeyPrefix(_defaultScopeName)); options.AddExpirationToken(new CancellationChangeToken(ctsDefault.Token)); string strKey = GetCacheKey(cacheKey, scope); _cache.Set(strKey, itemToCache, options); }
/// <summary> /// 从自定义的配置文件目录加载配置 /Configs 目录下的配置文件 /// 系统默认的配置文件 appsettings.json 会跟随系统的DI 过来 /// </summary> /// <param name="configFileName">json 文件名称</param> /// <param name="args">命令参数</param> /// <param name="isReloadOnChange">文件变更的时候,是否自动重新加载</param> /// <returns></returns> public static IConfiguration GetCustomConfiguration(string configFileName, string[] args = null, bool isReloadOnChange = true) { string configDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Configs"); string configFileFullPath = Path.Combine(configDir, configFileName); if (!File.Exists(configFileFullPath)) { throw new FileNotFoundException(string.Format("the config file : {0} is not be found.", configFileFullPath)); } var config = new ConfigurationBuilder() .SetBasePath(configDir) .AddJsonFile(configFileName, optional: true, reloadOnChange: isReloadOnChange) .AddEnvironmentVariables(prefix: "ASPNETCORE_"); if (null != args) { config.AddCommandLine(args); } var configRoot = config.Build(); if (true == isReloadOnChange) { //如果设置为自动 加载,当变更的时候,会产生一个 IOptionsSnapshot 快照对象 //但是这种强类型刷新快照按照官方的说法是基于DI 的方式,感觉找不到北,我们利用注册回调事件处理 FileCacheDependency dependency = new FileCacheDependency(configFileFullPath); string snapshotKey = string.Concat("__Snapshot_Config_", configFileName); var value = DateTime.Now; PostEvictionDelegate handler = null; handler = (key, valueNew, reason, state) => { try { //强制刷新配置 configRoot.Reload(); //重新设定新的值 并从新插入到缓存中进行监听 value = DateTime.Now; MonitorConfingSnapshot.Set(snapshotKey, value, dependency, handler); //通知订阅的事件触发 if (configRoot == AppSettingsConfiguration && null != OnHostingConfigChangedEvent) { OnHostingConfigChangedEvent.Invoke("ConfigHelper", new ConfigChangedEventArgs { ResultOfChangedConfig = configRoot }); } Logger.Info(string.Format("config file {0} has changed and the config object at application has reload!", configFileFullPath)); } catch (Exception ex) { throw new Exception(string.Format("can not Reload ConfigRoot! Error is:{0}", ex.ToString())); } }; MonitorConfingSnapshot.Set(snapshotKey, value, dependency, handler); } return(configRoot); }
public override void Insert(string cacheKey, object itemToCache, string scope = null, DateTimeOffset?absoluteExpiration = null, TimeSpan?slidingExpiration = null, FileCacheDependency dependency = null, RemoveDelegate onRemoveCallback = null) { if (dependency != null) { throw new NotSupportedException("RedisCacheProvider does not support file dependency."); } var key = GetCacheKey(cacheKey, scope); using (var redisClient = this.GetRedisClient()) { if (absoluteExpiration != null) { redisClient.Add(key, itemToCache, absoluteExpiration.Value); } else if (slidingExpiration != null) { redisClient.Add(key, itemToCache, slidingExpiration.Value); } else { redisClient.Add(key, itemToCache); } } }
/// <summary> /// /// </summary> /// <param name="category"></param> /// <param name="sourceCulture"></param> /// <param name="sourceText"></param> /// <param name="targetCulture"></param> /// <param name="objParams"></param> /// <returns></returns> public string Translate(string category, CultureInfo sourceCulture, string sourceText, CultureInfo targetCulture, params object[] objParams) { string targetText = sourceText; if (targetCulture.Name != sourceCulture.Name && string.IsNullOrEmpty(category) == false) { DictionaryItemKey key = new DictionaryItemKey() { SourceText = sourceText, SourceCultureName = sourceCulture.Name, TargetCultureName = targetCulture.Name, Category = category }; if (DictionaryCache.Instance.TryGetValue(key, out targetText) == false) { string fileName = GetCultureFilePath(category, targetCulture) + ".xml"; string physicalFileName = string.Empty; try { if (EnvironmentHelper.Mode != InstanceMode.Web) { return(sourceText); } XmlDocument xmlDoc = WebXmlDocumentCache.GetXmlDocument(fileName); XmlElement item = FindMatchedItem(sourceText, xmlDoc.DocumentElement.SelectNodes("Item")); if (item != null) { targetText = item.GetAttribute("target"); } else { targetText = sourceText; } physicalFileName = HttpContext.Current.Server.MapPath(fileName); } catch (System.IO.FileNotFoundException) { targetText = sourceText; } catch (System.IO.DirectoryNotFoundException) { targetText = sourceText; } if (string.IsNullOrEmpty(physicalFileName) == false) { FileCacheDependency dependency = new FileCacheDependency(physicalFileName); DictionaryCache.Instance.Add(key, targetText, dependency); } else { DictionaryCache.Instance.Add(key, targetText); } } } return(targetText); }
public static void Set <TItem>(this IMemoryCache cache, string key, TItem value, FileCacheDependency dependency) { var fileInfo = new FileInfo(dependency.FileName); var fileProvider = new PhysicalFileProvider(fileInfo.DirectoryName); cache.Set(key, value, new MemoryCacheEntryOptions().AddExpirationToken(fileProvider.Watch(fileInfo.Name))); }
/// <summary> /// /// </summary> /// <param name="category"></param> /// <param name="sourceCulture"></param> /// <param name="sourceText"></param> /// <param name="targetCulture"></param> /// <param name="objParams"></param> /// <returns></returns> public string Translate(string category, CultureInfo sourceCulture, string sourceText, CultureInfo targetCulture, params object[] objParams) { string targetText = sourceText; if (targetCulture.Name != sourceCulture.Name && string.IsNullOrEmpty(category) == false) { DictionaryItemKey key = new DictionaryItemKey() { SourceText = sourceText, SourceCultureName = sourceCulture.Name, TargetCultureName = targetCulture.Name, Category = category }; if (DictionaryCache.Instance.TryGetValue(key, out targetText) == false) { string fileName = GetCultureFilePath(category, targetCulture) + ".xml"; string physicalFileName = string.Empty; try { if (EnvironmentHelper.Mode != InstanceMode.Web) { return sourceText; } XmlDocument xmlDoc = WebXmlDocumentCache.GetXmlDocument(fileName); XmlElement item = FindMatchedItem(sourceText, xmlDoc.DocumentElement.SelectNodes("Item")); if (item != null) targetText = item.GetAttribute("target"); else targetText = sourceText; physicalFileName = HttpContext.Current.Server.MapPath(fileName); } catch (System.IO.FileNotFoundException) { targetText = sourceText; } catch (System.IO.DirectoryNotFoundException) { targetText = sourceText; } if (string.IsNullOrEmpty(physicalFileName) == false) { FileCacheDependency dependency = new FileCacheDependency(physicalFileName); DictionaryCache.Instance.Add(key, targetText, dependency); } else { DictionaryCache.Instance.Add(key, targetText); } } } return targetText; }