Saturday, July 24, 2010

How to add/get a list from Cache/ Clear Cache - Asp.net

public class CacheWrapper
{
    public static void AddAll<T>(List<T> cacheObjectList, string keyPrefix) where T : class
    {
        foreach (T item in cacheObjectList)
            HttpContext.Current.Cache.Insert(
                string.Concat(keyPrefix, 
                cacheObjectList.IndexOf(item).ToString()), 
                item);
    }
    public static List<T> GetAll<T>(string keyPrefix) where T : class
    {
        List<T> items = new List<T>();
        IDictionaryEnumerator cacheContents = HttpContext.Current.Cache.GetEnumerator();
        while (cacheContents.MoveNext())
        {
            string key = cacheContents.Key.ToString();
            if (key.Contains(keyPrefix) && HttpContext.Current.Cache[key] is T)
                items.Add(HttpContext.Current.Cache[key] as T);
        }
        return items;
    }
    public static void Clear()
    {
        IDictionaryEnumerator cacheContents = HttpContext.Current.Cache.GetEnumerator();
        while (cacheContents.MoveNext())
            HttpContext.Current.Cache.Remove(cacheContents.Key.ToString());
    }
}

Usage
List<string> items = new List<string>();
///
/// Add to cache
///
items.Add("Category 1");
items.Add("Category 2");
items.Add("Category 3");
items.Add("Category 4");
items.Add("Category 5");
 
CacheWrapper.AddAll<string>(items, "Category");
///
/// Get from the cache
///
items = new List<string>();
items = CacheWrapper.GetAll<string>("Category");

No comments:

Azure Storage Account Types

Defferent Types of Blobs Block blobs store text and binary data. Block blobs are made up of blocks of data that can be managed individually...