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 : ICacheProvider { internal readonly ConcurrentDictionary StaticCache = new ConcurrentDictionary(); public virtual void ClearAllCache() { StaticCache.Clear(); } public virtual void ClearCacheItem(string key) { object val; StaticCache.TryRemove(key, out val); } public virtual void ClearCacheObjectTypes(string typeName) { foreach (var key in StaticCache.Keys) { if (StaticCache[key] != null && StaticCache[key].GetType().ToString().InvariantEquals(typeName)) { object val; StaticCache.TryRemove(key, out val); } } } public virtual void ClearCacheObjectTypes() { foreach (var key in StaticCache.Keys) { if (StaticCache[key] != null && StaticCache[key].GetType() == typeof(T)) { object val; StaticCache.TryRemove(key, out val); } } } public virtual void ClearCacheByKeySearch(string keyStartsWith) { foreach (var key in StaticCache.Keys) { if (key.InvariantStartsWith(keyStartsWith)) { ClearCacheItem(key); } } } public virtual void ClearCacheByKeyExpression(string regexString) { foreach (var key in StaticCache.Keys) { if (Regex.IsMatch(key, regexString)) { ClearCacheItem(key); } } } public virtual 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 virtual T GetCacheItem(string cacheKey) { var result = StaticCache[cacheKey]; if (result == null) { return default(T); } return result.TryConvertTo().Result; } public virtual T GetCacheItem(string cacheKey, Func getCacheItem) { return (T)StaticCache.GetOrAdd(cacheKey, getCacheItem()); } } }