using System;
using System.Collections;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using System.Web;
namespace PalGain.Core
{
///
/// Represents a manager for caching during an HTTP request (short term caching)
///
public partial class PerRequestCacheManager : ICacheManager
{
private readonly HttpContextBase _context;
///
/// Ctor
///
/// Context
public PerRequestCacheManager(HttpContextBase context)
{
this._context = context;
}
///
/// Creates a new instance of the NopRequestCache class
///
protected virtual IDictionary GetItems()
{
if (_context != null)
return _context.Items;
return null;
}
///
/// 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)
{
var items = GetItems();
if (items == null)
return default(T);
return (T)items[key];
}
///
/// Adds the specified key and object to the cache.
///
/// key
/// Data
/// Cache time
public virtual void Set(string key, object data, int cacheTime)
{
var items = GetItems();
if (items == null)
return;
if (data != null)
{
if (items.Contains(key))
items[key] = data;
else
items.Add(key, data);
}
}
///
/// Gets a value indicating whether the value associated with the specified key is cached
///
/// key
/// Result
public virtual bool IsSet(string key)
{
var items = GetItems();
if (items == null)
return false;
return (items[key] != null);
}
///
/// Removes the value with the specified key from the cache
///
/// /key
public virtual void Remove(string key)
{
var items = GetItems();
if (items == null)
return;
items.Remove(key);
}
///
/// Removes items by pattern
///
/// pattern
public virtual void RemoveByPattern(string pattern)
{
var items = GetItems();
if (items == null)
return;
var enumerator = items.GetEnumerator();
var regex = new Regex(pattern, RegexOptions.Singleline | RegexOptions.Compiled | RegexOptions.IgnoreCase);
var keysToRemove = new List();
while (enumerator.MoveNext())
{
if (regex.IsMatch(enumerator.Key.ToString()))
{
keysToRemove.Add(enumerator.Key.ToString());
}
}
foreach (string key in keysToRemove)
{
items.Remove(key);
}
}
///
/// Clear all cache data
///
public virtual void Clear()
{
var items = GetItems();
if (items == null)
return;
var enumerator = items.GetEnumerator();
var keysToRemove = new List();
while (enumerator.MoveNext())
{
keysToRemove.Add(enumerator.Key.ToString());
}
foreach (string key in keysToRemove)
{
items.Remove(key);
}
}
}
}