Project Description
The WebCacheHelper provides an easy to use strongly typed abstraction on top of the Session and Cache classes of ASP.NET. The Session and Cache classes are useful in many scenarios, and this small library makes working with them a little easier and less prone to errors. In addition, there's also support for file caching which uses a CacheDependency to ensure cached copies of files remain up to date.

Session and Cache
Using this library is as simple as declaring your static variables...

public readonly static WebCacheHelper.Session<string> Username = new WebCacheHelper.Session<string>();

public readonly static WebCacheHelper.Session<DateTime> LastVisit = new WebCacheHelper.Session<DateTime>();

public readonly static WebCacheHelper.Cache<int> RegisteredUserCount = new WebCacheHelper.Cache<int>(new TimeSpan(0, 0, 5));

And then accessing them with the Value property like so...
Globals.Username.Value = "SWortham";
Globals.LastVisit.Value = DateTime.Now;
Globals.RegisteredUserCount.Value++;

And since the Value property is strongly typed, you don't have to perform any type checking or conversions in your code.

You can also supply the Cache object with an interval and a function. The return value of the function is used to set the initial value of the cache, and is then called again at the specified interval. You'd do that like this...

public readonly static WebCacheHelper.Cache<int> RegisteredUsersCount = new WebCacheHelper.Cache<int>(new TimeSpan(0, 5, 0), () => GetRegisteredUsersCount()); 

In effect this will call GetRegisteredUsersCount() when the cache is first accessed, and again every 5 minutes after that. The subsequent calls are done with System.Threading.Timer behind the scenes, which means that it's actually running on a background thread.

FileCache
The FileCache class is a little different as it only contains a few static members and doesn't require you to instantiate an object. For example, if you wanted to read all the text from a file you could do this...

ViewBag.Message = WebCacheHelper.FileCache.ReadAllTextRelative("~/welcome.txt");

The benefits here are enormous since reading a file from the file system repeatedly is very expensive. Using FileCache can be over 100 times faster. Behind the scenes this is also calling WebCacheHelper.FileCache.MapPath which caches the result of a call to System.Web.Hosting.HostingEnvironment.MapPath for even more performance.

Last edited Jul 16, 2012 at 6:12 AM by SWortham, version 11