public async Task OnlyOneFactoryGetsCalledEvenInHighConcurrencyAsync(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;

                var tasks = new ConcurrentBag <Task>();
                Parallel.For(0, accessorsCount, _ =>
                {
                    var task = cache.GetOrAddAsync <int>(
                        "foo",
                        async _ =>
                    {
                        Interlocked.Increment(ref factoryCallsCount);
                        await Task.Delay(FactoryDuration).ConfigureAwait(false);
                        return(42);
                    }
                        );
                    tasks.Add(task);
                });

                await Task.WhenAll(tasks);

                Assert.Equal(1, factoryCallsCount);
            }
        }
    public KerberosReceiverSecurityToken ReadFromCache(string contextUsername)
    {
        IAppCache appCache = new CachingService();
        KerberosReceiverSecurityToken token = appCache.Get <KerberosReceiverSecurityToken>(contextUsername.ToLower());

        return(token);
    }
Esempio n. 3
0
        public void AddEmptyKeyThrowsExceptionWithSliding()
        {
            var    sut = new CachingService();
            Action act = () => sut.Add("", new object(), new TimeSpan(1000));

            act.ShouldThrow <ArgumentOutOfRangeException>();
        }
Esempio n. 4
0
        public void AddNullKeyThrowsExceptionWithExpiration()
        {
            var    sut = new CachingService();
            Action act = () => sut.Add(null, new object(), DateTimeOffset.Now.AddHours(1));

            act.ShouldThrow <ArgumentNullException>();
        }
Esempio n. 5
0
        public void AddNullKeyThrowsException()
        {
            var    sut = new CachingService();
            Action act = () => sut.Add(null, new object());

            act.ShouldThrow <ArgumentNullException>();
        }
        public ActionResult nationalRanking(int?id)
        {
            if (!id.HasValue || !(id >= 2009 && id <= KSU.maxPlayerSeason))
            {
                return(RedirectToAction("national-ranking", "nationalranking", new { id = KSU.maxPlayerSeason }));
            }

            int year = id.Value;

            // Get Dates
            List <double> pollDates = _dataBL.GetRankingDates(year);
            double        maxDate   = pollDates.Max();

            var cacheService = new CachingService();

            var cacheMaxDate = cacheService.Get <double>("chart" + year + "maxdate");

            if (cacheMaxDate < maxDate)
            {
                createChart(year, maxDate, pollDates);
            }

            NationalRankingModel ranking = new NationalRankingModel(new GameListModel(_gameBL.GamesBySeason(year)), year, cacheService.Get <string>("chart" + year + "imagemap"));

            return(View(ranking));
        }
Esempio n. 7
0
        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);
        }
Esempio n. 8
0
            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);
            }
Esempio n. 9
0
        public void AddEmptyKeyThrowsExceptionWithPolicy()
        {
            var    sut = new CachingService();
            Action act = () => sut.Add("", new object(), new CacheItemPolicy());

            act.ShouldThrow <ArgumentOutOfRangeException>();
        }
Esempio n. 10
0
        public void GetEmptyKeyThrowsException()
        {
            var    sut = new CachingService();
            Action act = () => sut.Get <object>("");

            act.ShouldThrow <ArgumentOutOfRangeException>();
        }
Esempio n. 11
0
        public void DeleteFromCache()
        {
            IAppCache cache = new CachingService();

            var profiles = cache.GetOrAddAllProfileNamesAndSdp(
                () => new List <ProfileNameAndSdp>()
            {
                new ProfileNameAndSdp()
                {
                    Name = "Profile 1", Sdp = "Sdp A"
                },
                new ProfileNameAndSdp()
                {
                    Name = "Profile 2", Sdp = "Sdp B"
                },
                new ProfileNameAndSdp()
                {
                    Name = "Profile 3", Sdp = "Sdp C"
                }
            });

            Assert.IsNotNull(profiles);
            Assert.AreEqual(3, profiles.Count);
            Assert.AreEqual("Profile 3", profiles[2].Name);

            cache.ClearProfiles();

            var sameProfiles = cache.GetOrAddAllProfileNamesAndSdp(null);

            Assert.IsNull(sameProfiles);
        }
        static void Main(string[] args)
        {
            Person p1 = new Person {
                Id = 1, Age = 10, Name = ""
            };
            Person p2 = new Person {
                Id = 2, Age = 11, Name = ""
            };
            Person p3 = new Person {
                Id = 3, Age = 12, Name = ""
            };
            ICachingService <int, Person> cache = new CachingService <int, Person>();

            //ICachingService<int, Person> cache = new CachingService<int, Person>(new LRUAlgorithm<int, Person>());
            //ICachingService<int, Person> cache = new CachingService<int, Person>(new MRUAlgorithm<int, Person>());
            cache.Add(1, p1);
            cache.Add(2, p2);
            cache.Add(3, p3);
            var rez = cache.Get(2);
            ICachingService <int, Person2> cache2 = new CachingService <int, Person2>();
            Person2 p4 = new Person2 {
                Id = 1, Age = 13, Name = ""
            };

            cache2.Add(1, p4);
            var rez2 = cache.Get(1);
            var rez3 = cache2.Get(1);
        }
Esempio n. 13
0
        public void Get_ReturnsNullWhenItemNotCached()
        {
            CachingService cachingService = new CachingService();
            string         response       = cachingService.Get("abc") as string;

            Assert.Null(response);
        }
Esempio n. 14
0
        /// <inheritdoc />
        public void Execute(admin_zeegzagContext db)
        {
            var alias      = ";" + _currencyShort + ";";
            var currencyId = CachingService.CurrencyIdByName(_currencyShort,
                                                             () => db.CurrencyT.FirstOrDefault(c => c.ShortName == _currencyShort || c.Alias.Contains(alias))?.Id);

            if (!currencyId.HasValue)
            {
                if (_isActive.GetValueOrDefault(true))
                {
                    //add new coin (since we do not call savechanges() immediately, we do not have id yet. So txfee will be updated on next turn)
                    db.CurrencyT.Add(new CurrencyT()
                    {
                        Name      = _currencyLong ?? _currencyShort,
                        ShortName = _currencyShort,
                    });
                    DatabaseService.EnqueueBroadcast(437907950, $"New coin is added to ZeegZag: {_currencyShort}",
                                                     new InlineKeyboardMarkup(new InlineKeyboardButton[] { new InlineKeyboardUrlButton("Advertise here", "https://www.zeegzag.com"), }));
                }
            }
            else
            {
                //update txfee
                var borsaCurrency = db.BorsaCurrencyT
                                    .Where(bc => bc.BorsaId == _exchangeId && bc.ToCurrencyId == currencyId).ToList();
                foreach (var bc in borsaCurrency)
                {
                    bc.TxFee = _txFee;
                    if (_isActive.HasValue)
                    {
                        bc.Disabled = !_isActive.Value;
                    }
                }
            }
        }
Esempio n. 15
0
        public void AddNullKeyThrowsExceptionWithSliding()
        {
            var    sut = new CachingService();
            Action act = () => sut.Add(null, new object(), new TimeSpan(1000));

            act.ShouldThrow <ArgumentNullException>();
        }
Esempio n. 16
0
 public ProductDetailController(Ecommerce_socksService service, PathProvider provider,
                                CachingService caching)
 {
     this.service        = service;
     this.cachingService = caching;
     this.provider       = provider;
 }
Esempio n. 17
0
        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);
            }
        }
Esempio n. 18
0
        public void AddEmptyKeyThrowsExceptionWithExpiration()
        {
            var    sut = new CachingService();
            Action act = () => sut.Add("", new object(), DateTimeOffset.Now.AddHours(1));

            act.ShouldThrow <ArgumentOutOfRangeException>();
        }
Esempio n. 19
0
        public void AddWithPolicyReturnsCachedItem()
        {
            var sut = new CachingService();

            sut.Add(TestKey, "testObject", new CacheItemPolicy());
            Assert.AreEqual("testObject", sut.Get <string>(TestKey));
        }
Esempio n. 20
0
        public void AddWithOffsetReturnsCachedItem()
        {
            var sut = new CachingService();

            sut.Add(TestKey, "testObject", DateTimeOffset.Now.AddSeconds(1));
            Assert.AreEqual("testObject", sut.Get <string>(TestKey));
        }
Esempio n. 21
0
 public CategorySectionController(Ecommerce_socksService service,
                                  IMemoryCache memoryCache, CachingService caching)
 {
     this.service        = service;
     this.memoryCache    = memoryCache;
     this.cachingService = caching;
 }
Esempio n. 22
0
        public void AddWithSlidingReturnsCachedItem()
        {
            var sut = new CachingService();

            sut.Add(TestKey, "testObject", new TimeSpan(5000));
            Assert.AreEqual("testObject", sut.Get <string>(TestKey));
        }
Esempio n. 23
0
        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);
        }
Esempio n. 24
0
        public void GetNullKeyThrowsException()
        {
            var    sut = new CachingService();
            Action act = () => sut.Get <object>(null);

            act.ShouldThrow <ArgumentNullException>();
        }
Esempio n. 25
0
        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);
        }
Esempio n. 26
0
        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();
        }
Esempio n. 27
0
        public void AddThenGetReturnsCachedObject()
        {
            var sut = new CachingService();

            sut.Add(TestKey, "testObject");
            Assert.AreEqual("testObject", sut.Get <string>(TestKey));
        }
Esempio n. 28
0
        static void Main(string[] arguments)
        {
            var runPath = AppDomain.CurrentDomain.BaseDirectory;

            using (SerilogSupport.InitLogger(new Uri(string.Concat(runPath, "serilog.config"))))
            {
                AppDomain.CurrentDomain.UnhandledException += (sender, args) => {
                    var ex = args.ExceptionObject as Exception;
                    Logging.Log().Error(ex, "Unhandled exception: {ExceptionObject} (isTerminating: {IsTerminating})", args.ExceptionObject, args.IsTerminating);
                };
                Logging.Log().Information("Version: {ApplicationVersion}", typeof(Program).Assembly.GetName().Version);
                var assemblyLocation = typeof(Program).Assembly.Location;

                if (assemblyLocation != null)
                {
                    var productVersion = FileVersionInfo.GetVersionInfo(assemblyLocation).ProductVersion;
                    Logging.Log().Information("Product Version: {ApplicationVersion}", typeof(Program).Assembly.GetName().Version);
                }

                var       environment = EnvironmentResolver.GetEnvironmentName();
                IAppCache cache       = new CachingService {
                    DefaultCacheDuration = 60 * 5
                };
                IConfigReader        configReader = ConfigReaderFactory.Create(cache, environment, "API");
                IWebApiConfiguration webApiConfig = new WebApiConfig(configReader);

                Host.Run(() => new ServiceApp(webApiConfig));

                Logging.Log().Information("Application terminated.");
            }
        }
Esempio n. 29
0
        public void AddNullThrowsException()
        {
            var    sut = new CachingService();
            Action act = () => sut.Add <object>(TestKey, null);

            act.ShouldThrow <ArgumentNullException>();
        }
        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);
            }
        }
Esempio n. 31
0
 public void AddComplexObjectThenGetReturnsCachedObject()
 {
     var sut = new CachingService();
     sut.Add(TestKey, new ComplexTestObject());
     var actual = sut.Get<ComplexTestObject>(TestKey);
     var expected = new ComplexTestObject();
     Assert.AreEqual(ComplexTestObject.SomeMessage, ComplexTestObject.SomeMessage);
     Assert.AreEqual(expected.SomeItems, actual.SomeItems);
 }
Esempio n. 32
0
        public void ShouldRemoveItemFromCache()
        {
            var cache = new CachingService();

              cache.AddToCache("test","test",CachePriority.Default,null);

              cache.RemoveCachedItem("test");

              Assert.That(cache.GetCachedItem("test"),Is.Null);
        }
Esempio n. 33
0
        public void ShouldAddItemToCache()
        {
            var cache = new CachingService();

              cache.AddToCache("test","test",CachePriority.Default,null);

              var result = cache.GetCachedItem("test");

              Assert.That(result,Is.Not.Null);
        }
Esempio n. 34
0
        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);
        }
Esempio n. 35
0
 public void GetWithClassTypeParamReturnsType()
 {
     var sut = new CachingService();
     var cached = new EventArgs();
     sut.Add(TestKey, cached);
     Assert.AreEqual(cached, sut.Get<EventArgs>(TestKey));
 }
 /// <summary>
 /// Default c'tor with predefined Services
 /// </summary>
 public PredefinedServiceFacade()
 {
     RequestService = new RequestService();
     RequestParameterService = new UrlRequestParameterService();
     MappingService = new JsonMapperService();
     GeolocationMappingService = new GoogleGeolocationMappingService();
     CachingService = new CachingService();
     SerializationService = new JsonSerializationService();
     ThreadService = new ThreadService();
     MailService = new SystemNetMail();
 }
Esempio n. 37
0
 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);
 }
Esempio n. 38
0
 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);
 }
Esempio n. 39
0
        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);
        }
Esempio n. 40
0
 public void RemovedItemCannotBeRetrievedFromCache()
 {
     var sut = new CachingService();
     sut.Add(TestKey, new object());
     Assert.NotNull(sut.Get<object>(TestKey));
     sut.Remove(TestKey);
     Assert.Null(sut.Get<object>(TestKey));
 }
Esempio n. 41
0
 public void GetWithWrongStructTypeParamReturnsNull()
 {
     var sut = new CachingService();
     var cached = new DateTime();
     sut.Add(TestKey, cached);
     Assert.AreEqual(new TimeSpan(), sut.Get<TimeSpan>(TestKey));
 }
Esempio n. 42
0
 public void AddEmptyKeyThrowsExceptionWithPolicy()
 {
     var sut = new CachingService();
     Action act = () => sut.Add("", new object(), new CacheItemPolicy());
     act.ShouldThrow<ArgumentOutOfRangeException>();
 }
Esempio n. 43
0
 public void AddEmptyKeyThrowsExceptionWithExpiration()
 {
     var sut = new CachingService();
     Action act = () => sut.Add("", new object(), DateTimeOffset.Now.AddHours(1));
     act.ShouldThrow<ArgumentOutOfRangeException>();
 }
Esempio n. 44
0
 public void AddEmptyKeyThrowsExceptionWithSliding()
 {
     var sut = new CachingService();
     Action act = () => sut.Add("", new object(), new TimeSpan(1000));
     act.ShouldThrow<ArgumentOutOfRangeException>();
 }
Esempio n. 45
0
 public void AddNullKeyThrowsExceptionWithExpiration()
 {
     var sut = new CachingService();
     Action act = () => sut.Add(null, new object(), DateTimeOffset.Now.AddHours(1));
     act.ShouldThrow<ArgumentNullException>();
 }
Esempio n. 46
0
 public void AddNullKeyThrowsExceptionWithPolicy()
 {
     var sut = new CachingService();
     Action act = () => sut.Add(null, new object(), new CacheItemPolicy());
     act.ShouldThrow<ArgumentNullException>();
 }
Esempio n. 47
0
        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);
        }
Esempio n. 48
0
 public void GetWithWrongClassTypeParamReturnsNull()
 {
     var sut = new CachingService();
     var cached = new EventArgs();
     sut.Add(TestKey, cached);
     Assert.IsNull(sut.Get<ArgumentNullException>(TestKey));
 }
Esempio n. 49
0
 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);
 }
Esempio n. 50
0
 public void GetWithValueTypeParamReturnsType()
 {
     var sut = new CachingService();
     const int cached = 3;
     sut.Add(TestKey, cached);
     Assert.AreEqual(3, sut.Get<int>(TestKey));
 }
Esempio n. 51
0
        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);
        }
Esempio n. 52
0
 public void GetWithStructTypeParamReturnsType()
 {
     var sut = new CachingService();
     var cached = new DateTime(2000, 1, 1);
     sut.Add(TestKey, cached);
     Assert.AreEqual(cached, sut.Get<DateTime>(TestKey));
 }
Esempio n. 53
0
        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);
        }
Esempio n. 54
0
 public void GetWithNullableIntRetunsCachedNonNullableInt()
 {
     var sut = new CachingService();
     const int expected = 123;
     sut.Add(TestKey, expected);
     Assert.AreEqual(expected, sut.Get<int?>(TestKey));
 }
Esempio n. 55
0
 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);
 }
Esempio n. 56
0
 public void GetWithIntRetunsDefualtIfNotCached()
 {
     var sut = new CachingService();
     Assert.AreEqual(default(int), sut.Get<int>(TestKey));
 }
Esempio n. 57
0
        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);
        }
Esempio n. 58
0
 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);
 }
Esempio n. 59
0
 public void GetEmptyKeyThrowsException()
 {
     var sut = new CachingService();
     Action act = () => sut.Get<object>("");
     act.ShouldThrow<ArgumentOutOfRangeException>();
 }
Esempio n. 60
0
 public void GetNullKeyThrowsException()
 {
     var sut = new CachingService();
     Action act = () => sut.Get<object>(null);
     act.ShouldThrow<ArgumentNullException>();
 }