protected void Page_Load(object sender, EventArgs e) { //Ao carregar a página pela 1 vez if (!Page.IsPostBack) { //Armazenei o caminho fisico do arquivo com o nome ARQUIVO.txt String CaminhoArquivo = Server.MapPath("") + @"\Arquivo.txt"; //Classe responsável por fazer o acesso ao arquivo StreamReader Leitor = new StreamReader(CaminhoArquivo); //Abri o arquivo e armazenei o seu conteúdo na variável Conteudo String Conteudo = Leitor.ReadToEnd(); Leitor.Close(); //Classe responsável por AGRUPAR as dependências dos arquivos AggregateCacheDependency Agrupador = new AggregateCacheDependency(); //Classe responsável por criar uma dependência ao arquivo Agrupador.Add(new CacheDependency(Server.MapPath("") + @"\Arquivo.xml")); //Classe responsável por criar uma dependência ao arquivo Agrupador.Add(new CacheDependency(Server.MapPath("") + @"\Web.config")); //Inseri o conteúdo do arquivo no cache Cache.Insert("ARQUIVOS", Conteudo, Agrupador); } }
public AggregateCacheDependency GetAggregateDependency(HttpContext context) { CacheDependency dependency1 = new CacheDependency(context.Server.MapPath("~/test1.txt")); CacheDependency dependency2 = new CacheDependency(context.Server.MapPath("~/test2.txt")); CacheDependency dependency3 = new CacheDependency(null, new string[] {"key1"}); AggregateCacheDependency aggDependency = new AggregateCacheDependency(); aggDependency.Add(new CacheDependency[] {dependency1, dependency2, dependency3 }); return aggDependency; }
protected void Page_Load(object sender, EventArgs e) { if (!this.IsPostBack) { lblInfo.Text += "Creating dependent item...<br>"; Cache.Remove("Dependent"); System.Web.Caching.CacheDependency dep1 = new System.Web.Caching.CacheDependency(Server.MapPath("dependency.txt")); System.Web.Caching.CacheDependency dep2 = new System.Web.Caching.CacheDependency(Server.MapPath("dependency2.txt")); // Create the aggregate. CacheDependency[] dependencies = new CacheDependency[] { dep1, dep2 }; AggregateCacheDependency aggregateDep = new AggregateCacheDependency(); aggregateDep.Add(dependencies); string item = "Dependent cached item"; lblInfo.Text += "Adding dependent item<br>"; Cache.Insert("Dependent", item, aggregateDep); } }
public IList <Station> findStation(long zoneId) { IList <Station> stations = null; string group_key = "Select_Station" + zoneId; //如果不允许缓存 if (enableCaching) { stations = HttpRuntime.Cache[group_key] as IList <Station>; } if (stations == null) { stations = manager.findStation(zoneId); } // Check if the data exists in the data cache if (stations != null && stations.Count() > 0) { //// If the data is not in the cache then fetch the data from the business logic tier AggregateCacheDependency cd = DependencyFacade.GetStationSelDependency(); // Store the output in the data cache, and Add the necessary AggregateCacheDependency object HttpRuntime.Cache.Add(group_key, stations, cd, DateTime.Now.AddHours(UserRegTimeout), Cache.NoSlidingExpiration, CacheItemPriority.High, null); } return(stations); }
public String GetCities() { String html = (String)Cache[HTML_CACHE_KEY]; if (html == null) { html = File.ReadAllText(MapPath(fileName)); AggregateCacheDependency aggDep = new AggregateCacheDependency(); aggDep.Add(new CacheDependency(MapPath(fileName))); aggDep.Add(new RequestCountDependency(3)); Cache.Insert(HTML_CACHE_KEY, html, aggDep, DateTime.Now.AddMinutes(30), Cache.NoSlidingExpiration //new CacheDependency(MapPath(fileName)) //new RequestCountDependency(3) ); } else { cached = true; } return(html); }
public void SingleDependency() { string depFile = Path.Combine(_tempFolder, "dep.tmp"); AggregateCacheDependency aggregate = new AggregateCacheDependency(); aggregate.Add(new CacheDependency(depFile)); DateTime absoluteExpiration = DateTime.Now.AddSeconds(4); TimeSpan slidingExpiration = TimeSpan.Zero; CacheItemPriority priority = CacheItemPriority.Default; string original = "MONO"; HttpRuntime.Cache.Insert("key", original, aggregate, absoluteExpiration, slidingExpiration, priority, null); string cachedValue = HttpRuntime.Cache.Get("key") as string; Assert.IsNotNull(cachedValue, "#A1"); Assert.AreEqual("MONO", cachedValue, "#A2"); Assert.IsFalse(aggregate.HasChanged, "#A3"); cachedValue = HttpRuntime.Cache.Get("key") as string; Assert.IsNotNull(cachedValue, "#B1"); Assert.AreEqual("MONO", cachedValue, "#B2"); Assert.IsFalse(aggregate.HasChanged, "#B3"); File.WriteAllText(depFile, "OK", Encoding.UTF8); Thread.Sleep(500); cachedValue = HttpRuntime.Cache.Get("key") as string; Assert.IsNull(cachedValue, "#C1"); Assert.IsTrue(aggregate.HasChanged, "#C2"); }
/// <summary> /// 获取当前开奖ID对应投注数列表 /// </summary> /// <param name="nId"></param> /// <returns></returns> public static List <Model.RunLottery> GetList(int pageIndex, int pageSize, out int totalCount) { BLL.RunLottery bll = new BLL.RunLottery(); totalCount = 0; if (!enableCaching) { return(bll.GetList(pageIndex, pageSize, out totalCount, "", null)); } string key = "runLottery_" + pageIndex + "_" + pageSize + ""; string keyCount = "runLotteryCount_" + pageIndex + "_" + pageSize + ""; List <Model.RunLottery> data = (List <Model.RunLottery>)HttpRuntime.Cache[key]; if (HttpRuntime.Cache[keyCount] != null) { totalCount = (Int32)HttpRuntime.Cache[keyCount]; } if (data == null) { data = bll.GetList(pageIndex, pageSize, out totalCount, "", null); if (pageIndex > 1) { DateTime currTime = DateTime.Now; AggregateCacheDependency cd = DependencyFactory.GetRunLotteryDependency(); HttpRuntime.Cache.Add(key, data, cd, currTime.AddMinutes(1), Cache.NoSlidingExpiration, CacheItemPriority.High, null); HttpRuntime.Cache.Add(keyCount, totalCount, null, currTime.AddMinutes(1), Cache.NoSlidingExpiration, CacheItemPriority.High, null); } } return(data); }
//Get the appropriate dependencies to be used for the file cache private CacheDependency GetCacheDependencies() { //Manage and reuse Cache dependencies //File dependencies CacheDependency deps = new CacheDependency(this.Dependencies.ToArray()); //If there are any additional special dependency... if (this.SpecialDependencies != null) { //If a previous aggregate dependence exits, the special dependencies can't be added twice //so create one just the first time (reuse it) if (_aggregateCacheDependency == null) { _aggregateCacheDependency = new AggregateCacheDependency(); _aggregateCacheDependency.Add(this.SpecialDependencies.ToArray()); } //Combine files and folders with the special dependencies _aggregateCacheDependency.Add(deps); deps = _aggregateCacheDependency; } return(deps); }
public static Model.ProductInfo GetProduct(string productId) { BLL.Product bll = new BLL.Product(); if (!enableCaching) { return(bll.GetModel(productId)); } string key = "product_" + productId; Model.ProductInfo data = (Model.ProductInfo)HttpRuntime.Cache[key]; if (data == null) { data = bll.GetModel(productId); AggregateCacheDependency cd = DependencyFactory.GetProductDependency(); HttpRuntime.Cache.Add(key, data, cd, DateTime.Now.AddHours(productTimeout), Cache.NoSlidingExpiration, CacheItemPriority.High, null); } return(data); }
public static List <SysEnumInfo> GetList(string parentName) { SysEnum bll = new SysEnum(); SqlParameter parm = new SqlParameter("@EnumName", parentName); if (!enableCaching) { return(bll.GetList(1, 100000, "and t2.EnumName = @EnumName", parm)); } string key = "sysEnum_list_" + parentName + ""; List <SysEnumInfo> data = (List <SysEnumInfo>)HttpRuntime.Cache[key]; if (data == null) { data = bll.GetList(1, 100000, "and t2.EnumName = @EnumName", parm); AggregateCacheDependency cd = DependencyFacade.GetSysEnumDependency(); HttpRuntime.Cache.Add(key, data, cd, DateTime.Now.AddHours(sysEnumTimeout), Cache.NoSlidingExpiration, CacheItemPriority.High, null); } return(data); }
private ArrayList GetAggregatedDependencies(AggregateCacheDependency aggregatedDependency) { var fieldInfo = typeof(AggregateCacheDependency).GetField("_dependencies", BindingFlags.Instance | BindingFlags.NonPublic); return((ArrayList)fieldInfo.GetValue(aggregatedDependency)); }
public override SiteMapNode BuildSiteMap() { try { lock (this) { if (root != null) { return(root); } base.Clear(); string nodeKey, nodeTitle, nodeUrl, nodeDescription; SiteMapDataContext dbSiteMap = new SiteMapDataContext(SystemSetting.SageFrameConnectionString); string userName = SystemSetting.AnonymousUsername; if (HttpContext.Current.User != null) { if (Membership.GetUser() != null) { userName = Membership.GetUser().UserName; } } IList rootRoles = new ArrayList(); rootRoles.Add("*"); root = new SiteMapNode(this, "root", "~/" + CommonHelper.DefaultPage, "Home", "", rootRoles, null, null, null); AddNode(root); var pages = dbSiteMap.sp_GetSiteMapNodeWithRolesByParentNodeID(0, userName, GetPortalID); foreach (var page in pages) { nodeKey = page.PageID.ToString(); nodeTitle = page.PageName; if (string.IsNullOrEmpty(page.Url)) { nodeUrl = "~" + page.TabPath; } else { nodeUrl = page.Url; } nodeDescription = page.Description; string[] PageRoles = page.PageRoles.Split(','); IList roles = new ArrayList(); for (int i = 0; i < PageRoles.Length; i++) { roles.Add(PageRoles[i]); } SiteMapNode childNode = FindSiteMapNodeFromKey(nodeKey); if (childNode == null) { childNode = new SiteMapNode(this, nodeKey, nodeUrl, nodeTitle, nodeDescription, roles, null, null, null); AddNode(childNode, root); AddPages(childNode); } } SqlCacheDependency pagesTableDependency = new SqlCacheDependency(SystemSetting.SageFrameDBName, "Pages"); SqlCacheDependency MembershipTableDependency = new SqlCacheDependency(SystemSetting.SageFrameDBName, "aspnet_Membership"); SqlCacheDependency UsersTableDependency = new SqlCacheDependency(SystemSetting.SageFrameDBName, "aspnet_users"); AggregateCacheDependency aggregateDependencies = new AggregateCacheDependency(); aggregateDependencies.Add(pagesTableDependency); aggregateDependencies.Add(MembershipTableDependency); aggregateDependencies.Add(UsersTableDependency); HttpRuntime.Cache.Insert(CacheDependencyKey, DateTime.Now, aggregateDependencies , DateTime.Now , Cache.NoSlidingExpiration , CacheItemPriority.Normal , new CacheItemRemovedCallback(OnSiteMapChanged)); return(root); } } catch { return(root); } }
internal override void CacheBuildResult(string cacheKey, BuildResult result, long hashCode, DateTime utcStart) { ICollection virtualDependencies = result.VirtualPathDependencies; Debug.Trace("BuildResultCache", "Adding cache " + cacheKey + " in the memory cache"); CacheDependency cacheDependency = null; if (virtualDependencies != null) { cacheDependency = result.VirtualPath.GetCacheDependency(virtualDependencies, utcStart); // If we got a cache dependency, remember that in the BuildResult if (cacheDependency != null) { result.UsesCacheDependency = true; } } // If it should not be cached to memory, leave it alone if (!result.CacheToMemory) { return; } if (BuildResultCompiledType.UsesDelayLoadType(result)) { // If the result is delaying loading of assembly, then don't cache // to avoid having to load the assembly. return; } BuildResultCompiledAssemblyBase compiledResult = result as BuildResultCompiledAssemblyBase; if (compiledResult != null && compiledResult.ResultAssembly != null && !compiledResult.UsesExistingAssembly) { // Insert a new cache entry using the assembly path as the key string assemblyKey = GetAssemblyCacheKey(compiledResult.ResultAssembly); Assembly a = (Assembly)_cache.Get(assemblyKey); if (a == null) { Debug.Trace("BuildResultCache", "Adding marker cache entry " + compiledResult.ResultAssembly); // VSWhidbey 500049 - add as NotRemovable to prevent the assembly from being prematurely deleted _cache.UtcInsert(assemblyKey, compiledResult.ResultAssembly, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null); } else { Debug.Assert(a == compiledResult.ResultAssembly); } // Now create a dependency based on that key. This way, by removing that key, we are able to // remove all the pages that live in that assembly from the cache. CacheDependency assemblyCacheDependency = new CacheDependency(0, null, new string[] { assemblyKey }); if (cacheDependency != null) { // We can't share the same CacheDependency, since we don't want the UtcStart // behavior for the assembly. Use an Aggregate to put the two together. AggregateCacheDependency tmpDependency = new AggregateCacheDependency(); tmpDependency.Add(new CacheDependency[] { cacheDependency, assemblyCacheDependency }); cacheDependency = tmpDependency; } else { cacheDependency = assemblyCacheDependency; } } string key = GetMemoryCacheKey(cacheKey); // Only allow the cache item to expire if the result can be unloaded. Otherwise, // we may as well cache it forever (e.g. for Assemblies and Types). CacheItemPriority cachePriority; if (result.IsUnloadable) { cachePriority = CacheItemPriority.Default; } else { cachePriority = CacheItemPriority.NotRemovable; } CacheItemRemovedCallback onRemoveCallback = null; // If the appdomain needs to be shut down when the item becomes invalid, register // a callback to do the shutdown. if (result.ShutdownAppDomainOnChange || result is BuildResultCompiledAssemblyBase) { // Create the delegate on demand if (_onRemoveCallback == null) { _onRemoveCallback = new CacheItemRemovedCallback(OnCacheItemRemoved); } onRemoveCallback = _onRemoveCallback; } _cache.UtcInsert(key, result, cacheDependency, result.MemoryCacheExpiration, result.MemoryCacheSlidingExpiration, cachePriority, onRemoveCallback); }
public static XslTransformExecutionContext GetXslt(string nodePath, bool resolveScripts) { string nodeKey = "xslt:" + nodePath; XslTransformExecutionContext context = (XslTransformExecutionContext)(Cache.Get(nodeKey)); if (context == null) { context = new XslTransformExecutionContext(); context.XslCompiledTransform = new XslCompiledTransform(Debugger.IsAttached); RepositoryPathResolver resolver = new RepositoryPathResolver(); try { context.XslCompiledTransform.Load(nodePath, XsltSettings.Default, resolver); } catch (NullReferenceException e) // rethrow { throw new NullReferenceException(e.Message + "<br/>" + nodePath + " (or include)"); } AggregateCacheDependency aggregatedDependency = new AggregateCacheDependency(); context.NamespaceExtensions = resolver.ImportNamespaceCollection.Distinct().ToArray(); context.ImportScriptCollection = resolver.ImportScriptCollection; context.ImportCssCollection = resolver.ImportCssCollection; foreach (var dependencyPath in resolver.DependencyPathCollection) { // Create an aggregate cache dependeny that includes NodeId, Path, NodeTypeId // Our cache item will be invalidated if the dependency node is invalidated // - by node id // - by path // - by nodeType string fsFilePath = null; if (HttpContext.Current != null && WebApplication.DiskFSSupportMode == DiskFSSupportMode.Prefer) { fsFilePath = HttpContext.Current.Server.MapPath(dependencyPath); } if (!string.IsNullOrEmpty(fsFilePath) && System.IO.File.Exists(fsFilePath)) { SnTrace.Repository.Write("Cannot create cache dependency for a filesystem entry: {0}", fsFilePath); } else { var nodeHead = NodeHead.Get(dependencyPath); aggregatedDependency.Add( new PathDependency(nodeHead.Path), new NodeIdDependency(nodeHead.Id), new NodeTypeDependency(nodeHead.NodeTypeId) ); } } Cache.Insert(nodeKey, context, aggregatedDependency); } if (resolveScripts) { foreach (var script in context.ImportScriptCollection) { UITools.AddScript(script); } foreach (var css in context.ImportCssCollection) { UITools.AddStyleSheetToHeader(UITools.GetHeader(), css); } } return(context); }
public static List <T> FromCache <T>(this System.Linq.IQueryable <T> q, System.Data.Linq.DataContext dc) { try { string CacheId = q.ToString() + "?"; foreach (System.Data.Common.DbParameter dbp in dc.GetCommand(q).Parameters) { CacheId += dbp.ParameterName + "=" + dbp.Value.ToString() + "&"; } List <T> objCache; //if (Environment.StackTrace.Contains("CMS\\")) //{ objCache = q.ToList(); return(objCache); //} //else //{ //System.Threading.Thread.Sleep(500); objCache = (List <T>)System.Web.HttpRuntime.Cache.Get(CacheId); //} if (objCache == null) { List <string> tablesNames = dc.Mapping.GetTables().Where(t => (t.TableName.Contains("[")) ? CacheId.Contains(t.TableName.Substring(4)) : CacheId.Contains("[" + t.TableName.Substring(4) + "]")).Select(t => t.TableName.Substring(4)).ToList(); string connStr = dc.Connection.ConnectionString; using (System.Data.SqlClient.SqlConnection conn = new System.Data.SqlClient.SqlConnection(connStr)) { conn.Open(); System.Web.Caching.SqlCacheDependencyAdmin.EnableNotifications(connStr); System.Web.Caching.SqlCacheDependency sqldep; AggregateCacheDependency aggDep = new AggregateCacheDependency(); foreach (string tableName in tablesNames) { if (!System.Web.Caching.SqlCacheDependencyAdmin.GetTablesEnabledForNotifications(connStr).Contains(tableName)) { System.Web.Caching.SqlCacheDependencyAdmin.EnableTableForNotifications(connStr, tableName); } if (tableName.Contains("Comment") || tableName.Contains("PollDetail")) { sqldep = new System.Web.Caching.SqlCacheDependency("PlatformCacheSmallPollTime", tableName); } else { sqldep = new System.Web.Caching.SqlCacheDependency("PlatformCache", tableName); } aggDep.Add(sqldep); } objCache = q.ToList(); if (objCache != null) { System.Web.HttpRuntime.Cache.Insert(CacheId, objCache, aggDep, DateTime.Now.AddDays(1), System.Web.Caching.Cache.NoSlidingExpiration); } } } //Return the created (or cached) List return(objCache); } catch (Exception ex) { throw ex; } }
protected internal override void Render(HtmlTextWriter output) { CacheDependency dependency = null; if (this._outputString != null) { output.Write(this._outputString); this.RegisterValidationEvents(); } else if (this._cachingDisabled || !RuntimeConfig.GetAppConfig().OutputCache.EnableFragmentCache) { this._cachedCtrl.RenderControl(output); } else { string str; DateTime noAbsoluteExpiration; TimeSpan noSlidingExpiration; if (this._sqlDependency != null) { dependency = SqlCacheDependency.CreateOutputCacheDependency(this._sqlDependency); } this._cacheEntry.CssStyleString = this.GetCssStyleRenderString(output.GetType()); StringWriter tw = new StringWriter(); HtmlTextWriter writer = Page.CreateHtmlTextWriterFromType(tw, output.GetType()); TextWriter writer3 = this.Context.Response.SwitchWriter(tw); try { this.Page.PushCachingControl(this); this._cachedCtrl.RenderControl(writer); this.Page.PopCachingControl(); } finally { this.Context.Response.SwitchWriter(writer3); } this._cacheEntry.OutputString = tw.ToString(); output.Write(this._cacheEntry.OutputString); CacheDependency dependencies = this._cacheDependency; if (dependency != null) { if (dependencies == null) { dependencies = dependency; } else { AggregateCacheDependency dependency3 = new AggregateCacheDependency(); dependency3.Add(new CacheDependency[] { dependencies }); dependency3.Add(new CacheDependency[] { dependency }); dependencies = dependency3; } } ControlCachedVary cachedVary = null; if (((this._varyByParamsCollection == null) && (this._varyByControlsCollection == null)) && (this._varyByCustom == null)) { str = this._cacheKey; } else { string[] varyByParams = null; if (this._varyByParamsCollection != null) { varyByParams = this._varyByParamsCollection.GetParams(); } cachedVary = new ControlCachedVary(varyByParams, this._varyByControlsCollection, this._varyByCustom); HashCodeCombiner combinedHashCode = new HashCodeCombiner(this._nonVaryHashCode); str = this.ComputeVaryCacheKey(combinedHashCode, cachedVary); } if (this._useSlidingExpiration) { noAbsoluteExpiration = Cache.NoAbsoluteExpiration; noSlidingExpiration = (TimeSpan)(this._utcExpirationTime - DateTime.UtcNow); } else { noAbsoluteExpiration = this._utcExpirationTime; noSlidingExpiration = Cache.NoSlidingExpiration; } try { OutputCache.InsertFragment(this._cacheKey, cachedVary, str, this._cacheEntry, dependencies, noAbsoluteExpiration, noSlidingExpiration, this._provider); } catch { if (dependencies != null) { dependencies.Dispose(); } throw; } } }
/// <internalonly/> /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> protected internal override void Render(HtmlTextWriter output) { CacheDependency sqlCacheDep = null; // If the output is cached, use it and do nothing else if (_outputString != null) { output.Write(_outputString); RegisterValidationEvents(); return; } // If caching was turned off, just render the control if (_cachingDisabled || !RuntimeConfig.GetAppConfig().OutputCache.EnableFragmentCache) { _cachedCtrl.RenderControl(output); return; } // Create SQL cache dependency before we render the page if (_sqlDependency != null) { sqlCacheDep = SqlCacheDependency.CreateOutputCacheDependency(_sqlDependency); } _cacheEntry.CssStyleString = GetCssStyleRenderString(output.GetType()); // Create a new HtmlTextWriter, with the same type as the current one (see ASURT 118922) StringWriter tmpWriter = new StringWriter(); HtmlTextWriter tmpHtmlWriter = Page.CreateHtmlTextWriterFromType(tmpWriter, output.GetType()); CacheDependency cacheDep; TextWriter savedWriter = Context.Response.SwitchWriter(tmpWriter); try { // Make sure the Page knows about us while the control's OnPreRender is called Page.PushCachingControl(this); _cachedCtrl.RenderControl(tmpHtmlWriter); Page.PopCachingControl(); } finally { Context.Response.SwitchWriter(savedWriter); } _cacheEntry.OutputString = tmpWriter.ToString(); // Send the output to the response output.Write(_cacheEntry.OutputString); // Cache the output cacheDep = _cacheDependency; if (sqlCacheDep != null) { if (cacheDep == null) { cacheDep = sqlCacheDep; } else { AggregateCacheDependency aggr = new AggregateCacheDependency(); aggr.Add(cacheDep); aggr.Add(sqlCacheDep); cacheDep = aggr; } } ControlCachedVary cachedVary = null; string realItemCacheKey; // If there are no varies, use the non-varying key if (_varyByParamsCollection == null && _varyByControlsCollection == null && _varyByCustom == null) { realItemCacheKey = _cacheKey; } else { string[] varyByParams = null; if (_varyByParamsCollection != null) { varyByParams = _varyByParamsCollection.GetParams(); } cachedVary = new ControlCachedVary(varyByParams, _varyByControlsCollection, _varyByCustom); HashCodeCombiner combinedHashCode = new HashCodeCombiner(_nonVaryHashCode); realItemCacheKey = ComputeVaryCacheKey(combinedHashCode, cachedVary); } // Compute the correct expiration, sliding or absolute DateTime utcExpirationTime; TimeSpan slidingExpiration; if (_useSlidingExpiration) { utcExpirationTime = Cache.NoAbsoluteExpiration; slidingExpiration = _utcExpirationTime - DateTime.UtcNow; } else { utcExpirationTime = _utcExpirationTime; slidingExpiration = Cache.NoSlidingExpiration; } try { OutputCache.InsertFragment(_cacheKey, cachedVary, realItemCacheKey, _cacheEntry, cacheDep /*dependencies*/, utcExpirationTime, slidingExpiration, _provider); } catch { if (cacheDep != null) { cacheDep.Dispose(); } throw; } }
private static AggregateCacheDependency GetQueryDependency( string key, ISessionImplementor session, string connectionString, List <QueryDependencyConfiguration> queryDependencies) { var dialectString = session.Factory.Dialect.ToString(); HashSet <QueryDependencyConfiguration> filteredConfigs = new HashSet <QueryDependencyConfiguration>( new QueryDependencyConfigComparer()); if (dialectString.Contains("MsSql")) { foreach (var queryDependency in queryDependencies) { if (key.Contains(queryDependency.QualifiedTableName) && queryDependency.DatabaseType == DatabaseType.Sql) { if (queryDependency.IsPollingDependencyUsed) { filteredConfigs.Add(queryDependency); } else { bool passed = true; var commandDependency = queryDependency as QueryCommandDependencyConfiguration; foreach (var columnName in commandDependency.KeyColumnNames) { if (!key.Contains(columnName)) { passed = false; break; } } if (passed) { filteredConfigs.Add(commandDependency); } } } } } else if (dialectString.Contains("Oracle")) { foreach (var queryDependency in queryDependencies) { if (key.Contains(queryDependency.QualifiedTableName) && queryDependency.DatabaseType == DatabaseType.Oracle) { if (queryDependency.IsPollingDependencyUsed) { filteredConfigs.Add(queryDependency); } else { bool passed = true; var commandDependency = queryDependency as QueryCommandDependencyConfiguration; foreach (var columnName in commandDependency.KeyColumnNames) { if (!key.Contains(columnName)) { passed = false; break; } } if (passed) { filteredConfigs.Add(commandDependency); } } } } } else { return(null); } List <CacheDependency> cacheDependencies = new List <CacheDependency>(); foreach (var filteredConfig in filteredConfigs) { cacheDependencies.Add( filteredConfig.CreateDependency( connectionString)); } if (cacheDependencies.Count > 0) { AggregateCacheDependency aggregateCacheDependency = new AggregateCacheDependency(); aggregateCacheDependency.Add(cacheDependencies.ToArray()); return(aggregateCacheDependency); } return(null); }
private static AggregateCacheDependency GetDependency( object key, object value, string regionPrefix, RegionConfig regionConfig, string connectionString) { CacheEntry cachedEntry = null; if (value is CachedItem item) { if (item.Value is CacheEntry entry) { cachedEntry = entry; } else { return(null); } } else if (value is CacheLock cacheLock) { return(null); } else { cachedEntry = value as CacheEntry; if (cachedEntry == null) { return(null); } } var id = (key as CacheKey).Key; var entityClassFullName = cachedEntry.Subclass; var dependencies = NCacheProvider.GetEntityDependencyConfigs( regionPrefix, entityClassFullName) .ToArray(); if (dependencies.Length == 0) { return(null); } List <CacheDependency> cacheDependencies = new List <CacheDependency>(dependencies.Length); for (int i = 0; i < dependencies.Length; i++) { var cacheDependency = dependencies[i].GetCacheDependency( connectionString, id); cacheDependencies.Add(cacheDependency); } var aggregateDependency = new AggregateCacheDependency(); aggregateDependency.Add(cacheDependencies.ToArray()); return(aggregateDependency); }
public static IndexBuilderConfiguration GetConfig() { try { if ( (HttpRuntime.Cache["CIndexBuilderConfiguration"] != null) && (HttpRuntime.Cache["CIndexBuilderConfiguration"] is IndexBuilderConfiguration) ) { return((IndexBuilderConfiguration)HttpRuntime.Cache["CIndexBuilderConfiguration"]); } IndexBuilderConfiguration indexBuilderConfig = new IndexBuilderConfiguration(); String configFolderName = "~/Setup/ProviderConfig/indexbuilders/"; string pathToConfigFolder = HostingEnvironment.MapPath(configFolderName); if (!Directory.Exists(pathToConfigFolder)) { return(indexBuilderConfig); } DirectoryInfo directoryInfo = new DirectoryInfo(pathToConfigFolder); FileInfo[] configFiles = directoryInfo.GetFiles("*.config"); foreach (FileInfo fileInfo in configFiles) { XmlDocument configXml = new XmlDocument(); configXml.Load(fileInfo.FullName); indexBuilderConfig.LoadValuesFromConfigurationXml(configXml.DocumentElement); } AggregateCacheDependency aggregateCacheDependency = new AggregateCacheDependency(); string pathToWebConfig = HostingEnvironment.MapPath("~/Web.config"); aggregateCacheDependency.Add(new CacheDependency(pathToWebConfig)); System.Web.HttpRuntime.Cache.Insert( "CIndexBuilderConfiguration", indexBuilderConfig, aggregateCacheDependency, DateTime.Now.AddYears(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, null); return((IndexBuilderConfiguration)HttpRuntime.Cache["CIndexBuilderConfiguration"]); } catch (HttpException ex) { log.Error(ex); } catch (System.Xml.XmlException ex) { log.Error(ex); } catch (ArgumentException ex) { log.Error(ex); } catch (NullReferenceException ex) { log.Error(ex); } return(null); }
public static SitePreDeleteHandlerProviderConfig GetConfig() { try { if ( (HttpRuntime.Cache["SitePreDeleteHandlerProviderConfig"] != null) && (HttpRuntime.Cache["UserRegisteredHandlerProviderConfig"] is SitePreDeleteHandlerProviderConfig) ) { return((SitePreDeleteHandlerProviderConfig)HttpRuntime.Cache["SitePreDeleteHandlerProviderConfig"]); } SitePreDeleteHandlerProviderConfig config = new SitePreDeleteHandlerProviderConfig(); String configFolderName = "~/Setup/ProviderConfig/sitepredeletehandlers/"; string pathToConfigFolder = HttpContext.Current.Server.MapPath(configFolderName); if (!Directory.Exists(pathToConfigFolder)) { return(config); } DirectoryInfo directoryInfo = new DirectoryInfo(pathToConfigFolder); FileInfo[] configFiles = directoryInfo.GetFiles("*.config"); foreach (FileInfo fileInfo in configFiles) { XmlDocument configXml = new XmlDocument(); configXml.Load(fileInfo.FullName); config.LoadValuesFromConfigurationXml(configXml.DocumentElement); } AggregateCacheDependency aggregateCacheDependency = new AggregateCacheDependency(); string pathToWebConfig = HttpContext.Current.Server.MapPath("~/Web.config"); aggregateCacheDependency.Add(new CacheDependency(pathToWebConfig)); System.Web.HttpRuntime.Cache.Insert( "SitePreDeleteHandlerProviderConfig", config, aggregateCacheDependency, DateTime.Now.AddYears(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, null); return((SitePreDeleteHandlerProviderConfig)HttpRuntime.Cache["SitePreDeleteHandlerProviderConfig"]); } catch (HttpException ex) { log.Error(ex); } catch (System.Xml.XmlException ex) { log.Error(ex); } catch (ArgumentException ex) { log.Error(ex); } catch (NullReferenceException ex) { log.Error(ex); } return(null); }
public static mojoEncryptionConfiguration GetConfig() { //return (mojoEncryptionConfiguration)ConfigurationManager.GetSection("system.web/mojoEncryption"); try { if ( (HttpRuntime.Cache["mojoEncryptionConfiguration"] != null) && (HttpRuntime.Cache["mojoEncryptionConfiguration"] is mojoEncryptionConfiguration) ) { return((mojoEncryptionConfiguration)HttpRuntime.Cache["mojoEncryptionConfiguration"]); } mojoEncryptionConfiguration config = new mojoEncryptionConfiguration(); string pathToConfigFile = System.Web.Hosting.HostingEnvironment.MapPath(ConfigHelper.GetStringProperty("mojoCryptoHelperKeyFile", "~/mojoEncryption.config")); log.Debug("path to crypto key " + pathToConfigFile); if (!File.Exists(pathToConfigFile)) { log.Error("crypto file not found " + pathToConfigFile); return(config); } FileInfo fileInfo = new FileInfo(pathToConfigFile); XmlDocument configXml = new XmlDocument(); configXml.Load(fileInfo.FullName); config.LoadValuesFromConfigurationXml(configXml.DocumentElement); AggregateCacheDependency aggregateCacheDependency = new AggregateCacheDependency(); aggregateCacheDependency.Add(new CacheDependency(pathToConfigFile)); System.Web.HttpRuntime.Cache.Insert( "mojoEncryptionConfiguration", config, aggregateCacheDependency, DateTime.Now.AddYears(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, null); return((mojoEncryptionConfiguration)HttpRuntime.Cache["mojoEncryptionConfiguration"]); } catch (HttpException ex) { log.Error(ex); } catch (System.Xml.XmlException ex) { log.Error(ex); } catch (ArgumentException ex) { log.Error(ex); } catch (NullReferenceException ex) { log.Error(ex); } return(null); }