/// <summary> /// This method add an object to cache with a default expiration date of 1day. /// </summary> /// <param name="key">The Cache key</param> /// <param name="objectToInsert">The object to save in cache</param> /// <param name="expirationTime">The time the cache should expire. the default is 1hour</param> public static void AddObjectToCache(string key, object objectToInsert, DateTime?expirationTime, bool ObjectIsPerPerson, ApplicationEnums.CacheExpiration expiration) { ILog log = log4net.LogManager.GetLogger(typeof(CacheHelper)); try { MemoryCache cache = MemoryCache.Default; if (!expirationTime.HasValue) { expirationTime = DateTime.Now.AddHours(1); } string keyForCache = key; if (ObjectIsPerPerson) { keyForCache = GetKeyForUser(key); } CacheItemPolicy policy = new CacheItemPolicy(); switch (expiration) { case ApplicationEnums.CacheExpiration.Midnight: policy.AbsoluteExpiration = new DateTimeOffset(DateTime.Today.AddDays(1.0)); break; case ApplicationEnums.CacheExpiration.Fix: policy.AbsoluteExpiration = new DateTimeOffset(expirationTime.Value); break; case ApplicationEnums.CacheExpiration.Sliding: TimeSpan time = expirationTime.Value - DateTime.Now; policy.SlidingExpiration = time; break; case ApplicationEnums.CacheExpiration.In_2_Hours: policy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddHours(2)); break; default: break; } // configuration setting to determine if cache is used if (true)//(leads.Properties.Settings.Default.UseCache) { log.Debug(String.Concat("AddObjectToCache : Cache key -> ", keyForCache)); cache.Set(keyForCache, objectToInsert, policy); } } catch (Exception e) { log.Error("[AddObjectToCache] - Exception Caught" + e.ToString()); throw; } }
/// <summary> /// Adds a cache object for a user /// </summary> /// <param name="key"></param> /// <param name="userId"></param> public static void AddObjectToCache(string key, object objectToInsert, DateTime?expirationTime, string userId, ApplicationEnums.CacheExpiration expiration) { ILog log = log4net.LogManager.GetLogger(typeof(CacheHelper)); try { string cacheKey = String.Format("username={0};key={1};", userId, key); AddObjectToCache(cacheKey, objectToInsert, expirationTime, false, expiration); } catch (Exception e) { log.Error("[AddObjectToCache] - Exception Caught" + e.ToString()); throw; } }