using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Linq; using System.Text.RegularExpressions; using System.Web.Caching; namespace Umbraco.Core.Cache { /// /// A cache provider that statically caches everything in an in memory dictionary /// internal class StaticCacheProvider : CacheProviderBase { private readonly ConcurrentDictionary _staticCache = new ConcurrentDictionary(); public override void ClearAllCache() { _staticCache.Clear(); } public override void ClearCacheItem(string key) { object val; _staticCache.TryRemove(key, out val); } public override void ClearCacheObjectTypes(string typeName) { _staticCache.RemoveAll(kvp => kvp.Value != null && kvp.Value.GetType().ToString().InvariantEquals(typeName)); } public override void ClearCacheObjectTypes() { var typeOfT = typeof (T); _staticCache.RemoveAll(kvp => kvp.Value != null && kvp.Value.GetType() == typeOfT); } public override void ClearCacheObjectTypes(Func predicate) { var typeOfT = typeof(T); _staticCache.RemoveAll(kvp => kvp.Value != null && kvp.Value.GetType() == typeOfT && predicate(kvp.Key, (T)kvp.Value)); } public override void ClearCacheByKeySearch(string keyStartsWith) { _staticCache.RemoveAll(kvp => kvp.Key.InvariantStartsWith(keyStartsWith)); } public override void ClearCacheByKeyExpression(string regexString) { _staticCache.RemoveAll(kvp => Regex.IsMatch(kvp.Key, regexString)); } public override IEnumerable GetCacheItemsByKeySearch(string keyStartsWith) { return (from KeyValuePair c in _staticCache where c.Key.InvariantStartsWith(keyStartsWith) select c.Value.TryConvertTo() into attempt where attempt.Success select attempt.Result).ToList(); } public override T GetCacheItem(string cacheKey) { var result = _staticCache[cacheKey]; if (result == null) { return default(T); } return result.TryConvertTo().Result; } public override T GetCacheItem(string cacheKey, Func getCacheItem) { return (T)_staticCache.GetOrAdd(cacheKey, key => getCacheItem()); } } }