Created
September 16, 2012 19:43
-
-
Save crilleengvall/3734068 to your computer and use it in GitHub Desktop.
A wrapper around HttpRuntime.Cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
string simpleString = "this string will be cached"; | |
HttpRuntimeCache cache = new HttpRuntimeCache(); | |
cache.Add("simpleString", simpleString); | |
string fromCache = cache.Get("simpleString") as string; | |
cache.Remove("simpleString"); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
string simpleString = "this string will be cached"; | |
HttpRuntimeCache cache = new HttpRuntimeCache(); | |
cache.Expiration = DateTime.Now.AddHours(1); | |
cache.Add("simpleString", simpleString); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Web; | |
using System.Web.Caching; | |
public class HttpRuntimeCache | |
{ | |
private DateTime _Expiration; | |
public DateTime Expiration | |
{ | |
get | |
{ | |
return this._Expiration; | |
} | |
set | |
{ | |
this._Expiration = value; | |
} | |
} | |
public HttpRuntimeCache() | |
{ | |
this._Expiration = DateTime.Now.AddHours(4); | |
} | |
public void Add(string key, object objectToCache) | |
{ | |
this.ValidateKey(key); | |
this.ValidateCacheObject(objectToCache); | |
HttpRuntime.Cache.Add(key, objectToCache, null, this._Expiration, Cache.NoSlidingExpiration, CacheItemPriority.Normal, null); | |
} | |
public object Get(string key) | |
{ | |
this.ValidateKey(key); | |
return HttpRuntime.Cache.Get(key); | |
} | |
public void Remove(string key) | |
{ | |
this.ValidateKey(key); | |
HttpRuntime.Cache.Remove(key); | |
} | |
private void ValidateKey(string key) | |
{ | |
if (key == null) | |
{ | |
this.ThrowNullKeyError(); | |
} | |
if (key.Length == 0) | |
{ | |
this.ThrowEmptyKeyError(); | |
} | |
} | |
private void ValidateCacheObject(object objectToCache) | |
{ | |
if (objectToCache == null) | |
{ | |
this.ThrowObjectError(); | |
} | |
} | |
private void ThrowObjectError() | |
{ | |
throw new ArgumentNullException("objectToCache"); | |
} | |
private void ThrowNullKeyError() | |
{ | |
throw new ArgumentNullException("key"); | |
} | |
private void ThrowEmptyKeyError() | |
{ | |
throw new ArgumentException("Input cannot be empty", "key"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment