Exemplo n.º 1
0
        public void TestMethod1()
        {
            int percent = 0;

            var repository = new SdeRepository("srvprodist", "5151", "bdgd", "bdgd", "sde.DEFAULT");
            var cache = new InMemoryCache(repository, repository.GetFullExtent("admgid.Switch_PT"), "admgid.Switch_PT");

            cache.OnProgress += delegate(int i)
                {
                    percent = i;
                };

            cache.BuildAllCache();

            IList<IGeometry> list = new List<IGeometry>();

            var envelop = new Envelope(325017, 320003, 7392018, 7391712);
            IEnvelope affected = null;

            var inicio = DateTime.Now;
            var result = cache.RetriveData(envelop, ref list, ref affected);
            var tempo1 = (DateTime.Now - inicio).TotalMilliseconds;

            inicio = DateTime.Now;
            var fromSde = repository.GetByEnvelope("admgid.Switch_PT", envelop);
            var tempo2 = (DateTime.Now - inicio).TotalMilliseconds;

            Assert.AreEqual(list.Count, fromSde.Count());
            Assert.IsTrue(tempo1 < tempo2);
            Assert.AreEqual(percent, 100);
        }
Exemplo n.º 2
0
        private static void SimpleCachingDemo()
        {
            ICache cache = new InMemoryCache();
            CachingPolicy cachingPolicy = CachingPolicy.CacheAll;

            // log SQL from all connections to the console
            EFTracingProviderConfiguration.LogToConsole = true;

            for (int i = 0; i < 3; ++i)
            {
                Console.WriteLine();
                Console.WriteLine("*** Pass #{0}...", i);
                Console.WriteLine();
                using (var context = new ExtendedDataBase())
                {
                    // set up caching
                    context.Cache = cache;
                    context.CachingPolicy = cachingPolicy;

                    //cust.Orders.Load();
                    //context.SaveChanges();
                }
            }

            Console.WriteLine();

            //Console.WriteLine("*** Cache statistics: Hits:{0} Misses:{1} Hit ratio:{2}% Adds:{3} Invalidations:{4}",
            //    cache.CacheHits,
            //    cache.CacheMisses,
            //    100.0 * cache.CacheHits / (cache.CacheHits + cache.CacheMisses),
            //    cache.CacheItemAdds,
            //    cache.CacheItemInvalidations);
        }
Exemplo n.º 3
0
        public SmartDbConfiguration()
        {
            IEfDataProvider provider = null;
            try
            {
                provider = (new EfDataProviderFactory(DataSettings.Current).LoadDataProvider()) as IEfDataProvider;
            }
            catch { /* SmartStore is not installed yet! */ }

            if (provider != null)
            {
                base.SetDefaultConnectionFactory(provider.GetConnectionFactory());

                // prepare EntityFramework 2nd level cache
                ICache cache = null;
                try
                {
                    var innerCache = EngineContext.Current.Resolve<Func<Type, SmartStore.Core.Caching.ICache>>();
                    cache = new EfCacheImpl(innerCache(typeof(SmartStore.Core.Caching.StaticCache)));
                }
                catch
                {
                    cache = new InMemoryCache();
                }

                var transactionHandler = new CacheTransactionHandler(cache);
                AddInterceptor(transactionHandler);

                Loaded +=
                  (sender, args) => args.ReplaceService<DbProviderServices>(
                    (s, _) => new CachingProviderServices(s, transactionHandler,
                      new EfCachingPolicy()));
            }
        }
        static ICache<CodeFeatureId, ICachedCodeFeatureState> CreateInMemoryCache(IEnumerable<ICachedCodeFeatureState> codeFeatureStates)
        {
            var cache = new InMemoryCache<CodeFeatureId, ICachedCodeFeatureState>();

            foreach (ICachedCodeFeatureState featureState in codeFeatureStates)
                cache.TryAdd(featureState.Id, featureState);
            return cache;
        }
Exemplo n.º 5
0
 /// <summary>
 /// This method is an implementation of System.Web.Mvc.IActionFilter.OnActionExecuted(System.Web.Mvc.ActionExecutedContext)
 /// and supports the ASP.NET MVC infrastructure. It is not intended to be used directly from your code.
 /// </summary>
 /// <param name="filterContext">The filter context</param>
 public override void OnActionExecuted(ActionExecutedContext filterContext)
 {
     if (!_foundInCache)
     {
         ICacheService cacheService = new InMemoryCache();
         cacheService.InsertIntoCache(GenerateKey, filterContext.Result, _duration);
     }
     base.OnActionExecuted(filterContext);
 }
Exemplo n.º 6
0
        public void Create_A_New_Instance_Of_MemoryCache()
        {
            // Arrange
            const string cacheName = "SuperHeroesCache";

            // Act
            var cache = new InMemoryCache( cacheName );

            // Assert
            Assert.NotNull( cache.MemoryCache );
        }
Exemplo n.º 7
0
        public void Name_The_Instance_Of_MemoryCache()
        {
            // Arrange
            const string cacheName = "SuperHeroesCache";

            // Act
            var cache = new InMemoryCache( cacheName );

            // Assert
            Assert.That( cache.MemoryCache.Name == cacheName );
        }
Exemplo n.º 8
0
 public void Given()
 {
     _cache = new InMemoryCache();
     _urlRegistry = new TestUrlRegistry();
     _dbContext = new DbTestContext();
     Setup();
     _search = new SearchEndpoint(new ISearchPlugin[] {
         new SearchOnPosts(_cache, _urlRegistry, GetContentFactory), 
         new SearchOnTags(_cache, _urlRegistry, GetTagFactory),
         new SearchOnTime(_cache, _urlRegistry, ()=>DBContext.Session)
     });
 }
Exemplo n.º 9
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 );
        }
Exemplo n.º 10
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 );
        }
        public void DependenciesTest3()
        {
            InMemoryCache imc = new InMemoryCache();

            imc.PutItem("A", "A1", new string[] { "set1" }, TimeSpan.Zero, DateTime.MaxValue);
            imc.PutItem("B", "B1", new string[] { "set1", "set2" }, TimeSpan.Zero, DateTime.MaxValue);
            imc.PutItem("C", "C1", new string[] { "set2", "set3" }, TimeSpan.Zero, DateTime.MaxValue);
            imc.PutItem("D", "D1", new string[] { "set3", "set1" }, TimeSpan.Zero, DateTime.MaxValue);

            Assert.AreEqual("D|C|B|A", GetItemKeysInLruOrder(imc));

            imc.InvalidateSets(new string[] { "set77" });
            Assert.AreEqual("D|C|B|A", GetItemKeysInLruOrder(imc));
        }
Exemplo n.º 12
0
 public ManageController(
     IUsersService users, 
     IChildService children, 
     IGiftService gifts, 
     ICategoryService categories, 
     INeedService needs,
     InMemoryCache cache)
     : base(users)
 {
     this.children = children;
     this.gifts = gifts;
     this.categories = categories;
     this.needs = needs;
     this.cache = cache;
 }
Exemplo n.º 13
0
        public static VersionInformationEntity GetVersionInformation()
        {
            if (!VersionInformationConfiguration.Settings.Enabled)
            {
                return null;
            }

            if (HttpContext.Current != null && VersionInformationConfiguration.Settings.LocalOnly &&
                !HttpContext.Current.Request.IsLocal)
            {
                return null;
            }

            var cachedVersionInformationEntity = new InMemoryCache().Get("VersionInformation", null, Cache.NoAbsoluteExpiration, TimeSpan.FromDays(30), () =>
                {
                    var myAssemblies = Thread.GetDomain().GetAssemblies();
                    var applicationAssembly = GetWebEntryAssembly();

                    var versionInformationEntity = new VersionInformationEntity();
                    versionInformationEntity.WebApplicationVersion = GetAssemblyInformationFromAssembly(applicationAssembly);

                    if (!VersionInformationConfiguration.Settings.IncludeWebApplicationName)
                    {
                        versionInformationEntity.WebApplicationVersion.Name = null;
                    }

                    if (!VersionInformationConfiguration.Settings.IncludeMachineName)
                    {
                        versionInformationEntity.WebApplicationVersion.MachineName = null;
                    }

                    if (VersionInformationConfiguration.Settings.AllAssemblies)
                    {
                        versionInformationEntity.Assemblies =
                            myAssemblies.Where(
                                t => !t.IsDynamic && (!t.GlobalAssemblyCache || VersionInformationConfiguration.Settings.IncludeGac))
                                        .Select(
                                            GetAssemblyInformationFromAssembly)
                                        .OrderBy(t => t.Name).ToList();
                    }
                    return versionInformationEntity;
                });

            return cachedVersionInformationEntity;
        }
Exemplo n.º 14
0
        private async void Instantiate()
        {
            _container.AddInstance<IAuthenticator>(authentication.Object);
            _container.AddInstance<ISecurityTokenizer>(tokenizer.Object);

            _container.AddInstance<IUserInfo>(userInfo.Object);
            _container.AddInstance<IUserPreferences>(userPreferences.Object);
            //setup custom cache using ICache
            var cache = _container.BuildServiceProvider().GetService<IMemoryCache>();
            var bookshelfCustomCache = new InMemoryCache(cache);
            _container.AddInstance<ICache>(bookshelfCustomCache);
            
            //instantiate session stuff
            ISessionManager sessionManager =new ServerSessionManager(_sessionTimeoutInterval, "BookshelfSessionId", bookshelfCustomCache);
            _container.AddInstance(sessionManager);
            //inject filters
            _container.AddInstance(new SessionFilter(sessionManager));

        }
Exemplo n.º 15
0
        public static void Main()
        {
            Console.WriteLine("Caching demo");
            Console.WriteLine("============");
            Console.WriteLine();

            _cacheService = new InMemoryCache();

            Console.WriteLine("First time, this should be slooooow");
            CacheDemo();

            Console.WriteLine("Second time, this should be fast!");
            CacheDemo();

            Console.WriteLine("Asynchronous Caching demo");
            Console.WriteLine("=========================");
            Console.WriteLine();

            _cacheService = new InMemoryCache();

            Console.WriteLine("First time, this should be slooooow");
            CacheDemoAsync().Wait();

            Console.WriteLine("Second time, this should be fast!");
            CacheDemoAsync().Wait();

            Console.WriteLine("Asynchronous Caching demo with a parameter");
            Console.WriteLine("==========================================");
            Console.WriteLine();

            _cacheService = new InMemoryCache();

            Console.WriteLine("First time, this should be slooooow");
            ParameterisedCacheDemoAsync().Wait();

            Console.WriteLine("Second time, this should be fast!");
            ParameterisedCacheDemoAsync().Wait();

            Console.WriteLine();
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }
Exemplo n.º 16
0
        /// <summary>
        /// This method is an implementation of System.Web.Mvc.IActionFilter.OnActionExecuting(System.Web.Mvc.ActionExecutingContext)
        /// and supports the ASP.NET MVC infrastructure. It is not intended to be used directly from your code.
        /// </summary>
        /// <param name="filterContext">The filter context</param>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
            Action = filterContext.ActionDescriptor.ActionName;
            ActionParameters = filterContext.ActionParameters;

            ICacheService cacheService = new InMemoryCache();

            var cacheResult = cacheService.ReadFromCache<ActionResult>(GenerateKey);

            if (cacheResult == null)
            {
                _foundInCache = false;
                base.OnActionExecuting(filterContext);
            }
            else
            {
                filterContext.Result = cacheResult;
                _foundInCache = true;
            }
        }
Exemplo n.º 17
0
        public IEnumerable<RoadSegmentViewModel> FindPath(string startStreetName, string stopStreetName)
        {
            var data = new InMemoryCache().GetOrSet("data", () => new DataProvider.DataProvider().LoadRoadSegments().ToList());

            var startNode = data
                            .Where(x => x.RoadName.ToLower().Contains(startStreetName.ToLower()))
                            .OrderByDescending(x => x.Order)
                            .ToList();

            var stopNode = data
                            .Where(x => x.RoadName.ToLower()
                            .Contains(stopStreetName.ToLower()))
                            .OrderBy(x => x.Order)
                            .ThenBy(x => x.RoadName.Length)
                            .ToList();

            if (!startNode.Any() || !stopNode.Any())
                return new RoadSegmentViewModel[0];

            var start = startNode.First().StartNodeId;
            var goal = stopNode.First().StartNodeId;

            return new AStarAlg().FindPath(start, goal, data);
        }
Exemplo n.º 18
0
 public SpotifyService(SpotifyApi api)
 {
     _api         = api;
     _myPlaylists = new InMemoryCache <Task <IEnumerable <SpotifyPlaylist> > >(GetMyPlaylistsFromApiAsync, TimeSpan.FromHours(1));
 }
        public void InMemoryCacheCacheExpirationTest2()
        {
            InMemoryCache cache = new InMemoryCache();

            object value;

            // current time is 10:00
            cache.GetCurrentDate = () => new DateTime(2009, 1, 1, 10, 0, 0);

            // set expiration time to 1 hour from the last access
            cache.PutItem("Item1", "someValue", new string[0], TimeSpan.FromHours(1), DateTime.MaxValue);

            // make sure the item is still there
            cache.GetCurrentDate = () => new DateTime(2009, 1, 1, 10, 59, 59);
            Assert.IsTrue(cache.GetItem("Item1", out value));
            Assert.AreEqual(value, "someValue");
            Assert.AreEqual(0, cache.CacheItemInvalidations);

            // make sure the item does not get evicted at 11:00 because we have touched it a second ago
            cache.GetCurrentDate = () => new DateTime(2009, 1, 1, 11, 00, 00);
            Assert.IsTrue(cache.GetItem("Item1", out value));
            Assert.AreEqual(value, "someValue");
            Assert.AreEqual(0, cache.CacheItemInvalidations);

            Assert.IsNotNull(cache.LruChainHead);

            // make sure the item does not get evicted at 12:00 because we have touched it an hour ago
            cache.GetCurrentDate = () => new DateTime(2009, 1, 1, 12, 00, 00);
            Assert.IsFalse(cache.GetItem("Item1", out value));
            Assert.AreEqual(1, cache.CacheItemInvalidations);

            Assert.IsNull(cache.LruChainHead);
            Assert.IsNull(cache.LruChainTail);
        }
Exemplo n.º 20
0
 public OrderBookService()
 {
     _cache = new InMemoryCache <OrderBook>(orderBook => orderBook.AssetPairId, true);
 }
Exemplo n.º 21
0
 public OrderBookService(ISettingsService settingsService, IIndexSettingsService indexSettingsService)
 {
     _indexSettingsService = indexSettingsService;
     _settingsService      = settingsService;
     _cache = new InMemoryCache <OrderBook>(GetKey, true);
 }
        public void InMemoryCacheCacheExpirationTest1()
        {
            InMemoryCache cache = new InMemoryCache();

            object value;

            // current time is 10:00
            cache.GetCurrentDate = () => new DateTime(2009,1,1,10,0,0);

            // set expiration time to 11:00
            cache.PutItem("Item1", "someValue", new string[0], TimeSpan.Zero, new DateTime(2009, 1, 1, 11, 0, 0));

            // make sure the item is still there
            cache.GetCurrentDate = () => new DateTime(2009, 1, 1, 10, 59, 59);
            Assert.IsTrue(cache.GetItem("Item1", out value));
            Assert.AreEqual(value, "someValue");
            Assert.AreEqual(0, cache.CacheItemInvalidations);

            // make sure the item gets evicted at 11:00
            cache.GetCurrentDate = () => new DateTime(2009, 1, 1, 11, 00, 00);
            Assert.IsFalse(cache.GetItem("Item1", out value));
            Assert.AreEqual(1, cache.CacheItemInvalidations);
        }
Exemplo n.º 23
0
        /// <summary>
        /// In this demo we are running a set of queries 3 times and logging SQL commands to the console.
        /// Note that queries are actually executed only in the first pass, while in second and third they are fulfilled
        /// completely from the cache.
        /// </summary>
        private static void SimpleCachingDemo()
        {
            ICache cache = new InMemoryCache();
            CachingPolicy cachingPolicy = CachingPolicy.CacheAll;

            // log SQL from all connections to the console
            EFTracingProviderConfiguration.LogToConsole = true;

            for (int i = 0; i < 3; ++i)
            {
                Console.WriteLine();
                Console.WriteLine("*** Pass #{0}...", i);
                Console.WriteLine();
                using (var context = new ExtendedNorthwindEntities())
                {
                    // set up caching
                    context.Cache = cache;
                    context.CachingPolicy = cachingPolicy;

                    Console.WriteLine("Loading customer...");
                    var cust = context.Customers.First(c => c.CustomerID == "ALFKI");
                    Console.WriteLine("Customer name: {0}", cust.ContactName);
                    Console.WriteLine("Loading orders...");
                    cust.Orders.Load();
                    Console.WriteLine("Order count: {0}", cust.Orders.Count);
                }
            }

            Console.WriteLine();

            //Console.WriteLine("*** Cache statistics: Hits:{0} Misses:{1} Hit ratio:{2}% Adds:{3} Invalidations:{4}",
            //    cache.CacheHits,
            //    cache.CacheMisses,
            //    100.0 * cache.CacheHits / (cache.CacheHits + cache.CacheMisses),
            //    cache.CacheItemAdds,
            //    cache.CacheItemInvalidations);
        }
Exemplo n.º 24
0
 public CarPaintProvider(IRepository <CarPaintEntity, PaintFilter, int> repository)
 {
     _repository    = repository;
     _inMemoryCache = InMemoryCache <CarPaintEntity> .Instance;
 }
        public void LruWithLimitTest2()
        {
            InMemoryCache imc = new InMemoryCache(3);

            Assert.AreEqual(3, imc.MaxItems);

            imc.PutItem("A", "A1", new string[0], TimeSpan.Zero, DateTime.MaxValue);
            imc.PutItem("B", "B1", new string[0], TimeSpan.Zero, DateTime.MaxValue);
            imc.PutItem("C", "C1", new string[0], TimeSpan.Zero, DateTime.MaxValue);
            imc.PutItem("D", "D1", new string[0], TimeSpan.Zero, DateTime.MaxValue);

            Assert.AreEqual("D|C|B", GetItemKeysInLruOrder(imc));
            imc.PutItem("E", "E1", new string[0], TimeSpan.Zero, DateTime.MaxValue);
            Assert.AreEqual("E|D|C", GetItemKeysInLruOrder(imc));
            imc.PutItem("F", "F1", new string[0], TimeSpan.Zero, DateTime.MaxValue);
            Assert.AreEqual("F|E|D", GetItemKeysInLruOrder(imc));
        }
 public TimersSettingsService(ITimersSettingsRepository timersSettingsRepository)
 {
     _timersSettingsRepository = timersSettingsRepository;
     _cache = new InMemoryCache <TimersSettings>(settings => CacheKey, true);
 }
 public MarketMakerStateService(IMarketMakerStateRepository marketMakerStateRepository, ILogFactory logFactory)
 {
     _marketMakerStateRepository = marketMakerStateRepository;
     _cache = new InMemoryCache <MarketMakerState>(settings => CacheKey, true);
     _log   = logFactory.CreateLog(this);
 }
Exemplo n.º 28
0
 public UnitOfWork()
 {
     Cache    = new InMemoryCache();
     _context = new DataContext();
 }
Exemplo n.º 29
0
 public PostRepository(IConnectionFactory connectionFactory, InMemoryCache memoryCacheService)
 {
     _connectionFactory  = connectionFactory;
     _memoryCacheService = memoryCacheService;
 }
Exemplo n.º 30
0
 public TyreProvider(IRepository <TyreEntity, TyreFilter, int> repository)
 {
     _repository    = repository;
     _inMemoryCache = InMemoryCache <TyreEntity> .Instance;
 }
        public void InMemoryCacheCacheMissTests()
        {
            InMemoryCache cache = new InMemoryCache();
            object value;

            Assert.IsFalse(cache.GetItem("NoSuchItem", out value));
            Assert.IsNull(value);
            Assert.AreEqual(0, cache.CacheHits);
            Assert.AreEqual(1, cache.CacheMisses);
            Assert.AreEqual(0, cache.CacheItemInvalidations);
            Assert.AreEqual(0, cache.CacheItemAdds);
        }
 public LimitOrderService()
 {
     _cache = new InMemoryCache <OrderBook>(GetKey, true);
 }
 public void InMemoryCacheInitialStatisticsAreAllZero()
 {
     InMemoryCache cache = new InMemoryCache();
     Assert.AreEqual(0, cache.CacheHits);
     Assert.AreEqual(0, cache.CacheItemAdds);
     Assert.AreEqual(0, cache.CacheItemInvalidations);
     Assert.AreEqual(0, cache.CacheMisses);
 }
Exemplo n.º 34
0
 public UsersController(EventStoreService eventStore, CacheDatabaseManager db, InMemoryCache cache,
                        IOptions <EndpointConfig> endpointConfig, ILogger <UsersController> logger)
 {
     _eventStore     = eventStore;
     _db             = db;
     _entityIndex    = cache.Index <EntityIndex>();
     _userIndex      = cache.Index <UserIndex>();
     _endpointConfig = endpointConfig.Value;
     _logger         = logger;
 }
        private static string GetItemKeysInLruOrder(InMemoryCache imc)
        {
            StringBuilder sb = new StringBuilder();
            string separator = "";
            HashSet<string> visisted = new HashSet<string>();

            InMemoryCache.CacheEntry lastEntry = null;

            for (InMemoryCache.CacheEntry ce = imc.LruChainHead; ce != null; ce = ce.NextEntry)
            {
                if (visisted.Contains(ce.Key))
                {
                    throw new InvalidOperationException("Cycle in the LRU chain on: " + ce);
                }

                if (ce.PreviousEntry != lastEntry)
                {
                    throw new InvalidOperationException("Invalid previous pointer on LRU chain: " + ce + " Is: " + ce.PreviousEntry + " expected: " + lastEntry);
                }

                if (lastEntry != null && ce.LastAccessTime < lastEntry.LastAccessTime)
                {
                    throw new InvalidOperationException("Invalid LastAccess time. Current: " + ce.LastAccessTime.Ticks + " previous: " + lastEntry.LastAccessTime.Ticks);
                }

                sb.Append(separator);
                sb.Append(ce.Key);
                separator = "|";
                visisted.Add(ce.Key);
                lastEntry = ce;
            }

            Assert.AreSame(lastEntry, imc.LruChainTail);

            return sb.ToString();
        }
Exemplo n.º 36
0
        } // end of WriteFastSingleRowToRepository function

        /// <summary>Saves data into dictionary and data table for multi-value metrics</summary>
        private void WriteMultipleRowsToRepository(int targetId, MetricGroup metricGroup, ProbeResultingData data)
        {
            int        id;
            CacheTable dictCache, dataCache;
            List <int> newDictRows;
            List <Tuple <int, int> > oldDictRows;

            object[] key, attributes;
            string   dataTableName, dictTableName;

            byte           tryCount    = 0;
            bool           canExit     = false;
            SqlTransaction tran        = null;
            string         dictSqlStmt = string.Empty;
            string         dataSqlStmt = string.Empty;

            newDictRows = new List <int>();               // ids of records that should be added to the dictionary (new rows or rows with updated attributes)
            oldDictRows = new List <Tuple <int, int> >(); // ids and dictionary ids of records that changed since last probe and need to be closed

            dataTableName = SqlServerProbe.DataTableName(targetId, metricGroup);
            _logger.Debug("Name of data table: " + dataTableName);

            dictTableName = SqlServerProbe.DictTableName(targetId, metricGroup);
            _logger.Debug("Name of dictionary: " + dictTableName);

            // load the dictionary cache table if it doesn't exist
            if (!InMemoryCache.ContainsKey(dictTableName))
            {
                InMemoryCache.LoadDictionaryIntoCache(targetId, metricGroup, false);
            }

            dictCache = Configuration.inMemoryCache[dictTableName];

            // load the dictionary cache table if it doesn't exist
            if (!InMemoryCache.ContainsKey(dataTableName))
            {
                InMemoryCache.LoadDataIntoCache(targetId, metricGroup, false);
            }

            /*
             * Checks for changed or new records in dictionary and if needed prepares SQL statement to update dictionary table
             */
            switch (metricGroup.multiRowKeyAttributesChangeSpeed)
            {
            case ChangeSpeed.Static:
                // check whether all records are in the dictionary or some need to be added to it
                for (int i = 0; i < data.NumberOfRows; i++)
                {
                    key = new object[metricGroup.NumberOfMultiRowKeys];

                    for (int j = 0; j < metricGroup.NumberOfMultiRowKeys; j++)
                    {
                        key[j] = data.values[i, j];
                    }

                    if (dictCache.GetIdByKey(key) == -1)
                    {
                        newDictRows.Add(i);
                    }
                }

                // generate SQL statements if there are any new dictionary records
                if (newDictRows.Count > 0)
                {
                    dictSqlStmt = GenerateSqlStaticDict(targetId, metricGroup, data, newDictRows);
                }

                break;

            case ChangeSpeed.Slow:
                // check whether all records are in the dictionary or some need to be added to it
                for (int i = 0; i < data.NumberOfRows; i++)
                {
                    key = new object[metricGroup.NumberOfMultiRowKeys];
                    for (int j = 0; j < metricGroup.NumberOfMultiRowKeys; j++)
                    {
                        key[j] = data.values[i, j];
                    }

                    id = dictCache.GetIdByKey(key);
                    if (id == -1)
                    {
                        newDictRows.Add(i);
                    }
                    else     // check that attributes match
                    {
                        attributes = new object[metricGroup.NumberOfMultiRowKeyAttributes];
                        for (int j = 0; j < metricGroup.NumberOfMultiRowKeyAttributes; j++)
                        {
                            attributes[j] = data.values[i, metricGroup.NumberOfMultiRowKeys + j];
                        }

                        if (!dictCache.CompareAttributesForKey(id, attributes))
                        {
                            oldDictRows.Add(new Tuple <int, int>(i, id));    // this is to close the old record - UPDATE
                        }
                    }
                }

                // generate SQL statements if there are any changes or new records in dictionary
                if (oldDictRows.Count > 0 || newDictRows.Count > 0)
                {
                    dictSqlStmt = GenerateSqlSlowDict(targetId, metricGroup, data, oldDictRows, newDictRows);
                }

                break;

            default:
                throw new Exception("Unknown dictionary change speed");
            }

            /*
             * Write new data into dictionary but don't close transaction yet
             */
            if (dictSqlStmt.CompareTo(string.Empty) != 0)
            {
                _logger.Trace(dictSqlStmt);

                // If tables don't exist, will try to create them and rerun SQL statements
                while (!canExit && tryCount < 2)
                {
                    try
                    {
                        // we will write to the dictionary first and then to the data table so we need to begin a transaction
                        tran = this.reposConn.BeginTransaction();

                        if (dictSqlStmt.CompareTo(string.Empty) != 0)
                        {
                            // save dictionary changes
                            using (SqlCommand cmd = this.reposConn.CreateCommand())
                            {
                                cmd.Transaction = tran;
                                cmd.CommandType = System.Data.CommandType.Text;
                                cmd.CommandText = dictSqlStmt;
                                int rowCount = cmd.ExecuteNonQuery();
                                _logger.Debug("Rows affected: " + rowCount.ToString());
                            }
                        }

                        InMemoryCache.LoadDictionaryIntoCache(targetId, metricGroup, true, this.reposConn, tran);
                        canExit = true;
                    }
                    catch (SqlException e)
                    {
                        if (tran != null)
                        {
                            tran.Rollback();
                            tran.Dispose();
                            tran = null;
                        }

                        switch (e.Number)
                        {
                        case 208:     // Invalid object
                            // Do not create tables if target has been deleted
                            if (!Configuration.targets.ContainsKey(targetId))
                            {
                                return;
                            }

                            SqlServerProbe.CreateTablesForMetricGroup(targetId, metricGroup);
                            break;

                        default:
                            _logger.Error("SqlException: " + e.Message + " ErrorCode: " + e.Number.ToString());
                            break;
                        }
                    }

                    tryCount++;
                }
            }

            /*
             * Prepare SQL statement to save data with right references to the dictionary records
             */
            switch (metricGroup.changeSpeed)
            {
            case ChangeSpeed.Fast:
                dataSqlStmt = "INSERT INTO " + dataTableName + " (dt,dictId,";

                for (int i = 0; i < metricGroup.NumberOfMetrics; i++)
                {
                    dataSqlStmt += metricGroup.metrics[i].name.Replace(' ', '_') + ",";
                }

                dataSqlStmt  = dataSqlStmt.Remove(dataSqlStmt.Length - 1);    // remove last comma
                dataSqlStmt += ")" + Environment.NewLine + "VALUES";

                for (int i = 0; i < data.NumberOfRows; i++)
                {
                    dataSqlStmt += Environment.NewLine + "('" + SqlServerProbe.DateTimeToString(data.probeDateTime) + "',";

                    // retrieve corresponding id from dictionary
                    key = new object[metricGroup.NumberOfMultiRowKeys];

                    for (int k = 0; k < metricGroup.NumberOfMultiRowKeys; k++)
                    {
                        key[k] = data.values[i, k];
                    }

                    id           = dictCache.GetIdByKey(key);
                    dataSqlStmt += id.ToString() + ",";

                    // add metric values
                    for (int j = 0; j < metricGroup.NumberOfMetrics; j++)
                    {
                        dataSqlStmt += SqlServerProbe.DataValueToString(metricGroup.metrics[j].type, data.values[i, metricGroup.NumberOfMultiRowKeys + metricGroup.NumberOfMultiRowKeyAttributes + j]) + ",";
                    }

                    dataSqlStmt  = dataSqlStmt.Remove(dataSqlStmt.Length - 1);    // remove last comma
                    dataSqlStmt += "),";
                }

                dataSqlStmt = dataSqlStmt.Remove(dataSqlStmt.Length - 1);     // remove last comma
                _logger.Trace(dataSqlStmt);
                break;

            default:
                throw new Exception("Unsupported data change speed");
            }

            /*
             * Executes SQL statements
             * If tables don't exist, will try to create them and rerun SQL statements
             */
            try
            {
                // save data
                using (SqlCommand cmd = this.reposConn.CreateCommand())
                {
                    if (tran != null) // use same transaction as for the dictionary
                    {
                        cmd.Transaction = tran;
                    }

                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.CommandText = dataSqlStmt;
                    int rowCount = cmd.ExecuteNonQuery();
                    _logger.Debug("Rows affected: " + rowCount.ToString());
                }

                if (tran != null)
                {
                    tran.Commit();
                }

                InMemoryCache.LoadDictionaryIntoCache(targetId, metricGroup, true);
                dictCache = Configuration.inMemoryCache[dictTableName];

                // Update in-memory data cache
                object[] newValues;

                dataCache = Configuration.inMemoryCache[dataTableName];

                for (int i = 0; i < data.NumberOfRows; i++)
                {
                    key = new object[metricGroup.NumberOfMultiRowKeys];

                    for (int j = 0; j < metricGroup.NumberOfMultiRowKeys; j++)
                    {
                        key[j] = data.values[i, j];
                    }

                    id = dictCache.GetIdByKey(key);

                    newValues = new object[metricGroup.NumberOfMetrics];

                    for (int j = 0; j < metricGroup.NumberOfMetrics; j++)
                    {
                        newValues[j] = data.values[i, metricGroup.NumberOfMultiRowKeys + metricGroup.NumberOfMultiRowKeyAttributes + j];
                    }

                    dataCache.AddOrUpdateRowValues(id, new object[0], newValues);
                }

                canExit = true;
            }
            catch (SqlException e)
            {
                _logger.Error("SqlException: " + e.Message + " ErrorCode: " + e.Number.ToString());
                if (tran != null)
                {
                    tran.Rollback();
                    InMemoryCache.LoadDictionaryIntoCache(targetId, metricGroup, true);
                }
            }
        }
        public void CheckAutoFlush(int attempt)
        {
            const int    maxAttempts      = 10;
            const double autoFlushSeconds = 1d;

            // Don't retry if we don't have too.
            if (_success)
            {
                Assert.True(true);
                return;
            }

            // Detect errors on other threads.
            _unhandledException = null;
            ExceptionManager.UnhandledException += (source, args) =>
            {
                if (!args.Exception.StackTrace.Contains(@"InMemoryCache", StringComparison.OrdinalIgnoreCase))
                {
                    return;
                }
                _unhandledException = args.Exception;
            };

            var c = new InMemoryCache <string, DisposableMock>(TimeSpan.FromSeconds(autoFlushSeconds), s =>
            {
                var mock = new DisposableMock
                {
                    Id = s
                };
                return(mock);
            }, true, false);
            const string key = @"TEST";
            var          x1  = c[key];

            Assert.Equal(key, x1.Id);
            Thread.Sleep(TimeSpan.FromSeconds(autoFlushSeconds * 1.5d));

            // x1 hasn't been disposed of because AutoFlush is off.
            Assert.False(x1.IsDisposed);
            var x2 = c[key];

            // x1 will be disposed of now because it will have been cleared when the item was selected
            Assert.True(x1.IsDisposed);
            Assert.False(x2.IsDisposed);
            Assert.NotSame(x1, x2);

            // Now clear the cache and try again.
            c.Flush();
            c.Clear();
            c.Flush();
            var flushCount = 0;

            c.Flushed    += (a, b) => { Interlocked.Increment(ref flushCount); };
            c.AutoDispose = true;
            c.AutoDispose = true;
            c.AutoFlush   = true;
            c.AutoFlush   = true; // The second call should take a different path - we can check in code coverage to ensure this is the case.
            Assert.True(c.AutoFlush);
            flushCount = 0;
            x1         = c[key];
            Assert.Equal(key, x1.Id);
            Assert.False(x1.IsDisposed);
            var       loops    = 0;
            const int maxLoops = 5;

            Assert.Equal(c.AutoDispose, true);
            Assert.Equal(c.AutoFlush, true);

            // Allow multiple iterations in case there is some thread starvation.
            while ((loops++ < maxLoops) && (flushCount <= 0))
            {
                Assert.Equal(c.AutoDispose, true);
                Assert.Equal(c.AutoFlush, true);

                // While we are asleep all expired members of the cache should be automatically disposed of
                Thread.Sleep(TimeSpan.FromSeconds(autoFlushSeconds));

                Assert.Equal(c.AutoDispose, true);
                Assert.Equal(c.AutoFlush, true);
            }

            try
            {
                Assert.Null(_unhandledException);

                // Now x1 has been disposed, even though it hasn't been re-fetched.
                Assert.True(x1.IsDisposed, "Cached value has been disposed of.");

                // There has been a flush, without us needing to do anything.
                Assert.True(flushCount >= 1, "Auto-flush is responsible for disposing of the cached value.");

                _success = true;
            }
            catch
            {
                if (attempt >= maxAttempts)
                {
                    // Allow a couple of attempts because occasionally it fails for no reason.
                    throw;
                }
            }
        }
Exemplo n.º 38
0
 public void Setup()
 {
     Environment.SetEnvironmentVariable(new UniqueResultTimeoutMillisecondsKey(), "500");
     Environment.SetEnvironmentVariable(new UniqueResultPollingFrequencyKey(), "10");
     InMemoryCache.Instance().Remove(Id);
 }
Exemplo n.º 39
0
        /// <summary>
        /// In this demo we are running a set of queries and updates and 3 times and logging SQL commands to the console.
        /// Notice how performing an update on Customer table causes the cache entry to be invalidated so we get 
        /// a query in each pass. Because we aren't modifying OrderDetails table, the collection of order details
        /// for the customer doesn't require a query in second and third pass.
        /// </summary>
        private static void CacheInvalidationDemo()
        {
            var cache = new InMemoryCache();

            // log SQL from all connections to the console
            EFTracingProviderConfiguration.LogToConsole = true;

            for (int i = 0; i < 3; ++i)
            {
                Console.WriteLine();
                Console.WriteLine("*** Pass #{0}...", i);
                Console.WriteLine();
                using (var context = new ExtendedNorthwindEntities())
                {
                    // set up caching
                    context.Cache = cache;
                    context.CachingPolicy = CachingPolicy.CacheAll;

                    Console.WriteLine("Loading customer...");
                    var cust = context.Customers.First(c => c.CustomerID == "ALFKI");
                    Console.WriteLine("Customer name: {0}", cust.ContactName);
                    cust.ContactName = "Change" + Environment.TickCount;
                    Console.WriteLine("Loading orders...");
                    cust.Orders.Load();

                    for (int o = 0; o < 10; ++o)
                    {
                        var order = new Order();
                        order.OrderDate = DateTime.Now;
                        cust.Orders.Add(order);
                    }

                    Console.WriteLine("Order count: {0}", cust.Orders.Count);
                    context.SaveChanges();
                }
            }

            Console.WriteLine();
        }
Exemplo n.º 40
0
 public DnsResolver()
 {
     cache = new InMemoryCache();
 }
Exemplo n.º 41
0
 public BaseController()
 {
     unitOfWork    = new Core.UnitOfWork.UnitOfWork();
     messageSource = new Models.MessageSource();
     cacheService  = new InMemoryCache();
 }
Exemplo n.º 42
0
        } // end of GenerateSqlStaticDict method

        // Generates UPDATE statement for closing records and INSERT statement for openning records
        private static string GenerateSqlSlowDict(int targetId, MetricGroup metricGroup, ProbeResultingData data, List <Tuple <int, int> > rowsChanged, List <int> rowsNotInDict)
        {
            CacheTable dict    = Configuration.inMemoryCache[InMemoryCache.GetCacheKey(targetId, metricGroup, CacheType.Dictionary)];
            string     sqlStmt = string.Empty;

            // old rows where endDate need to be updated
            if (rowsChanged.Count > 0)
            {
                sqlStmt  = "UPDATE " + SqlServerProbe.DictTableName(targetId, metricGroup) + Environment.NewLine;
                sqlStmt += "SET endDate = '" + SqlServerProbe.DateTimeToString(data.probeDateTime) + "'" + Environment.NewLine;
                sqlStmt += "WHERE";

                foreach (Tuple <int, int> ids in rowsChanged)
                {
                    sqlStmt += Environment.NewLine + "(id = " + ids.Item2.ToString() + " AND ";
                    sqlStmt += "startDate = '" + SqlServerProbe.DateTimeToString((DateTime)dict[ids.Item2][metricGroup.NumberOfMultiRowKeys + metricGroup.NumberOfMultiRowKeyAttributes]) + "')";
                    sqlStmt += " OR ";
                }

                sqlStmt  = sqlStmt.Remove(sqlStmt.Length - 4); // remove last ' OR '
                sqlStmt += ";" + Environment.NewLine;

                // new records for changed rows
                sqlStmt += "INSERT INTO " + SqlServerProbe.DictTableName(targetId, metricGroup) + " (id,";
                for (int i = 0; i < metricGroup.NumberOfMultiRowKeys; i++)
                {
                    sqlStmt += Environment.NewLine + metricGroup.multiRowKeys[i].name.Replace(' ', '_') + ",";
                }

                for (int i = 0; i < metricGroup.NumberOfMultiRowKeyAttributes; i++)
                {
                    sqlStmt += Environment.NewLine + metricGroup.multiRowKeyAttributes[i].name.Replace(' ', '_') + ",";
                }

                sqlStmt += "startDate,endDate)" + Environment.NewLine;
                sqlStmt += "VALUES " + Environment.NewLine;

                foreach (Tuple <int, int> ids in rowsChanged)
                {
                    sqlStmt += "(" + ids.Item2.ToString() + ",";
                    for (int j = 0; j < metricGroup.NumberOfMultiRowKeys; j++)
                    {
                        sqlStmt += SqlServerProbe.DataValueToString(metricGroup.multiRowKeys[j].type, data.values[ids.Item1, j]) + ",";
                    }

                    for (int j = 0; j < metricGroup.NumberOfMultiRowKeyAttributes; j++)
                    {
                        sqlStmt += SqlServerProbe.DataValueToString(metricGroup.multiRowKeyAttributes[j].type, data.values[ids.Item1, metricGroup.NumberOfMultiRowKeys + j]) + ",";
                    }

                    // add startDate and endDate
                    sqlStmt += "'" + SqlServerProbe.DateTimeToString(data.probeDateTime) + "',NULL),";
                }

                sqlStmt = sqlStmt.Remove(sqlStmt.Length - 1); // remove last comma
            }

            // new rows
            if (rowsNotInDict.Count > 0)
            {
                sqlStmt += "INSERT INTO " + SqlServerProbe.DictTableName(targetId, metricGroup) + " (id,";
                for (int i = 0; i < metricGroup.NumberOfMultiRowKeys; i++)
                {
                    sqlStmt += Environment.NewLine + metricGroup.multiRowKeys[i].name.Replace(' ', '_') + ",";
                }

                for (int i = 0; i < metricGroup.NumberOfMultiRowKeyAttributes; i++)
                {
                    sqlStmt += Environment.NewLine + metricGroup.multiRowKeyAttributes[i].name.Replace(' ', '_') + ",";
                }

                sqlStmt += "startDate,endDate)" + Environment.NewLine;
                sqlStmt += "VALUES " + Environment.NewLine;

                foreach (int i in rowsNotInDict)
                {
                    sqlStmt += "(NEXT VALUE FOR " + SqlServerProbe.SchemaName(targetId) + ".seq_" + metricGroup.dictTableName + ",";
                    for (int j = 0; j < metricGroup.NumberOfMultiRowKeys; j++)
                    {
                        sqlStmt += SqlServerProbe.DataValueToString(metricGroup.multiRowKeys[j].type, data.values[i, j]) + ",";
                    }

                    for (int j = 0; j < metricGroup.NumberOfMultiRowKeyAttributes; j++)
                    {
                        sqlStmt += SqlServerProbe.DataValueToString(metricGroup.multiRowKeyAttributes[j].type, data.values[i, metricGroup.NumberOfMultiRowKeys + j]) + ",";
                    }

                    // add startDate and endDate
                    sqlStmt += "'" + SqlServerProbe.DateTimeToString(data.probeDateTime) + "',NULL),";
                }

                sqlStmt = sqlStmt.Remove(sqlStmt.Length - 1); // remove last comma
            }

            return(sqlStmt);
        } // end of GenerateSqlSlowDict method
Exemplo n.º 43
0
 public QuoteThresholdSettingsService(IQuoteThresholdSettingsRepository quoteThresholdSettingsRepository)
 {
     _quoteThresholdSettingsRepository = quoteThresholdSettingsRepository;
     _cache = new InMemoryCache <QuoteThresholdSettings>(settings => CacheKey, false);
 }
 public FooController(EventStoreService eventStore, CacheDatabaseManager db, InMemoryCache cache)
 {
     _eventStore  = eventStore;
     _db          = db;
     _entityIndex = cache.Index <EntityIndex>();
 }
Exemplo n.º 45
0
 public CarEngineProvider(IRepository <CarEngineEntity, EngineFilter, Guid> repository)
 {
     _repository    = repository;
     _inMemoryCache = InMemoryCache <CarEngineEntity> .Instance;
 }
Exemplo n.º 46
0
        static Asset()
        {
            try
            {
                Cache = new InMemoryCache <Asset>();

                Cache.Set(
                    new[] {
                    new Asset("ADA", 8),
                    new Asset("ADX", 8),
                    new Asset("AE", 8),
                    new Asset("AION", 8),
                    new Asset("AMB", 8),
                    new Asset("APPC", 8),
                    new Asset("ARK", 8),
                    new Asset("ARN", 8),
                    new Asset("AST", 8),
                    new Asset("BAT", 8),
                    new Asset("BCC", 8),
                    new Asset("BCD", 8),
                    new Asset("BCN", 8),
                    new Asset("BCPT", 8),
                    new Asset("BLZ", 8),
                    new Asset("BNB", 8),
                    new Asset("BNT", 8),
                    new Asset("BQX", 8),
                    new Asset("BRD", 8),
                    new Asset("BTC", 8),
                    new Asset("BTG", 8),
                    new Asset("BTS", 8),
                    new Asset("CDT", 8),
                    new Asset("CHAT", 8),
                    new Asset("CLOAK", 8),
                    new Asset("CMT", 8),
                    new Asset("CND", 8),
                    new Asset("DASH", 8),
                    new Asset("DGD", 8),
                    new Asset("DLT", 8),
                    new Asset("DNT", 8),
                    new Asset("EDO", 8),
                    new Asset("ELF", 8),
                    new Asset("ENG", 8),
                    new Asset("ENJ", 8),
                    new Asset("EOS", 8),
                    new Asset("ETC", 8),
                    new Asset("ETH", 8),
                    new Asset("EVX", 8),
                    new Asset("FUEL", 8),
                    new Asset("FUN", 8),
                    new Asset("GAS", 8),
                    new Asset("GNT", 8),
                    new Asset("GRS", 8),
                    new Asset("GTO", 8),
                    new Asset("GVT", 8),
                    new Asset("GXS", 8),
                    new Asset("HSR", 8),
                    new Asset("ICN", 8),
                    new Asset("ICX", 8),
                    new Asset("INS", 8),
                    new Asset("IOST", 8),
                    new Asset("IOTA", 8),
                    new Asset("KMD", 8),
                    new Asset("KNC", 8),
                    new Asset("LEND", 8),
                    new Asset("LINK", 8),
                    new Asset("LOOM", 8),
                    new Asset("LRC", 8),
                    new Asset("LSK", 8),
                    new Asset("LTC", 8),
                    new Asset("LUN", 8),
                    new Asset("MANA", 8),
                    new Asset("MCO", 8),
                    new Asset("MDA", 8),
                    new Asset("MOD", 8),
                    new Asset("MTH", 8),
                    new Asset("MTL", 8),
                    new Asset("NANO", 8),
                    new Asset("NAV", 8),
                    new Asset("NCASH", 8),
                    new Asset("NEBL", 8),
                    new Asset("NEO", 8),
                    new Asset("NULS", 8),
                    new Asset("OAX", 8),
                    new Asset("OMG", 8),
                    new Asset("ONT", 8),
                    new Asset("OST", 8),
                    new Asset("PIVX", 8),
                    new Asset("POA", 8),
                    new Asset("POE", 8),
                    new Asset("POWR", 8),
                    new Asset("PPT", 8),
                    new Asset("QLC", 8),
                    new Asset("QSP", 8),
                    new Asset("QTUM", 8),
                    new Asset("RCN", 8),
                    new Asset("RDN", 8),
                    new Asset("REP", 8),
                    new Asset("REQ", 8),
                    new Asset("RLC", 8),
                    new Asset("RPX", 8),
                    new Asset("SALT", 8),
                    new Asset("SNGLS", 8),
                    new Asset("SNM", 8),
                    new Asset("SNT", 8),
                    new Asset("STEEM", 8),
                    new Asset("STORJ", 8),
                    new Asset("STORM", 8),
                    new Asset("STRAT", 8),
                    new Asset("SUB", 8),
                    new Asset("SYS", 8),
                    new Asset("TNB", 8),
                    new Asset("TNT", 8),
                    new Asset("TRIG", 8),
                    new Asset("TRX", 8),
                    new Asset("USDT", 8),
                    new Asset("VEN", 8),
                    new Asset("VIA", 8),
                    new Asset("VIB", 8),
                    new Asset("VIBE", 8),
                    new Asset("WABI", 8),
                    new Asset("WAN", 8),
                    new Asset("WAVES", 8),
                    new Asset("WINGS", 8),
                    new Asset("WPR", 8),
                    new Asset("WTC", 8),
                    new Asset("XEM", 8),
                    new Asset("XLM", 8),
                    new Asset("XMR", 8),
                    new Asset("XRP", 8),
                    new Asset("XVG", 8),
                    new Asset("XZC", 8),
                    new Asset("YOYO", 8),
                    new Asset("ZEC", 8),
                    new Asset("ZIL", 8),
                    new Asset("ZRX", 8),
                });

                AddCacheRedirections();
            }
            catch (Exception e)
            {
                Console.Error?.WriteLine($"{nameof(Binance)}.{nameof(Asset)}(): \"{e.Message}\"");
            }
        }
        public void InMemoryCacheCacheExpirationTest3()
        {
            InMemoryCache cache = new InMemoryCache();

            object value;

            // current time is 10:00
            cache.GetCurrentDate = () => new DateTime(2009, 1, 1, 10, 0, 0);
            cache.PutItem("Item1", "someValue", new string[0], TimeSpan.Zero, new DateTime(2009, 1, 1, 10, 0, 0));
            cache.PutItem("Item2", "someValue", new string[0], TimeSpan.Zero, new DateTime(2009, 1, 1, 10, 1, 0));
            cache.PutItem("Item3", "someValue", new string[0], TimeSpan.Zero, new DateTime(2009, 1, 1, 10, 2, 0));
            cache.PutItem("Item4", "someValue", new string[0], TimeSpan.Zero, new DateTime(2009, 1, 1, 10, 3, 0));

            cache.GetCurrentDate = () => new DateTime(2009, 1, 1, 10, 2, 0);

            // no invalidation happens until we try to get an item
            Assert.AreEqual("Item4|Item3|Item2|Item1", GetItemKeysInLruOrder(cache));

            Assert.IsFalse(cache.GetItem("Item1", out value));
            Assert.AreEqual("Item4", GetItemKeysInLruOrder(cache));
        }
Exemplo n.º 48
0
 public CacheManager(string sqlConnection, int sqlSlidingExpiryTimeInSeconds, int memoryAbsoluteExpiryTimeInSeconds)
 {
     SqlCache      = new SqlCache(sqlConnection, sqlSlidingExpiryTimeInSeconds);
     InMemoryCache = new InMemoryCache(memoryAbsoluteExpiryTimeInSeconds);
 }
        public void InMemoryCacheCacheReplaceTests()
        {
            InMemoryCache cache = new InMemoryCache();

            object value;

            cache.PutItem("Item1", "someValue", new string[0], TimeSpan.Zero, DateTime.MaxValue);
            cache.PutItem("Item1", "someOtherValue", new string[0], TimeSpan.Zero, DateTime.MaxValue);
            Assert.IsTrue(cache.GetItem("Item1", out value));
            Assert.AreEqual(value, "someOtherValue");
            Assert.AreEqual(1, cache.CacheHits);
            Assert.AreEqual(0, cache.CacheMisses);
            Assert.AreEqual(1, cache.CacheItemInvalidations);
            Assert.AreEqual(2, cache.CacheItemAdds);
        }
Exemplo n.º 50
0
 public MessageSource()
 {
     unitOfWork   = new UnitOfWork();
     cacheService = new InMemoryCache();
 }
        public void LruTest1()
        {
            InMemoryCache imc = new InMemoryCache();
            Assert.AreEqual(Int32.MaxValue, imc.MaxItems);

            imc.PutItem("A", "A1", new string[0], TimeSpan.Zero, DateTime.MaxValue);
            imc.PutItem("B", "B1", new string[0], TimeSpan.Zero, DateTime.MaxValue);
            imc.PutItem("C", "C1", new string[0], TimeSpan.Zero, DateTime.MaxValue);
            imc.PutItem("D", "D1", new string[0], TimeSpan.Zero, DateTime.MaxValue);

            Assert.AreEqual("D|C|B|A", GetItemKeysInLruOrder(imc));

            object value;
            imc.GetItem("D", out value);
            Assert.AreEqual("D|C|B|A", GetItemKeysInLruOrder(imc));
            imc.GetItem("C", out value);
            Assert.AreEqual("C|D|B|A", GetItemKeysInLruOrder(imc));
            imc.GetItem("D", out value);
            Assert.AreEqual("D|C|B|A", GetItemKeysInLruOrder(imc));
            imc.GetItem("A", out value);
            Assert.AreEqual("A|D|C|B", GetItemKeysInLruOrder(imc));
            imc.GetItem("B", out value);
            Assert.AreEqual("B|A|D|C", GetItemKeysInLruOrder(imc));
            imc.InvalidateItem("B");
            Assert.AreEqual("A|D|C", GetItemKeysInLruOrder(imc));
            imc.InvalidateItem("C");
            Assert.AreEqual("A|D", GetItemKeysInLruOrder(imc));
            imc.InvalidateItem("A");
            Assert.AreEqual("D", GetItemKeysInLruOrder(imc));
            imc.InvalidateItem("D");
            Assert.AreEqual("", GetItemKeysInLruOrder(imc));
        }
        public void InMemoryCacheObjectReturnsNullWithInvalidKey()
        {
            ICache cache = new InMemoryCache(600);

            Assert.Equal(null, cache.Get <string>("mykey"));
        }
        public void MicroStressTest()
        {
            // run a bunch of concurrent reads and writes, make sure we get no exceptions

            var imc = new InMemoryCache(100);
            int numberOfRequestBatches = 50; // will be multiplied by 5 (3 readers + 1 writer + 1 invalidator)
            int numberOfIterationsPerThread = 10000;

            ManualResetEvent startEvent = new ManualResetEvent(false);

            Action writer = () =>
            {
                startEvent.WaitOne();
                Random random = new Random();

                for (int i = 0; i < numberOfIterationsPerThread; ++i)
                {
                    string randomKey = Guid.NewGuid().ToString("N").Substring(0, 4);
                    string randomValue = randomKey + "_V";
                    List<string> dependentSets = new List<string>();
                    int numberOfDependencies = random.Next(5);
                    for (int j = 0; j < numberOfDependencies; ++j)
                    {
                        string randomSetName = new string((char)('A' + random.Next(26)), 1);
                        dependentSets.Add(randomSetName);
                    }

                    imc.PutItem(randomKey, randomValue, dependentSets, TimeSpan.Zero, DateTime.MaxValue);
                }
            };

            Action invalidator = () =>
            {
                startEvent.WaitOne();
                Random random = new Random();

                for (int i = 0; i < numberOfIterationsPerThread; ++i)
                {
                    List<string> dependentSets = new List<string>();
                    int numberOfDependencies = random.Next(5);
                    for (int j = 0; j < numberOfDependencies; ++j)
                    {
                        string randomSetName = new string((char)('A' + random.Next(26)), 1);
                        dependentSets.Add(randomSetName);
                    }

                    imc.InvalidateSets(dependentSets);
                }
            };

            Action reader = () =>
            {
                startEvent.WaitOne();
                Random random = new Random();

                for (int i = 0; i < numberOfIterationsPerThread; ++i)
                {
                    string randomKey = Guid.NewGuid().ToString("N").Substring(0, 4);
                    object value;

                    if (imc.GetItem(randomKey, out value))
                    {
                        Assert.AreEqual(randomKey + "_V", value);
                    }
                }
            };

            List<Thread> threads = new List<Thread>();

            for (int i = 0; i < numberOfRequestBatches; ++i)
            {
                threads.Add(new Thread(() => writer()));
                threads.Add(new Thread(() => invalidator()));
                threads.Add(new Thread(() => reader()));
                threads.Add(new Thread(() => reader()));
                threads.Add(new Thread(() => reader()));
            }

            foreach (Thread t in threads)
            {
                t.Start();
            }

            startEvent.Set();

            foreach (Thread t in threads)
            {
                t.Join();
            }
        }
Exemplo n.º 54
0
 public HedgeSettingsService(IHedgeSettingsRepository hedgeSettingsRepository)
 {
     _hedgeSettingsRepository = hedgeSettingsRepository;
     _cache = new InMemoryCache <HedgeSettings>(settings => CacheKey, true);
 }
        public B2C2OrderBookService(ILogFactory logFactory)
        {
            _cache = new InMemoryCache <OrderBook>(orderBook => orderBook.AssetPairId, true);

            _log = logFactory.CreateLog(this);
        }
Exemplo n.º 56
0
        /// <summary>
        /// In this demo we are a query based on time (whose results are non-deterministic, because it uses DateTime.Now)
        /// Such queries are not cached, so we get a store query every time.
        ///
        /// Note that non-cacheable queries don't count as cache misses.
        /// </summary>
        private static void NonDeterministicQueryCachingDemo()
        {
            var cache = new InMemoryCache();

            // log SQL from all connections to the console
            EFTracingProviderConfiguration.LogToConsole = true;

            for (int i = 0; i < 3; ++i)
            {
                Console.WriteLine();
                Console.WriteLine("*** Pass #{0}...", i);
                Console.WriteLine();
                using (var context = new ExtendedNorthwindEntities())
                {
                    // set up caching
                    context.Cache = cache;
                    context.CachingPolicy = CachingPolicy.CacheAll;

                    Console.WriteLine("Loading orders...");
                    context.Orders.Where(c => c.ShippedDate < DateTime.Now).ToList();
                }
            }

            Console.WriteLine();

            Console.WriteLine("*** Cache statistics: Hits:{0} Misses:{1} Hit ratio:{2}% Adds:{3} Invalidations:{4}",
                cache.CacheHits,
                cache.CacheMisses,
                100.0 * cache.CacheHits / (cache.CacheHits + cache.CacheMisses),
                cache.CacheItemAdds,
                cache.CacheItemInvalidations);
        }
Exemplo n.º 57
0
 public WorkerService(ISortService sortService, ILogger <WorkerService> logger, InMemoryCache cache)
 {
     _sortService = sortService;
     _logger      = logger;
     _cache       = cache;
 }
Exemplo n.º 58
0
        // ReSharper Restore All


        public ActionBaseController(EventStoreService eventStore, InMemoryCache cache)
        {
            _eventStore  = eventStore;
            _entityIndex = cache.Index <EntityIndex>();
        }
 public StudentDetailsController(EventStoreService eventStore, InMemoryCache cache)
 {
     _eventStore = eventStore;
     _userIndex  = cache.Index <UserIndex>();
 }
Exemplo n.º 60
0
        /// <summary>Returns true if new data matches in-memory copy or no history is found - single row - slow changing</summary>
        private int CompareSlowSingleRowWithInMemoryData(int targetId, MetricGroup metricGroup, ProbeResultingData data, SqlConnection connection)
        {
            bool       noHistory = false;
            CacheTable dataCache;

            // create in-memory cache table if it doesn't exist
            if (!InMemoryCache.ContainsKey(InMemoryCache.GetCacheKey(-1, metricGroup)))
            {
                // Do not create tables if target has been deleted
                if (!Configuration.targets.ContainsKey(targetId))
                {
                    return(-1);
                }

                InMemoryCache.CreateCacheTableSingleRow(metricGroup, CacheType.Data);
            }

            dataCache = Configuration.inMemoryCache[InMemoryCache.GetCacheKey(-1, metricGroup, CacheType.Data)];
            // load latest row from the repository if it is not in-memory yet
            int id = dataCache.GetIdByKey(new object[] { targetId });

            if (id == -1)
            {
                string sqlStmt = "SELECT ";

                for (int i = 0; i < metricGroup.NumberOfMetrics; i++)
                {
                    sqlStmt += metricGroup.metrics[i].name.Replace(' ', '_') + ",";
                }

                sqlStmt  = sqlStmt.Remove(sqlStmt.Length - 1); // remove last comma
                sqlStmt += " FROM " + SqlServerProbe.DataTableName(targetId, metricGroup);
                sqlStmt += " WHERE startDate = (SELECT MAX(startDate) FROM " + SqlServerProbe.DataTableName(targetId, metricGroup) + ")";

                using (SqlCommand cmd = connection.CreateCommand())
                {
                    cmd.CommandType = System.Data.CommandType.Text;
                    cmd.CommandText = sqlStmt;

                    try
                    {
                        SqlDataReader dataReader = cmd.ExecuteReader();

                        if (dataReader.Read())
                        {
                            object[] oldValues = new object[metricGroup.NumberOfMetrics];

                            for (int i = 0; i < metricGroup.NumberOfMetrics; i++)
                            {
                                // check data type before casting
                                switch (metricGroup.metrics[i].type)
                                {
                                case DataType.Ansi:
                                    if (!DataTypeMappingSqlServer.DoesBelong(dataReader.GetDataTypeName(i), DataType.Ansi))
                                    {
                                        throw new Exception("Data type of column #" + (i + 1).ToString() + " of '" + metricGroup.name + "' metric does not match any allowed data type for internal data type Ansi");
                                    }

                                    oldValues[i] = (object)dataReader.GetString(i);

                                    break;

                                case DataType.Unicode:
                                    if (!DataTypeMappingSqlServer.DoesBelong(dataReader.GetDataTypeName(i), DataType.Unicode))
                                    {
                                        throw new Exception("Data type of column #" + (i + 1).ToString() + " of '" + metricGroup.name + "' metric does not match any allowed data type for internal data type Unicode");
                                    }

                                    oldValues[i] = (object)dataReader.GetString(i);

                                    break;

                                case DataType.Double:
                                    if (!DataTypeMappingSqlServer.DoesBelong(dataReader.GetDataTypeName(i), DataType.Double))
                                    {
                                        throw new Exception("Data type of column #" + (i + 1).ToString() + " of '" + metricGroup.name + "' metric does not match any allowed data type for internal data type Double");
                                    }

                                    oldValues[i] = (object)dataReader.GetDouble(i);

                                    break;

                                case DataType.SmallInt:
                                    if (!DataTypeMappingSqlServer.DoesBelong(dataReader.GetDataTypeName(i), DataType.SmallInt))
                                    {
                                        throw new Exception("Data type of column #" + (i + 1).ToString() + " of '" + metricGroup.name + "' metric does not match any allowed data type for internal data type Int16");
                                    }

                                    oldValues[i] = (object)dataReader.GetInt16(i);

                                    break;

                                case DataType.Datetime:
                                    if (!DataTypeMappingSqlServer.DoesBelong(dataReader.GetDataTypeName(i), DataType.Datetime))
                                    {
                                        throw new Exception("Data type of column #" + (i + 1).ToString() + " of '" + metricGroup.name + "' metric does not match any allowed data type for internal data type Datetime");
                                    }

                                    oldValues[i] = (object)dataReader.GetDateTime(i);

                                    break;

                                default:
                                    throw new Exception("Unknown data type");
                                } // end of switch
                                i++;
                            }

                            id = dataCache.Add(-1, new object[] { targetId }, oldValues);
                        }
                        else
                        {
                            noHistory = true;
                        }

                        dataReader.Close();
                        dataReader.Dispose();
                    }
                    catch (SqlException e)
                    {
                        if (e.Number == 208) // Invalid object
                        {
                            // Do not create tables if target has been deleted
                            if (!Configuration.targets.ContainsKey(targetId))
                            {
                                return(-1);
                            }

                            SqlServerProbe.CreateTablesForMetricGroup(targetId, metricGroup);
                            noHistory = true;
                        }
                        else
                        {
                            throw;
                        }
                    }
                }

                if (noHistory)
                {
                    return(-1);
                }
            }

            // compare old and new values
            object[] newValues = new object[metricGroup.NumberOfMetrics];
            for (int i = 0; i < metricGroup.NumberOfMetrics; i++)
            {
                newValues[i] = data.values[0, i];
            }

            if (dataCache.CompareAttributesForKey(id, newValues))
            {
                return(0);
            }
            else
            {
                return(1);
            }
        }