using System;
using System.Collections.Generic;
using System.Runtime.Caching;
using System.Text.RegularExpressions;
namespace PalGain.Core
{
///
/// Represents a manager for caching between HTTP requests (long term caching)
///
public partial class MemoryCacheManager : ICacheManager
{
///
/// Cache object
///
protected ObjectCache Cache
{
get
{
return MemoryCache.Default;
}
}
///
/// Gets or sets the value associated with the specified key.
///
/// Type
/// The key of the value to get.
/// The value associated with the specified key.
public virtual T Get(string key)
{
return (T)Cache[key];
}
///
/// Adds the specified key and object to the cache.
///
/// key
/// Data
/// Cache time
public virtual void Set(string key, object data, int cacheTime)
{
if (data == null)
return;
var policy = new CacheItemPolicy();
policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromMinutes(cacheTime);
Cache.Add(new CacheItem(key, data), policy);
}
///
/// Gets a value indicating whether the value associated with the specified key is cached
///
/// key
/// Result
public virtual bool IsSet(string key)
{
return (Cache.Contains(key));
}
///
/// Removes the value with the specified key from the cache
///
/// /key
public virtual void Remove(string key)
{
Cache.Remove(key);
}
///
/// Removes items by pattern
///
/// pattern
public virtual void RemoveByPattern(string pattern)
{
var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
var keysToRemove = new List();
foreach (var item in Cache)
if (regex.IsMatch(item.Key))
keysToRemove.Add(item.Key);
foreach (string key in keysToRemove)
{
Remove(key);
}
}
///
/// Clear all cache data
///
public virtual void Clear()
{
foreach (var item in Cache)
Remove(item.Key);
}
}
}