static void Main() { //check one - basic LazyCache IAppCache cache = new CachingService(CachingService.DefaultCacheProvider); var item = cache.GetOrAdd("Program.Main.Person", () => Tuple.Create("Joe Blogs", DateTime.UtcNow)); System.Console.WriteLine(item.Item1); //check two - using Ninject IKernel kernel = new StandardKernel(new LazyCacheModule()); cache = kernel.Get <IAppCache>(); item = cache.GetOrAdd("Program.Main.Person", () => Tuple.Create("Joe Blogs", DateTime.UtcNow)); System.Console.WriteLine(item.Item1); System.Console.WriteLine("Enumerating keys..."); foreach (var key in cache.GetCacheKeys().Keys) { System.Console.WriteLine($"{key}"); } System.Console.WriteLine("Finished enumerating keys..."); System.Console.ReadLine(); }
public void GetOrAddWithPolicyWillAddOnFirstCallButReturnCachedOnSecond() { var times = 0; var sut = new CachingService(); var expectedFirst = sut.GetOrAdd(TestKey, () => { times++; return(new DateTime(2001, 01, 01)); }, new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(1), Priority = CacheItemPriority.NotRemovable }); var expectedSecond = sut.GetOrAdd(TestKey, () => { times++; return(new DateTime(2002, 01, 01)); }, new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(1), Priority = CacheItemPriority.NotRemovable }); Assert.AreEqual(2001, expectedFirst.Year); Assert.AreEqual(2001, expectedSecond.Year); Assert.AreEqual(1, times); }
public JsonNetResult GetActiveFranchises() { List <FranchiseSelectViewModel> _listFranchises = new List <FranchiseSelectViewModel>(); IAppCache cache = new CachingService(); _listFranchises = cache.GetOrAdd("Active_Franchises", () => GetActiveFranchisesPrivate(), new TimeSpan(8, 0, 0)); if (_listFranchises == null || _listFranchises.Count == 0) { LogHelper log = new LogHelper(); log.Log(LogHelper.LogLevels.Warning, "Error loading active franchises - Franchise cache will be reset and attempted again", nameof(GetActiveFranchises)); cache.Remove("Active_Franchises"); _listFranchises = cache.GetOrAdd("Active_Franchises", () => GetActiveFranchisesPrivate(), new TimeSpan(8, 0, 0)); } if (_listFranchises == null || _listFranchises.Count == 0) { throw new ApplicationException($"Active franchise list could not be loaded."); } return(new JsonNetResult() { Data = new { list = _listFranchises }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); }
public static ChartValues <int> totaleCasi(DateTime start, DateTime end, string region) { ChartValues <int> filtered = new ChartValues <int>(); IAppCache cache = new CachingService(); Func <List <Dati> > getData = () => ReadCSV(); var records = cache.GetOrAdd("italia.Get", getData); if (region == "Italia") { records = cache.GetOrAdd("italia.Get", getData); } else { records = cache.GetOrAdd("regioni.Get", getData); } foreach (var record in records) { var filter = records[records.Count - 1]; if (DateTime.Compare(record.data, start) == 0 | DateTime.Compare(record.data, start) == 1) { if (DateTime.Compare(record.data, end) == 0 | DateTime.Compare(record.data, end) == -1) { if (record.regione == region) { filtered.Add(record.totaleCasi); } } } } return(filtered); }
public void GetFromCacheTwiceAtSameTimeOnlyAddsOnce() { var times = 0; var sut = new CachingService(); var t1 = Task.Factory.StartNew(() => { sut.GetOrAdd(TestKey, () => { Interlocked.Increment(ref times); return(new DateTime(2001, 01, 01)); }); }); var t2 = Task.Factory.StartNew(() => { sut.GetOrAdd(TestKey, () => { Interlocked.Increment(ref times); return(new DateTime(2001, 01, 01)); }); }); Task.WaitAll(t1, t2); Assert.AreEqual(1, times); }
public void LazyCache_MemoryProvider() { Parallel.For(0, ParallelIterations, i => { LazyCache.GetOrAdd("GetOrSet_TestKey", () => "Hello World", TimeSpan.FromDays(1)); }); }
public void OnlyOneFactoryGetsCalledEvenInHighConcurrency(int accessorsCount) { using (var memoryCache = new MemoryCache(new MemoryCacheOptions())) { var cache = new CachingService(new MemoryCacheProvider(memoryCache)); cache.DefaultCachePolicy = new CacheDefaults { DefaultCacheDurationSeconds = 10 }; var factoryCallsCount = 0; Parallel.For(0, accessorsCount, _ => { cache.GetOrAdd <int>( "foo", _ => { Interlocked.Increment(ref factoryCallsCount); Thread.Sleep(FactoryDuration); return(42); } ); }); Assert.Equal(1, factoryCallsCount); } }
public void LazyCache() { using (var cache = new MemoryCache(new MemoryCacheOptions())) { var appcache = new CachingService(new MemoryCacheProvider(cache)); appcache.DefaultCachePolicy = new CacheDefaults { DefaultCacheDurationSeconds = (int)(CacheDuration.TotalSeconds) }; for (int i = 0; i < Rounds; i++) { var tasks = new ConcurrentBag <Task>(); Parallel.ForEach(Keys, key => { Parallel.For(0, Accessors, _ => { appcache.GetOrAdd <SamplePayload>( key, () => { Thread.Sleep(FactoryDurationMs); return(new SamplePayload()); } ); }); }); } // CLEANUP cache.Compact(1); } }
public static List <Dati> Filtered(DateTime date) { List <Dati> filtered = new List <Dati>(); IAppCache cache = new CachingService(); Func <List <Dati> > getData = () => ReadCSV(); var records = cache.GetOrAdd("italia.Get", getData, TimeSpan.FromMinutes(10)); foreach (var record in records) { var filter = records[records.Count - 1]; filtered.Add(filter); if (record.data.ToString("dd MMMM yyyy") == date.ToString("dd MMMM yyyy")) { filter = record; filtered.Clear(); filtered.Add(filter); } } return(filtered); }
static void Main(string[] args) { //check one - basic LazyCache IAppCache cache = new CachingService(CachingService.DefaultCacheProvider); var item = cache.GetOrAdd("Program.Main.Person", () => Tuple.Create("Joe Blogs", DateTime.UtcNow)); System.Console.WriteLine(item.Item1); //check two - using Ninject IKernel kernel = new StandardKernel(new LazyCacheModule()); cache = kernel.Get <IAppCache>(); item = cache.GetOrAdd("Program.Main.Person", () => Tuple.Create("Joe Blogs", DateTime.UtcNow)); System.Console.WriteLine(item.Item1); }
public void GetOrAddAndThenGetValueObjectReturnsCorrectType() { var sut = new CachingService(); Func <int> fetch = () => 123; sut.GetOrAdd(TestKey, fetch); var actual = sut.Get <int>(TestKey); Assert.AreEqual(123, actual); }
public void GetOrAddAndThenGetWrongtypeObjectReturnsNull() { var sut = new CachingService(); Func <ComplexTestObject> fetch = () => new ComplexTestObject(); sut.GetOrAdd(TestKey, fetch); var actual = sut.Get <Exception>(TestKey); Assert.IsNull(actual); }
public void GetOrAddAndThenGetObjectReturnsCorrectType() { var sut = new CachingService(); Func <ComplexTestObject> fetch = () => new ComplexTestObject(); sut.GetOrAdd(TestKey, fetch); var actual = sut.Get <ComplexTestObject>(TestKey); Assert.IsNotNull(actual); }
public JsonResult GetSearchSuburbs() { IAppCache cache = new CachingService(); List <String> suburbs = (List <string>)cache.GetOrAdd("SuburbNames", () => GetSuburbNames(), new TimeSpan(1, 0, 0)); return(new JsonNetResult() { Data = new { item = suburbs }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); }
public JsonResult GetSettings(int?incDisabled) { List <UpdateSettingsViewModel> _editSettings = new List <UpdateSettingsViewModel>(); IAppCache cache = new CachingService(); if (incDisabled != null && incDisabled == 1) { _editSettings = cache.GetOrAdd("System_Settings_All", () => GetSettingsPrivate(incDisabled), new TimeSpan(1, 0, 0)); } else { _editSettings = cache.GetOrAdd("System_Settings_Active", () => GetSettingsPrivate(incDisabled), new TimeSpan(1, 0, 0)); } return(new JsonNetResult() { Data = new { list = _editSettings }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); }
public void LazyCache_MemoryProvider() { var lazyCache = new CachingService(); LoopAction(Iterations, () => { lazyCache.Add("TestKey", 123, TimeSpan.FromDays(1)); lazyCache.Get <int>("TestKey"); lazyCache.GetOrAdd("TestKey", () => "Hello World", TimeSpan.FromDays(1)); }); }
private IAppCache CreateLazyCache() { var cache = new CachingService(); foreach ((Guid key, int value) in Data) { cache.GetOrAdd(key.ToString(), () => value, TimeSpan.FromHours(1)); } return(cache); }
public void DefaultContructorThenGetOrAddFromSecondCachingServiceHasSharedUnderlyingCache() { var cacheOne = new CachingService(); var cacheTwo = new CachingService(); var resultOne = cacheOne.GetOrAdd(TestKey, () => "resultOne"); var resultTwo = cacheTwo.GetOrAdd(TestKey, () => "resultTwo"); // should not get executed resultOne.Should().Be("resultOne", "GetOrAdd should execute the delegate"); resultTwo.Should().Be("resultOne", "CachingService should use a shared cache by default"); }
public void GetOrAddWithPolicyAndThenGetObjectReturnsCorrectType() { var sut = new CachingService(); Func <ComplexTestObject> fetch = () => new ComplexTestObject(); sut.GetOrAdd(TestKey, fetch, new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(1), Priority = CacheItemPriority.NotRemovable }); var actual = sut.Get <ComplexTestObject>(TestKey); Assert.IsNotNull(actual); }
public void GetOrAddWillAddOnFirstCallButReturnCachedOnSecond() { var times = 0; var sut = new CachingService(); var expectedFirst = sut.GetOrAdd(TestKey, () => { times++; return(new DateTime(2001, 01, 01)); }); var expectedSecond = sut.GetOrAdd(TestKey, () => { times++; return(new DateTime(2002, 01, 01)); }); Assert.AreEqual(2001, expectedFirst.Year); Assert.AreEqual(2001, expectedSecond.Year); Assert.AreEqual(1, times); }
/// <summary> /// Returns list of zones for a given suburb /// </summary> /// <returns>The zone list by suburb.</returns> /// <param name="suburbName">Suburb name.</param> public static List <string> GetZoneListBySuburb(this string suburbName, Boolean withDefaults) { if (String.IsNullOrWhiteSpace(suburbName)) { return(new List <string>()); } IAppCache cache = new CachingService(); List <string> zoneList = cache.GetOrAdd($"SuburbZones_{suburbName}", () => GetZoneList(suburbName), new TimeSpan(0, 20, 0)); if (zoneList.Count == 0) { cache.Remove($"SuburbZones_{suburbName}"); if (withDefaults) { zoneList = cache.GetOrAdd($"SuburbZones_Defaults", () => GetDefaultZoneList(), new TimeSpan(0, 20, 0)); } } return(zoneList); }
public void GetOrAddWithPolicyAndThenGetValueObjectReturnsCorrectType() { var sut = new CachingService(); Func <int> fetch = () => 123; sut.GetOrAdd(TestKey, fetch, new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddHours(1), Priority = CacheItemPriority.NotRemovable }); var actual = sut.Get <int>(TestKey); Assert.AreEqual(123, actual); }
public JsonResult GetComputerName(string computerName) { var userDevices = new UserDevices(User.Identity.Name); // Cache has a default time limit of 20 minutes, so will get new results every 20 minutes IAppCache cache = new CachingService(); Func <List <string> > complexObjectFactory = () => userDevices.GetDevices(); List <string> fullDeviceList = cache.GetOrAdd("CMComputerList", complexObjectFactory); var returnList = fullDeviceList.Where(p => p.ToLower().Contains(computerName.ToLower())); //.Select(p => new { label = p }); return(Json(returnList.Take(50), JsonRequestBehavior.AllowGet)); }
public JsonNetResult GetAddressTypesJson() { var enumVals = new List <object>(); IAppCache cache = new CachingService(); enumVals = cache.GetOrAdd("address_types", () => GetAddressTypes(), new TimeSpan(8, 0, 0)); return(new JsonNetResult() { Data = new { item = enumVals }, JsonRequestBehavior = JsonRequestBehavior.AllowGet }); }
private Author PollAuthor(string foreignAuthorId) { return(_authorCache.GetOrAdd(foreignAuthorId, () => PollAuthorUncached(foreignAuthorId), new LazyCacheEntryOptions { AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10), ImmediateAbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(10), Size = 1, SlidingExpiration = TimeSpan.FromMinutes(1), ExpirationMode = ExpirationMode.ImmediateEviction }.RegisterPostEvictionCallback((key, value, reason, state) => _logger.Debug($"Clearing cache for {key} due to {reason}")))); }
public KerberosReceiverSecurityToken WriteToCache(string contextUsername, string contextPassword) { KerberosSecurityTokenProvider provider = new KerberosSecurityTokenProvider("YOURSPN", TokenImpersonationLevel.Impersonation, new NetworkCredential(contextUsername.ToLower(), contextPassword, "yourdomain")); KerberosRequestorSecurityToken requestorToken = provider.GetToken(TimeSpan.FromMinutes(double.Parse(ConfigurationManager.AppSettings["KerberosTokenExpiration"]))) as KerberosRequestorSecurityToken; KerberosReceiverSecurityToken receiverToken = new KerberosReceiverSecurityToken(requestorToken.GetRequest()); IAppCache appCache = new CachingService(); KerberosReceiverSecurityToken tokenFactory() => receiverToken; return(appCache.GetOrAdd(contextUsername.ToLower(), tokenFactory)); // this will either add the token or get the token if it exists }
protected IEnumerable <T> GetList <T>(TimeSpan time) { IEnumerable <T> results = new List <T>(); String cacheName = (typeof(T)).ToString(); if (String.IsNullOrWhiteSpace(cacheName)) { return(results); } IAppCache cache = new CachingService(); return(cache.GetOrAdd(cacheName, () => GetListFromDb <T>(), time)); }
public void GetOrAddWithOffsetWillAddAndReturnCached() { var sut = new CachingService(); var expectedFirst = sut.GetOrAdd( TestKey, () => new DateTime(2001, 01, 01), DateTimeOffset.Now.AddSeconds(5) ); var expectedSecond = sut.Get <DateTime>(TestKey); Assert.AreEqual(2001, expectedFirst.Year); Assert.AreEqual(2001, expectedSecond.Year); }
//https://codeshare.co.uk/blog/how-to-show-utc-time-relative-to-the-users-local-time-on-a-net-website/ private static IEnumerable <String> GetTimeZonesByCountry() { String countryCode = UserCountryCode(); IAppCache cache = new CachingService(); IEnumerable <String> zoneIds = cache.GetOrAdd($"dateTimeZoneList-{countryCode}", () => GetTimeZonesByCountryPrivate(countryCode), new TimeSpan(0, 30, 0)); if (zoneIds == null || zoneIds.Count() == 0) { cache.Remove($"dateTimeZoneList-{countryCode}"); return(new List <String>()); } return(zoneIds.ToList()); }
// TimeZone from browser internal static DateTimeZone GetDateTimeZone() { String countryCode = UserCountryCode(); IAppCache cache = new CachingService(); DateTimeZone TimeZone = cache.GetOrAdd($"dateTimeZone-{countryCode}", () => GetDateTimeZonePrivate(), new TimeSpan(0, 30, 0)); if (TimeZone == null) { // set default time zone TimeZone = DateTimeZoneProviders.Tzdb.GetSystemDefault(); } return(TimeZone); }
public void GetOrAddWillNotAddIfExistingData() { var times = 0; var sut = new CachingService(); var cached = new DateTime(1999, 01, 01); sut.Add(TestKey, cached); var expected = sut.GetOrAdd(TestKey, () => { times++; return new DateTime(2001, 01, 01); }); Assert.AreEqual(1999, expected.Year); Assert.AreEqual(0, times); }
public void GetOrAddWithPolicyWithCallbackOnRemovedReturnsTheOriginalCachedObject() { var sut = new CachingService(); Func<int> fetch = () => 123; CacheEntryRemovedArguments removedCallbackArgs = null; CacheEntryRemovedCallback callback = (args) => removedCallbackArgs = args; sut.GetOrAdd(TestKey, fetch, new CacheItemPolicy { AbsoluteExpiration = DateTimeOffset.Now.AddMilliseconds(100), RemovedCallback = callback}); var actual = sut.Get<int>(TestKey); sut.Remove(TestKey); //force removed callback to fire while(removedCallbackArgs == null) Thread.Sleep(500); Assert.AreEqual(123, removedCallbackArgs.CacheItem.Value); }
public void GetOrAddAndThenGetObjectReturnsCorrectType() { var sut = new CachingService(); Func<ComplexTestObject> fetch = () => new ComplexTestObject(); sut.GetOrAdd(TestKey, fetch); var actual = sut.Get<ComplexTestObject>(TestKey); Assert.IsNotNull(actual); }
public void GetOrAddWillAddOnFirstCallButReturnCachedOnSecond() { var times = 0; var sut = new CachingService(); var expectedFirst = sut.GetOrAdd(TestKey, () => { times++; return new DateTime(2001, 01, 01); }); var expectedSecond = sut.GetOrAdd(TestKey, () => { times++; return new DateTime(2002, 01, 01); }); Assert.AreEqual(2001, expectedFirst.Year); Assert.AreEqual(2001, expectedSecond.Year); Assert.AreEqual(1, times); }
public void GetOrAddAndThenGetValueObjectReturnsCorrectType() { var sut = new CachingService(); Func<int> fetch = () => 123; sut.GetOrAdd(TestKey, fetch); var actual = sut.Get<int>(TestKey); Assert.AreEqual(123, actual); }
public void GetOrAddWithPolicyAndThenGetValueObjectReturnsCorrectType() { var sut = new CachingService(); Func<int> fetch = () => 123; sut.GetOrAdd(TestKey, fetch, new CacheItemPolicy {AbsoluteExpiration = DateTimeOffset.Now.AddHours(1), Priority = CacheItemPriority.NotRemovable}); var actual = sut.Get<int>(TestKey); Assert.AreEqual(123, actual); }
public void GetOrAddWithPolicyWillAddOnFirstCallButReturnCachedOnSecond() { var times = 0; var sut = new CachingService(); var expectedFirst = sut.GetOrAdd(TestKey, () => { times++; return new DateTime(2001, 01, 01); }, new CacheItemPolicy {AbsoluteExpiration = DateTimeOffset.Now.AddHours(1), Priority = CacheItemPriority.NotRemovable}); var expectedSecond = sut.GetOrAdd(TestKey, () => { times++; return new DateTime(2002, 01, 01); }, new CacheItemPolicy {AbsoluteExpiration = DateTimeOffset.Now.AddHours(1), Priority = CacheItemPriority.NotRemovable}); Assert.AreEqual(2001, expectedFirst.Year); Assert.AreEqual(2001, expectedSecond.Year); Assert.AreEqual(1, times); }
public void GetOrAddWithPolicyAndThenGetObjectReturnsCorrectType() { var sut = new CachingService(); Func<ComplexTestObject> fetch = () => new ComplexTestObject(); sut.GetOrAdd(TestKey, fetch, new CacheItemPolicy {AbsoluteExpiration = DateTimeOffset.Now.AddHours(1), Priority = CacheItemPriority.NotRemovable}); var actual = sut.Get<ComplexTestObject>(TestKey); Assert.IsNotNull(actual); }
public void GetOrAddAndThenGetWrongtypeObjectReturnsNull() { var sut = new CachingService(); Func<ComplexTestObject> fetch = () => new ComplexTestObject(); sut.GetOrAdd(TestKey, fetch); var actual = sut.Get<Exception>(TestKey); Assert.IsNull(actual); }
public void GetFromCacheTwiceAtSameTimeOnlyAddsOnce() { var times = 0; var sut = new CachingService(); var t1 = Task.Factory.StartNew(() => { sut.GetOrAdd(TestKey, () => { Interlocked.Increment(ref times); return new DateTime(2001, 01, 01); }); }); var t2 = Task.Factory.StartNew(() => { sut.GetOrAdd(TestKey, () => { Interlocked.Increment(ref times); return new DateTime(2001, 01, 01); }); }); Task.WaitAll(t1, t2); Assert.AreEqual(1, times); }
public void GetOrAddWithOffsetWillAddAndReturnCached() { var sut = new CachingService(); var expectedFirst = sut.GetOrAdd( TestKey, () => new DateTime(2001, 01, 01), DateTimeOffset.Now.AddSeconds(5) ); var expectedSecond = sut.Get<DateTime>(TestKey); Assert.AreEqual(2001, expectedFirst.Year); Assert.AreEqual(2001, expectedSecond.Year); }