Cybercrux

Everything is achievable through technology

Cache Helper

public static class CacheHelper
{
/// <summary>
/// Insert value into the cache using
/// appropriate name/value pairs
/// </summary>
/// <typeparam name=”T”>Type of cached item</typeparam>
/// <param name=”o”>Item to be cached</param>
/// <param name=”key”>Name of item</param>
public static void Add<T>(T o, string key) where T : class
{
// NOTE: Apply expiration parameters as you see fit.
// In this example, I want an absolute
// timeout so changes will always be reflected
// at that time. Hence, the NoSlidingExpiration.
HttpContext.Current.Cache.Insert(
key,
o,
null,
DateTime.Now.AddMinutes(
ConfigurationHelper.CacheExpirationMinutes),
System.Web.Caching.Cache.NoSlidingExpiration);
}

/// <summary>
/// Remove item from cache
/// </summary>
/// <param name=”key”>Name of cached item</param>
public static void Clear(string key)
{
HttpContext.Current.Cache.Remove(key);
}

/// <summary>
/// Check for item in cache
/// </summary>
/// <param name=”key”>Name of cached item</param>
/// <returns></returns>
public static bool Exists(string key)
{
return HttpContext.Current.Cache[key] != null;
}

/// <summary>
/// Retrieve cached item
/// </summary>
/// <typeparam name=”T”>Type of cached item</typeparam>
/// <param name=”key”>Name of cached item</param>
/// <returns>Cached item as type</returns>
public static T Get<T>(string key) where T : class
{
try
{
return (T) HttpContext.Current.Cache[key];
}
catch
{
return null;
}
}
}

 

And here is a relatively standard sample usage of the library.
public override List<Employee> GetEmployeeList()
{
string key = ConfigurationHelper.CacheKeyEmployeeList;

List<Employee> employees = CacheHelper.Get<List<Employee>>(key);

if (employees == null)
{
employees = instance.GetEmployeeList();
CacheHelper.Add(employees, key);
}

return employees;
}

 
string key = “EmployeeList”;
List<Employee> employees;

if (!CacheHelper.Get(key, out employees))
{
employees = DataAccess.GetEmployeeList();
CacheHelper.Add(employees, key);
Message.Text =
“Employees not found but retrieved and added to cache for next lookup.”;
}
else
{
Message.Text = “Employees pulled from cache.”;
}

 

Leave a comment