Jawad Khan

Jawad's Lodge - The willingness to torture yourself before others is what makes a developer truly a unique breed.
posts - 45, comments - 150, trackbacks - 155

My Links

News

Archives

Post Categories

Image Galleries

Adding, Updating, Invalidating , Setting Callback and Removing Data Cache in ASP.Net ....

ASP.Net has a very powerful Cache Management component. Cache is part of the most enterprise level .Net project. ASP.Net Data Cache is very flexible and is also available to Windows application by making use of HttpRuntime.Cache object. Microsoft provides a Cache Management Application Block but it can be overkill for lot of applications .....

Since during my consulting assignments I came across all the time to implement this functionality; I have created a Cache Manager class that can provide all the Cache manipulation through simple function calls.

   Here is How to use Cache Manager Class to add Items in Cache ... where myObject is a Hashtable of Customers ... Duration is optional and is specified as 180 minutes here ...

  HttpCache.httpCache.SetItemForDuration(“Customers“,  myObject, 180);

   If you want to have a default Cache duration for the whole application you should specify it in the web.config file where the  Cache Manager is being used  ....in the Application configuration section of web.config

<add key="CacheDurationInMinutes" value="30"/>

   Here is the Cache Manager Class that can be called from any other Class/WebForm ....

using System;
using System.Web ;
using System.Web.Caching;
using System.Configuration ;
using System.Collections ;

namespace Jawad.Utils.CacheManagement
{
 ///


 /// Summary description for DataCache.
 ///

 sealed public class HttpCache
 {
  ///
  /// Singleton instance of Data Cache Class
  ///

  public static readonly HttpCache httpCache = new HttpCache();
  private Cache _cache;
  private int _cacheDuration = 30 ;   // Default value is 30 minutes ....

  private HttpCache()
  {
   _cache = System.Web.HttpContext.Current.Cache;
   string duration = ConfigurationSettings.AppSettings["CacheDurationInMinutes"];
   if ( duration != null)
    _cacheDuration = int.Parse (duration);
  }

  ///


  /// Get the Item from the Cache ...
  ///

  /// This is the key to look for when accessing Cache Item
  /// Data to be stored in the Cache
  /// True if Key is found in the Cache ...
  public bool GetItem(string key, out object item)
  {
   bool result = false;
   item = _cache[key];
   if ( item != null )
    result = true;
   return result;
  }

  ///


  /// Set the Item in the Cache ....
  ///

  /// The is the Key to be used to access the data Later ...
  /// This is the actual data to be stored in Cache ...
  public void SetItem(string key, object item)
  {
   _cache.Insert(key, item, null,
    DateTime.Now.AddMinutes(_cacheDuration), TimeSpan.Zero);
  }

  ///


  /// Set the Item in the Cache that expires after the specified duration in Minutes ....
  ///

  /// The is the Key to be used to access the data Later ...
  /// This is the actual data to be stored in Cache ...
  /// Minutes to keep the data in Cache ...
  public void SetItemForDuration(string key, object item, double MinutesDuration)
  {
   _cache.Insert(key, item, null,
    DateTime.Now.AddMinutes(MinutesDuration), TimeSpan.Zero);
  }
  ///
  /// Set the Item in the Cache that expires if not accessed for certain duration ....
  ///

  /// The is the Key to be used to access the data Later ...
  /// This is the actual data to be stored in Cache ...
  /// Minutes till last accessed to clear the Cache ...
  public void SetItemClearIfNotAccessed(string key, object item, double MinutesDuration)
  {
   _cache.Insert(key, item, null,
    Cache.NoAbsoluteExpiration, TimeSpan.FromMinutes(MinutesDuration));
  }

  ///


  /// Set the Item in the Cache that will never expire ....
  ///

  /// This is the Key to be used to access the data Later ...
  /// This is the actual data to be stored in Cache ...
  public void SetItemNeverExpire(string key, object item)
  {
   _cache.Insert(key, item, null,
    Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration);
  }

  ///


  /// Set the Item in the Cache that will Refresh it self by calling provided function ....
  ///

  /// This is the Key to be used to access the data Later ...
  /// This is the actual data to be stored in Cache ...
  /// Duration in Minutes to keep the item in Cache before refresh is called. Default Duration can Be acquired from Web.Config AppSettings
  /// A Function with the following Signature
  ///  public void CdiCacheItemRemovedCallback(string key, object val, CacheItemRemovedReason reason)
  ///  inside this fuction you should get the data again and then call "SetItemRefreshItSelf" function passing it
  ///  same function name you are in i.e. CdiCacheItemRemovedCallBack  as CdiCacheItemRemovedCallback parameter
  ///
  public void SetItemRefreshItSelf(string key, object item,
            int durationMinutes, CacheItemRemovedCallback CdiCacheItemRemovedCallback)
  {
   //create an instance of the callback delegate
   CacheItemRemovedCallback callBack =
    new CacheItemRemovedCallback(CdiCacheItemRemovedCallback);
   //insert the item in cache that expires in 10 seconds.
   //assign the callback instance to it
   
   _cache.Insert(key, item, null,
    DateTime.Now.AddMinutes(durationMinutes), Cache.NoSlidingExpiration,
    CacheItemPriority.Default, callBack);

  }
   //   SAMPLE DELEGATE FOR CACHE REFRESH
   //  public void CdiCacheItemRemovedCallback(string key,
   //   object val, CacheItemRemovedReason reason)
   //  {
   //   //set cache status, so that we can view what
   //   //happened the next time we request a status update
   //   Cache.Insert("CacheStatus","KEY: " + key + "
VALUE: "
   //    + val + "
REASON: " + reason.ToString());
   //  }


  ///


  /// Remove all the Cache Items from the Current Cache ...
  ///

  public string RemoveAllCache()
  {
   string cacheItemsCleared = "Cache cleared for :
";
   IDictionaryEnumerator CacheEnum = HttpRuntime.Cache.GetEnumerator();
   while (CacheEnum.MoveNext())
   {
    string key = CacheEnum.Key.ToString();
    HttpRuntime.Cache.Remove(key);
    cacheItemsCleared += key + "
";
   }
   if (cacheItemsCleared.Length < 32)
                   cacheItemsCleared = "No items in Cache to clear.";
   return cacheItemsCleared;
  }

  ///


  /// Removes the desired object from the Cache
  ///

  /// The key for the Cache object to be removed
  public void RemoveParticularObject(string key)
  {
    object garbage = _cache.Remove (key);
  }
 }
}
        

Print | posted on Monday, May 23, 2005 10:08 PM | Filed Under [ ASP.NET ]

Feedback

Gravatar

# re: Adding, Updating, Invalidating , Setting Callback and Removing Data Cache in ASP.Net ....

Sir,


In our application we are using mulitple cache managers for multiple tasks.
the object that needs to be remain for longer duration we have given it as Absolute Expiration.

Scenario: Suppose I am fetching some data from database which will get updated once a day Once i fill the cache with the object it will not expire for some amount of time .But if db gets updated then before the cache object expire I need to get the newer data from db and put it in Cache.
So now if user accesses the application he/she will get new data.

I am trying using some call back method such as "Refresh" which is in ICacheRefershAction interface which gets called when some cache object gets expired.

Can you give me some guidence how to achive above?


Thanks,
Nikhil
10/7/2005 6:27 AM | nikhil
Gravatar

# re: Adding, Updating, Invalidating , Setting Callback and Removing Data Cache in ASP.Net ....

In Order to have ASP.Net Cache depended on the Database in ASP.NET 1.x look at the Jon Galloway solution here

weblogs.asp.net jgalloway archive 2005 05 07 406056.aspx

For some reason I can not add slashes in the post so add slashes in place of spaces in above url
10/13/2005 10:02 AM | JawadKhan
Gravatar

# re: Adding, Updating, Invalidating , Setting Callback and Removing Data Cache in ASP.Net ....

pls give me
5/10/2006 1:25 AM | LeaN1
Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification:
 

Powered by: