Exemplo n.º 1
0
        public void IsFull_When_NotFull_Expect_False()
        {
            var cache = new Cache <int, int>(capacity: 5);

            cache.AddOrUpdate(0, 10);
            cache.AddOrUpdate(1, 20);
            cache.AddOrUpdate(2, 30);
            cache.AddOrUpdate(3, 40);
            Assert.False(cache.IsFull);
        }
Exemplo n.º 2
0
        public void Can_Update_Existing_Values()
        {
            var cache = new Cache <string, int>(10);

            cache.AddOrUpdate("one", 1);
            cache.AddOrUpdate("one", 2);

            var result = cache.TryGetValue("one", out var value);

            Assert.That(result, Is.True);
            Assert.That(value, Is.EqualTo(2));
        }
Exemplo n.º 3
0
        private static Cache <int, string> _Cache2 = new Cache <int, string>();                                     //GC (1)
        public static void Run()
        {
            _Cache1.TryAdd(1, "value1", DateTimeOffset.Now.AddMinutes(1));
            _Cache1.TryAdd(2, () => "value2", DateTimeOffset.Now.AddMinutes(2));
            _Cache1.TryAdd(3, () => ("value3", DateTimeOffset.Now.AddDays(3)));

            _Cache1.TryAdd(101, "value101", TimeSpan.FromMinutes(1));
            _Cache1.TryAdd(102, "value102", TimeSpan.FromMinutes(2));
            _Cache1.TryAdd(103, "value103", TimeSpan.FromMinutes(3));


            _Cache1.TryUpdate(1, "newValue1", out var oldValue1);
            _Cache1.TryUpdate(2, value1 => "newValue2", out var oldValue2);
            _Cache1.TryUpdate(3, DateTimeOffset.Now.AddDays(1), out var value3);
            _Cache1.TryUpdate(4, "newValue4", DateTimeOffset.Now.AddDays(2), out var oldValue4);
            _Cache1.TryUpdate(5, (value5) => "newValue5", DateTimeOffset.Now.AddDays(3), out var oldValue5);
            _Cache1.TryUpdate(6, (value5, expire5) => ("newValue6", DateTimeOffset.Now.AddDays(4)), out var oldValue6);


            _Cache1.AddOrUpdate(1, "value1", DateTimeOffset.Now.AddYears(1));
            _Cache1.AddOrUpdate(2, "newValue2", DateTimeOffset.Now.AddYears(2), (value2) => "updateValue2");
            _Cache1.AddOrUpdate(3, () => ("newValue2", DateTimeOffset.Now.AddYears(3)), (value3, expire3) => ("updateValue3", DateTimeOffset.Now.AddYears(3)));


            _Cache1.GetOrAdd(4, "Value4", DateTimeOffset.Now.AddSeconds(1));
            _Cache1.GetOrAdd(5, () => "Value5", DateTimeOffset.Now.AddSeconds(2));
            _Cache1.GetOrAdd(6, () => ("Value6", DateTimeOffset.Now.AddSeconds(3)));


            _Cache1.TryGetValue(1, out var getValue1);
            _Cache1.TryGetValue(2, out var getValue2);
            _Cache1.TryGetValue(3, out var getValue3);
            _Cache1.TryGetValue(4, out var getValue4);
            _Cache1.TryGetValue(5, out var getValue5);
            _Cache1.TryGetValue(6, out var getValue6);
            Console.WriteLine(getValue1);
            Console.WriteLine(getValue2);
            Console.WriteLine(getValue3);
            Console.WriteLine(getValue4);
            Console.WriteLine(getValue5);
            Console.WriteLine(getValue6);


            _Cache1.ForEach((key, value, expire) => {
                Console.WriteLine($"{key}={value},{expire}");
            });

            _Cache1.TryRemove(1, out var oldValue11);

            _Cache1.Collect();
            //_Cache1.Clear();
        }
Exemplo n.º 4
0
        public void Least_Recently_Inserted_Key_Is_Removed_On_AddOrUpdate()
        {
            var cache = new Cache <string, string>(2);

            cache.AddOrUpdate("apple", "first");
            cache.AddOrUpdate("banana", "second");
            cache.AddOrUpdate("pear", "third");

            var result = cache.TryGetValue("apple", out var value);

            Assert.That(result, Is.False);
            Assert.That(value, Is.EqualTo(null));
        }
Exemplo n.º 5
0
        //Updating existing node (same key, different value) a few times
        //Expect value of the node to be the lastest updated one
        public void AddOrUpdate_When_KeyIdentical_Expect_ValueToBeUpdated()
        {
            var    cache            = new Cache <int, string>(capacity: 5);
            var    key              = 0;
            string MostUpdatedValue = "Last update for initial node";
            string valueInCache;

            cache.AddOrUpdate(0, "Initial node");
            cache.AddOrUpdate(0, "Same node updated");
            cache.AddOrUpdate(0, MostUpdatedValue);

            Assert.True(cache.TryGetValue(key, out valueInCache));
            Assert.AreEqual(MostUpdatedValue, valueInCache, "Value in cache does not match value put in");
        }
Exemplo n.º 6
0
        public void Cache_Update_Item_Ok()
        {
            Cache  c  = new Cache();
            object o1 = new object();
            object o2 = new object();

            c.AddOrUpdate("test", o1, 1);
            Assert.Same(c.Get("test"), o1);
            c.AddOrUpdate("test", o2, 1);
            Assert.Same(c.Get("test"), o2);

            Thread.Sleep(1050);
            Assert.False(c.Exists("test"));
        }
Exemplo n.º 7
0
        public static ITokenManager GetTokenManager()
        {
            ITokenManager tokenManager;

            try
            {
                tokenManager = Cache.Get <ITokenManager>("tokenManager");
                if (null != tokenManager)
                {
                    return(tokenManager);
                }
                var certificateDetails = Cache.Get <ICertificateDetails>("ICertificateDetails");
                var thumbPrint         = certificateDetails.GetCertificateThumbPrint();
                if (String.IsNullOrEmpty(thumbPrint))
                {
                    tokenManager = new SymmetricKeyTokenManager();
                }
                else
                {
                    tokenManager = new CertificateTokenManager(certificateDetails);
                }
            }
            catch (Exception)
            {
                tokenManager = new SymmetricKeyTokenManager();
            }

            Cache.AddOrUpdate(tokenManager, "tokenManager", 20000);
            return(tokenManager);
        }
Exemplo n.º 8
0
        public Int32 getKey(string value)
        {
            object key;
            string desc;

            if (caseSensitive)
            {
                desc = value;
            }
            else
            {
                desc = value.ToLower();
            }
            if (!Cache.TryGet(keyContext, desc, out key))
            {
                aLock.AcquireReaderLock(TIMEOUT);
                try {
                    findKey.Parameters["@value"].Value = desc;
                    key = findKey.ExecuteScalar();
                    if (key == null)
                    {
                        key = AddEntry(desc);
                    }
                    Cache.AddOrUpdate(keyContext, desc, key);
                }
                finally {
                    aLock.ReleaseReaderLock();
                }
            }
            return((Int32)key);
        }
Exemplo n.º 9
0
        public ReportAccessHub(IUserQueryService userQuerySvc, IReportQueueService reportQueueService)
        {
            _userQuerySvc       = userQuerySvc;
            _reportQueueService = reportQueueService;

            // Get cached user information.
            // TODO: Determine how to handle cache expiration.
            _reportUsers = Cache.Get <ConcurrentDictionary <Guid, List <Guid> > >("reportUsers");
            if (_reportUsers == null)
            {
                _reportUsers = new ConcurrentDictionary <Guid, List <Guid> >();
                Cache.AddOrUpdate(_reportUsers, "reportUsers");
            }
            _userConnections = Cache.Get <ConcurrentDictionary <Guid, List <string> > >("reportUserConnections");
            if (_userConnections == null)
            {
                _userConnections = new ConcurrentDictionary <Guid, List <string> >();
                Cache.AddOrUpdate(_userConnections, "reportUserConnections");
            }
            _reportMonitors = Cache.Get <ConcurrentDictionary <string, List <Guid> > >("reportMonitors");
            if (_reportMonitors == null)
            {
                _reportMonitors = new ConcurrentDictionary <string, List <Guid> >();
                Cache.AddOrUpdate(_reportMonitors, "reportMonitors");
            }
        }
Exemplo n.º 10
0
        public void ObjectUpdate(TimeSpan elapsedTime)
        {
            var users = ServerContext.Game.Clients.Where(i => i != null &&
                                                         i.Aisling != null && i.Aisling.CurrentMapId == ID)
                        .Select(i => i.Aisling).ToArray();

            Sprite[] ObjectCache = null;

            if (!AreaObjectCache.Exists(Name))
            {
                ObjectCache = GetAreaObjects();

                if (ObjectCache.Length > 0)
                {
                    AreaObjectCache.AddOrUpdate(Name, ObjectCache, 3);
                }
            }
            else
            {
                ObjectCache = AreaObjectCache.Get(Name);
            }

            if (ObjectCache != null && ObjectCache.Length > 0)
            {
                if (users.Length > 0)
                {
                    UpdateMonsterObjects(elapsedTime, ObjectCache.OfType <Monster>());
                    UpdateMundaneObjects(elapsedTime, ObjectCache.OfType <Mundane>());
                    UpdateItemObjects(elapsedTime, ObjectCache.OfType <Money>().Concat <Sprite>(ObjectCache.OfType <Item>()));
                }
            }
        }
Exemplo n.º 11
0
        public void Can_Add_And_Retrieve_Values_By_Key()
        {
            var cache = new Cache <string, int>(10);

            cache.AddOrUpdate("one", 1);
            cache.AddOrUpdate("two", 2);

            var result = cache.TryGetValue("one", out var value);

            Assert.That(result, Is.True);
            Assert.That(value, Is.EqualTo(1));

            result = cache.TryGetValue("two", out value);
            Assert.That(result, Is.True);
            Assert.That(value, Is.EqualTo(2));
        }
Exemplo n.º 12
0
        protected sealed override TOutputToMap ComputeByIndexImpl(IReadOnlyList <TMappedInput> mappedInputs, int index)
        {
            var tick = default(TOutputToMap);

            if (index < InitialValueIndex)
            {
                tick = ComputeNullValue(mappedInputs, index);
            }
            else if (index == InitialValueIndex)
            {
                tick = ComputeInitialValue(mappedInputs, index);
            }
            else
            {
                // get start index of calculation to cache
                int cacheStartIndex = Cache.Keys.DefaultIfEmpty(InitialValueIndex).Where(k => k >= InitialValueIndex).Max();
                for (int i = cacheStartIndex; i < index; i++)
                {
                    var prevTick = Cache.GetOrAdd(i, _i => ComputeByIndexImpl(mappedInputs, _i));
                    tick = ComputeCumulativeValue(mappedInputs, i + 1, prevTick);

                    // The result will be cached in the base class for the return tick
                    if (i < index - 1)
                    {
                        Cache.AddOrUpdate(i + 1, tick, (_i, _t) => tick);
                    }
                }
            }

            return(tick);
        }
Exemplo n.º 13
0
        public void AddOrReplace(K key, V value, Func <UpdateableCacheEntry <V>, bool> invalidation,
                                 Func <V, CancellationToken, Task <V> > update)
        {
            var cacheEntry = UpdateableCacheEntry.From(value, DateTimeOffset.UtcNow, invalidation, update);

            Cache.AddOrUpdate(key, cacheEntry, (k, e) => UpdateableCacheEntry.From(e, value, _clock.UtcNow));
        }
Exemplo n.º 14
0
        public void UpdateAreaObjects(TimeSpan elapsedTime)
        {
            var users = ServerContextBase.Game.Clients.Where(i => i?.Aisling != null && i.Aisling.CurrentMapId == ID)
                        .Select(i => i.Aisling).ToArray();

            Sprite[] objectCache;

            if (!AreaObjectCache.Exists(Name))
            {
                objectCache = GetAreaObjects();

                if (objectCache.Length > 0)
                {
                    AreaObjectCache.AddOrUpdate(Name, objectCache, 3);
                }
            }
            else
            {
                objectCache = AreaObjectCache.Get(Name);
            }

            if (objectCache == null || objectCache.Length <= 0)
            {
                return;
            }

            if (users.Length <= 0)
            {
                return;
            }

            UpdateMonsterObjects(elapsedTime, objectCache.OfType <Monster>());
            UpdateMundaneObjects(elapsedTime, objectCache.OfType <Mundane>());
            UpdateItemObjects(elapsedTime, objectCache.OfType <Money>().Concat <Sprite>(objectCache.OfType <Item>()));
        }
Exemplo n.º 15
0
        /// <summary>
        /// Attempts to load a new dataset and replaces the old one if load was successful
        /// </summary>
        /// <param name="arguments">The arguments for the update event.</param>
        protected virtual void UpdateLoadedDataSet(ResourceUpdatedEventArgs arguments)
        {
            RunExclusiveAction action = AllowMultipleThreadsLoadingDataSet ? m_action : s_action;

            action.Do(() =>
            {
                if (arguments.IsInitialLoad)
                {
                    ULSLogging.LogTraceTag(0x23821004 /* tag_967ae */, Categories.ConfigurationDataSet, Levels.Verbose,
                                           "Adding data set type '{0}' to cache.", typeof(T).Name);

                    if (Cache.GetOrAdd(typeof(IConfigurationDataSetLoader <T>),
                                       () => CreateCachedConfigurationDataSet(new CachedConfigurationDataSet <T>(DataSetOverride), arguments),
                                       out bool wasAdded) is CachedConfigurationDataSet <T> result && wasAdded)
                    {
                        OnLoad(result.LoadDetails);
                    }
                }
                else
                {
                    ULSLogging.LogTraceTag(0x23850399 /* tag_97qoz */, Categories.ConfigurationDataSet, Levels.Verbose,
                                           "Updating data set type '{0}' in cache.", typeof(T).Name);
                    CachedConfigurationDataSet <T> dataSets             = DataSets;
                    IList <ConfigurationDataSetLoadDetails> loadDetails = dataSets.LoadDetails;

                    if (Cache.AddOrUpdate(typeof(IConfigurationDataSetLoader <T>),
                                          () => CreateCachedConfigurationDataSet(dataSets, arguments),
                                          out bool wasUpdated) is CachedConfigurationDataSet <T> result && wasUpdated)
                    {
                        OnReload(loadDetails, result.LoadDetails);
                    }
                }
            });
        }
Exemplo n.º 16
0
        public void AddOrUpdate_WithRegionAndValidity()
        {
            Cache.AddOrUpdate(_cacheItem, Key, Region, 2000);
            var cacheDetails = Cache.Get <CacheItem>(Key);

            cacheDetails.Should().NotBeNull();
        }
Exemplo n.º 17
0
        private void InitializeTokenManager()
        {
            ICertificateDetails fedCertificateDetails = new FedCertificateDetails();

            Cache.AddOrUpdate(fedCertificateDetails, "ICertificateDetails", 20000);
            TokenManagerFactory.GetTokenManager();
        }
Exemplo n.º 18
0
        public void AddOrUpdate_WithKey()
        {
            Cache.AddOrUpdate(_cacheItem, Key);
            var cacheDetails = Cache.Get <CacheItem>(Key);

            cacheDetails.Should().NotBeNull();
        }
Exemplo n.º 19
0
        public void Cache_Restart_Timer_Ok()
        {
            Cache  c  = new Cache();
            object o1 = new object();

            c.AddOrUpdate("test", o1, 1);
            Thread.Sleep(800);                   // wait almost a second
            Assert.True(c.Exists("test"));       // still exists

            c.AddOrUpdate("test", o1, 1, true);  // update and refresh the timer
            Thread.Sleep(1000);                  // wait another second
            Assert.True(c.Exists("test"));       // still exists

            c.AddOrUpdate("test", o1, 1, false); // default parameter 4: false - no refresh of the timer
            Thread.Sleep(500);                   // it should expire now
            Assert.Null(c.Get("test"));          // no longer cached
        }
 public void Setup()
 {
     _cache = new Cache <int, int>(10);
     for (int i = 0; i < 9; i++)
     {
         _cache.AddOrUpdate(i, i);
     }
 }
Exemplo n.º 21
0
        public override void AddOrReplace(TKey key, TValue value)
        {
            var cacheEntry = CacheEntry.From(value, DateTimeOffset.UtcNow);

            Cache.AddOrUpdate(key,
                              _ => cacheEntry,
                              (_1, _2) => cacheEntry);
        }
Exemplo n.º 22
0
        public void Cache_Timeout_Zero_Throws()
        {
            Cache c = new Cache();

            void act() => c.AddOrUpdate("test", new object(), 0);

            Assert.Throws <ArgumentOutOfRangeException>(act);
        }
Exemplo n.º 23
0
        public void Cache_Indexer_Found_Ok()
        {
            Cache  c  = new Cache();
            object o1 = new object();

            c.AddOrUpdate("test", o1, 1);
            Assert.Same(c["test"], o1);
        }
Exemplo n.º 24
0
        public void Cache_Remove_By_Pattern_Ok()
        {
            Cache c = new Cache();

            c.AddOrUpdate("test1", new object());
            c.AddOrUpdate("test2", new object());
            c.AddOrUpdate("test3", new object());
            c.AddOrUpdate("Other", new object());
            Assert.True(c.Exists("test1"));
            Assert.True(c.Exists("Other"));

            c.Remove(k => k.StartsWith("test"));
            Assert.False(c.Exists("test1"));
            Assert.False(c.Exists("test2"));
            Assert.False(c.Exists("test3"));
            Assert.True(c.Exists("Other"));
        }
Exemplo n.º 25
0
        public void Cache_Clear_Ok()
        {
            Cache c = new Cache();

            c.AddOrUpdate("test", new object());
            Assert.True(c.Exists("test"));
            c.Clear();
            Assert.False(c.Exists("test"));
        }
Exemplo n.º 26
0
        public void TokenManagerFactory_GetCertificateTokenManager()
        {
            var fedCertificateDetails = new FedCertificateDetails();

            Cache.AddOrUpdate(fedCertificateDetails, "ICertificateDetails", 20000);
            var tokenManager = TokenManagerFactory.GetTokenManager();

            Assert.IsNotNull(tokenManager);
        }
Exemplo n.º 27
0
        public void ShouldCollectStatistic()
        {
            // when
            Cache.AddOrUpdate("key1", new object());

            // then
            CacheStatistics statistics = Cache.As <IStatisticsCache>().Statistics;

            Assert.That(statistics.HasStatictic(CacheStatisticsKeys.LastWrite), Is.True);
        }
Exemplo n.º 28
0
        protected TOutputToMap ComputeByIndex(IEnumerable <TMappedInput> mappedInputs, int index)
        {
            if (Cache.TryGetValue(index, out TOutputToMap value))
            {
                return(value);
            }

            value = ComputeByIndexImpl(mappedInputs, index);
            Cache.AddOrUpdate(index, value);
            return(value);
        }
Exemplo n.º 29
0
        public void Rejects_Null_Key()
        {
            var cache = new Cache <string, string>(10);

            var e = Assert.Throws <ArgumentNullException>(() => cache.AddOrUpdate(null, "value"));

            Assert.That(e.Message, Is.EqualTo("key cannot be null.\r\nParameter name: key"));

            e = Assert.Throws <ArgumentNullException>(() => cache.TryGetValue(null, out var value));
            Assert.That(e.Message, Is.EqualTo("key cannot be null.\r\nParameter name: key"));
        }
Exemplo n.º 30
0
        public void Cache_Can_Store_Null_Value_For_Key()
        {
            var cache = new Cache <string, string>(10);

            cache.AddOrUpdate("one", null);

            var result = cache.TryGetValue("one", out var value);

            Assert.That(result, Is.True);
            Assert.That(value, Is.Null);
        }