using System;
using System.Web;
using System.Web.Caching;
namespace Neo.Afx.Common
{
///
/// Cache provider for HttpContext
///
public class CacheContextWeb : ICacheContext
{
///
/// Get the cached value based on a specified key
///
///
///
///
public T Get(string key)
{
var current = HttpContext.Current;
if (current == null)
{
return default(T);
}
else
{
var v = (byte[])current.Cache.Get(key);
if (v != null)
{
return (T)SerializationUtilities.Deserialize(v);
}
else
{
return default(T);
}
}
}
///
/// Set the cached value
///
///
///
///
public void Set(string key, object value, int cacheExpirationMinutes)
{
var current = HttpContext.Current;
if (current != null)
{
current.Cache.Insert(key, SerializationUtilities.Serialize(value), null, DateTime.Now.AddMinutes(cacheExpirationMinutes), System.Web.Caching.Cache.NoSlidingExpiration);
}
}
///
/// Remove a cached value
///
///
public void Remove(string key)
{
var current = HttpContext.Current;
if (current != null)
{
current.Cache.Remove(key);
}
}
///
/// Clear the cache
///
public void Clear()
{
var current = HttpContext.Current;
if (current != null)
{
// Note: not thread safe
var d = current.Cache.GetEnumerator();
while (d.MoveNext())
{
current.Cache.Remove(d.Key.ToString());
}
}
}
}
}