Simplify data caching with the .NET Caching Application Block

The Caching Application Block can save time and resources by caching Web services data for your distributed apps. It also offers a system for data security, expiration and scavenging, and a variety of storage options. See what the CAB has to offer.

The Caching Application Block (CAB) is designed to work with the Aggregation Application Block and Asynchronous Invocation Application Block to improve the availability, scalability, and performance of .NET-based Web services. It's also useful for other tasks, such as providing access to rarely used data from costly storage devices, like the file system.

Although ASP.NET and Windows Forms each has state management solutions, the CAB provides a much broader solution. Aside from being open source and able to fit fully with new solutions regardless of how they work with the .NET Framework, the CAB also has a system for data security, expiration and scavenging, and a number of storage options. These options make it suitable for practically any state management problem for any system.

Getting started
You can download the CAB from the Patterns and Practices pages. You must load the project after installing the package and build the blocks using Visual Studio .NET 2002 or 2003 (or the command line SDK). You'll need an assembly reference on each file or form or a base class:
using Microsoft.ApplicationBlocks.Cache;

Also, these namespaces may be useful for your project when using their functionality:
using Microsoft.ApplicationBlocks.Cache.DataProtection
using Microsoft.ApplicationBlocks.Cache.Expirations
using Microsoft.ApplicationBlocks.Cache.Scavenging
using Microsoft.ApplicationBlocks.Cache.Storages

If SQL Server is your chosen caching space, you will need to run the CachingFrameworkScripts.sql file using Query Analyzer. This file is part of the downloaded MSI file. When building the project for initial use, pay careful attention to the App.Config file in the solutions items where the storage is defined. For instance, an appropriate StorageInfo key for a SQL Server database might look like the following:
ConnectionString="user id=user;

In addition, if you are using scavenging, expiration, or a custom storage class, the details are stored in another configuration file, CacheStorage.Config. This file is also used by the Microsoft.ApplicationBlocks.Cache.dll build and describes the options needed for those features.

Using the CAB
The CAB can be used for the simplest of state management solutions. For instance, one of the most common reasons for caching small pieces of data is accessing a Web service. Because of the network overhead involved with this operation, storing the results for a short period of time is preferable to repeatedly calling a method over the network. Let's examine an example of a temperature service.

We have an application that uses the ambient temperature in various cities for user needs. Rather than call the CapeScience GlobalWeather service every time a city is requested, we want to cache the values for the most often used cities.

The service has a private method called temperature, which accepts the airportCode and returns the temperature:
private string temperature(string airportCode) {
//Get the cache object
CacheManager cacheManager = CacheManager.GetCacheManager();
//Check to see if the value is in the cache already
//We used the airport code as the key
object weather = cacheManager.GetData(airportCode);
if (weather==null) {
//It's not there, so we need to go get it.
//Get the weather objects globalWeather =
new; weatherReport =
//Get the weather specified in the textbox
weatherReport = globalWeather.getWeatherReport(airportCode);
//And, get the temp from that weatherReport object
temperature = weatherReport.temperature.ambient.ToString();
//Next we are going to store it.
//We will use the airport code as the key
//just like we checked above.
cacheManager.Add(airportCode, temperature);
} else {
//The result of the caching operation is an object
//so we need to convert to a string.
temperature = weather.ToString();
//return the temperature.
return temperature;

The code assumes the cache has the value, but a new lookup is performed when nothing is returned. Storing and retrieving cache data is as simple as using the ASP.NET ViewState object. The SqlServerCacheStorage class references the Data Application Block for database functionality.

Additional functionality
The methods above could be implemented using existing tools with a minimum of code. Four major additional namespaces provide the functionality you can't find in the various ASP.NET state models:
  • DataProtection contains DefaultDataProtection, which defines the methods that implement the Win32 Data Protection API. These help you fight against data spoofing attacks.
  • Expirations define four classes that help you get rid of old data. AbsoluteTime describes a traditional expire date. ExtendedFormatTime gives a few more options to the timing style. FileDependancy uses file deltas to determine expiration. SlidingTime is the most useful, and it bases expiration on when the item was last used.
  • Scavenging implements LruScavenging, which uses a least recently used model similar to SlidingTime to remove cached items when storage gets below defined minimums.
  • Storages allow us to choose from a plethora of options that determine where to put the cache. Three sample storage models are included with the block: MmfCacheStorage, SingletonCacheStorage, and SqlServerCacheStorage.

The CAB fits right in with the Exception Management and Data Blocks as code you can use in your systems today. With a basic implementation and a series of complex options, it can fit in a variety of situations.

Editor's Picks