My Development Notes

By Haemoglobin
3/10/2010 (revision 1)

Caching

Cache.Insert("FileCache", "CacheContents", new System.Web.Caching.CacheDependency(Server.MapPath("SourceFile.xml"))); 
//Or use for multiple dependencies
new AggregateCacheDependency().Add(new CacheDependency()); 

//Absolute
Cache.Insert("FileCache", "CacheContents", null, DateTime.Now.AddMinutes(10), Cache.NoSlidingExpiration);

//Sliding (renewed when accessed) - note any access to cache can be null if it has been removed.
Cache.Insert("Cached Item", "CacheContents", null, Cache.NoAboluteExpiration, new TimeSpan(0,10,0));

Page output caching

    //In page
    <%@ OutputCache Duration="15" VaryByParam="none" Location="Any(Default)|Client|Downstream|Server|None"%> 
    <%@ OutputCache Duration="15" VaryByParam="location;count" %> 

    <%@ OutputCache Duration="15" VaryByControl="State" %>  //VaryByHeader, VaryByCustom, SqlDependency

    Response.Cache.SetExpires(DateTime.Now.AddSeconds(60))
    Response.Cache.SetCacheability(HttpCacheability.Public(Any)|Private(Client)|Server|)

VaryByControl stores a separate cache entry for every different value for that control.
Parts of the page (non-dynamic) can be cached by creating a user control and adding OutputCache directive.

Substitution

All parts of page cached except Substitution control.

Page_Load() {
    Substitution1.MethodName = "GetCurrentDateTime"; 
}

public static string GetCurrentDateTime(HttpContext context) {
    return DateTime.Now.ToString(); 
}

Invalidating Cached Pages

Page_Load() {
    Response.Cache.AddValidationCallback(new HttpCacheValidateHandler(ValidateCacheOutput), null); 
}

public static void ValidateCacheOutput(HttpContext context, Object data, ref HttpValidationStatus status) {
    status = HttpValidationStatus.Invalid; //refresh cache 
    status = HttpValidationStatus.IgnoreThisRequests; //dynamically generate this request but don't invalidate existing cache. 
    status = HttpValidationStatus.Valid; //use cached copy 

}

//Create cache dependency
Response.AddCacheDependency(cacheDependency); 
Response.AddCacheItemDependency(anotherCacheItem); 
Response.AddFileDependency(file); 

Entire Application Caching Configuration

caching
    outputCacheSettings
        add name="OneMinuteProfile" enabled="true" duration="60" [other OutputCache properties]

<%@ OutputCache CacheProfile="OneMinuteProfile" VaryByParam="none" %> //can override properties in profile at page level. 

Comments

Powered by BlogEngine.NET 1.6.1.0 | Design by styleshout | Enhanced by GravityCube.net | 1.4.5 Changes by zembian.com | Adapted by HamishGraham.NET
(c) 2010 Hamish Graham. Banner Image (c) Chris Gin