예제 #1
0
        public void AddAddsItemToCache()
        {
            // arrange
            const string key   = "key";
            const string value = "value";

            // act
            _cache.Add(key, value);

            // assert
            _cache.Get().Should().HaveCount(1);
            _cache.Get(key).Should().BeEquivalentTo(value);
        }
예제 #2
0
        /// <summary>
        /// Get the status of the selected component
        /// </summary>
        /// <returns>Dependency object containing the status and other information</returns>
        public Dependency GetHealth()
        {
            //Prevent multiple parallel invocations
            lock (lockObj)
            {
                //Initially assume status is down
                attachedDependency.Status = Enums.DependencyStatus.DOWN;

                try
                {
                    if (cache.IsCached)
                    {
                        if (cacheManager.Contains(attachedDependency.Name))
                        {
                            return(cacheManager.GetData <Dependency>(attachedDependency.Name));
                        }
                    }

                    SetHealthImplementation();

                    if (cache.IsCached)
                    {
                        //TODO: cache policy/expiry handling
                        cacheManager.Add <Dependency>(attachedDependency.Name, attachedDependency);
                    }
                }
                catch
                {
                    //TODO: Log?
                }
                return(attachedDependency);
            }
        }
예제 #3
0
        public void ChainCacheGet_Success()
        {
            Customer customer = TestData.CreateCustomer();
            // Create the 2 Caches
            ICache localCache  = new InMemoryCache();
            ICache remoteCache = new InMemoryCache();

            // Add item to remoteCache
            remoteCache.Add <Customer>(customer.Id, customer);


            // IChainedCache
            // Hookup the cache Chain
            ChainedCache chainedCache = new ChainedCache();

            chainedCache.LinkFirst(remoteCache);
            chainedCache.LinkFirst(localCache);

            // This should have 1 miss (debug it to ensure)
            Customer cachedCustomer = (Customer)chainedCache.Get(customer.Id);

            // This should have 0 miss (debug it to ensure) since it was added in the last Get()
            cachedCustomer = (Customer)chainedCache.Get(customer.Id);

            // Assert
            Assert.IsNotNull(cachedCustomer);
        }
예제 #4
0
        } // end of GenerateSqlSlowDict method

        #endregion private static methods declarations

        #region private methods declarations

        /// <summary>Saves single row & slow changing metric</summary>
        private void WriteSlowSingleRowToRepository(int targetId, MetricGroup metricGroup, ProbeResultingData data)
        {
            int    dataMatches;
            string dataSqlStmt;

            object[] newValues;

            // compare with in-memory data
            dataMatches = this.CompareSlowSingleRowWithInMemoryData(targetId, metricGroup, data, this.reposConn);

            // generate SQL statement
            dataSqlStmt = GenerateSqlSingleRowSlow(targetId, metricGroup, dataMatches, data);
            _logger.Trace(dataSqlStmt);

            SqlServerProbe.ExecuteSql(dataSqlStmt, targetId, metricGroup);

            // update in-memory data
            newValues = new object[data.NumberOfColumns];
            for (int i = 0; i < data.NumberOfColumns; i++)
            {
                newValues[i] = data.values[0, i];
            }

            if (dataMatches == -1)
            {
                InMemoryCache.Add(InMemoryCache.GetCacheKey(targetId, metricGroup), -1, new object[] { targetId }, newValues);
            }
            else
            {
                Configuration.inMemoryCache[InMemoryCache.GetCacheKey(targetId, metricGroup)].UpdateRowValues(new object[] { targetId }, newValues);
            }
        } // end of WriteSlowSingleRowToRepository function
예제 #5
0
        public ImportJob(
            IImportJobRepository importJobRepository,
            InMemoryCache <TradeAccountModel> tradeAcccountModel,
            InMemoryCache <TradeMasterAccountModel> tradeMasterAccountModel,
            InMemoryCache <TradeInstrumentModel> tradeInstrumentModel,
            InMemoryCache <TradeFeeTypeModel> tradeFeeTypesModel,
            IContract wcf,
            FileNameMatcher fileNameMatcher,
            IExtractFileService extractFileService) : base(wcf)
        {
            _job = Job.Import;

            _tradeAccountModel       = tradeAcccountModel;
            _tradeInstrumentModel    = tradeInstrumentModel;
            _tradeFeeTypesModel      = tradeFeeTypesModel;
            _tradeMasterAccountModel = tradeMasterAccountModel;
            _importJobRepository     = importJobRepository;
            _extractFileService      = extractFileService;
            _fileNameMatcher         = fileNameMatcher;
            using (var tradeContext = _importJobRepository.BeginOperation())
            {
                foreach (var masterAccount in _importJobRepository.GetAllMasterAccounts())
                {
                    _tradeMasterAccountModel.Add(masterAccount.AccountName,
                                                 new TradeMasterAccountModel {
                        Id = masterAccount.Id
                    });
                }

                foreach (var instrument in _importJobRepository.GetTradeInstrument())
                {
                    _tradeInstrumentModel.Add(instrument.InstrumentName,
                                              new TradeInstrumentModel {
                        Id = instrument.Id
                    });
                }

                foreach (var trade in _importJobRepository.GetTradeAccount())
                {
                    _tradeAccountModel.Add(trade.AccountName, new TradeAccountModel {
                        Id = trade.Id
                    });
                }

                foreach (var tradeFeeType in _importJobRepository.GetTradeFeeType())
                {
                    _tradeFeeTypesModel.Add(tradeFeeType.TradeFeeTypeName,
                                            new TradeFeeTypeModel {
                        Id = tradeFeeType.Id
                    });
                }
            }
        }
예제 #6
0
        public void Return_True_When_A_Value_Is_Successfully_Added()
        {
            // Arrange
            const string cacheName = "SuperHeroesCache";
            var cache = new InMemoryCache( cacheName );
            var superman = new SuperHero { SuperHeroName = "Superman", RealFirstName = "Clark", RealLastName = "Kent" };

            // Act
            var valueAdded = cache.Add( superman.SuperHeroName, superman );

            // Assert
            Assert.True( valueAdded );
        }
예제 #7
0
        public void Return_False_When_A_Null_Value_Is_Added()
        {
            // Arrange
            const string cacheName = "SuperHeroesCache";
            var cache = new InMemoryCache( cacheName );
            SuperHero superman = null;

            // Act
            var valueAdded = cache.Add( "Superman", superman );

            // Assert
            Assert.False( valueAdded );
        }
예제 #8
0
        public ImportJob(
            IImportJobRepository importJobRepository,
            InMemoryCache <TradeAccountModel> tradeAcccountModel,
            InMemoryCache <TradeInstrumentModel> tradeInstrumentModel,
            InMemoryCache <TradeFeeTypeModel> tradeFeeTypesModel,
            FileNameMatcher fileNameMatcher,
            IExtractFileService extractFileService)
        {
            var jobInterval = ConfigurationManager.AppSettings["job:ImportJobInterval"];

            if (string.IsNullOrEmpty(jobInterval))
            {
                throw new ConfigurationErrorsException("Please add 'job:ImportJobInterval' settigns to .config file.");
            }

            JobInterval = int.Parse(jobInterval);

            _tradeAccountModel    = tradeAcccountModel;
            _tradeInstrumentModel = tradeInstrumentModel;
            _tradeFeeTypesModel   = tradeFeeTypesModel;
            _importJobRepository  = importJobRepository;
            _extractFileService   = extractFileService;
            _fileNameMatcher      = fileNameMatcher;

            using (var tradeContext = _importJobRepository.BeginOperation())
            {
                foreach (var instrument in _importJobRepository.GetTradeInstrument())
                {
                    _tradeInstrumentModel.Add(instrument.InstrumentName,
                                              new TradeInstrumentModel {
                        Id = instrument.Id
                    });
                }

                foreach (var trade in _importJobRepository.GetTradeAccount())
                {
                    _tradeAccountModel.Add(trade.AccountName, new TradeAccountModel {
                        Id = trade.Id
                    });
                }

                foreach (var tradeFeeType in _importJobRepository.GetTradeFeeType())
                {
                    _tradeFeeTypesModel.Add(tradeFeeType.TradeFeeTypeName,
                                            new TradeFeeTypeModel {
                        Id = tradeFeeType.Id
                    });
                }
            }
        }
예제 #9
0
        public void GoingOverTheAllowedMemoryShouldTriggerAnImmediateCleanUp()
        {
            var timeMock = new Mock <ICurrentDateAndTimeProvider>(MockBehavior.Strict);

            timeMock.Setup(x => x.GetCurrentDateTime()).Returns(DateTime.UtcNow.AddDays(-1));

            using (InMemoryCache cache = new InMemoryCache(_cleanupInterval, 1000, timeMock.Object))
            {
                cache.SetLastExpirationScan(DateTime.MinValue);
                cache.Add(Guid.NewGuid().ToString(), new CachedObject {
                    ObjectSize = 10000, Value = _testObject1, ExpireAt = DateTime.UtcNow.AddDays(-1)
                });
                WaitFor(0.1);
                Assert.Equal(0, cache.Count);
            }
        }
예제 #10
0
        public void AddGetRemove_Success()
        {
            // Arrange
            Customer customer = TestData.CreateCustomer();
            ICache   cache    = new InMemoryCache();

            // Add, Get and Assert
            cache.Add(customer.Id.ToString(), customer);
            object customerObject = cache.Get(customer.Id.ToString());

            // Assert
            Assert.IsNotNull(customerObject);
            Assert.IsInstanceOfType(customerObject, typeof(Customer));


            // Remove and Assert
            cache.Remove(customer.Id.ToString());
            customerObject = cache.Get(customer.Id.ToString());
            Assert.IsNull(customerObject);
        }
예제 #11
0
        public void AddingLargeItemsToCacheShouldDelayTheCleanUpUntilMaximumAllowedItemIsReached()
        {
            var cleanupInterval = TimeSpan.FromSeconds(5);

            using (InMemoryCache cache = new InMemoryCache(cleanupInterval, 1000))
            {
                var sw  = Stopwatch.StartNew();
                var cpt = 0;
                while (sw.Elapsed < cleanupInterval.Subtract(TimeSpan.FromMilliseconds(200)))
                {
                    cache.Add(Guid.NewGuid().ToString(), new CachedObject {
                        ObjectSize = 10000, Value = _testObject1, ExpireAt = DateTime.UtcNow.AddDays(-1)
                    });
                    WaitFor(0.1);
                    cpt++;

                    Assert.NotEqual(0, cache.Count);
                }

                WaitFor(0.5);

                Assert.Equal(0, cache.Count);
            }
        }
예제 #12
0
        public async Task <IPEndPoint> ResolveAsync(string endpoint, int port, IpVersion ipVersion = IpVersion.IpV4, CancellationToken token = default(CancellationToken))
        {
            string cacheKey = $"{endpoint}:{port}:{ipVersion}";

            if (port < IPEndPoint.MinPort || port > IPEndPoint.MaxPort)
            {
                throw new ArgumentOutOfRangeException(nameof(port));
            }

            if (cache.HasKey(cacheKey))
            {
                return(cache.Get <IPEndPoint>(cacheKey));
            }

            var addressFamily = ipVersion.HasFlag(IpVersion.IpV4)
                ? AddressFamily.InterNetwork
                : AddressFamily.InterNetworkV6;


            token.ThrowIfCancellationRequested();

            IPEndPoint ipEndpoint;

            var ipAddress = TryGetIpAddress(endpoint);

            if (ipAddress != null)
            {
                ipEndpoint = new IPEndPoint(ipAddress, port);
                cache.Add(cacheKey, ipEndpoint, TimeSpan.FromMinutes(60));
                return(ipEndpoint);
            }

            try
            {
#if NET40
                var allAddresses = Dns.GetHostAddresses(endpoint);
#else
                var allAddresses = await Dns.GetHostAddressesAsync(endpoint);
#endif

                var firstAddressInFamily = allAddresses.FirstOrDefault(x => x.AddressFamily == addressFamily);
                if (firstAddressInFamily != null)
                {
                    ipEndpoint = new IPEndPoint(firstAddressInFamily, port);
                    cache.Add(cacheKey, ipEndpoint, TimeSpan.FromMinutes(60));
                    return(ipEndpoint);
                }


                if (addressFamily == AddressFamily.InterNetwork && ipVersion.HasFlag(IpVersion.IpV6))
                {
                    ipEndpoint = await ResolveAsync(endpoint, port, IpVersion.IpV6, token);

                    if (ipEndpoint != null)
                    {
                        cache.Add(cacheKey, ipEndpoint, TimeSpan.FromMinutes(60));
                        return(ipEndpoint);
                    }
                }

                var firstAddress = allAddresses.FirstOrDefault();
                if (firstAddress == null)
                {
                    return(null);
                }

                switch (firstAddress.AddressFamily)
                {
                case AddressFamily.InterNetwork:
#if NET40
                    ipEndpoint = new IPEndPoint(firstAddress, port);
#else
                    ipEndpoint = new IPEndPoint(firstAddress.MapToIPv6(), port);
#endif
                    break;

                case AddressFamily.InterNetworkV6:
#if NET40
                    ipEndpoint = new IPEndPoint(firstAddress, port);
#else
                    ipEndpoint = new IPEndPoint(firstAddress.MapToIPv4(), port);
#endif
                    break;

                default:
                    return(null);
                }

                cache.Add(cacheKey, ipEndpoint, TimeSpan.FromMinutes(60));

                return(ipEndpoint);
            }
            catch
            {
                return(null);
            }
        }
예제 #13
0
 public void CountShouldReturnTheNumberOfItemsInTheCache()
 {
     Assert.Equal(0, _cache.Count);
     _cache.Add(_testObject1.Value.ToString(), new CachedObject {
         ObjectSize = 1, Value = _testObject1
     });
     Assert.Equal(1, _cache.Count);
     Assert.Equal(1, _cache.OrderedCacheKeysCount);
     Assert.Equal(1, _cache.EstimatedMemorySize);
     _cache.Add(_testObject2.Value.ToString(), new CachedObject {
         ObjectSize = 2, Value = _testObject2
     });
     Assert.Equal(2, _cache.Count);
     Assert.Equal(2, _cache.OrderedCacheKeysCount);
     Assert.Equal(3, _cache.EstimatedMemorySize);
     _cache.Remove(_testObject1.Value.ToString());
     Assert.Equal(1, _cache.Count);
     Assert.Equal(1, _cache.OrderedCacheKeysCount);
     Assert.Equal(2, _cache.EstimatedMemorySize);
 }