Don't you just hate it when you release some CSS to a live site but the client's browser doesn't pull down the latest version and the site they see looks horrific?
This article talks you through a simple control I have created that forces the browser to retrieve the latest version of a CSS include.
Using the Code
From a usage point of view, we just need to drag and drop the control from the toolbox. The user specific properties can be set either during design time or runtime.
Below is the markup that will need to be used in your ASP.NET Web Form or User Control:
<CWeb:CSSInclude ID="CSSInclude1" runat="server"
Rel="stylesheet" Type="text/css" CacheKey="BaseCSS" />
The properties supported by the control are:
HRef - Gets or sets the
href to the CSS file in the resulting link element.
Rel - Gets or sets the
rel for the resulting link element.
Type - Gets or sets the type for the resulting link element.
CacheKey - Gets or sets the cache key name to be used to store version information about the CSS file in the cache.
The control creates a date stamp based on the last write time to the file. This date stamp is then stored in the cache and a cache dependency is created against the CSS file. When the file changes, the date stamp will change, therefore the client will get the latest stylesheet.
Below is the code used to get the version information for the file:
private string GetIncludeUrlWithVersion()
string url = string.Empty;
string version = "1";
throw new ArgumentException("The cacheKey must have a value.");
if (Page.Cache[CacheKey] == null)
FileInfo fileInfo = new FileInfo(Page.Server.MapPath(HRef));
version = fileInfo.LastWriteTime.ToString("ddMMyyyyhhmmss");
CacheDependency cacheDependency = new CacheDependency(fileInfo.FullName);
Page.Cache.Insert(CacheKey, version, cacheDependency,);
version = Page.Cache[CacheKey] as string;
return ResolveUrl(HRef) + "?v=" + version;
Points of Interest
The same technique could also be used with script includes to force the browser to pull down the latest versions of js files. The caching issue could also be prevented through the client browser, through IIS, or by adding custom headers to the outgoing response. The technique I have described here is just another way of achieving the same result :)
- 14th January, 2010: Initial version.
I have been developing web and software applications for 9 years originally in Microsoft Visual Fox Pro. But for the last 8 years I have been using Microsoft.Net.
I love writing code and especially enjoy writing tools to aid development.
I have developed my own code generator which generates C# code from a SQL Server database. The generator generates Business Components, Data Components and entities and is optimised for performance as it uses stored procedures and SqlDataReaders.
FrameworkGen can be downloaded for free from http://www.elencysolutions.co.uk.