Skip to content

Instantly share code, notes, and snippets.

@mykeels
Created January 17, 2017 19:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mykeels/4fb0020742b77b03a1a3112a24bb8378 to your computer and use it in GitHub Desktop.
Save mykeels/4fb0020742b77b03a1a3112a24bb8378 to your computer and use it in GitHub Desktop.
ASP.NET Cache Helper Methods
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Caching;
using System.Text.RegularExpressions;
namespace CacheHelpers
{
public class MCache
{
public static dynamic Add(string key, dynamic value, long milliseconds = 18000000, CacheItemPriority priority = CacheItemPriority.Normal)
{
if (HttpContext.Current.Cache.Get(key) == null)
{
HttpContext.Current.Cache.Add(key, value, null, DateTime.Now.AddMilliseconds(Convert.ToDouble(milliseconds)), TimeSpan.Zero, priority, null);
}
else
{
HttpContext.Current.Cache.Remove(key);
HttpContext.Current.Cache.Add(key, value, null, DateTime.Now.AddMilliseconds(Convert.ToDouble(milliseconds)), TimeSpan.Zero, priority, null);
}
return value;
}
public static void Remove(string key)
{
if (Contains(key))
{
HttpContext.Current.Cache.Remove(key);
}
}
public static bool Contains(string key)
{
return HttpContext.Current.Cache.Get(key) != null;
}
public static T Get<T>(string key, Func<T> retfn = null, bool byPass = false)
{
if ((!Contains(key) && retfn != null) || byPass)
{
T rett = Add(key, retfn());
return rett;
}
if (!Contains(key)) return default(T);
T ret = (T)HttpContext.Current.Cache[key];
return ret;
}
public static List<string> Keys()
{
List<string> ret = new List<string>();
foreach (var c in HttpContext.Current.Cache)
{
ret.Add((string)((DictionaryEntry)c).Key);
}
return ret;
}
public static void Clear()
{
foreach (var key in Keys())
{
Remove(key);
}
}
public static void Clear(string keyPattern)
{
foreach (var key in Keys().Where(key => Regex.IsMatch(key, keyPattern)))
{
Remove(key);
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment