//Microsoft Public License (Ms-PL)
//http://visualizer.codeplex.com/license
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Redwerb.BizArk.Core.Util
{
///
///
public class Cache
{
#region Initialization and Destruction
///
///
public Cache()
{
// The default expiration time is 5 minutes.
DefaultExpiration = new TimeSpan(0, 5, 0);
}
#endregion
#region Fields and Properties
private Dictionary
///
///
///
///
public object this[string key]
{
get { return GetValue(key); }
set { SetValue(key, value, DefaultExpiration); }
}
///
///
public TimeSpan DefaultExpiration { get; set; }
#endregion
#region Methods
///
///
///
///
public void SetValue(string key, object value)
{
SetValue(key, value, DefaultExpiration);
}
///
///
///
///
///
public void SetValue(string key, object value, TimeSpan expiration)
{
if (mItems.ContainsKey(key))
mItems.Remove(key);
// We don't store nulls.
if (value == null) return;
mItems.Add(key, new CacheItem(key, value, DateTime.Now.Add(expiration)));
}
///
///
///
public void ClearValue(string key)
{
SetValue(key, null);
}
///
///
///
///
public object GetValue(string key)
{
if (mItems.ContainsKey(key))
{
var item = mItems[key];
if (item.HasExpired)
return null;
else
return item.Value;
}
else
return null;
}
///
///
///
///
///
///
public T GetValue
{
var value = GetValue(key);
if (value == null)
return defaultVal;
else
return (T)value;
}
///
///
public void PurgeCache()
{
var items = mItems.Values;
foreach (var item in items)
{
if (item.HasExpired)
mItems.Remove(item.Key);
}
}
///
///
public void ClearCache()
{
mItems.Clear();
}
#endregion
#region CacheItem
private class CacheItem
{
public CacheItem(string key, object value, DateTime expirationDate)
{
Key = key;
ExpirationDate = expirationDate;
mValRef = new WeakReference(value);
}
private WeakReference mValRef;
public string Key { get; private set; }
///
///
public object Value
{
get
{
if (mValRef.IsAlive)
return mValRef.Target;
else
return null;
}
}
public DateTime ExpirationDate { get; private set; }
public bool HasExpired
{
get
{
if (!mValRef.IsAlive)
return false;
else if (DateTime.Now < ExpirationDate)
return false;
else
return true;
}
}
}
#endregion
}
}
[/csharp]