public override CacheDependency GetCacheDependency( string virtualPath, IEnumerable virtualPathDependencies, DateTime utcStart) { if (virtualPath.Contains("App_Themes/default")) { String pathToDependencyFile = CacheHelper.GetPathToThemeCacheDependencyFile(); String pathToThemeFile = SiteUtils.GetFullPathToThemeFile(); if(pathToDependencyFile != null) { AggregateCacheDependency dependency = new AggregateCacheDependency(); dependency.Add(new CacheDependency(pathToDependencyFile)); try { dependency.Add(new CacheDependency(pathToThemeFile)); } catch (HttpException) { // this can happen if the site is configured for a skin that doesn't exist } return dependency; } } return base.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart); }
protected virtual void SaveDataToCacheInternal(string key, object data, CacheDependency dependency) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } if (!this.Enabled) { throw new InvalidOperationException(System.Web.SR.GetString("DataSourceCache_CacheMustBeEnabled")); } DateTime noAbsoluteExpiration = Cache.NoAbsoluteExpiration; TimeSpan noSlidingExpiration = Cache.NoSlidingExpiration; switch (this.ExpirationPolicy) { case DataSourceCacheExpiry.Absolute: noAbsoluteExpiration = DateTime.UtcNow.AddSeconds((this.Duration == 0) ? ((double) 0x7fffffff) : ((double) this.Duration)); break; case DataSourceCacheExpiry.Sliding: noSlidingExpiration = TimeSpan.FromSeconds((double) this.Duration); break; } AggregateCacheDependency dependencies = new AggregateCacheDependency(); string[] cachekeys = null; if (this.KeyDependency.Length > 0) { cachekeys = new string[] { this.KeyDependency }; dependencies.Add(new CacheDependency[] { new CacheDependency(null, cachekeys) }); } if (dependency != null) { dependencies.Add(new CacheDependency[] { dependency }); } HttpRuntime.CacheInternal.UtcInsert(key, data, dependencies, noAbsoluteExpiration, noSlidingExpiration); }
internal override void CacheBuildResult(string cacheKey, BuildResult result, long hashCode, DateTime utcStart) { if (!BuildResultCompiledType.UsesDelayLoadType(result)) { ICollection virtualPathDependencies = result.VirtualPathDependencies; CacheDependency dependencies = null; if (virtualPathDependencies != null) { dependencies = result.VirtualPath.GetCacheDependency(virtualPathDependencies, utcStart); if (dependencies != null) { result.UsesCacheDependency = true; } } if (result.CacheToMemory) { CacheItemPriority normal; BuildResultCompiledAssemblyBase base2 = result as BuildResultCompiledAssemblyBase; if (((base2 != null) && (base2.ResultAssembly != null)) && !base2.UsesExistingAssembly) { string assemblyCacheKey = BuildResultCache.GetAssemblyCacheKey(base2.ResultAssembly); Assembly assembly = (Assembly) this._cache.Get(assemblyCacheKey); if (assembly == null) { this._cache.UtcInsert(assemblyCacheKey, base2.ResultAssembly, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null); } CacheDependency dependency2 = new CacheDependency(0, null, new string[] { assemblyCacheKey }); if (dependencies != null) { AggregateCacheDependency dependency3 = new AggregateCacheDependency(); dependency3.Add(new CacheDependency[] { dependencies, dependency2 }); dependencies = dependency3; } else { dependencies = dependency2; } } string memoryCacheKey = GetMemoryCacheKey(cacheKey); if (result.IsUnloadable) { normal = CacheItemPriority.Normal; } else { normal = CacheItemPriority.NotRemovable; } CacheItemRemovedCallback onRemoveCallback = null; if (result.ShutdownAppDomainOnChange || (result is BuildResultCompiledAssemblyBase)) { if (this._onRemoveCallback == null) { this._onRemoveCallback = new CacheItemRemovedCallback(this.OnCacheItemRemoved); } onRemoveCallback = this._onRemoveCallback; } this._cache.UtcInsert(memoryCacheKey, result, dependencies, result.MemoryCacheExpiration, result.MemoryCacheSlidingExpiration, normal, onRemoveCallback); } } }
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"); }
//建立DataSet缓存的汇总依赖项 //将缓存与多个对相关联 void AddDependency() { //依赖项一,XML文件依赖项 CacheDependency fileDep = new CacheDependency(Server.MapPath("~/App_Data/Employees.xml")); //依赖项二,Key依赖项 string[] keyDependencies = { "Company" }; CacheDependency keyDep = new CacheDependency(null, keyDependencies); //聚合依赖项 AggregateCacheDependency aggDep = new AggregateCacheDependency(); aggDep.Add(fileDep); //加入文件依赖项 aggDep.Add(keyDep); //加入Key依赖项 Cache.Insert("Employees", dsEmployee, aggDep); }
public void Insert(string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemUpdateCallback onUpdateCallback) { if (((dependencies == null) && (absoluteExpiration == NoAbsoluteExpiration)) && (slidingExpiration == NoSlidingExpiration)) { throw new ArgumentException(System.Web.SR.GetString("Invalid_Parameters_To_Insert")); } if (onUpdateCallback == null) { throw new ArgumentNullException("onUpdateCallback"); } DateTime utcAbsoluteExpiration = DateTimeUtil.ConvertToUniversalTime(absoluteExpiration); this._cacheInternal.DoInsert(true, key, value, null, NoAbsoluteExpiration, NoSlidingExpiration, CacheItemPriority.NotRemovable, null, true); string[] cachekeys = new string[] { key }; CacheDependency expensiveObjectDependency = new CacheDependency(null, cachekeys); if (dependencies == null) { dependencies = expensiveObjectDependency; } else { AggregateCacheDependency dependency2 = new AggregateCacheDependency(); dependency2.Add(new CacheDependency[] { dependencies, expensiveObjectDependency }); dependencies = dependency2; } this._cacheInternal.DoInsert(false, "w" + key, new SentinelEntry(key, expensiveObjectDependency, onUpdateCallback), dependencies, utcAbsoluteExpiration, slidingExpiration, CacheItemPriority.NotRemovable, s_sentinelRemovedCallback, true); }
// // private helper methods // private static void AddCacheKeyToDependencies(ref CacheDependency dependencies, string cacheKey) { CacheDependency keyDep = new CacheDependency(0, null, new string[1] { cacheKey }); if (dependencies == null) { dependencies = keyDep; } else { // if it's not an aggregate, we have to create one because you can't add // it to anything but an aggregate AggregateCacheDependency agg = dependencies as AggregateCacheDependency; if (agg != null) { agg.Add(keyDep); } else { agg = new AggregateCacheDependency(); agg.Add(keyDep, dependencies); dependencies = agg; } } }
/// <summary> /// Creates a cache dependency based on the specified virtual paths. /// </summary> /// <param name="definition">The definition.</param> /// <param name="virtualPath">The path to the primary virtual resource.</param> /// <returns> /// A <see cref="T:System.Web.Caching.CacheDependency"/> object for the specified virtual resources. /// </returns> public virtual CacheDependency GetCacheDependency(PathDefinition definition, string virtualPath, IEnumerable virtualPathDependencies, DateTime utcStart) { CacheDependency result = this.GetCurrentCacheDependency(definition, virtualPath, virtualPathDependencies, utcStart); //If the requested file does not exist in the current resolver then keep these dependencies and add dependencies of the next resolver. //This will allow the resolvers higher in the chain to be pinged again when the file might be available to them. if (this.Next != null && !this.CurrentExists(definition, virtualPath)) { var nextDependencies = this.Next.GetCacheDependency(definition, virtualPath, virtualPathDependencies, utcStart); if (nextDependencies != null) { if (result != null) { var aggr = new AggregateCacheDependency(); aggr.Add(result, nextDependencies); result = aggr; } else { result = nextDependencies; } } } return result; }
public static CacheDependency CreateOutputCacheDependency(string dependency) { Sql7DependencyInfo info; if (dependency == null) { throw new HttpException(System.Web.SR.GetString("Invalid_sqlDependency_argument", new object[] { dependency })); } if (StringUtil.EqualsIgnoreCase(dependency, "CommandNotification")) { HttpContext current = HttpContext.Current; SqlCacheDependency dependency2 = new SqlCacheDependency(); current.SqlDependencyCookie = dependency2._sqlYukonDep.Id; return(dependency2); } AggregateCacheDependency dependency3 = null; ArrayList list = ParseSql7OutputCacheDependency(dependency); if (list.Count == 1) { info = (Sql7DependencyInfo)list[0]; return(CreateSql7SqlCacheDependencyForOutputCache(info._database, info._table, dependency)); } dependency3 = new AggregateCacheDependency(); for (int i = 0; i < list.Count; i++) { info = (Sql7DependencyInfo)list[i]; dependency3.Add(new CacheDependency[] { CreateSql7SqlCacheDependencyForOutputCache(info._database, info._table, dependency) }); } return(dependency3); }
//ContentListTypeId //BinaryPropertyTypeIds internal static CacheDependency CreateNodeDataDependency(NodeData nodeData) { if (nodeData == null) { throw new ArgumentNullException("nodeData"); } var aggregateCacheDependency = new System.Web.Caching.AggregateCacheDependency(); aggregateCacheDependency.Add( new NodeIdDependency(nodeData.Id), new PathDependency(nodeData.Path), //new VersionIdDependency(nodeData.VersionId), new NodeTypeDependency(nodeData.NodeTypeId) ); //Add cache dependency for resource files, if //node data contains string resource keys. if (SR.ResourceManager.Running) { var resourcePaths = new List <string>(); //deal with string properties only foreach (var propertyType in nodeData.PropertyTypes.Where(propertyType => propertyType.DataType == Schema.DataType.String)) { AddResourceDependencyIfNeeded(aggregateCacheDependency, nodeData.GetDynamicRawData(propertyType) as string, resourcePaths); } //display name is not a dynamic raw data, add it separately AddResourceDependencyIfNeeded(aggregateCacheDependency, nodeData.DisplayName, resourcePaths); } return(aggregateCacheDependency); }
/// <summary> /// Salva os dados para o cache. /// </summary> /// <param name="key"></param> /// <param name="data"></param> /// <param name="dependency"></param> protected virtual void SaveDataToCacheInternal(string key, object data, CacheDependency dependency) { if (string.IsNullOrEmpty(key)) { throw new ArgumentNullException("key"); } if (!this.Enabled) { throw new InvalidOperationException("Cannot perform operation when cache is not enabled."); } DateTime noAbsoluteExpiration = System.Web.Caching.Cache.NoAbsoluteExpiration; TimeSpan noSlidingExpiration = System.Web.Caching.Cache.NoSlidingExpiration; switch (this.ExpirationPolicy) { case System.Web.UI.DataSourceCacheExpiry.Absolute: noAbsoluteExpiration = DateTime.UtcNow.AddSeconds((this.Duration == 0) ? ((double)0x7fffffff) : ((double)this.Duration)); break; case System.Web.UI.DataSourceCacheExpiry.Sliding: noSlidingExpiration = TimeSpan.FromSeconds((double)this.Duration); break; } var dependencies = new System.Web.Caching.AggregateCacheDependency(); string[] cachekeys = null; if (this.KeyDependency.Length > 0) { cachekeys = new string[] { this.KeyDependency }; dependencies.Add(new CacheDependency[] { new CacheDependency(null, cachekeys) }); } if (dependency != null) { dependencies.Add(new CacheDependency[] { dependency }); } HttpRuntime.Cache.Insert(key, data, dependencies, noAbsoluteExpiration, noSlidingExpiration); }
public void Create(DependencyCreateArgs args) { AggregateDependencyCreateArgs arg = (AggregateDependencyCreateArgs)args; IDependencyWrapper[] wrappers = arg.Wrappers; instance = new AggregateCacheDependency(); foreach (IDependencyWrapper wrapper in wrappers) { instance.Add((CacheDependency)wrapper.Instance); } }
private static CacheDependency CreateNodeDependency(int id, string path, int nodeTypeId) { var aggregateCacheDependency = new System.Web.Caching.AggregateCacheDependency(); aggregateCacheDependency.Add( new NodeIdDependency(id), new PathDependency(path), new NodeTypeDependency(nodeTypeId) ); return aggregateCacheDependency; }
private static CacheDependency CreateNodeDependency(int id, string path, int nodeTypeId) { var aggregateCacheDependency = new System.Web.Caching.AggregateCacheDependency(); aggregateCacheDependency.Add( new NodeIdDependency(id), new PathDependency(path), new NodeTypeDependency(nodeTypeId) ); return(aggregateCacheDependency); }
public static void SetToCache(object dataCache, string cacheName, string[] tableNameInDatabase) { System.Web.Caching.SqlCacheDependency[] sqlDep = new SqlCacheDependency[tableNameInDatabase.Length]; for (int i = 0; i < tableNameInDatabase.Length; i++) { sqlDep[i] = new System.Web.Caching.SqlCacheDependency(DATABASE_NAME, tableNameInDatabase[i]); } System.Web.Caching.AggregateCacheDependency agg = new System.Web.Caching.AggregateCacheDependency(); agg.Add(sqlDep); HttpContext.Current.Cache.Insert(cacheName, dataCache, agg, DateTime.Now.AddDays(1), Cache.NoSlidingExpiration); }
// DevDiv Bugs 162763: // Add a an event that fires *before* an item is evicted from the ASP.NET Cache public void Insert( string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemUpdateCallback onUpdateCallback) { if (dependencies == null && absoluteExpiration == Cache.NoAbsoluteExpiration && slidingExpiration == Cache.NoSlidingExpiration) { throw new ArgumentException(SR.GetString(SR.Invalid_Parameters_To_Insert)); } if (onUpdateCallback == null) { throw new ArgumentNullException("onUpdateCallback"); } DateTime utcAbsoluteExpiration = DateTimeUtil.ConvertToUniversalTime(absoluteExpiration); // Insert updatable cache entry ObjectCache.Insert(key, value, new CacheInsertOptions() { Priority = CacheItemPriority.NotRemovable }); // Ensure the sentinel depends on its updatable entry string[] cacheKeys = { key }; CacheDependency expensiveObjectDep = new CacheDependency(null, cacheKeys); if (dependencies == null) { dependencies = expensiveObjectDep; } else { AggregateCacheDependency deps = new AggregateCacheDependency(); deps.Add(dependencies, expensiveObjectDep); dependencies = deps; } // Insert sentinel entry for the updatable cache entry HttpRuntime.Cache.InternalCache.Insert( CacheInternal.PrefixValidationSentinel + key, new SentinelEntry(key, expensiveObjectDep, onUpdateCallback), new CacheInsertOptions() { Dependencies = dependencies, AbsoluteExpiration = utcAbsoluteExpiration, SlidingExpiration = slidingExpiration, Priority = CacheItemPriority.NotRemovable, OnRemovedCallback = Cache.s_sentinelRemovedCallback }); }
public static void SetCache(DataTable dataCache, string cacheName, string[] tableNameInDatabase) { //System.Web.Caching.SqlCacheDependency sqlDep1 = new System.Web.Caching.SqlCacheDependency(Const.DATABASE_NAME, "tblTradeTransaction"); //System.Web.Caching.SqlCacheDependency sqlDep2 = new System.Web.Caching.SqlCacheDependency(Const.DATABASE_NAME, "tblRemainTransaction"); System.Web.Caching.SqlCacheDependency[] sqlDep = new SqlCacheDependency[tableNameInDatabase.Length]; for (int i = 0; i < tableNameInDatabase.Length; i++) { sqlDep[i] = new System.Web.Caching.SqlCacheDependency(DATABASE_NAME, tableNameInDatabase[i]); } System.Web.Caching.AggregateCacheDependency agg = new System.Web.Caching.AggregateCacheDependency(); //agg.Add(sqlDep1, sqlDep2); agg.Add(sqlDep); HttpContext.Current.Cache.Insert(cacheName, dataCache, agg, DateTime.Now.AddDays(1), Cache.NoSlidingExpiration); }
internal static CacheDependency CreateNodeHeadDependency(NodeHead nodeHead) { if (nodeHead == null) throw new ArgumentNullException("nodeHead", "NodeHead cannot be null."); var aggregateCacheDependency = new System.Web.Caching.AggregateCacheDependency(); aggregateCacheDependency.Add( new NodeIdDependency(nodeHead.Id), new PathDependency(nodeHead.Path) ); return aggregateCacheDependency; }
public static EditorConfiguration GetConfig() { EditorConfiguration editorConfig = null; if ( (HttpRuntime.Cache["mojoEditorConfig"] != null) && (HttpRuntime.Cache["mojoEditorConfig"] is EditorConfiguration) ) { return (EditorConfiguration)HttpRuntime.Cache["mojoEditorConfig"]; } else { String configFileName = "mojoEditor.config"; if (ConfigurationManager.AppSettings["mojoEditorConfigFileName"] != null) { configFileName = ConfigurationManager.AppSettings["mojoEditorConfigFileName"]; } if (!configFileName.StartsWith("~/")) { configFileName = "~/" + configFileName; } String pathToConfigFile = HttpContext.Current.Server.MapPath(configFileName); XmlDocument configXml = new XmlDocument(); configXml.Load(pathToConfigFile); editorConfig = new EditorConfiguration(configXml.DocumentElement); AggregateCacheDependency aggregateCacheDependency = new AggregateCacheDependency(); aggregateCacheDependency.Add(new CacheDependency(pathToConfigFile)); System.Web.HttpRuntime.Cache.Insert( "mojoEditorConfig", editorConfig, aggregateCacheDependency, DateTime.Now.AddYears(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, null); return (EditorConfiguration)HttpRuntime.Cache["mojoEditorConfig"]; } //return editorConfig; }
//ContentListTypeId //BinaryPropertyTypeIds internal static CacheDependency CreateNodeDataDependency(NodeData nodeData) { if (nodeData == null) throw new ArgumentNullException("nodeData"); var aggregateCacheDependency = new System.Web.Caching.AggregateCacheDependency(); aggregateCacheDependency.Add( new NodeIdDependency(nodeData.Id), new PathDependency(nodeData.Path), //new VersionIdDependency(nodeData.VersionId), new NodeTypeDependency(nodeData.NodeTypeId) ); return aggregateCacheDependency; }
internal static CacheDependency CreateNodeHeadDependency(NodeHead nodeHead) { if (nodeHead == null) { throw new ArgumentNullException("nodeHead", "NodeHead cannot be null."); } var aggregateCacheDependency = new System.Web.Caching.AggregateCacheDependency(); aggregateCacheDependency.Add( new NodeIdDependency(nodeHead.Id), new PathDependency(nodeHead.Path) ); return(aggregateCacheDependency); }
protected override void SaveDataToCacheInternal(string key, object data, CacheDependency dependency) { string[] array = new string[this.FileDependencies.Count]; this.FileDependencies.CopyTo(array, 0); CacheDependency dependency2 = new CacheDependency(0, array); if (dependency != null) { AggregateCacheDependency dependency3 = new AggregateCacheDependency(); dependency3.Add(new CacheDependency[] { dependency2, dependency }); dependency = dependency3; } else { dependency = dependency2; } base.SaveDataToCacheInternal(key, data, dependency); }
//ContentListTypeId //BinaryPropertyTypeIds internal static CacheDependency CreateNodeDataDependency(NodeData nodeData) { if (nodeData == null) { throw new ArgumentNullException("nodeData"); } var aggregateCacheDependency = new System.Web.Caching.AggregateCacheDependency(); aggregateCacheDependency.Add( new NodeIdDependency(nodeData.Id), new PathDependency(nodeData.Path), //new VersionIdDependency(nodeData.VersionId), new NodeTypeDependency(nodeData.NodeTypeId) ); return(aggregateCacheDependency); }
/// <devdoc> /// Saves data to the ASP.NET cache using the specified key. /// </devdoc> protected override void SaveDataToCacheInternal(string key, object data, CacheDependency dependency) { int fileCount = FileDependencies.Count; string[] filenames = new string[fileCount]; FileDependencies.CopyTo(filenames, 0); CacheDependency fileDependency = new CacheDependency(0, filenames); if (dependency != null) { // There was another dependency passed in, aggregate them AggregateCacheDependency aggregateDependency = new AggregateCacheDependency(); aggregateDependency.Add(fileDependency, dependency); dependency = aggregateDependency; } else { // No other dependencies, just the file one dependency = fileDependency; } base.SaveDataToCacheInternal(key, data, dependency); }
protected override void SaveDataToCacheInternal(string key, object data, CacheDependency dependency) { string sqlCacheDependency = this.SqlCacheDependency; if ((sqlCacheDependency.Length > 0) && !string.Equals(sqlCacheDependency, "CommandNotification", StringComparison.OrdinalIgnoreCase)) { CacheDependency dependency2 = System.Web.Caching.SqlCacheDependency.CreateOutputCacheDependency(sqlCacheDependency); if (dependency != null) { AggregateCacheDependency dependency3 = new AggregateCacheDependency(); dependency3.Add(new CacheDependency[] { dependency2, dependency }); dependency = dependency3; } else { dependency = dependency2; } } base.SaveDataToCacheInternal(key, data, dependency); }
public static CacheDependency CreateOutputCacheDependency(string dependency) { if (dependency == null) { throw new HttpException(InvalidDependencyFormatMessage(dependency)); } if (dependency.Length == 0) { throw new ArgumentException(InvalidDependencyFormatMessage(dependency), "dependency"); } int colon; string[] pairs = dependency.Split(';'); var dependencies = new List <SqlCacheDependency> (); foreach (string pair in pairs) { colon = pair.IndexOf(':'); if (colon == -1) { throw new ArgumentException(InvalidDependencyFormatMessage(dependency), "dependency"); } dependencies.Add(new SqlCacheDependency(pair.Substring(0, colon), pair.Substring(colon + 1))); } switch (dependencies.Count) { case 0: return(null); case 1: return(dependencies [0]); default: var acd = new AggregateCacheDependency(); acd.Add(dependencies.ToArray()); return(acd); } }
private static void AddCacheKeyToDependencies(ref CacheDependency dependencies, string cacheKey) { CacheDependency dependency = new CacheDependency(0, null, new string[] { cacheKey }); if (dependencies == null) { dependencies = dependency; } else { AggregateCacheDependency dependency2 = dependencies as AggregateCacheDependency; if (dependency2 != null) { dependency2.Add(new CacheDependency[] { dependency }); } else { dependency2 = new AggregateCacheDependency(); dependency2.Add(new CacheDependency[] { dependency, dependencies }); dependencies = dependency2; } } }
public static Collection<WebPageInfo> GetPhysicalPages( string fileExtensionPattern) { Collection<WebPageInfo> physicalPages = null; string cachekey = "physicalwebpages" + fileExtensionPattern; if ( (HttpContext.Current != null) && (HttpRuntime.Cache[cachekey] == null) ) { log.Debug("couldn't find cache item " + cachekey + " creating cache item now."); physicalPages = LoadPhysicalPages(fileExtensionPattern); AggregateCacheDependency aggregateCacheDependency = new AggregateCacheDependency(); aggregateCacheDependency.Add(new CacheDependency(HttpContext.Current.Server.MapPath("~/Web.config"))); DateTime absoluteExpiration = DateTime.Now.AddMinutes(WebConfigSettings.WebPageInfoCacheMinutes); TimeSpan slidingExpiration = TimeSpan.Zero; CacheItemPriority priority = CacheItemPriority.Default; CacheItemRemovedCallback callback = null; HttpRuntime.Cache.Insert( cachekey, physicalPages, aggregateCacheDependency, absoluteExpiration, slidingExpiration, priority, callback); } physicalPages = HttpRuntime.Cache[cachekey] as Collection<WebPageInfo>; return physicalPages; }
/// <devdoc> /// Saves data to the ASP.NET cache using the specified key. /// </devdoc> protected override void SaveDataToCacheInternal(string key, object data, CacheDependency dependency) { string sqlCacheDependency = SqlCacheDependency; // Here we only create cache dependencies for SQL Server 2000 and // earlier that use a polling based mechanism. For SQL Server 2005 // and after, the data source itself creates the SqlCacheDependency // and passes it in as a parameter. if (sqlCacheDependency.Length > 0 && !String.Equals(sqlCacheDependency, Sql9CacheDependencyDirective, StringComparison.OrdinalIgnoreCase)) { // Call internal helper method to parse the dependency list CacheDependency sqlDependency = System.Web.Caching.SqlCacheDependency.CreateOutputCacheDependency(sqlCacheDependency); if (dependency != null) { // There was another dependency passed in, aggregate them AggregateCacheDependency aggregateDependency = new AggregateCacheDependency(); aggregateDependency.Add(sqlDependency, dependency); dependency = aggregateDependency; } else { // No other dependencies, just the SQL one dependency = sqlDependency; } } base.SaveDataToCacheInternal(key, data, dependency); }
/// <summary> /// Creates the cache item for the cache region which all other cache items in the region /// will be dependent upon /// </summary> /// <remarks> /// <para>Specified Region dependencies will be associated to the cache item</para> /// </remarks> private void CacheRootItem() { if (log.IsDebugEnabled) { log.DebugFormat("Creating root cache entry for cache region: {0}", _name); } //register ant cache dependencies for change notifications //and build an aggragate dependency if multiple dependencies exist CacheDependency rootCacheDependency = null; if (_dependencyEnlisters.Count > 0) { var dependencies = new List<CacheDependency>(_dependencyEnlisters.Count); foreach (ICacheDependencyEnlister enlister in _dependencyEnlisters) { log.Debug("Enlisting cache dependency for change notification"); dependencies.Add(enlister.Enlist()); } if (dependencies.Count == 1) { rootCacheDependency = dependencies[0]; } else { var jointDependency = new AggregateCacheDependency(); jointDependency.Add(dependencies.ToArray()); rootCacheDependency = jointDependency; } log.Debug("Attaching cache dependencies to root cache entry. Cache entry will be removed when change is detected."); } _webCache.Add(_rootCacheKey, _rootCacheKey, rootCacheDependency, System.Web.Caching.Cache.NoAbsoluteExpiration, System.Web.Caching.Cache.NoSlidingExpiration, _priority, RootCacheItemRemovedCallback); //flag the root cache item as beeing cached _isRootItemCached = true; }
/// <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 CacheDependency GetDependencies() { if (string.IsNullOrEmpty(SqlDependencyName)) return null; var a = new AggregateCacheDependency(); foreach (string t in WatchTables) { a.Add(new SqlCacheDependency(SqlDependencyName, t)); } return a; }
// DevDiv Bugs 162763: // Add a an event that fires *before* an item is evicted from the ASP.NET Cache public void Insert( string key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration, CacheItemUpdateCallback onUpdateCallback) { if (dependencies == null && absoluteExpiration == Cache.NoAbsoluteExpiration && slidingExpiration == Cache.NoSlidingExpiration) { throw new ArgumentException(SR.GetString(SR.Invalid_Parameters_To_Insert)); } if (onUpdateCallback == null) { throw new ArgumentNullException("onUpdateCallback"); } DateTime utcAbsoluteExpiration = DateTimeUtil.ConvertToUniversalTime(absoluteExpiration); // Insert updatable cache entry _cacheInternal.DoInsert ( true, key, value, null, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, null, true); // Ensure the sentinel depends on its updatable entry string[] cacheKeys = { key }; CacheDependency expensiveObjectDep = new CacheDependency(null, cacheKeys); if (dependencies == null) { dependencies = expensiveObjectDep; } else { AggregateCacheDependency deps = new AggregateCacheDependency(); deps.Add(dependencies, expensiveObjectDep); dependencies = deps; } // Insert sentinel entry for the updatable cache entry _cacheInternal.DoInsert( false, CacheInternal.PrefixValidationSentinel + key, new SentinelEntry(key, expensiveObjectDep, onUpdateCallback), dependencies, utcAbsoluteExpiration, slidingExpiration, CacheItemPriority.NotRemovable, Cache.s_sentinelRemovedCallback, true); }
internal CacheDependency CreateCacheDependency(CacheDependencyType dependencyType, CacheDependency dependency) { if (this._dependencies != null) { if ((dependencyType == CacheDependencyType.Files) || (dependencyType == CacheDependencyType.CacheItems)) { foreach (ResponseDependencyInfo info in this._dependencies) { using (CacheDependency dependency2 = dependency) { if (dependencyType == CacheDependencyType.Files) { dependency = new CacheDependency(0, info.items, null, dependency2, info.utcDate); } else { dependency = new CacheDependency(null, info.items, dependency2, DateTimeUtil.ConvertToLocalTime(info.utcDate)); } } } return dependency; } CacheDependency dependency3 = null; VirtualPathProvider virtualPathProvider = HostingEnvironment.VirtualPathProvider; if ((virtualPathProvider != null) && (this._requestVirtualPath != null)) { dependency3 = virtualPathProvider.GetCacheDependency(this._requestVirtualPath, this.GetDependencies(), this._oldestDependency); } if (dependency3 == null) { return dependency; } AggregateCacheDependency dependency4 = new AggregateCacheDependency(); dependency4.Add(new CacheDependency[] { dependency3 }); if (dependency != null) { dependency4.Add(new CacheDependency[] { dependency }); } dependency = dependency4; } return dependency; }
public override SiteMapNode BuildSiteMap() { // Use a lock to make this method thread-safe lock (siteMapLock) { // First, see if we already have constructed the // rootNode. If so, return it... if (root != null) { return(root); } // We need to build the site map! // Clear out the current site map structure base.Clear(); // Get the categories and products information from the database ProductsBLL productsAPI = new ProductsBLL(); Northwind.ProductsDataTable products = productsAPI.GetProducts(); // Create the root SiteMapNode root = new SiteMapNode( this, "root", "~/SiteMapProvider/Default.aspx", "All Categories"); AddNode(root); // Create SiteMapNodes for the categories and products foreach (Northwind.ProductsRow product in products) { // Add a new category SiteMapNode, if needed string categoryKey, categoryName; bool createUrlForCategoryNode = true; if (product.IsCategoryIDNull()) { categoryKey = "Category:None"; categoryName = "None"; createUrlForCategoryNode = false; } else { categoryKey = string.Concat("Category:", product.CategoryID); categoryName = product.CategoryName; } SiteMapNode categoryNode = FindSiteMapNodeFromKey(categoryKey); // Add the category SiteMapNode if it does not exist if (categoryNode == null) { string productsByCategoryUrl = string.Empty; if (createUrlForCategoryNode) { productsByCategoryUrl = "~/SiteMapProvider/ProductsByCategory.aspx?CategoryID=" + product.CategoryID; } categoryNode = new SiteMapNode( this, categoryKey, productsByCategoryUrl, categoryName); AddNode(categoryNode, root); } // Add the product SiteMapNode string productUrl = "~/SiteMapProvider/ProductDetails.aspx?ProductID=" + product.ProductID; SiteMapNode productNode = new SiteMapNode( this, string.Concat("Product:", product.ProductID), productUrl, product.ProductName); AddNode(productNode, categoryNode); } // Add a "dummy" item to the cache using a SqlCacheDependency // on the Products and Categories tables System.Web.Caching.SqlCacheDependency productsTableDependency = new System.Web.Caching.SqlCacheDependency("NorthwindDB", "Products"); System.Web.Caching.SqlCacheDependency categoriesTableDependency = new System.Web.Caching.SqlCacheDependency("NorthwindDB", "Categories"); // Create an AggregateCacheDependency System.Web.Caching.AggregateCacheDependency aggregateDependencies = new System.Web.Caching.AggregateCacheDependency(); aggregateDependencies.Add(productsTableDependency, categoriesTableDependency); // Add the item to the cache specifying a callback function HttpRuntime.Cache.Insert( CacheDependencyKey, DateTime.Now, aggregateDependencies, Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, new CacheItemRemovedCallback(OnSiteMapChanged)); // Finally, return the root node return(root); } }
public static mojoProfileConfiguration GetConfig() { mojoProfileConfiguration profileConfig = null; string cacheKey = GetCacheKey(); if ( (System.Web.HttpRuntime.Cache[cacheKey] != null) && (System.Web.HttpRuntime.Cache[cacheKey] is mojoProfileConfiguration) ) { return (mojoProfileConfiguration)System.Web.HttpRuntime.Cache[cacheKey]; } else { string configFileName = GetConfigFileName(); if (configFileName.Length == 0) { return profileConfig; } if (!configFileName.StartsWith("~/")) { configFileName = "~/" + configFileName; } string pathToConfigFile = HttpContext.Current.Server.MapPath(configFileName); XmlDocument configXml = new XmlDocument(); configXml.Load(pathToConfigFile); profileConfig = new mojoProfileConfiguration(configXml.DocumentElement); AggregateCacheDependency aggregateCacheDependency = new AggregateCacheDependency(); aggregateCacheDependency.Add(new CacheDependency(pathToConfigFile)); // more dependencies can be added if needed System.Web.HttpRuntime.Cache.Insert( cacheKey, profileConfig, aggregateCacheDependency, DateTime.Now.AddYears(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, null); return (mojoProfileConfiguration)System.Web.HttpRuntime.Cache[cacheKey]; } }
internal CacheDependency CreateCacheDependencyForResponse() { if (this._cacheDependencyForResponse == null) { CacheDependency dependency = this._cacheItemDependencyList.CreateCacheDependency(CacheDependencyType.CacheItems, null); dependency = this._fileDependencyList.CreateCacheDependency(CacheDependencyType.Files, dependency); dependency = this._virtualPathDependencyList.CreateCacheDependency(CacheDependencyType.VirtualPaths, dependency); if (this._userAddedDependencies != null) { AggregateCacheDependency dependency2 = new AggregateCacheDependency(); dependency2.Add(this._userAddedDependencies); if (dependency != null) { dependency2.Add(new CacheDependency[] { dependency }); } this._userAddedDependencies = null; this._cacheDependencyForResponse = dependency2; } else { this._cacheDependencyForResponse = dependency; } } return this._cacheDependencyForResponse; }
public static TinyMceConfiguration GetConfig() { TinyMceConfiguration config = new TinyMceConfiguration(); try { if ( (HttpRuntime.Cache["mojoTinyConfiguration"] != null) && (HttpRuntime.Cache["mojoTinyConfiguration"] is TinyMceConfiguration) ) { return (TinyMceConfiguration)HttpRuntime.Cache["mojoTinyConfiguration"]; } string pathToConfigFile = HostingEnvironment.MapPath("~/" + GetConfigFileName()); XmlDocument configXml = new XmlDocument(); configXml.Load(pathToConfigFile); if(WebConfigSettings.TinyMceUseV4) { config.LoadV4FromConfigurationXml(configXml.DocumentElement); } else { config.LoadValuesFromConfigurationXml(configXml.DocumentElement); } AggregateCacheDependency aggregateCacheDependency = new AggregateCacheDependency(); string pathToWebConfig = HostingEnvironment.MapPath("~/Web.config"); aggregateCacheDependency.Add(new CacheDependency(pathToWebConfig)); HttpRuntime.Cache.Insert( "mojoTinyConfiguration", config, aggregateCacheDependency, DateTime.Now.AddYears(1), TimeSpan.Zero, CacheItemPriority.Default, null); return (TinyMceConfiguration)HttpRuntime.Cache["mojoTinyConfiguration"]; } catch (HttpException ex) { log.Error(ex); } catch (XmlException ex) { log.Error(ex); } catch (ArgumentException ex) { log.Error(ex); } catch (NullReferenceException ex) { log.Error(ex); } return config; }
// // private helper methods // private static void AddCacheKeyToDependencies(ref CacheDependency dependencies, string cacheKey) { CacheDependency keyDep = new CacheDependency(0, null, new string[1] {cacheKey}); if (dependencies == null) { dependencies = keyDep; } else { // if it's not an aggregate, we have to create one because you can't add // it to anything but an aggregate AggregateCacheDependency agg = dependencies as AggregateCacheDependency; if (agg != null) { agg.Add(keyDep); } else { agg = new AggregateCacheDependency(); agg.Add(keyDep, dependencies); dependencies = agg; } } }
/// <devdoc> /// Returns the XmlDocument representing the XML data. /// If necessary, the XML data will be reloaded along with the transform, if available. /// </devdoc> public XmlDocument GetXmlDocument() { string cacheKey = null; if (!_cacheLookupDone && Cache.Enabled) { // If caching is enabled, attempt to load from cache. cacheKey = CreateCacheKey(); _xmlDocument = Cache.LoadDataFromCache(cacheKey) as XmlDocument; _cacheLookupDone = true; } if (_xmlDocument == null) { // Load up the data _xmlDocument = new XmlDocument(); CacheDependency transformCacheDependency; CacheDependency dataCacheDependency; PopulateXmlDocument(_xmlDocument, out dataCacheDependency, out transformCacheDependency); if (cacheKey != null) { Debug.Assert(Cache.Enabled); // If caching is enabled, save the XmlDocument to cache. CacheDependency fileDependency; if (dataCacheDependency != null) { if (transformCacheDependency != null) { // We have both a data file as well as a transform file dependency AggregateCacheDependency aggregateDependency = new AggregateCacheDependency(); aggregateDependency.Add(dataCacheDependency, transformCacheDependency); fileDependency = aggregateDependency; } else { // We only have a data file dependency fileDependency = dataCacheDependency; } } else { // We have at most only a transform file dependency (or no dependency at all) fileDependency = transformCacheDependency; } Cache.SaveDataToCache(cacheKey, _xmlDocument, fileDependency); } } return _xmlDocument; }
public static PayPalIPNHandlerProviderConfig GetConfig() { try { if ( (HttpRuntime.Cache["PayPalIPNHandlerProviderConfig"] != null) && (HttpRuntime.Cache["PayPalIPNHandlerProviderConfig"] is PayPalIPNHandlerProviderConfig) ) { return (PayPalIPNHandlerProviderConfig)HttpRuntime.Cache["PayPalIPNHandlerProviderConfig"]; } PayPalIPNHandlerProviderConfig config = new PayPalIPNHandlerProviderConfig(); String configFolderName = "~/Setup/ProviderConfig/paypalipnhandlers/"; 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( "PayPalIPNHandlerProviderConfig", config, aggregateCacheDependency, DateTime.Now.AddYears(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, null); return (PayPalIPNHandlerProviderConfig)HttpRuntime.Cache["PayPalIPNHandlerProviderConfig"]; } 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 IndexBuilderConfiguration GetConfig() { try { if ( (HttpRuntime.Cache["mojoIndexBuilderConfiguration"] != null) && (HttpRuntime.Cache["mojoIndexBuilderConfiguration"] is IndexBuilderConfiguration) ) { return (IndexBuilderConfiguration)HttpRuntime.Cache["mojoIndexBuilderConfiguration"]; } 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( "mojoIndexBuilderConfiguration", indexBuilderConfig, aggregateCacheDependency, DateTime.Now.AddYears(1), TimeSpan.Zero, System.Web.Caching.CacheItemPriority.Default, null); return (IndexBuilderConfiguration)HttpRuntime.Cache["mojoIndexBuilderConfiguration"]; } 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; }