Tuesday, July 8, 2008

ASP.NET Simple Cache Implementation

I was working on a Windows Media Center Web Hosted project a few days ago. For this project we were working on, we had the need to save some objects on the server side cache for retrieving them later from the client (Windows Media Center application). Since we needed to save only a couple of objects on the server side cache it didn’t make much sense to implement the whole server side caching structure for caching several pages and information. We needed a quick way to save a couple of objects with the information retrieved from the xml services in the server, avoiding the need to parse the whole xml again each time the client requested the information. The solution was to implement the out of the box ASP.NET native server side cache.

To implement the native ASP.NET cache is really simple (at least for what we needed). We use the Cache.Insert() method to insert the object in the ASP.NET Cache instance. We implemented it using this constructor:

Cache.Insert(String key, object value, CacheDependency dependencies, DateTime absoluteExpiration, TimeSpan slidingExpiration);

As follows:

Cache.Insert("mykeyName", object, null,DateTime.Now.AddMinutes(Double.Parse(System.Configuration.ConfigurationManager.AppSettings["cacheExpirationTime"])), TimeSpan.Zero);

Our object is a list of MyClass instances containing the information we needed to save. Doing this inserts our object in the server side ASP.NET cache for the time we configured in the web.config file.
Now for retrieving the cache object when we needed we followed this implementation:

// Verifying if the object is on cache
List cacheItem = Cache[("mykeyName"] as List;
if (cacheItem != null)
{
this.myObjectList = cacheItem;
}


Notice that we are doing a cast to List when we are retrieving the object, so we have the desirable object with the corresponding type it is supposed to be. After that we can check if it is null and perform the tasks we want to.
This is a very out of the box basic implementation, but it solved our needs and might help you on your projects too.

The very cool thing about it is that you can save any object in the ASP.NET cache instance, set the expiration time from the web.config file and retrieved any time you want. The Cache ASP.NET instance has other methods and properties so be sure to check them out.

-arbbot

1 comment: