Ejemplo n.º 1
0
        public void Clear_ReturnsTheNumberOfItemsRemoved(int itemCount)
        {
            for (var i = 0; i < itemCount; ++i)
            {
                Cache.AddTimed(StringItems[i], StringItems[i], Cache.Clock.GetCurrentInstant() + Duration.FromMinutes(10));
            }

            Assert.That(Cache.Clear(), Is.EqualTo(itemCount));
            Assert.That(Cache.Count(), Is.EqualTo(0));
            Assert.That(Cache.LongCount(), Is.EqualTo(0L));
        }
        public void PurgeSportEventCacheItem()
        {
            Assert.AreEqual(0, _eventCache.Count());

            var ci = _sportEventCacheItemFactory.Build(new FixtureDTO(RMF.GetFixture()), DefaultCulture);

            _eventCache.Add(new CacheItem(ci.Id.ToString(), ci), null);
            Assert.AreEqual(1, _eventCache.Count());

            _sportEventCache.PurgeItem(ci.Id);

            Assert.AreEqual(0, _eventCache.Count());
        }
Ejemplo n.º 3
0
        public void InVariantMarketDescriptionCacheIsCachingTest()
        {
            const string callType = "GetMarketDescriptionsAsync";
            var          market   = _inVariantMdCache.GetMarketDescriptionAsync(178, "lcoo:markettext:1", TestData.Cultures).Result;

            Assert.IsNotNull(market);
            Assert.AreEqual(178, market.Id);
            Assert.AreEqual(750, _invariantMemoryCache.Count());
            Assert.AreEqual(3, _dataRouterManager.GetCallCount(callType), $"{callType} should be called exactly 3 times.");

            market = _inVariantMdCache.GetMarketDescriptionAsync(178, "lcoo:markettext:1", TestData.Cultures).Result;
            Assert.IsNotNull(market);
            Assert.AreEqual(750, _invariantMemoryCache.Count());
            Assert.AreEqual(3, _dataRouterManager.GetCallCount(callType), $"{callType} - no new call should be made.");
        }
Ejemplo n.º 4
0
        public void ClearPages_Should_Set_TempData_Message_And_Clear_Cache_And_Clear_All_Pages()
        {
            // Arrange
            _repository.AddNewPage(new Page()
            {
                Id = 1
            }, "text", "admin", DateTime.UtcNow);
            _repository.AddNewPage(new Page()
            {
                Id = 2
            }, "text", "admin", DateTime.UtcNow);

            _pageCache.Add(1, new PageViewModel());
            _listCache.Add("list.somekey", new List <string>());
            _siteCache.AddMenu("should not be cleared");

            // Act
            RedirectToRouteResult result = _toolsController.ClearPages() as RedirectToRouteResult;

            // Assert
            Assert.That(result, Is.Not.Null, "RedirectToRouteResult");
            Assert.That(result.RouteValues["action"], Is.EqualTo("Index"));

            Assert.That(_toolsController.TempData["SuccessMessage"], Is.EqualTo(SiteStrings.SiteSettings_Tools_ClearDatabase_Message));
            Assert.That(_cache.Count(), Is.EqualTo(1));
            Assert.That(_repository.AllPages().Count(), Is.EqualTo(0));
        }
 private static void DeleteOlderItem()
 {
     if (cache.Count() > 5)
     {
         cache.Remove(keys[0]);
         keys.RemoveAt(0);
     }
 }
Ejemplo n.º 6
0
 public void Dispose_CustomSystemMemoryCache_ObjectDisposedExceptionAfterDispose()
 {
     Cache = new MemoryCache(new MemoryCacheSettings {
         CacheName = "PINO"
     });
     Cache.Dispose();
     Assert.Throws <ObjectDisposedException>(() => { Cache.Count(); });
 }
Ejemplo n.º 7
0
 /// <summary>
 ///     Starts the health check and returns <see cref="HealthCheckResult" />
 /// </summary>
 public HealthCheckResult StartHealthCheck()
 {
     lock (_lock)
     {
         return(_sportEventStatusCache.Any()
             ? HealthCheckResult.Healthy($"Cache has {_sportEventStatusCache.Count()} items.")
             : HealthCheckResult.Unhealthy("Cache is empty."));
     }
 }
Ejemplo n.º 8
0
        public CacheStatus GetStatus()
        {
            var status = new CacheStatus()
            {
                Size = _cache.Count(),
                Name = _cache.Name,
                Type = CacheType.Volatile
            };

            return(status);
        }
Ejemplo n.º 9
0
        /// <summary>
        ///     Starts the health check and returns <see cref="HealthCheckResult" />
        /// </summary>
        public HealthCheckResult StartHealthCheck()
        {
            var keys    = _cache.Select(w => w.Key).ToList();
            var details =
                $" [Players: {keys.Count(c => c.Contains("player"))}, Competitors: {keys.Count(c => c.Contains("competitor"))}, Teams: {keys.Count(c => c.Equals("team"))}, SimpleTeams: {keys.Count(c => c.Contains(SdkInfo.SimpleTeamIdentifier))}]";

            //var otherKeys = _cache.Where(w => !w.Key.Contains("competitor")).Select(s => s.Key);
            //CacheLog.Debug($"Ids: {string.Join(",", otherKeys)}");
            return(_cache.Any()
                ? HealthCheckResult.Healthy($"Cache has {_cache.Count()} items{details}.")
                : HealthCheckResult.Unhealthy("Cache is empty."));
        }
Ejemplo n.º 10
0
        /// <summary>
        ///     Starts the health check and returns <see cref="HealthCheckResult" />
        /// </summary>
        public HealthCheckResult StartHealthCheck()
        {
            var keys    = Cache.Select(w => w.Key).ToList();
            var details =
                $" [Match: {keys.Count(c => c.Contains("match"))}, Stage: {keys.Count(c => c.Contains("race") || c.Contains("stage"))}, Season: {keys.Count(c => c.Contains("season"))}, Tournament: {keys.Count(c => c.Contains("tournament"))}, Draw: {keys.Count(c => c.Contains("draw"))}, Lottery: {keys.Count(c => c.Contains("lottery"))}]";

            //var otherKeys = Cache.Where(w => w.Key.Contains("tournament")).Select(s=>s.Key);
            //CacheLog.Debug($"Tournament Ids: {string.Join(",", otherKeys)}");
            return(Cache.Any()
                ? HealthCheckResult.Healthy($"Cache has {Cache.Count()} items{details}.")
                : HealthCheckResult.Unhealthy("Cache is empty."));
        }
Ejemplo n.º 11
0
        public void TestMemoryCacheCacheItem()
        {
            // Prepare
            var cache = new MemoryCache();
            var item  = new CacheItem("Key", new object());

            // Act
            cache.Add(item);

            // Assert
            Assert.AreEqual(1, cache.Count());
        }
Ejemplo n.º 12
0
        public void TestMemoryCacheAdd()
        {
            // Prepare
            var cache = new MemoryCache();
            var key   = "Key";
            var value = new object();

            // Act
            cache.Add(key, value);

            // Assert
            Assert.AreEqual(1, cache.Count());
        }
Ejemplo n.º 13
0
        public void AddItem(string key, object value)
        {
            lock (padlock)
            {
                byte cacheLimit = Settings.Default.cacheLimit;

                if (cache.Count() >= cacheLimit) // last queries
                {
                    cache.Remove(cache.FirstOrDefault().Key);
                }
                cache.Add(key, value, DateTimeOffset.MaxValue);
            }
        }
Ejemplo n.º 14
0
        public void Index_POST_Should_Clear_Site_Cache()
        {
            // Arrange
            _siteCache.AddMenu("some menu");
            _siteCache.AddAdminMenu("admin menu");
            _siteCache.AddLoggedInMenu("logged in menu");

            SettingsViewModel model = new SettingsViewModel();

            // Act
            ViewResult result = _settingsController.Index(model) as ViewResult;

            // Assert
            Assert.That(_cache.Count(), Is.EqualTo(0));
        }
Ejemplo n.º 15
0
        /// <summary>
        ///     Gets the cache count by region (region not supported in memorycache)
        /// </summary>
        public override async Task <long> Count(string region)
        {
            if (!_isEnabled)
            {
                return(0);
            }

            return(await Task.Factory.StartNew(() =>
            {
                lock (Sync)
                {
                    return _cache.Count();
                }
            }));
        }
Ejemplo n.º 16
0
        public void clear_should_redirect_and_clear_all_cache_items()
        {
            // Arrange
            _applicationSettings.UseObjectCache = true;
            _pageCache.Add(1, new PageViewModel());
            _listCache.Add <string>("test", new List <string>());
            _siteCache.AddMenu("menu");

            // Act
            RedirectToRouteResult result = _cacheController.Clear() as RedirectToRouteResult;

            // Assert
            Assert.That(result, Is.Not.Null, "RedirectToRouteResult");
            Assert.That(result.RouteValues["action"], Is.EqualTo("Index"));
            Assert.That(_cacheController.TempData["CacheCleared"], Is.EqualTo(true));

            Assert.That(_cache.Count(), Is.EqualTo(0));
        }
        public void Edit_POST_Should_Save_Setting_Values_To_Repository_From_Model_And_Clear_SiteCache()
        {
            // Arrange
            _pageViewModelCache.Add(1, new PageViewModel());             // dummmy items
            _listCache.Add("a key", new List <string>()
            {
                "1", "2"
            });

            TextPluginStub plugin = new TextPluginStub();

            plugin.Repository  = _repository;
            plugin.PluginCache = _siteCache;
            plugin.Settings.SetValue("name1", "default-value1");
            plugin.Settings.SetValue("name2", "default-value2");

            _pluginFactory.RegisterTextPlugin(plugin);

            PluginViewModel model = new PluginViewModel();

            model.Id            = plugin.Id;
            model.SettingValues = new List <SettingValue>();
            model.SettingValues.Add(new SettingValue()
            {
                Name = "name1", Value = "new-value1"
            });
            model.SettingValues.Add(new SettingValue()
            {
                Name = "name2", Value = "new-value2"
            });

            // Act
            ViewResult result = _controller.Edit(model) as ViewResult;

            // Assert
            List <SettingValue> values = _repository.TextPlugins[0].Settings.Values.ToList();

            Assert.That(values[0].Value, Is.EqualTo("new-value1"));
            Assert.That(values[1].Value, Is.EqualTo("new-value2"));

            Assert.That(_memoryCache.Count(), Is.EqualTo(0));
        }
Ejemplo n.º 18
0
        private ValueTask <HealthCheckResult> StartHealthCheck()
        {
            var keys    = _cache.Select(w => w.Key).ToList();
            var details = $" [Players: {keys.Count(c => c.Contains("player"))}, Competitors: {keys.Count(c => c.Contains("competitor"))}, Teams: {keys.Count(c => c.Equals("team"))}, SimpleTeams: {keys.Count(URN.IsSimpleTeam)}]";

            return(_cache.Any()
                ? new ValueTask <HealthCheckResult>(HealthCheckResult.Healthy($"Cache has { _cache.Count() } items{ details}."))
                : new ValueTask <HealthCheckResult>(HealthCheckResult.Unhealthy("Cache is empty.")));
        }
Ejemplo n.º 19
0
 public void Dispose_DefaultSystemMemoryCache_CannotWorkAfterDispose()
 {
     Cache = new MemoryCache(new MemoryCacheSettings());
     Cache.Dispose();
     Assert.Throws <ObjectDisposedException>(() => { Cache.Count(); });
 }
Ejemplo n.º 20
0
        public string SendCommandToDeivce(string id, COMMAND command, STAT stat, POWERSTAT powerStat)
        {
            MemoryCache cache = MemoryCache.Default;

            if (cache.Count() > 0)
            {
                //Message = cache.Count() + " device(s) have been registered";
                //foreach (var oc in cache.Distinct())
                //{
                //    DeviceInformation deviceInformation = (DeviceInformation)oc.Value;
                //    DeviceInfoList.Add("ID: " + deviceInformation.DeviceID + "-IP: " + deviceInformation.IP + " -DeviceStat: " + deviceInformation.DeviceStat + " -PowerStat: " + deviceInformation.PowerStat.ToString("00") + " -Ver: " + deviceInformation.DeviceVer);
                //}
                DeviceInformation deviceInformation = (DeviceInformation)cache.Get(id);
                IPEndPoint        ipEndPoint        = new IPEndPoint(IPAddress.Parse(deviceInformation.IP), deviceInformation.port);
                Socket            clientSocket      = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                clientSocket.Connect(ipEndPoint);
                //DMProtocol dmProtocol = null;
                string msg = null;
                byte[] data;
                //switch (command)
                //{
                //    case COMMAND.KEEPLIVE: //废弃
                //        //if (cmd.Equals("111"))
                //        //{
                //        //    //    0    1     2   3      4     5                                         6      7
                //        //    msg = "SXZL,V0100,01,DM77712,3696,00," + DateTime.Now.ToString("yyyyMMddHHmmss") + ",9910";
                //        //}
                //        dmProtocol = new DMProtocol(HEADER.XXZL.ToString(), VERSION.V0100.ToString(),deviceInformation.DeviceID,00,0,0, DateTime.Now.ToString("yyyyMMddHHmmss"));
                //        msg = dmProtocol.makeMessage();
                //        //int count;
                //        try
                //        {
                //            //clientSocket.Send(Encoding.UTF8.GetBytes(msg));
                //            //data = new byte[1024];
                //            //count = clientSocket.Receive(data);
                //            //msg = Encoding.UTF8.GetString(data, 0, count);

                //            msg = sendAndReceive(msg, clientSocket);
                //            Console.WriteLine("Receive:" + msg);
                //        }
                //        catch (Exception ex)
                //        {
                //            Console.WriteLine(ex.Message);
                //        }
                //        break;
                //    case COMMAND.ASK:
                //        dmProtocol = new DMProtocol(HEADER.XXZL.ToString(), VERSION.V0100.ToString(), deviceInformation.DeviceID, (int)command, 0, 0, DateTime.Now.ToString("yyyyMMddHHmmss"));
                //        msg = dmProtocol.makeMessage();
                //        try
                //        {
                //            msg = sendAndReceive(msg, clientSocket);
                //            Console.WriteLine("Receive:" + msg);
                //        }
                //        catch (Exception ex)
                //        {
                //            Console.WriteLine(ex.Message);
                //        }
                //        break;
                //    case COMMAND.REMIND:
                //        dmProtocol = new DMProtocol(HEADER.XXZL.ToString(), VERSION.V0100.ToString(), deviceInformation.DeviceID, (int)command, 0, 0, DateTime.Now.ToString("yyyyMMddHHmmss"));
                //        msg = dmProtocol.makeMessage();
                //        try
                //        {
                //            msg = sendAndReceive(msg, clientSocket);
                //            Console.WriteLine("Receive:" + msg);
                //        }
                //        catch (Exception ex)
                //        {
                //            Console.WriteLine(ex.Message);
                //        }
                //        break;
                //    case COMMAND.SETUP:
                //        dmProtocol = new DMProtocol(HEADER.XXZL.ToString(), VERSION.V0100.ToString(), deviceInformation.DeviceID, (int)command, (int)stat, (int)powerStat, DateTime.Now.ToString("yyyyMMddHHmmss"));
                //        msg = dmProtocol.makeMessage();
                //        try
                //        {
                //            msg = sendAndReceive(msg, clientSocket);
                //            Console.WriteLine("Receive:" + msg);
                //        }
                //        catch (Exception ex)
                //        {
                //            Console.WriteLine(ex.Message);
                //        }
                //        break;
                //    case COMMAND.UPDATE:
                //        dmProtocol = new DMProtocol(HEADER.XXZL.ToString(), VERSION.V0100.ToString(), deviceInformation.DeviceID, (int)command, 0, 0, DateTime.Now.ToString("yyyyMMddHHmmss"));
                //        msg = dmProtocol.makeMessage();
                //        try
                //        {
                //            msg = sendAndReceive(msg, clientSocket);
                //            Console.WriteLine("Receive:" + msg);
                //        }
                //        catch (Exception ex)
                //        {
                //            Console.WriteLine(ex.Message);
                //        }
                //        break;
                //}
                return(msg);
            }
            else
            {
                return("Device pool is empty");
            }
        }
Ejemplo n.º 21
0
 public void Dispose_DefaultSystemMemoryCache_CannotWorkAfterDispose()
 {
     Cache = new MemoryCache(new MemoryCacheSettings());
     Cache.Dispose();
     Cache.Count();
 }
 /// <summary>
 /// Returns the number of items in the cache.
 /// </summary>
 /// <returns>Returns an integer representing the number of items in the cache.</returns>
 public int Count()
 {
     return(_cache.Count());
 }
Ejemplo n.º 23
0
        public void GetScheduleForDate()
        {
            Assert.AreEqual(0, _memoryCache.Count());
            Assert.AreEqual(0, _dataRouterManager.GetCallCount(DateSchedule), $"{DateSchedule} should be called exactly 0 times.");
            Assert.AreEqual(0, _dataRouterManager.GetCallCount(SportEventSummary), $"{SportEventSummary} should be called exactly 0 times.");

            Task.Run(async() =>
            {
                await _sportEventCache.GetEventIdsAsync(DateTime.Now, TestData.Culture);
            }).GetAwaiter().GetResult();

            Assert.AreEqual(ScheduleEventCount, _memoryCache.Count());
            Assert.AreEqual(1, _dataRouterManager.GetCallCount(DateSchedule), $"{DateSchedule} should be called exactly 1 times.");
            Assert.AreEqual(0, _dataRouterManager.GetCallCount(SportEventSummary), $"{SportEventSummary} should be called exactly 0 times.");

            var a = _sportEventCache.GetEventCacheItem(TestData.EventId);

            Assert.IsNotNull(a, "Cached item not found.");
        }
Ejemplo n.º 24
0
 public int Count()
 => memoryCache.Count();
Ejemplo n.º 25
0
        public void player_profile_gets_cached()
        {
            const string callType = "GetPlayerProfileAsync";

            Assert.AreEqual(0, _dataRouterManager.GetCallCount(callType), "Should be called exactly 0 times.");
            Assert.IsTrue(!_memoryCache.Any());
            var player = _profileCache.GetPlayerProfileAsync(CreatePlayerUrn(1), TestData.Cultures).Result;

            Assert.IsNotNull(player);
            Assert.AreEqual(1, _memoryCache.Count());

            Assert.AreEqual(TestData.Cultures.Count, _dataRouterManager.GetCallCount(callType), $"{callType} should be called exactly {TestData.Cultures.Count} times.");

            //if we call again, should not fetch again
            player = _profileCache.GetPlayerProfileAsync(CreatePlayerUrn(1), TestData.Cultures).Result;
            Assert.IsNotNull(player);
            Assert.AreEqual(1, _memoryCache.Count());

            Assert.AreEqual(TestData.Cultures.Count, _dataRouterManager.GetCallCount(callType), $"{callType} should be called exactly {TestData.Cultures.Count} times.");
        }
Ejemplo n.º 26
0
 public void Dispose_CustomSystemMemoryCache_ObjectDisposedExceptionAfterDispose()
 {
     Cache = new MemoryCache(new MemoryCacheSettings { CacheName = "PINO" });
     Cache.Dispose();
     Cache.Count();
 }
 /// <summary>
 /// Starts the health check and returns <see cref="HealthCheckResult"/>
 /// </summary>
 public HealthCheckResult StartHealthCheck()
 {
     return(_cache.Any() ? HealthCheckResult.Healthy($"Cache has {_cache.Count()} items.") : HealthCheckResult.Healthy("Cache is empty."));
 }
Ejemplo n.º 28
0
        public void player_profile_is_called_only_once()
        {
            const string callType = "GetPlayerProfileAsync";

            Assert.AreEqual(0, _memoryCache.Count());
            Assert.AreEqual(0, _dataRouterManager.GetCallCount(callType), $"{callType} should be called 0 time.");
            var name = _nameProvider.GetOutcomeNameAsync("sr:player:2", TestData.Cultures.First()).Result;

            Assert.AreEqual("Cole, Ashley", name, "The generated name is not correct");
            Assert.AreEqual(1, _memoryCache.Count());
            Assert.AreEqual(1, _dataRouterManager.GetCallCount(callType), $"{callType} should be called 1 time.");
        }