Skip to content

Instantly share code, notes, and snippets.

@csharpforevermore
Forked from crilleengvall/CacheExample.cs
Last active August 29, 2015 14:22
Show Gist options
  • Save csharpforevermore/4f327c27aec8ec1b6c31 to your computer and use it in GitHub Desktop.
Save csharpforevermore/4f327c27aec8ec1b6c31 to your computer and use it in GitHub Desktop.
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");
string simpleString = "this string will be cached";
HttpRuntimeCache cache = new HttpRuntimeCache();
cache.Expiration = DateTime.Now.AddHours(1);
cache.Add("simpleString", simpleString);
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