PageRenderTime 28ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/csToolkit/csToolkit/Cache/HelperCache.cs

#
C# | 294 lines | 202 code | 10 blank | 82 comment | 49 complexity | 58aa8cb5f772e76b254771864d553a06 MD5 | raw file
  1. using System;
  2. using System.Configuration;
  3. using System.Collections.Generic;
  4. using System.Web;
  5. using System.Web.Caching;
  6. using System.Collections;
  7. using System.Reflection;
  8. namespace MikeKappel.Com.CS
  9. {
  10. public class HelperCache
  11. {
  12. private static partial class Config
  13. {
  14. public static Boolean EnableCaching
  15. {
  16. get
  17. {
  18. Boolean reuslt = true;
  19. return (!Boolean.TryParse(ConfigurationManager.AppSettings["EnableCaching"], out reuslt) || reuslt);
  20. }
  21. }
  22. public static String CacheClearing
  23. {
  24. get
  25. {
  26. return ConfigurationManager.AppSettings["EnableCaching"];
  27. }
  28. }
  29. public static Int32 CachingTimeSpan
  30. {
  31. get
  32. {
  33. Int32 result = 0;
  34. return (Int32.TryParse(ConfigurationManager.AppSettings["CachingTimeSpan"], out result)) ? result : result;
  35. }
  36. }
  37. public static Int32 CachingShortTerm
  38. {
  39. get
  40. {
  41. Int32 result = 0;
  42. return (Int32.TryParse(ConfigurationManager.AppSettings["CachingShortTerm"], out result)) ? result : result;
  43. }
  44. }
  45. }
  46. public static Cache cache = HttpContext.Current.Cache;
  47. /// <summary>
  48. /// Indicates weather caching is enabled.
  49. /// </summary>
  50. public static Boolean IsEnabled
  51. {
  52. get
  53. {
  54. return Config.EnableCaching;
  55. }
  56. }
  57. /// <summary>
  58. /// Indicates weather caching is enabled.
  59. /// </summary>
  60. public static Boolean ClearingIsEnabled
  61. {
  62. get
  63. {
  64. return (Config.CacheClearing != "");
  65. }
  66. }
  67. /// <summary>
  68. /// Date and time the next cache clear was performed.
  69. /// </summary>
  70. public static Nullable<DateTime> NextClearingTime
  71. {
  72. get
  73. {
  74. if (!IsEnabled || !ClearingIsEnabled) return null;
  75. Boolean WillClearToday = LastCleared.HasValue
  76. && LastCleared.Value.Date == DateTime.Now.Date
  77. && DateTime.Compare(DateTime.Now, Convert.ToDateTime(DateTime.Now.Date.ToString("MM/dd/yyyy") + " " + Config.CacheClearing)) < 0;
  78. return (WillClearToday) ?
  79. DateTime.Parse(DateTime.Now.Date.ToString("MM/dd/yyyy") + " " + Config.CacheClearing) :
  80. DateTime.Parse(DateTime.Now.AddDays(1).Date.ToString("MM/dd/yyyy") + " " + Config.CacheClearing);
  81. }
  82. }
  83. /// <summary>
  84. /// Date and time the last cache clear was performed.
  85. /// </summary>
  86. public static Nullable<DateTime> LastCleared
  87. {
  88. get
  89. {
  90. if (!IsEnabled || !ClearingIsEnabled) return null;
  91. if (HttpContext.Current.Cache["CacheLastCleared"] == null) Clear();
  92. return (DateTime)HttpContext.Current.Cache["CacheLastCleared"];
  93. }
  94. }
  95. /// <summary>
  96. /// If cache is due to be clear cleared this will clear it.
  97. /// </summary>
  98. public static void Check()
  99. {
  100. if (NextClearingTime.HasValue && NextClearingTime.Value < DateTime.Now) Clear();
  101. }
  102. /// <summary>
  103. /// Clears all items from cache
  104. /// </summary>
  105. public static void Clear()
  106. {
  107. if (IsEnabled)
  108. {
  109. IDictionaryEnumerator CacheEnum = HttpContext.Current.Cache.GetEnumerator();
  110. while (CacheEnum.MoveNext()) HttpContext.Current.Cache.Remove(CacheEnum.Key.ToString());
  111. HttpContext.Current.Cache["CacheLastCleared"] = DateTime.Now;
  112. }
  113. }
  114. public enum CachingTime
  115. {
  116. LongTermAbsolute,
  117. LongTermSliding,
  118. ShortTermSliding
  119. }
  120. /// <summary>
  121. /// Will add object to Cache if:
  122. /// 1. Debug mode is "ON" and "DebugCacheDisabled" session is not "True"
  123. /// 2. If caching is enabled
  124. /// 3. The object is not Null
  125. /// 4. The object is not already in Cache
  126. /// 5. The object is Cacheable
  127. /// </summary>
  128. /// <typeparam name="T">Type of Object</typeparam>
  129. /// <param name="key">Key to retrieve Object</param>
  130. /// <param name="obj">Object to store in Cache</param>
  131. /// <returns></returns>
  132. public static CacheAddResult Add(String key, Object obj, CachingTime SpecialCacheSetting)
  133. {
  134. if (HttpContext.Current.IsDebuggingEnabled && Helper.ParseTo<Boolean>(HttpContext.Current.Session["DebugCacheDisabled"]))
  135. return CacheAddResult.DebugDisabled;
  136. Check();
  137. TimeSpan CacheTimeSpan;
  138. if (
  139. (
  140. (!Config.EnableCaching || Config.CachingTimeSpan == 0)
  141. &&
  142. (SpecialCacheSetting == CachingTime.LongTermAbsolute || SpecialCacheSetting == CachingTime.LongTermSliding)
  143. )
  144. || (SpecialCacheSetting == CachingTime.ShortTermSliding && Config.CachingShortTerm == 0)
  145. )
  146. {
  147. return CacheAddResult.Disabled;
  148. }
  149. else if (obj == null)
  150. {
  151. return CacheAddResult.Null;
  152. }
  153. else if (HttpContext.Current.Cache[key] != null)
  154. {
  155. return CacheAddResult.Conflict;
  156. }
  157. else if (SpecialCacheSetting == CachingTime.ShortTermSliding)
  158. {
  159. CacheTimeSpan = TimeSpan.FromMinutes(Config.CachingShortTerm);
  160. }
  161. else
  162. {
  163. CacheTimeSpan = TimeSpan.FromHours(Config.CachingTimeSpan);
  164. }
  165. Object objToCache = CacheableClone(obj);
  166. if (objToCache == null)
  167. return CacheAddResult.Forbidden;
  168. if (SpecialCacheSetting == CachingTime.LongTermAbsolute)
  169. {
  170. cache.Add(key, objToCache, null, DateTime.Now.Add(CacheTimeSpan), System.Web.Caching.Cache.NoSlidingExpiration, CacheItemPriority.High, null);
  171. }
  172. else
  173. {
  174. cache.Add(key, objToCache, null, System.Web.Caching.Cache.NoAbsoluteExpiration, CacheTimeSpan, CacheItemPriority.High, null);
  175. }
  176. return CacheAddResult.OK;
  177. }
  178. /// <summary>
  179. /// Will add object to Cache if:
  180. /// 1. Debug mode is "ON" and "DebugCacheDisabled" session is not "True"
  181. /// 2. If caching is enabled
  182. /// 3. The object is not Null
  183. /// 4. The object is not already in Cache
  184. /// 5. The object is Cacheable
  185. /// </summary>
  186. /// <typeparam name="T">Type of Object</typeparam>
  187. /// <param name="key">Key to retrieve Object</param>
  188. /// <param name="obj">Object to store in Cache</param>
  189. /// <returns></returns>
  190. public static CacheAddResult Add(String key, Object obj)
  191. {
  192. return Add(key, obj, CachingTime.LongTermSliding);
  193. }
  194. /// <summary>
  195. /// Site cache method outcomes
  196. /// </summary>
  197. public enum CacheAddResult
  198. {
  199. /// <summary>
  200. /// Added to Cache
  201. /// </summary>
  202. OK,
  203. /// <summary>
  204. /// If caching is Disabled
  205. /// </summary>
  206. Disabled,
  207. /// <summary>
  208. /// Debug is Disabled
  209. /// </summary>
  210. DebugDisabled,
  211. /// <summary>
  212. /// The object to be added is Null
  213. /// </summary>
  214. Null,
  215. /// <summary>
  216. /// The key is not already in Cache
  217. /// </summary>
  218. Conflict,
  219. /// <summary>
  220. /// Object not allowed
  221. /// </summary>
  222. Forbidden
  223. }
  224. /// <summary>
  225. ///
  226. /// </summary>
  227. /// <typeparam name="T"></typeparam>
  228. /// <param name="key"></param>
  229. /// <param name="obj"></param>
  230. /// <returns></returns>
  231. public static T Get<T>(String key)
  232. {
  233. if (cache[key] != null)
  234. {
  235. T result = (T)cache[key];
  236. return result;
  237. }
  238. else
  239. {
  240. return default(T);
  241. }
  242. }
  243. /// <summary>
  244. ///
  245. /// </summary>
  246. /// <param name="obj"></param>
  247. /// <returns></returns>
  248. private static Object CacheableClone(Object obj)
  249. {
  250. Object result = null;
  251. if (Attribute.IsDefined(obj.GetType(), typeof(CachingForbidden)))
  252. throw new Exception(obj.GetType().ToString() + " could not invoke CacheableClone in HelperCache");
  253. if (obj is List<ICloneable> && (obj as List<ICloneable>) != null)
  254. {
  255. Object newList = (obj as List<ICloneable>).FindAll(item => true);
  256. (newList as List<Object>).ForEach(item => item = CacheableClone(item));
  257. }
  258. else if (obj is ICloneable)
  259. {
  260. result = (obj as ICloneable).Clone();
  261. // Iterate through all the properties of the class.
  262. foreach (PropertyInfo pInfo in result.GetType().GetProperties())
  263. if (Attribute.IsDefined(pInfo, typeof(CachingForbidden)))
  264. pInfo.SetValue(result, null, null);
  265. }
  266. else
  267. result = obj;
  268. return result;
  269. }
  270. /// <summary>
  271. /// Indicates whether a Property or Class should be stored in cache.
  272. /// </summary>
  273. [AttributeUsage(AttributeTargets.Property | AttributeTargets.Class, AllowMultiple = false, Inherited = true)]
  274. public class CachingForbidden : System.Attribute
  275. {
  276. /// <summary>
  277. /// Use of his custom Attribute prevents the Helper Cache from caching Property or class it is attributed to.
  278. /// </summary>
  279. public CachingForbidden()
  280. {
  281. }
  282. }
  283. }
  284. }