public void GetKeyExtractor_ConventionEnabled()
 {
     _config = new CacheConfiguration(new MemoryCache("CacheConfigurationTests"));
     var keyExtractor = _config.GetKeyExtractor(typeof(Person));
     Assert.IsNotNull(keyExtractor);
     Assert.AreEqual("1", keyExtractor(new Person { Id = 1 }));
 }
Exemple #2
0
 public Level1Fixture()
 {
     CacheConfiguration config = new CacheConfiguration()
         .WithFirstLevel(FirstLevelCacheType.ConcurrentDictionary);
     this.Cache = config.CreateCache();
     this.Elector = new ConfiguredElection(true);
 }
        public void ItemExpires_RemovedFromCache()
        {
            var redis = new RedisConnectionManager();
            // this is just testing the built in expiry
            var config = new CacheConfiguration(redis);

            var cache = new RedisCacheProvider(config); 
            cache.Logger = new TestRedisLogger();

            string key = "TagCacheTests:ItemExpires_RemovedFromCache";
            String value = "Hello World!";
            DateTime expires = DateTime.Now.AddSeconds(3);

            string tag1 = "tag1";
            string tag2 = "tag2";

            cache.Set(key, value, expires, new List<string> { tag1, tag2 });
            var result = cache.Get<String>(key);

            Assert.IsNotNull(result);
            Assert.AreEqual(value, result);
            
            Thread.Sleep(1000);

            result = cache.Get<String>(key);

            Assert.IsNotNull(result);
            Assert.AreEqual(value, result);

            Thread.Sleep(2500);

            result = cache.Get<String>(key);

            Assert.IsNull(result);  
        }
        public void GetKeyExtractor_WhenConventionTrowsException_OnVerifyFitInConvetion()
        {
            var convention = new Mock<Convention>();
            _config = new CacheConfiguration(new MemoryCache("CacheConfigurationTests"), convention.Object);
            convention.Setup(p => p.FitInConvention(It.IsAny<Type>())).Throws(new System.Exception());

            _config.GetKeyExtractor(typeof(City));
        }
        public ConcurrentCaches()
        {
            CacheConfiguration config = new CacheConfiguration();
            config.WithFirstLevel(FirstLevelCacheType.ConcurrentDictionary);
            config.WithSecondLevel(0, new RedisServer { Hostname = "127.0.0.1", Port = 6379 });

            this._cache1 = config.CreateCache();
            this._cache2 = config.CreateCache();
        }
        public void CreatePartialKey()
        {
            _config = new CacheConfiguration(new MemoryCache("KeyCreatorTests"), new MalformedConvention());
            _keyCreator = new KeyCreator(_config);

            var person = new Person { Id = 1, Name = "Maria" };

            var createdKey = _keyCreator.CreateKey(person);
        }
Exemple #7
0
        public Level2Fixture()
        {
            CacheConfiguration config = new CacheConfiguration()
                 .WithFirstLevel(FirstLevelCacheType.ConcurrentDictionary)
                 .WithSecondLevel(0, new RedisServer { Hostname = "127.0.0.1", Port = 6379 });

            Cache cc = config.CreateCache();
            this.Cache = cc;
            this.Elector = new DistributedMutexElection(cc.DistributedCache);
        }
        private static CacheConfiguration GenerateCacheConfiguration(ConfigurationInfo info)
        {
            CacheConfiguration configuration = new CacheConfiguration();

            foreach (ConfigNode node in info)
            {                                
                configuration.SchedulerConfiguration.Add(node.Convert());
            }

            return configuration;
        }
        public void CreateKey()
        {
            _config = new CacheConfiguration(new MemoryCache("KeyCreatorTests"));
            _keyCreator = new KeyCreator(_config);

            var person = new Person { Id = 2, Name = "person" };
            var key = CreateKey(person, person.Id.ToString());

            var createdKey = _keyCreator.CreateKey(person);

            Assert.AreEqual(key, createdKey);
        }
        public CacheConfiguration BuildConfiguration()
        {
            var fixedForOneHour = new CacheInstruction(CacheType.Fixed, TimeSpan.FromHours(1));
            var cacheConfig = new CacheConfiguration();
            cacheConfig.ApplyCachingOn(x => x.DeclaringType.Name.EndsWith("Repository"), fixedForOneHour)
                .InvalidateOn(x => x.Name.StartsWith("Save"))
                .InvalidateOn(x => x.Name.StartsWith("Delete"))
                .InvalidateOn(x => x.Name.StartsWith("Update"));

            //apply exceptions
            //cacheConfig
            //    .ExceptFor<IPersonRepository>(x => x.GetByName(null))
            //    .InvalidateOn<IPersonRepository>(x => x.Save(null));
            return cacheConfig;
        }
Exemple #11
0
        /// <summary>
        /// Creates near cache.
        /// </summary>
        private INearCache CreateNearCache(CacheConfiguration cacheConfiguration)
        {
            var nearCfg = cacheConfiguration.PlatformNearConfiguration;

            Debug.Assert(nearCfg != null);

            Func <object> affinityTopologyVersionFunc = () => _affinityTopologyVersion;
            var           affinity   = _ignite.GetAffinity(cacheConfiguration.Name);
            var           keepBinary = nearCfg.KeepBinary;

            TypeResolver resolver = null;
            Func <string, string, Type> resolve = (typeName, fieldName) =>
            {
                if (typeName == null)
                {
                    return(typeof(object));
                }

                if (resolver == null)
                {
                    resolver = new TypeResolver();
                }

                var resolved = resolver.ResolveType(typeName);

                if (resolved == null)
                {
                    throw new InvalidOperationException(string.Format(
                                                            "Can not create .NET Near Cache: {0}.{1} is invalid. Failed to resolve type: '{2}'",
                                                            typeof(PlatformNearCacheConfiguration).Name, fieldName, typeName));
                }

                return(resolved);
            };

            var keyType = resolve(nearCfg.KeyTypeName, "KeyTypeName");
            var valType = resolve(nearCfg.ValueTypeName, "ValueTypeName");

            var cacheType = typeof(NearCache <,>).MakeGenericType(keyType, valType);
            var nearCache = Activator.CreateInstance(
                cacheType,
                affinityTopologyVersionFunc,
                affinity,
                keepBinary);

            return((INearCache)nearCache);
        }
Exemple #12
0
        public void Arrange()
        {
            _giasApiClientMock = new Mock <IGiasApiClient>();

            _stateRepositoryMock = new Mock <IStateRepository>();
            _stateRepositoryMock.Setup(r => r.GetLastStagingDateClearedAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync(DateTime.Today.AddDays(-15));

            _establishmentRepositoryMock = new Mock <IEstablishmentRepository>();

            _groupRepositoryMock = new Mock <IGroupRepository>();

            _localAuthorityRepositoryMock = new Mock <ILocalAuthorityRepository>();

            _mapperMock = new Mock <IMapper>();

            _eventPublisherMock = new Mock <IEventPublisher>();

            _establishmentProcessingQueueMock = new Mock <IEstablishmentProcessingQueue>();

            _groupProcessingQueueMock = new Mock <IGroupProcessingQueue>();

            _localAuthorityProcessingQueueMock = new Mock <ILocalAuthorityProcessingQueue>();

            _configuration = new CacheConfiguration
            {
                NumberOfDaysToRetainStagingData = 14,
            };

            _loggerMock = new Mock <ILoggerWrapper>();

            _manager = new CacheManager(
                _giasApiClientMock.Object,
                _stateRepositoryMock.Object,
                _establishmentRepositoryMock.Object,
                _groupRepositoryMock.Object,
                _localAuthorityRepositoryMock.Object,
                _mapperMock.Object,
                _eventPublisherMock.Object,
                _establishmentProcessingQueueMock.Object,
                _groupProcessingQueueMock.Object,
                _localAuthorityProcessingQueueMock.Object,
                _configuration,
                _loggerMock.Object);

            _cancellationToken = new CancellationToken();
        }
        public void TestCompositeKeyAllDataTypes()
        {
            var cfg   = new CacheConfiguration("composite_key_all", new QueryEntity(typeof(KeyAll), typeof(string)));
            var cache = Ignition.GetIgnite().CreateCache <KeyAll, string>(cfg);

            var key = new KeyAll
            {
                Byte    = byte.MaxValue,
                SByte   = sbyte.MaxValue,
                Short   = short.MaxValue,
                UShort  = ushort.MaxValue,
                Int     = int.MaxValue,
                UInt    = uint.MaxValue,
                Long    = long.MaxValue,
                ULong   = ulong.MaxValue,
                Float   = float.MaxValue,
                Double  = double.MaxValue,
                Decimal = decimal.MaxValue,
                Guid    = Guid.NewGuid(),
                String  = "привет",
                Key     = new Key(255, 65555)
            };

            // Test insert.
            var res = cache.QueryFields(new SqlFieldsQuery(
                                            "insert into string(byte, sbyte, short, ushort, int, uint, long, ulong, float, double, decimal, " +
                                            "guid, string, key, _val) values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)",
                                            key.Byte, key.SByte, key.Short, key.UShort, key.Int, key.UInt, key.Long, key.ULong, key.Float,
                                            key.Double, key.Decimal, key.Guid, key.String, key.Key, "VALUE"))
                      .GetAll();

            Assert.AreEqual(1, res.Count);
            Assert.AreEqual(1, res[0].Count);
            Assert.AreEqual(1, res[0][0]);

            // Compare resulting keys.
            Assert.AreEqual(key, cache.Single().Key);

            // Compare keys in binary form.
            var binKey    = cache.Ignite.GetBinary().ToBinary <IBinaryObject>(key);
            var binKeyRes = cache.WithKeepBinary <IBinaryObject, string>().Single().Key;

            Assert.AreEqual(binKey, binKeyRes);

            // Get by key to verify identity.
            Assert.AreEqual("VALUE", cache[key]);
        }
Exemple #14
0
        private static void StartTransactionStatsCache(string name,
                                                       bool loadCacheFromDatabase)
        {
            var cacheCfg = new CacheConfiguration
            {
                KeepBinaryInStore = false,  // Depends on your case
                CacheStoreFactory = new TransactionsStatsCacheStoreFactory(),
                Name = name,
            };

            TransactionsStatsCache = _ignite.GetOrCreateCache <string, object>(cacheCfg);
            if (loadCacheFromDatabase)
            {
                TransactionsStatsCache.Clear();
                TransactionsStatsCache.LoadCache(null);
            }
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            var cacheConfiguration = new CacheConfiguration();

            this._config.Bind(nameof(CacheConfiguration), cacheConfiguration);

            services.AddDistributedRedisCache(options =>
            {
                options.Configuration = cacheConfiguration.RedisConnectionString;
            });

            services.Configure <CacheConfiguration>(this._config.GetSection(nameof(CacheConfiguration)));
            services.AddScoped <IMyComplexValueRepository, MyComplexValueRepository>();
            services.AddSingleton <IHybridCacheManager <int, MyComplexValue>, HybridCacheManager <int, MyComplexValue> >();
        }
Exemple #16
0
        public async Task should_save_version_on_cache_create()
        {
            var version        = new Version(5, 32);
            var cacheContainer = new CacheContainer();

            cacheContainer.Register <ILogger, TestLogger>();
            cacheContainer.Register <IVersionProvider, TestVersionProvider>().WithValue("version", version);
            cacheContainer.Register <IStorage, TestStorage>().AsSingleton();
            cacheContainer.Register <ISerializer, ProtoBufSerializer>().WithDependency("storage", typeof(IStorage).FullName).WithValue("userTypes", null);
            var cacheConfiguration = new CacheConfiguration(1024, 5, 1024, 5);
            var cache = new Cache(cacheContainer, cacheConfiguration);
            await cache.Initialize();

            var storage = (TestStorage)cacheContainer.Resolve <IStorage>();

            storage.KeyToStrings[Cache.VersionEntryName].Should().BeEquivalentTo(version.ToString());
        }
Exemple #17
0
        public static void AdvancedConfigKeyValTypes()
        {
            var ignite = Ignition.Start();

            //tag::advancedConfigKeyValTypes[]
            var cacheCfg = new CacheConfiguration("people")
            {
                PlatformCacheConfiguration = new PlatformCacheConfiguration
                {
                    KeyTypeName   = typeof(long).FullName,
                    ValueTypeName = typeof(Guid).FullName
                }
            };

            var cache = ignite.CreateCache <long, Guid>(cacheCfg);
            //end::advancedConfigKeyValTypes[]
        }
Exemple #18
0
        public static async Task <CacheConfiguration> CreateTenantCacheConfigAsync(string cacheName)
        {
            CacheConfiguration cacheCfg = null;

            try
            {
                var models = new[] { new QueryEntityIndexFields()
                                     {
                                         PrimaryKeys = indexFields, ModelType = typeof(Employee)
                                     } };

                List <QueryEntity> queryList = new List <QueryEntity>();
                foreach (var modelObject in models)
                {
                    var query = new QueryEntity(typeof(string), modelObject.ModelType)
                    {
                        Indexes = new List <QueryIndex>(queryIndex)
                        {
                            new QueryIndex(modelObject.PrimaryKeys)
                        }
                    };

                    queryList.Add(query);
                }

                cacheCfg = new CacheConfiguration
                {
                    Name = cacheName,
                    KeepBinaryInStore = false,  // Cache store works with deserialized data.
                    //ReadThrough = true,
                    //WriteThrough = true,
                    //WriteBehindEnabled = true,
                    QueryEntities  = queryList,
                    EvictionPolicy = new LruEvictionPolicy
                    {
                        MaxSize = 1000000
                    }
                };
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(cacheCfg);
        }
Exemple #19
0
        private static async Task MainAsync()
        {
            var cfg = new IgniteConfiguration
            {
                DiscoverySpi = new TcpDiscoverySpi
                {
                    IpFinder = new TcpDiscoveryStaticIpFinder
                    {
                        Endpoints = new[] { "127.0.0.1:47500" }
                    },
                    SocketTimeout = TimeSpan.FromSeconds(0.3)
                }
            };

            using (var ignite = Ignition.Start(cfg))
            {
                var cacheCfg = new CacheConfiguration(
                    "cache1",
                    new QueryEntity(typeof(int), typeof(Person)));

                var cache = ignite.CreateCache <int, Person>(cacheCfg);

                cache.Put(1, new Person(1));
                Debug.Assert(1 == cache[1].Age);

                var resPerson = cache.AsCacheQueryable()
                                .Where(e => e.Key > 0 && e.Value.Name.StartsWith("Person"))
                                .Select(e => e.Value)
                                .Single();
                Debug.Assert(1 == resPerson.Age);

                using (var igniteThin = Ignition.StartClient(new IgniteClientConfiguration("127.0.0.1")))
                {
                    var cacheThin  = igniteThin.GetCache <int, Person>(cacheCfg.Name);
                    var personThin = await cacheThin.GetAsync(1);

                    Debug.Assert("Person-1" == personThin.Name);

                    var personNames = cacheThin.AsCacheQueryable()
                                      .Where(e => e.Key != 2 && e.Value.Age < 10)
                                      .Select(e => e.Value.Name)
                                      .ToArray();
                    Debug.Assert(personNames.SequenceEqual(new[] { "Person-1" }));
                }
            }
        }
Exemple #20
0
        public void CacheConfigDurationTest()
        {
            // Arrange
            const string cacheName = "AccessClient";

            var cacheManager = new CacheManager();
            var cache        = new InMemoryTestCache(cacheName);

            cacheManager.AddCache(cache);

            //Assert
            Assert.AreEqual(5, CacheConfiguration.Instance(cacheName).DefaultDuration, "Default duration");
            Assert.AreEqual(5, CacheConfiguration.Instance(cacheName).GetCacheTime("GetEntityWithDefaultDuration"), "Item with defafult duration");
            Assert.AreEqual(1, CacheConfiguration.Instance(cacheName).GetCacheTime("GetEntityWith1MinuteDuration"), "Item 1 min duration");
            Assert.AreEqual(0, CacheConfiguration.Instance(cacheName).GetCacheTime("GetEntityWithZeroDuration"), "Item 0 duration");
            Assert.AreEqual(0, CacheConfiguration.Instance(cacheName).GetCacheTime("NonExistingItem"), "Non-existing 0 duration");
        }
Exemple #21
0
        public static void QueryEntityDemo()
        {
            // tag::queryEntity[]
            var cacheCfg = new CacheConfiguration
            {
                Name          = "myCache",
                QueryEntities = new[]
                {
                    new QueryEntity
                    {
                        KeyType      = typeof(long),
                        KeyFieldName = "id",
                        ValueType    = typeof(dotnet_helloworld.Person),
                        Fields       = new[]
                        {
                            new QueryField
                            {
                                Name      = "id",
                                FieldType = typeof(long)
                            },
                            new QueryField
                            {
                                Name      = "name",
                                FieldType = typeof(string)
                            },
                            new QueryField
                            {
                                Name      = "salary",
                                FieldType = typeof(long)
                            },
                        },
                        Indexes = new[]
                        {
                            new QueryIndex("name"),
                            new QueryIndex(false, QueryIndexType.Sorted, new[] { "id", "salary" })
                        }
                    }
                }
            };

            Ignition.Start(new IgniteConfiguration
            {
                CacheConfiguration = new[] { cacheCfg }
            });
            // end::queryEntity[]
        }
Exemple #22
0
        public MemoryCacheService(
            IMemoryCache memoryCache,
            IOptions <CacheConfiguration> cacheConfig)
        {
            _memoryCache = memoryCache;
            _cacheConfig = cacheConfig.Value;

            if (_cacheConfig != null)
            {
                _cacheOptions = new MemoryCacheEntryOptions
                {
                    AbsoluteExpiration = DateTime.Now.AddHours(_cacheConfig.AbsoluteExpirationInHours),
                    Priority           = CacheItemPriority.High,
                    SlidingExpiration  = TimeSpan.FromMinutes(_cacheConfig.SlidingExpirationInMinutes)
                };
            }
        }
        public void TestAttributeFilterWithNullValues()
        {
            TestDelegate action = () =>
            {
                var _ = new CacheConfiguration
                {
                    NodeFilter = new AttributeNodeFilter
                    {
                        Attributes = null
                    },
                };
            };

            var ex = Assert.Throws <ArgumentNullException>(action);

            StringAssert.Contains("value", ex.Message);
        }
Exemple #24
0
        public async Task custom_config_cache_construction_should_work()
        {
            var cacheConfig = new CacheConfiguration(1024, 5, 1024, 5, TimeSpan.FromMinutes(1));

            var cache = await PortableCacheFactory.GetCache(cacheConfig, null, "someCacheName2");

            await cache.Set("key1", "stringValue");

            cache.Size.Should().BeGreaterThan(0);
            cache.Count.Should().Be(1);
            cache.Get <string>("key1").Result.Value.Should().Be("stringValue");
            await cache.Remove("key1");

            cache.Count.Should().Be(0);
            cache.Size.Should().Be(0);
            cache.Get <string>("key1").Result.Should().BeNull();
        }
Exemple #25
0
        public void TestCompositeKey()
        {
            var cfg   = new CacheConfiguration("composite_key_arr", new QueryEntity(typeof(Key), typeof(Foo)));
            var cache = Ignition.GetIgnite().CreateCache <Key, Foo>(cfg);

            // Test insert.
            var res = cache.Query(new SqlFieldsQuery("insert into foo(hi, lo, id, name) " +
                                                     "values (-1, 65500, 3, 'John'), (255, 128, 6, 'Mary')")).GetAll();

            Assert.AreEqual(1, res.Count);
            Assert.AreEqual(1, res[0].Count);
            Assert.AreEqual(2, res[0][0]);  // 2 affected rows

            var foos = cache.OrderByDescending(x => x.Key.Lo).ToArray();

            Assert.AreEqual(2, foos.Length);

            Assert.AreEqual(-1, foos[0].Key.Hi);
            Assert.AreEqual(65500, foos[0].Key.Lo);
            Assert.AreEqual(3, foos[0].Value.Id);
            Assert.AreEqual("John", foos[0].Value.Name);

            Assert.AreEqual(255, foos[1].Key.Hi);
            Assert.AreEqual(128, foos[1].Key.Lo);
            Assert.AreEqual(6, foos[1].Value.Id);
            Assert.AreEqual("Mary", foos[1].Value.Name);

            // Existence tests check that hash codes are consistent.
            var binary   = cache.Ignite.GetBinary();
            var binCache = cache.WithKeepBinary <IBinaryObject, IBinaryObject>();

            Assert.IsTrue(cache.ContainsKey(new Key(65500, -1)));
            Assert.IsTrue(cache.ContainsKey(foos[0].Key));
            Assert.IsTrue(binCache.ContainsKey(
                              binary.GetBuilder(typeof(Key)).SetField("hi", -1).SetField("lo", 65500).Build()));
            Assert.IsTrue(binCache.ContainsKey(  // Fields are sorted.
                              binary.GetBuilder(typeof(Key)).SetField("lo", 65500).SetField("hi", -1).Build()));

            Assert.IsTrue(cache.ContainsKey(new Key(128, 255)));
            Assert.IsTrue(cache.ContainsKey(foos[1].Key));
            Assert.IsTrue(binCache.ContainsKey(
                              binary.GetBuilder(typeof(Key)).SetField("hi", 255).SetField("lo", 128).Build()));
            Assert.IsTrue(binCache.ContainsKey(  // Fields are sorted.
                              binary.GetBuilder(typeof(Key)).SetField("lo", 128).SetField("hi", 255).Build()));
        }
        /// <summary>
        /// Tests the type registration.
        /// </summary>
        private static void Test(IIgnite ignite1, IIgnite ignite2)
        {
            var cfg = new CacheConfiguration("cache")
            {
                CacheMode = CacheMode.Partitioned,
                WriteSynchronizationMode = CacheWriteSynchronizationMode.FullSync
            };

            // Put on one grid.
            var cache1 = ignite1.GetOrCreateCache <int, object>(cfg);

            cache1[1] = new Foo {
                Int = 1, Str = "1"
            };
            cache1[2] = ignite1.GetBinary().GetBuilder(typeof(Bar)).SetField("Int", 5).SetField("Str", "s").Build();

            // Get on another grid.
            var cache2 = ignite2.GetOrCreateCache <int, Foo>(cfg);
            var foo    = cache2[1];

            Assert.AreEqual(1, foo.Int);
            Assert.AreEqual("1", foo.Str);

            var bar = cache2.WithKeepBinary <int, IBinaryObject>()[2];

            Assert.AreEqual("s", bar.GetField <string>("Str"));
            Assert.AreEqual(5, bar.GetField <int>("Int"));

            var bar0 = bar.Deserialize <Bar>();

            Assert.AreEqual("s", bar0.Str);
            Assert.AreEqual(5, bar0.Int);

            // Test compute.
            var serverNodeCount = ignite1.GetCluster().ForServers().GetNodes().Count;

            var res = ignite1.GetCompute().Broadcast(new CompFn <DateTime>(() => DateTime.Now));

            Assert.AreEqual(serverNodeCount, res.Count);

            // Variable capture.
            var res2 = ignite1.GetCompute().Broadcast(new CompFn <string>(() => bar0.Str));

            Assert.AreEqual(Enumerable.Repeat(bar0.Str, serverNodeCount), res2);
        }
Exemple #27
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            DatabaseConfigurations connectionString = Configuration.GetSection("ConnectionStrings")
                                                      .Get <DatabaseConfigurations>();
            EmailConfiguration emailConfiguration = Configuration.GetSection("EmailConfiguration")
                                                    .Get <EmailConfiguration>();
            CacheConfiguration cacheConfiguration = Configuration.GetSection("CacheConfiguration")
                                                    .Get <CacheConfiguration>();

            if (cacheConfiguration.IsEnabled)
            {
                services.AddStackExchangeRedisCache(options => options.Configuration = cacheConfiguration.ConnectionString);
                services.AddSingleton <IResponseCacheService, ResponseCacheService>();
            }
            CloudConfiguration cloudConfiguration = Configuration.GetSection("CLOUDINARY")
                                                    .Get <CloudConfiguration>();

            services.AddSingleton(cacheConfiguration);
            services.AddSingleton(emailConfiguration);
            services.AddSingleton(connectionString);
            services.AddSingleton(cloudConfiguration);
            services.AddTransient <IDBContext, DBContext>();
            services.AddScoped <IUserService, UserService>();
            services.AddScoped <IUserRepository, UserRepository>();
            services.AddScoped <ITokenManager, TokenManager>();
            services.AddScoped <IBooksRepository, BooksRepository>();
            services.AddScoped <IBookService, BookService>();
            services.AddScoped <IWishlistRepository, WishlistRepository>();
            services.AddScoped <IWishlistService, WishlistService>();
            services.AddScoped <ICartRepository, CartRepository>();
            services.AddScoped <ICartService, CartService>();
            services.AddScoped <IOrderRepository, OrderRepository>();
            services.AddScoped <IOrderService, OrderService>();
            services.AddScoped <IEmailSender, EmailSender>();
            services.AddScoped <IMqServices, MsmqServices>();
            services.AddScoped <IEmailItemDetails, EmailItemDetails>();
            services.AddScoped <ICacheRepository, CacheRepository>();
            services.AddScoped <IAddressRepository, AddressRepository>();
            services.AddScoped <IAddressService, AddressService>();
            services.AddScoped <ICloudService, CloudService>();
            services.AddAutoMapper(typeof(Startup));
            services.AddSwagger();
            services.AddCors();
        }
Exemple #28
0
        public async void Initialize()
        {
            var cacheContainer = new CacheContainer();

            cacheContainer.Register <ILogger, TestLogger>();
            cacheContainer.Register <IVersionProvider, TestVersionProvider>().WithValue("version", new Version("1.0"));
            cacheContainer.Register <IStorage, TestStorage>();
            cacheContainer.Register <ISerializer, ProtoBufSerializer>().WithDependency("storage", typeof(IStorage).FullName).WithValue("userTypes", null);

            var cacheConfiguration = new CacheConfiguration(2048, 6, 2048, 5);

            _cache = new Cache(cacheContainer, cacheConfiguration);
            await _cache.Initialize();

            await _cache.Set("key1", "string1", TimeSpan.FromMilliseconds(1));

            Thread.Sleep(10);
        }
        public CommonRegistry(CacheConfiguration cacheConfiguration)
        {
            For <IConfigurationManager>().Singleton().Use <ConfigurationManager>();
            For <IConfigurationService>().Singleton().Use <AzureBlobConfigurationService>().Name = "ConfigurationService";
            For <IDateTimeService>().Use <DateTimeService>();
            For <ICurrentUserService>().Use <CurrentUserService>();

            if (cacheConfiguration.UseCache)
            {
                For <IConfigurationService>()
                .Singleton()
                .Use <CachedConfigurationService>()
                .Ctor <IConfigurationService>()
                .Named("ConfigurationService")
                .Ctor <ICacheService>()
                .Named(cacheConfiguration.DefaultCache);
            }
        }
        public void TestCustomFilterIsNotSupported()
        {
            var cacheCfg = new CacheConfiguration
            {
                Name       = Guid.NewGuid().ToString(),
                CacheMode  = CacheMode.Replicated,
                NodeFilter = new CustomFilter()
            };

            TestDelegate action = () => { _grid1.CreateCache <object, object>(cacheCfg); };

            var ex = Assert.Throws <NotSupportedException>(action);

            Assert.AreEqual("Unsupported CacheConfiguration.NodeFilter: " +
                            "'CustomFilter'. " +
                            "Only predefined implementations are supported: " +
                            "'AttributeNodeFilter'", ex.Message);
        }
        public IgniteDbConfiguration(IIgnite ignite, CacheConfiguration metaCacheConfiguration,
                                     CacheConfiguration dataCacheConfiguration, IDbCachingPolicy policy)
        {
            IgniteArgumentCheck.NotNull(ignite, "ignite");

            metaCacheConfiguration = metaCacheConfiguration ?? GetDefaultMetaCacheConfiguration();
            dataCacheConfiguration = dataCacheConfiguration ?? GetDefaultDataCacheConfiguration();

            var efCache = new DbCache(ignite, metaCacheConfiguration, dataCacheConfiguration);

            var txHandler = new DbTransactionInterceptor(efCache);

            AddInterceptor(txHandler);

            // SetProviderServices is not suitable. We should replace whatever provider there is with our proxy.
            Loaded += (sender, args) => args.ReplaceService <DbProviderServices>(
                (services, a) => new DbProviderServicesProxy(services, policy, efCache, txHandler));
        }
Exemple #32
0
 public void Map(CacheConfiguration cacheConfiguration)
 {
     cacheConfiguration.AddCacheService <IDefensiveCacheMapping>(configuration =>
     {
         configuration.AddMethod(x => nameof(x.GetBool), "mapGetBool-{id}", 600);
         configuration.AddMethod(x => nameof(x.GetBoolAsync), "mapGetBoolAsync-{id}", 600);
         configuration.AddMethod(x => nameof(x.GetDateTime), "mapGetDateTime-{id}", 600);
         configuration.AddMethod(x => nameof(x.GetDateTimeAsync), "mapGetDateTimeAsync-{id}", 600);
         configuration.AddMethod(x => nameof(x.GetInt), "mapGetInt-{id}", 600);
         configuration.AddMethod(x => nameof(x.GetIntAsync), "mapGetIntAsync-{id}", 600);
         configuration.AddMethod(x => nameof(x.GetListObject), "mapGetListObject-{filter.Page}_{filter.Records}", 600);
         configuration.AddMethod(x => nameof(x.GetListObjectAsync), "mapGetListObjectAsync-{filter.Page}_{filter.Records}", 600);
         configuration.AddMethod(x => nameof(x.GetObject), "mapGetObject-{id}", 600);
         configuration.AddMethod(x => nameof(x.GetObjectAsync), "mapGetObjectAsync-{id}", 600);
         configuration.AddMethod(x => nameof(x.GetString), "mapGetString-{id}", 600);
         configuration.AddMethod(x => nameof(x.GetStringAsync), "mapGetStringAsync-{id}", 600);
     });
 }
Exemple #33
0
        /// <summary>
        /// Inits a grid.
        /// </summary>
        private void InitNode(int i, bool serverNear = true, bool waitForPrimary = true, int backups = 0)
        {
            var cacheConfiguration = new CacheConfiguration(CacheName)
            {
                NearConfiguration          = serverNear ? new NearCacheConfiguration() : null,
                PlatformCacheConfiguration = serverNear ? new PlatformCacheConfiguration() : null,
                Backups = backups
            };

            _ignite[i] = Ignition.Start(TestUtils.GetTestConfiguration(name: "node" + i));
            _cache[i]  = _ignite[i].GetOrCreateCache <int, Foo>(cacheConfiguration);

            if (i == 2 && waitForPrimary)
            {
                // ReSharper disable once AccessToDisposedClosure
                TestUtils.WaitForTrueCondition(() => TestUtils.GetPrimaryKey(_ignite[2], CacheName) == Key3, 300000);
            }
        }
        public void TestFailedCacheStoreException()
        {
            try
            {
                var ccfg = new CacheConfiguration("CacheWithFailedStore")
                {
                    CacheStoreFactory = new FailedCacheStoreFactory(),
                    ReadThrough       = true
                };

                Assert.Throws <CacheException>(() => Ignition.GetIgnite(GridName).GetOrCreateCache <int, int>(ccfg));
            }
            finally
            {
                // After failed cache grid is in ivalid state. Should be restarted.
                Restart();
            }
        }
Exemple #35
0
        /// <summary>
        /// Tests the key.
        /// </summary>
        private static void TestKey <T>(params T[] vals)
        {
            var cfg = new CacheConfiguration("primitive_key_dotnet_" + typeof(T),
                                             new QueryEntity(typeof(T), typeof(string)));
            var cache = Ignition.GetIgnite().CreateCache <T, string>(cfg);

            foreach (var val in vals)
            {
                var res = cache.Query(new SqlFieldsQuery(
                                          "insert into string(_key, _val) values (?, ?)", val, val.ToString())).GetAll();

                Assert.AreEqual(1, res.Count);
                Assert.AreEqual(1, res[0].Count);
                Assert.AreEqual(1, res[0][0]);

                Assert.AreEqual(val.ToString(), cache[val]);
            }
        }
Exemple #36
0
        public CombinedTestResult TestCacheIsSet(CacheConfiguration config, TestRequest payload)
        {
            // Arrange
            var consumer = new TestConsumer();

            consumer.InitData();
            var message = new Message <TestRequest>(MessageLabel.From("message.label"), payload);
            var context = new TestContext(message);
            var sut     = new CachingConsumerOf <TestRequest>(consumer, config);

            // Act
            sut.Handle(context);

            // Assert
            var cachedValue = config?.Cache.ContainsKey(message) ?? false ? ((TestResponse)config.Cache[message]).Value : null;

            return(new CombinedTestResult(cachedValue, context.Response.Value));
        }
        /// <summary>
        /// Initializes Ignite caching for specified <see cref="DbConfiguration"/>.
        /// This method should be used when it is not possible to use or inherit <see cref="IgniteDbConfiguration"/>.
        /// </summary>
        /// <param name="dbConfiguration"><see cref="DbConfiguration"/> instance to be initialized
        /// for Ignite caching.</param>
        /// <param name="ignite">The ignite instance to use.</param>
        /// <param name="metaCacheConfiguration">
        /// Configuration of the metadata cache which holds entity set information. Null for default configuration.
        /// <para />
        /// This cache holds small amount of data, but should not lose entries. At least one backup recommended.
        /// </param>
        /// <param name="dataCacheConfiguration">
        /// Configuration of the data cache which holds query results. Null for default configuration.
        /// <para />
        /// This cache tolerates lost data and can have no backups.
        /// </param>
        /// <param name="policy">The caching policy. Null for default <see cref="DbCachingPolicy" />.</param>
        private static void InitializeIgniteCachingInternal(DbConfiguration dbConfiguration, IIgnite ignite,
                                                            CacheConfiguration metaCacheConfiguration, CacheConfiguration dataCacheConfiguration,
                                                            IDbCachingPolicy policy)
        {
            Debug.Assert(ignite != null);
            Debug.Assert(dbConfiguration != null);

            metaCacheConfiguration = metaCacheConfiguration ?? GetDefaultMetaCacheConfiguration();
            dataCacheConfiguration = dataCacheConfiguration ?? GetDefaultDataCacheConfiguration();

            var efCache = new DbCache(ignite, metaCacheConfiguration, dataCacheConfiguration);

            var txHandler = new DbTransactionInterceptor(efCache);

            AddInterceptorDelegate(dbConfiguration, txHandler);

            RegisterProviderServicesReplacer(dbConfiguration, policy, efCache, txHandler);
        }
        public void Arrange()
        {
            _stateRepositoryMock = new Mock <IStateRepository>();

            _ukrlpApiClientMock = new Mock <IUkrlpApiClient>();

            _mapperMock = new Mock <IMapper>();
            _mapperMock.Setup(m => m.MapAsync <LearningProvider>(It.IsAny <Provider>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync((Provider provider, CancellationToken cancellationToken) => new LearningProvider
            {
                Name = provider.ProviderName,
            });

            _eventPublisherMock = new Mock <IEventPublisher>();

            _providerProcessingQueueMock = new Mock <IProviderProcessingQueue>();

            _providerRepositoryMock = new Mock <IProviderRepository>();
            _providerRepositoryMock.Setup(r => r.GetProviderAsync(It.IsAny <long>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync((PointInTimeProvider)null);
            _providerRepositoryMock.Setup(r =>
                                          r.GetProviderFromStagingAsync(It.IsAny <long>(), It.IsAny <DateTime>(), It.IsAny <CancellationToken>()))
            .ReturnsAsync((long ukprn, DateTime pointInTime, CancellationToken cancellationToken) => new PointInTimeProvider
            {
                UnitedKingdomProviderReferenceNumber = ukprn,
                ProviderName = ukprn.ToString(),
            });

            _configuration = new CacheConfiguration();

            _loggerMock = new Mock <ILoggerWrapper>();

            _manager = new CacheManager(
                _stateRepositoryMock.Object,
                _ukrlpApiClientMock.Object,
                _providerRepositoryMock.Object,
                _mapperMock.Object,
                _eventPublisherMock.Object,
                _providerProcessingQueueMock.Object,
                _configuration,
                _loggerMock.Object);

            _cancellationToken = new CancellationToken();
        }
Exemple #39
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.TryAddTransient <IResponseHelper, ResponseHelper>();
            services.AddControllers();
            services.AddCoreServiceConfig();
            services.AddStoreServiceConfig();
            services.AddConfigurationServiceConfig(Configuration);
            services.AddHostedService <HistoryService>();

            var corsConfig = new CorsConfiguration();

            Configuration.GetSection(CorsConfiguration.Configuration).Bind(corsConfig);

            if (corsConfig.Origins.Length != 0)
            {
                UseCors = true;
                services.AddCors(options =>
                {
                    options.AddDefaultPolicy(builder => builder.WithOrigins(corsConfig.Origins).AllowAnyMethod().AllowAnyHeader());
                });
            }

            var cacheConfig = new CacheConfiguration();

            Configuration.GetSection(CacheConfiguration.Configuration).Bind(cacheConfig);

            if (cacheConfig.UseRedis)
            {
                if (string.IsNullOrWhiteSpace(cacheConfig.Host) || string.IsNullOrWhiteSpace(cacheConfig.Instance))
                {
                    throw new Exception("Redis not configured properly");
                }

                services.AddStackExchangeRedisCache(options =>
                {
                    options.Configuration = cacheConfig.Host;
                    options.InstanceName  = cacheConfig.Instance;
                });
            }
            else
            {
                services.AddDistributedMemoryCache();
            }
        }
        public void Arrange()
        {
            _giasApiClientMock = new Mock <IGiasApiClient>();
            _giasApiClientMock.Setup(c => c.DownloadEstablishmentsAsync(It.IsAny <CancellationToken>()))
            .ReturnsAsync(new Establishment[0]);

            _stateRepositoryMock = new Mock <IStateRepository>();

            _establishmentRepositoryMock = new Mock <IEstablishmentRepository>();

            _groupRepositoryMock = new Mock <IGroupRepository>();

            _localAuthorityRepositoryMock = new Mock <ILocalAuthorityRepository>();

            _mapperMock = new Mock <IMapper>();

            _eventPublisherMock = new Mock <IEventPublisher>();

            _establishmentProcessingQueueMock = new Mock <IEstablishmentProcessingQueue>();

            _groupProcessingQueueMock = new Mock <IGroupProcessingQueue>();

            _localAuthorityProcessingQueueMock = new Mock <ILocalAuthorityProcessingQueue>();

            _configuration = new CacheConfiguration();

            _loggerMock = new Mock <ILoggerWrapper>();

            _manager = new CacheManager(
                _giasApiClientMock.Object,
                _stateRepositoryMock.Object,
                _establishmentRepositoryMock.Object,
                _groupRepositoryMock.Object,
                _localAuthorityRepositoryMock.Object,
                _mapperMock.Object,
                _eventPublisherMock.Object,
                _establishmentProcessingQueueMock.Object,
                _groupProcessingQueueMock.Object,
                _localAuthorityProcessingQueueMock.Object,
                _configuration,
                _loggerMock.Object);

            _cancellationToken = new CancellationToken();
        }
 public void Setup()
 {
     _config = new CacheConfiguration(new MemoryCache("CacheConfigurationTests"), false);
 }
 public void GetKeyExtractor_WhenTypeDoNotFitInConvention()
 {
     _config = new CacheConfiguration(new MemoryCache("CacheConfigurationTests"));
     var keyExtractor = _config.GetKeyExtractor(typeof(City));
 }
Exemple #43
0
 public CachingAdvice(ICacheProvider cacheProvider, ICacheConfigurationService configurationService)
 {
     _cacheProvider = cacheProvider;
     _cacheConfiguration = configurationService.BuildConfiguration();
 }
Exemple #44
0
 public CacheInformation()
 {
     Configuration = new CacheConfiguration();
     Statistics = new CacheStatistics();
 }
        public void ItemExpires_Tag_RemovedFromCache()
        {
            // this is testing that when expiry happens, the events kick in and remove the tags
            // see RedisExpireHandler

            var redis = new RedisConnectionManager();
            var config = new CacheConfiguration(redis);

            var cache = new RedisCacheProvider(config);
            var client = newRedisClient(config.RedisClientConfiguration);

            cache.Logger = new TestRedisLogger();
            Console.WriteLine("Start Logger");

            string key = "TagCacheTests:ItemExpires_Tag_RemovedFromCache";
            String value = "Hello World!";
            DateTime expires = DateTime.Now.AddSeconds(3);
            
            string tag1 = "tag1001";
            string tag2 = "tag1002";

            cache.Set(key, value, expires, new List<string>{tag1, tag2});

            // first check everything has been set
            var result = cache.Get<String>(key);

            Assert.IsNotNull(result);
            Assert.AreEqual(value, result);

            var keysForTag1 = client.GetKeysForTag(tag1);
            Assert.IsNotNull(keysForTag1);
            Assert.IsTrue(keysForTag1.Any(x => x == key));

            var tagsForKey = client.GetTagsForKey(key);
            Assert.IsNotNull(tagsForKey);
            Assert.IsTrue(tagsForKey.Any(x => x == tag1));
            Assert.IsTrue(tagsForKey.Any(x => x == tag2));

            // wait a while
            Thread.Sleep(1000);

            // check it has not expired yet
            result = cache.Get<String>(key);

            Assert.IsNotNull(result);
            Assert.AreEqual(value, result);

            keysForTag1 = client.GetKeysForTag(tag1);
            Assert.IsNotNull(keysForTag1);
            Assert.IsTrue(keysForTag1.Any(x => x == key));

            tagsForKey = client.GetTagsForKey(key);
            Assert.IsNotNull(tagsForKey);
            Assert.IsTrue(tagsForKey.Any(x => x == tag1));
            Assert.IsTrue(tagsForKey.Any(x => x == tag2));

            // now wait until it should have been removed
            Thread.Sleep(2500);
            
            // now check its all been removed
            result = cache.Get<String>(key);

            Assert.IsNull(result);
            
            keysForTag1 = client.GetKeysForTag(tag1);
            Assert.IsNotNull(keysForTag1);
            Assert.IsFalse(keysForTag1.Any(x => x == key));

            tagsForKey = client.GetTagsForKey(key);
            Assert.IsNotNull(tagsForKey);
            Assert.IsFalse(tagsForKey.Any(x => x == tag1));
            Assert.IsFalse(tagsForKey.Any(x => x == tag2));

        }
 public static async Task<ICache> GetInMemotyCache(CacheConfiguration cacheConfiguration, IEnumerable<Type> userTypes = null, string cacheName = "default")
 {
     return await Instance.InMemoryCache(cacheConfiguration, userTypes, cacheName);
 }
 public static async Task<ICache> GetInMemotyCache(CacheContainer cacheContainer, CacheConfiguration cacheConfiguration)
 {
     return await Instance.InMemoryCache(cacheContainer, cacheConfiguration);
 }
        public void GetKeyExtractor_WithCustomConvetion()
        {
            _config = new CacheConfiguration(new MemoryCache("CacheConfigurationTests"), new CityConvention());
            var keyExtractor = _config.GetKeyExtractor(typeof(City));
            var city = new City { Name = "city", PopulationCount = 12345 };
            var key = keyExtractor(city);

            Assert.AreEqual(city.PopulationCount.ToString(), key);
        }
Exemple #49
0
 public void Setup()
 {
     _internalCache = new MemoryCache("CacheTest");
     _config = new CacheConfiguration(_internalCache);
     _cache = new Cache(_config);
 }
Exemple #50
0
 internal KeyCreator(CacheConfiguration configuration)
 {
     _configuration = configuration;
 }