using System; using System.Collections; using System.Collections.Generic; using System.Runtime.Caching; using System.Web; namespace Common { public static class CacheHelper { public static void AddOrUpdate(string key, object value, int expiresinhours) { if (HttpContext.Current != null) { if (HttpContext.Current.Cache[key] != null) { HttpContext.Current.Cache[key] = value; } else { HttpContext.Current.Cache.Add(key, value, null, DateTime.Now.AddHours(expiresinhours), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null); } } else if (MemoryCache.Default != null) { if (MemoryCache.Default[key] != null) { MemoryCache.Default[key] = value; } else { CacheItemPolicy policy = new CacheItemPolicy(); policy.AbsoluteExpiration = DateTime.Now.AddHours(expiresinhours); MemoryCache.Default.Set(key, value, policy); } } } public static object Get(string key) { ObjectCache cache = MemoryCache.Default; if (HttpContext.Current!= null && HttpContext.Current.Cache[key] != null) { return HttpContext.Current.Cache[key]; } else if (MemoryCache.Default != null && MemoryCache.Default[key] != null) { return MemoryCache.Default[key]; } return null; } public static void DeleteCacheThatContains(string value) { if (HttpContext.Current != null) { List<string> keys = new List<string>(); // retrieve application Cache enumerator IDictionaryEnumerator enumerator = HttpContext.Current.Cache.GetEnumerator(); // copy all keys that currently exist in Cache while (enumerator.MoveNext()) { if (enumerator.Key.ToString().Contains(value)) keys.Add(enumerator.Key.ToString()); } // delete every key from cache for (int i = 0; i < keys.Count; i++) { HttpContext.Current.Cache.Remove(keys[i]); } } } public static void ClearAllCache() { if (HttpContext.Current != null) { List<string> keys = new List<string>(); // retrieve application Cache enumerator IDictionaryEnumerator enumerator = HttpContext.Current.Cache.GetEnumerator(); // copy all keys that currently exist in Cache while (enumerator.MoveNext()) { keys.Add(enumerator.Key.ToString()); } // delete every key from cache for (int i = 0; i < keys.Count; i++) { HttpContext.Current.Cache.Remove(keys[i]); } } } } }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter