What are Microsoft patterns & practices?

Microsoft patterns & practices provide scenario-specific recommendations illustrating how to design, develop, deploy, and operate architecturally sound applications for the Microsoft .NET platform. They offer deep technical guidance based on real-world experience that goes far beyond typical white papers and sample applications to help you quickly deliver sound solutions. Patterns & Practices provide proven architectures, production quality code, and recommended engineering practices. The technical guidance is created, reviewed, and approved by Microsoft architects, engineering teams, consultants, product support engineers, and by Microsoft partners and customers. The result is a thoroughly engineered and tested set of recommendations that can be followed with confidence when building your applications.

Microsoft patterns & practices are proven practices to help you generate predictable results.

The following article covers details on the Caching Application Block:

Enterprise Library Caching Application Block

The Developers and Architects of Enterprise applications and services need to overcome challenges such as

How does the Caching Application Block address the above issues?

Where can the Caching Application Block be used?

Developers can incorporate a local cache in their applications. This application block supports both In-memory cache and Backing store

The Caching Application Block can be used with any of the following application types:

Design of the Caching Application Block

The Goal of this design:

The CacheManager class is the primary interface between the application and the rest of the Caching Application Block. It handles operations related to Caching by creating a Cache object which is an in-memory representation of the Backing Store. Backing stores account for the persistence of cached data even if the application crashes.

This Manager class can be configured to store data only in memory, or it can be configured to store data both in memory and in persistent storage. The persistent storage is specified when you configure the backing store (discussed later).

To create an instance of a CacheManager object, the application uses the CacheFactory class, which in turn uses the CacheManagerFactory class. The CacheManagerFactory class creates all the internal classes needed to implement a CacheManager object.

Applications use the cached data via the CacheManager by invoking the GetData method on it. If the data is not present in the cache a NULL value is returned. The Add method on the CacheManager allows the addition of data (associated with a key) to the Cache. If the key already exists, the earlier data is overwritten with the new value.

Items added to the cache are represented as Cache Item. The Cache Item is stored in the in-memory hash table and has the following information:

This in-memory HashTable provides a locking strategy when adding new items if not found in the Hash table.

This Block adopts a strong exception safety guarantee. A failure in the Add operation results in the Cache being reverted to the state before the item was added.

A BackgroundScheduler object is responsible for expiring aging cache items and scavenging lower-priority cache items. A PollTimer object triggers the expiration cycle and a numeric limit triggers the scavenging process. These are set in the configuration file.

Steps in Configuring the Caching Application Block

Configuring the Cache Application Block involves 3 processes

The following figure represents a Configured Cached Application Block.

Fig: The Enterprise Configuration Manager to Configure the Caching Block.

Complete Steps:

If data needs to be written to a backing store, there are four options provided that enables you to configure the Caching Application Block.

By default, the cache stores items only in memory and assigns the value of the backing store to NullBackingStore. The Null Backing Store does not persist cached items.

The Data Cache Storage option uses the Data Access Application Block as a database provider and lets you store the cached data in a database. Appropriate Database Settings need to be configured and the relevant Database Instance node must be referenced for caching purposes. The Data Access Application Block backing store option is suitable for smart clients and for server applications where each application domain has its own cache, and where you have access to a database.

The Isolated storage uses a Partition Name to identify the portion of the isolated store that the cache manager will use. The Partition Name is an attribute that needs to be set on this Backing Store. When configuring to use isolated storage, the backing store is isolated by the cache instance name, the user name, the assembly, and the application domain.

Note: Since isolated storage is always segregated by user, server applications must impersonate the user making a request to the application

Isolated storage is appropriate in the following situations:

Scenarios where Isolated Storage should not be used:

The Custom Cache Storage option can be used if a custom backing store is being added.

Note An application can use more than one cache; each cache will be represented by a cache manager in the application's configuration. The Caching Application Block does not support the use of the same persistent backing store location and partition name by multiple cache managers in an application.

Cache Operations

Instantiating the CacheManager

NOTE : The following namespace must be included.

using Microsoft.Practices.EnterpriseLibrary.Caching;
using Microsoft.Practices.EnterpriseLibrary.Caching.Expirations;

CacheManager cacheManager;
cacheManager = CacheFactory.GetCacheManager("DataCacheManager");

Adding Items to Cache

The following code shows how to use the Add method. Add the code to the method that responds to the request to add an item to the cache.

string id="OrderId";
string name = "OrderName";
int price = 50;
Order order = new Order(id, name, price);
cacheManager.Add(order.id, order, 2, null, new SlidingTime(TimeSpan.FromMinutes(5)));

Note:
Defaults

Flushing the Cache

The following code shows how to use the Flush method. Add the code to the method that responds to the request to flush the cache.

cacheManager.Flush();

Removing an Item from Cache

The following code shows how to use the Remove method. Add the code to the method that responds to the request to remove an item from the cache.

cacheManager.Remove(order.id);

Retrieving data from Cache

The following code shows how to use the GetData method. Add the code to the method responding to the request to retrieve an item from the cache.

Order order = (Order) cacheManager.GetData(12);

Loading the Cache

There are two methods you can use for loading data:

The Expiration Policies

The Caching Application Block's expiration process is performed by the BackgroundScheduler. It periodically examines the CacheItems in the hash table to see if any items have expired. You control how frequently the expiration cycle occurs when you configure an instance of the CacheManager using the Configuration Console.

NOTE : The following namespace must be included

using Microsoft.Practices.EnterpriseLibrary.Caching;
using Microsoft.Practices.EnterpriseLibrary.Caching.Expirations;

Following are the Expiration policies

Time-based expirations

You should use time-based expiration when volatile cache items-such as those that have regular data refreshes or those that are valid for only a set amount of time-are stored in a cache. Time-based expiration enables you to set policies that keep items in the cache only as long as their data remains current. For example, if you are writing an application that tracks currency exchange rates by obtaining the data from a frequently updated Web site, you can cache the currency rates for the time that those rates remain constant on the source Web site. In this situation, you would set an expiration policy that is based on the frequency of the Web site updates-for example, once a day or every 20 minutes.

Time Based Expirations are of three types


Notification-based expirations

You can use notification-based expiration to define the validity of a cached item based on the properties of an application resource, such as a file, a folder, or any other type of data source. If a dependency changes, the cached item is invalidated and removed from the cache.

File dependency. This means the item expires after a specific file has been modified.

FileDependency expireNotice = new FileDependency(“Trigger.txt”); // expire if the file Trigger.txt is changed
cacheManager.Add("Key1", "Cache Item1", CacheItemPriority.Normal, null, expireNotice);

NOTE: You can create custom expirations by creating classes that implement ICacheItemExpiration

Configuring Expiration Poll Frequency

The Caching Application Block's expiration process is performed by the BackgroundScheduler. It periodically examines the CacheItems in the hash table to see if any items have expired. You control how frequently the expiration cycle occurs when you configure an instance of the CacheManager using the Configuration Console.

The configuration settings for the Caching Application Block should reflect both an application's caching usage pattern and its system environment, such as the amount of available memory. For example, if an application adds items to the cache at a greater rate than it removes them when scavenging (this is a configurable setting), the cache will continue grow. Over time, this can cause memory starvation. Use the application block's performance counters to help tune the configuration settings for each application.

The following can be configured

One of the four priorities can be assigned to a cached item

NOTE: The default value is Normal.

The onus of the items that need to be scavenged is placed on the BackGroundScheduler object. The BackGroundScheduler performs a:

Scavenging is done in one single pass

Expiration is a two-part process

Extending the Caching Application Block

Typically, to suit one's application needs one can extend and modify the Caching Application Block to accommodate the following

The following interfaces need to be implemented in case one needs to provide custom expiration policies

NOTE: The implementing class must be serializable.

NOTE: If you want to add new features to the application block, you can do so by modifying the source code (the installer includes both the source code and the binaries)

Instrumenting the Caching Application Block

The Caching Application block also incorporates the following instrumentation:

There are several WMI events available to monitor any Cache Related operations

CachingServiceEvent Is the base event class for all events related to Caching.This base class has a string property named Message that contains the message for the event.
CachingServiceFailureEvent

Is the base event class for all failure events. Includes the following properties:-

ExceptionStackTrace (string). The stack trace of the reported exception.

ExceptionMessage (string). The detailed message of the exception and the exception stack trace, if this failure is a result of an exception.

CachingServiceCacheFlushedEvent This event signifies the cache has been flushed
CachingServiceCacheScavengedEvent This event signifies the cache has been scavenged.
CachingServiceInternalFailureEvent This event class inherits from the CachingServiceFailureEvent. It signifies that an internal failure has occurred. It includes the string property ConfigurationFilePaththat contains the path of the main configuration file.