// Internal for unit testing internal DefaultChunkTreeCache( IFileProvider fileProvider, MemoryCacheOptions options) { _fileProvider = fileProvider; _chunkTreeCache = new MemoryCache(options); }
public ObjectCache() { var options = new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.FromMinutes(5) }; _expirationTimeSpan = TimeSpan.FromHours(2); _playerCache = new MemoryCache(options, new NullLoggerFactory()); _objectCache = new MemoryCache(options, new NullLoggerFactory()); _allianceCache = new MemoryCache(options, new NullLoggerFactory()); Logger.Log("Successfully loaded caches", null); }
public void MsMemory_Extensions_Named() { string name = "some instance name"; var expectedCacheOptions = new MemoryCacheOptions(); var cfg = new ConfigurationBuilder().WithMicrosoftMemoryCacheHandle(name).Build(); var cache = new BaseCacheManager <string>(cfg); cfg.CacheHandleConfigurations.First() .ConfigurationTypes.First().ShouldBeEquivalentTo(expectedCacheOptions); cfg.CacheHandleConfigurations.Count.Should().Be(1); cfg.CacheHandleConfigurations.First().Name.Should().Be(name); cfg.CacheHandleConfigurations.First().IsBackplaneSource.Should().BeFalse(); cache.CacheHandles.Count().Should().Be(1); }
public void GetAllNoEntriesListTest() { #region Test Setup var options = new MemoryCacheOptions(); var cache = new MemoryCache(options); var getAllMockDefinitionsCommand = new GetAllMockDefinitionsCommand(ref TestUtils.databaseLock); #endregion var Target = new GetAllMockDefinitionsHandler(cache, data); var Actual = Target.Handle(getAllMockDefinitionsCommand, CancellationToken.None).Result; Assert.Empty(Actual); }
protected LinkHcoMemoryUserCacheTestBase(MemoryCacheOptions options) { this.MemoryCacheOptions = new OptionsWrapper <MemoryCacheOptions>(options); this.MemoryCache = new MemoryCache(this.MemoryCacheOptions); this.UserCache = new LinkHcoMemoryUserCache <string, LinkHcoCacheEntry>( this.MemoryCache, CurrentUserIdentifier, SharedUserIdentifier, HcoEntryKeyBuilder, ControlEntryKeyBuilder, ConfigureEntryExpiration, ConfigureControlExpiration, ConfigureRootExpiration, RootControlTokenKey); }
public void MsMemory_Extensions_Simple() { var expectedCacheOptions = new MemoryCacheOptions(); var cfg = new ConfigurationBuilder().WithMicrosoftMemoryCacheHandle().Build(); var cache = new BaseCacheManager <string>(cfg); // disabling cfg check as they seem to alter the configuration internally after adding it... internal ms bs implementation //cfg.CacheHandleConfigurations.First() // .ConfigurationTypes.First().Should().BeEquivalentTo(expectedCacheOptions); cfg.CacheHandleConfigurations.Count.Should().Be(1); cfg.CacheHandleConfigurations.First().Name.Should().NotBeNullOrWhiteSpace(); cfg.CacheHandleConfigurations.First().IsBackplaneSource.Should().BeFalse(); cache.CacheHandles.Count().Should().Be(1); }
/// <summary> /// Method to initialize memory cache with options... /// </summary> private static void InitializeCacheOptions() { // Check if picture exists in cache. if (MemCache == null) { // Create cache options. MemoryCacheOptions mco = new MemoryCacheOptions { ExpirationScanFrequency = ExpirationScanFrequency }; // Create cache dictionary instance. MemCache = new MemoryCache(mco); } }
private NameCache( [Parameter(typeof(NameCacheConfiguration.CacheEntryExpiryTime))] double expirationDuration, [Parameter(typeof(NameCacheConfiguration.CacheMemoryLimit))] string memoryLimit, [Parameter(typeof(NameCacheConfiguration.PollingInterval))] string pollingInterval) { Logger.Log(Level.Warning, "Received a parameter \"PollingInterval\" which will be interpreted as ExpirationScanFrequency."); Logger.Log(Level.Warning, "Received a parameter \"CacheMemoryLimit\" which will be ignored."); var cacheConfig = new MemoryCacheOptions { ExpirationScanFrequency = TimeSpan.Parse(pollingInterval) }; _cache = new MemoryCache(cacheConfig); _expirationDuration = expirationDuration; }
//public static void ReadConfig(IConfiguration configuration) //{ // BeiKeUrl = configuration["Proxys:BeiKe"]; // JiGuangUrl = configuration["Proxys:JiGuang"]; // ZhiMaUrl = configuration["Proxys:ZhiMa"]; // FeiZhuUrl = configuration["Proxys:FeiZhu"]; //} static ProxyManager() { var op = new MemoryCacheOptions(); _MemoryCache = new MemoryCache(Options.Create(new MemoryCacheOptions())); _proxyHosts = new Stack <string>(); _stPlantSources = new Stack <PlantSource>(); //初始化代理平台 var pss = Enum.GetValues(typeof(PlantSource)); foreach (var v in pss) { PlantSource ps = (PlantSource)Enum.Parse(typeof(PlantSource), v.ToString()); _stPlantSources.Push(ps); } }
public NCacheWrapper(MemoryCacheOptions options) { if (!NCacheConfiguration.IsConfigured) { throw new Exception("NCache initialization configuration is not provided. Please use Alachisoft.NCache.EntityFrameworkCore.NCacheConfiguration.Configure() method to configure NCache before using it."); } if (NCacheConfiguration.InitParams != null) { _nCache = Web.Caching.NCache.InitializeCache(NCacheConfiguration.CacheId, NCacheConfiguration.InitParams); } else { _nCache = Web.Caching.NCache.InitializeCache(NCacheConfiguration.CacheId); } _defaultKeyGen = new DefaultKeyGenerator(); }
public void SaveMockDefinitionSuccessTest() { #region Test Setup var options = new MemoryCacheOptions(); var cache = new MemoryCache(options); #endregion var mockDefinition = mockDefinitionFake.Generate(); var saveMockDefinitionCommand = new SaveMockDefinitionCommand(mockDefinition, ref TestUtils.databaseLock); var Target = new SaveMockDefinitionHandler(cache, data); Target.Handle(saveMockDefinitionCommand, CancellationToken.None).Result.ToString(); cache.TryGetValue(mockDefinition.Metadata.Title, out var savedDefinition); Assert.NotNull(savedDefinition); }
public ClientRateLimitMiddlewareTests() { _url = "http://localhost:51879"; var cacheEntryOptions = new MemoryCacheOptions(); _rateLimitCounterHandler = new MemoryCacheRateLimitCounterHandler(new MemoryCache(cacheEntryOptions)); var httpContext = new DefaultHttpContext(); _downstreamContext = new DownstreamContext(httpContext); _downstreamContext.HttpContext.Response.Body = new FakeStream(); _loggerFactory = new Mock <IOcelotLoggerFactory>(); _logger = new Mock <IOcelotLogger>(); _loggerFactory.Setup(x => x.CreateLogger <ClientRateLimitMiddleware>()).Returns(_logger.Object); _next = context => Task.CompletedTask; _middleware = new ClientRateLimitMiddleware(_next, _loggerFactory.Object, _rateLimitCounterHandler); }
/// <summary> /// 绑定本地缓存管理 /// </summary> /// <remarks>引入 ICacheManager 使用</remarks> /// <param name="services">服务集合</param> /// <param name="memoryCacheOptions"></param> public static void AddCacheManager(this IServiceCollection services, MemoryCacheOptions memoryCacheOptions = null) { //services.AddSingleton<IMemoryCache, MemoryCache>(); if (memoryCacheOptions == null) { memoryCacheOptions = new MemoryCacheOptions() { } } ; services.AddSingleton <ICacheManager>(o => { return(new CacheManager(memoryCacheOptions)); }); }
public RpcMessageCorrelationManagerCacheTests() { _testScheduler = new TestScheduler(); var memoryCacheOptions = new MemoryCacheOptions(); var memoryCache = new MemoryCache(memoryCacheOptions); var logger = Substitute.For <ILogger>(); var changeTokenProvider = Substitute.For <IChangeTokenProvider>(); _cancellationTokenSource = new CancellationTokenSource(); var expirationToken = new CancellationChangeToken(_cancellationTokenSource.Token); changeTokenProvider.GetChangeToken().Returns(expirationToken); _rpcMessageCorrelationManager = new RpcMessageCorrelationManager(memoryCache, logger, changeTokenProvider, _testScheduler); }
public void UserSalesService_SetHeader_Record_GetSales(string row, string record) { ICSVReader csvReader = new CSVReader(); MemoryCacheOptions options = new MemoryCacheOptions(); IMemoryCache cache = new MemoryCache(options); IDataCache dataCache = new UserSalesCache(); dataCache.SetCache(cache); IUserSalesService userSalesService = new UserSalesService(csvReader); userSalesService.UseCache(dataCache); userSalesService.SetHeader(row); userSalesService.Record(record); List <UserSalesModel> userSales = userSalesService.GetSales(null, null); Assert.AreEqual("John Doe", userSales[0].User_Name); }
public bool TryAddPartition <T>(string key, MemoryCacheOptions memoryCacheOptions = null) { if (CachePartitions.TryGetValue(key, out _)) { return(false); } if (memoryCacheOptions == null) { CachePartitions.Add(key, new PartitionedCache <T>(new MemoryCache(new MemoryCacheOptions()))); } else { CachePartitions.Add(key, new PartitionedCache <T>(new MemoryCache(memoryCacheOptions))); } return(true); }
public static IServiceCollection AddMemoryCache <TCacheInstance>( this IServiceCollection services, Action <MemoryCacheOptions> setupInner = null, Action <MemoryCacheOptions <TCacheInstance> > setup = null) { MemoryCacheOptions innerOptions = new MemoryCacheOptions(); setupInner?.Invoke(innerOptions); MemoryCacheOptions <TCacheInstance> options = new MemoryCacheOptions <TCacheInstance>(new MemoryCache(innerOptions)); setup?.Invoke(options); services.TryAddSingleton(options); services.TryAddSingleton <IMemoryCache <TCacheInstance>, MemoryCache <TCacheInstance> >(); return(services); }
static void Main(string[] args) { var config = new SimpleConfig { BaseAddress = "http://api.openweathermap.org/data/2.5/weather", ApiKey = "62ffa8c4c1dfbc438b162198e174c4cb", State = "wa", IsoCountryCode = "au" }; var cacheOptions = new MemoryCacheOptions(); if (args.Length > 0) { config.State = args[0]; } if (args.Length > 1) { config.IsoCountryCode = args[1]; } var builder = new ContainerBuilder(); builder.RegisterType <WeatherServiceApplication>().AsImplementedInterfaces(); builder.RegisterInstance(config).AsImplementedInterfaces(); builder.RegisterModule <OpenWeatherModule>(); builder.RegisterType <OpenWeatherForecastProvider>().AsImplementedInterfaces(); builder.RegisterType <ConsoleInputHandler>().AsImplementedInterfaces(); builder.RegisterType <ConsoleOutputHandler>().AsImplementedInterfaces(); builder.RegisterInstance(cacheOptions).AsImplementedInterfaces(); builder.RegisterType <MemoryCache>().AsImplementedInterfaces(); builder.AddAutoMapper(typeof(OpenWeatherMappingProfile).Assembly); var container = builder.Build(); using (var scope = container.BeginLifetimeScope()) { var applicaiton = scope.Resolve <IWeatherServiceApplication>(); applicaiton.Run(); } }
public static Func <TInput, TResult> MemoizeWithMemoryCache <TInput, TResult>(this Func <TInput, TResult> func, MemoizeOptions options = null) { var memCacheOptions = new MemoryCacheOptions(); options?.MemoryCacheOptions?.Invoke(memCacheOptions); // create cache ("memo") var memo = new MemoryCache(memCacheOptions); // wrap provided function with cache handling // get a value from cache if it exists // if not, call factory method // MemCache will handle that internally return(input => memo.GetOrCreate(input, entry => { options?.CacheEntryOptions?.Invoke(entry); return func(input); })); }
public void UserSalesCache_Remove_Test() { MemoryCacheOptions options = new MemoryCacheOptions(); IMemoryCache cache = new MemoryCache(options); IDataCache dataCache = new UserSalesCache(); dataCache.SetCache(cache); IUserSales userSales = new UserSalesModel() { User_Name = "Renel Castro", }; string dateTime = DateTime.Now.ToString("YYYY-MM-dd"); dataCache.Create(userSales, DataCacheKey.Sales, DataCacheDuration.Short, dateTime); dataCache.Remove(DataCacheKey.Sales, dateTime); UserSalesModel userSalesCache = dataCache.Get <UserSalesModel>(DataCacheKey.Sales, dateTime); Assert.AreEqual(null, userSalesCache.User_Name); }
public void GetOrAdd_ExpiresEntriesAfterOneMinute() { // Arrange var path = @"Views\Home\_ViewStart.cshtml"; var fileProvider = new TestFileProvider(); fileProvider.AddFile(path, "some content"); var clock = new Mock <ISystemClock>(); var utcNow = DateTimeOffset.UtcNow; clock.SetupGet(c => c.UtcNow) .Returns(() => utcNow); var options = new MemoryCacheOptions { Clock = clock.Object }; using (var chunkTreeCache = new DefaultChunkTreeCache(fileProvider, options)) { var chunkTree1 = new ChunkTree(); var chunkTree2 = new ChunkTree(); // Act 1 var result1 = chunkTreeCache.GetOrAdd(path, fileInfo => chunkTree1); // Assert 1 Assert.Same(chunkTree1, result1); // Act 2 utcNow = utcNow.AddSeconds(59); var result2 = chunkTreeCache.GetOrAdd(path, fileInfo => { throw new Exception("Shouldn't be called."); }); // Assert 2 Assert.Same(chunkTree1, result2); // Act 3 utcNow = utcNow.AddSeconds(65); var result3 = chunkTreeCache.GetOrAdd(path, fileInfo => chunkTree2); // Assert 3 Assert.Same(chunkTree2, result3); } }
private void ConfigureApplicationRegistrations(TinyIoCContainer container) { container.Register(_appConfig); container.Register(_loggerFactory); container.Register(_logger); var options = new MemoryCacheOptions(); var eventLogger = LogFactory.CreateEventLogger(_loggingLevelSwitch, _appConfig); var serilogEventWriter = new SerilogEventWriter(eventLogger); container.Register <IEventWriter>(serilogEventWriter); container.Register(options); container.Register <IPropertySettings>(_appConfig.DefaultPropertySettings); container.Register(typeof(IOptions <>), typeof(OptionsManager <>)); container.Register <IMemoryCache, MemoryCache>(); container.Register <Domain.Defaults.Authorization>(); var httpClient = new HttpClient(); container.Register(httpClient); container.Register <IPersistenceConfigurator>((c, p) => { switch (_appConfig.StorageProvider.ToLowerInvariant()) { case StorageProviders.InMemory: return(new InMemoryConfigurator(_appConfig)); case StorageProviders.CouchDb: return(new CouchDbConfigurator(_appConfig)); case StorageProviders.SqlServer: return(new SqlServerConfigurator(_appConfig)); default: throw new ConfigurationException($"Invalid configuration for StorageProvider: {_appConfig.StorageProvider}. Valid storage providers are: {StorageProviders.InMemory}, {StorageProviders.CouchDb}, {StorageProviders.SqlServer}"); } }); var configurator = container.Resolve <IPersistenceConfigurator>(); configurator.ConfigureApplicationInstances(container); }
/// <summary> /// Creates a new <see cref="MemoryCache"/> instance. /// </summary> /// <param name="optionsAccessor">The options of the cache.</param> public MemoryCache(IOptions <MemoryCacheOptions> optionsAccessor) { if (optionsAccessor == null) { throw new ArgumentNullException(nameof(optionsAccessor)); } _options = optionsAccessor.Value; _entries = new ConcurrentDictionary <object, CacheEntry>(); _setEntry = SetEntry; _entryExpirationNotification = EntryExpired; if (_options.Clock == null) { _options.Clock = new SystemClock(); } _lastExpirationScan = _options.Clock.UtcNow; }
public void SavedTitleExistsInKeyCollections() { #region test setup var options = new MemoryCacheOptions(); var cache = new MemoryCache(options); #endregion var mockDefinition = mockDefinitionFake.Generate(); var saveMockDefinitionCommand = new SaveMockDefinitionCommand(mockDefinition, ref TestUtils.databaseLock); cache.Set(data.mockIds, new List <string> { mockDefinition.Metadata.Title }); cache.Set(mockDefinition.Metadata.Title, mockDefinition); var Target = new SaveMockDefinitionHandler(cache, data); Target.Handle(saveMockDefinitionCommand, CancellationToken.None).Result.ToString(); cache.TryGetValue(data.mockIds, out List <string> Actual); Assert.Contains(mockDefinition.Metadata.Title, Actual); }
public void SaveMockDefinitionCacheFailedNullTitleTest() { #region Test Setup var options = new MemoryCacheOptions(); var cache = new MemoryCache(options); var mockDefinition = mockDefinitionFake.Generate(); mockDefinition.Metadata.Title = null; var input = new { mockDefinition }; #endregion var saveMockDefinitionCommand = new SaveMockDefinitionCommand(input.mockDefinition, ref TestUtils.databaseLock); var Target = new SaveMockDefinitionHandler(cache, data); Assert.Throws <ArgumentNullException>(() => Target.Handle(saveMockDefinitionCommand, CancellationToken.None).Result); }
/// <summary> /// Return Settings object from cache or from the xml file /// </summary> /// <typeparam name="T">The type we will passing</typeparam> /// <param name="fileName"> </param> /// <returns></returns> /// public static T LoadJsonConfig <T>(string fileName) where T : class { if (string.IsNullOrEmpty(fileName)) { var filePath = string.Concat("/Config/", typeof(T).Name, ".json"); fileName = PlatformServices.Default.MapPath(filePath); } string cacheKey = fileName; IOptions <MemoryCacheOptions> option = new MemoryCacheOptions(); var myCache = new MemoryCache(option); T configObj = myCache.Get <T>(cacheKey); if (configObj == null) { configObj = LoadFromJson <T>(fileName); myCache.Set(cacheKey, configObj); } return(configObj); }
public void GetMockDefinitionTitleHandlerFailedTest() { #region Test Setup var faker = new Faker(); var options = new MemoryCacheOptions(); var cache = new MemoryCache(options); var input = new { title = faker.Random.AlphaNumeric(40) }; var getMockDefinitionCommand = new GetMockDefinitionByTitleCommand(input.title, ref TestUtils.databaseLock); #endregion var Target = new GetMockDefinitionByTitleHandler(cache); var Actual = Target.Handle(getMockDefinitionCommand, CancellationToken.None).Result; Assert.Null(Actual); }
public void MsMemory_Extensions_SimpleWithCfg() { var expectedCacheOptions = new MemoryCacheOptions() { Clock = new Microsoft.Extensions.Internal.SystemClock(), CompactOnMemoryPressure = true, ExpirationScanFrequency = TimeSpan.FromSeconds(20) }; var cfg = new ConfigurationBuilder().WithMicrosoftMemoryCacheHandle(expectedCacheOptions).Build(); var cache = new BaseCacheManager <string>(cfg); cfg.CacheHandleConfigurations.First() .ConfigurationTypes.First().ShouldBeEquivalentTo(expectedCacheOptions); cfg.CacheHandleConfigurations.Count.Should().Be(1); cfg.CacheHandleConfigurations.First().Name.Should().NotBeNullOrWhiteSpace(); cfg.CacheHandleConfigurations.First().IsBackplaneSource.Should().BeFalse(); cache.CacheHandles.Count().Should().Be(1); cache.CacheHandles.OfType <MemoryCacheHandle <string> >().First().MemoryCacheOptions.ShouldBeEquivalentTo(expectedCacheOptions); }
public async Task TestInsertAndGetByBase64Id() { MiniLinkContext context = GetContext(); IBaseRepository <LinkEntry> linkRepo; IBaseRepository <LinkEntryVisit> linkVisitRepo; MemoryCacheOptions options; IMemoryCache cache; async Task <ILinkEntryService> SetupAsync() { context = GetContext(); linkRepo = new BaseRepository <LinkEntry>(context); linkVisitRepo = new BaseRepository <LinkEntryVisit>(context); var options = new MemoryCacheOptions(); IMemoryCache cache = new MemoryCache(options); return(new LinkEntryService(linkRepo, linkVisitRepo, cache)); } ILinkEntryService linkEntryService = await SetupAsync(); var url = "https://www.google.com/"; var add = await linkEntryService.AddLinkEntry(url, ""); Assert.True(add.Success); // reset context to ensue ef doesnt keep the results context.Dispose(); linkEntryService = await SetupAsync(); var fetch = await linkEntryService.GetLinkEntryByBase64Id(add.Entry.Base64Id, true); Assert.Equal(fetch.URL, url); context.Dispose(); }
/// <summary> /// Return Settings object from cache or from the xml file /// </summary> /// <typeparam name="T">The type we will passing</typeparam> /// <param name="fileName"> </param> /// <returns></returns> /// public static T LoadConfig <T>(string fileName) where T : class { T configObj = null; if (string.IsNullOrEmpty(fileName)) { fileName = PlatformServices.Default.MapPath(string.Concat("/Config/", typeof(T).Name, ".config")); fileName = fileName.ToLower().Replace(@"\bin\debug\netcoreapp2.1", ""); OperatingSystem os = Environment.OSVersion; if (os.Platform == PlatformID.Unix) { fileName = PlatformServices.Default.MapPath("/Config"); fileName = fileName.Replace(@"/bin/Debug/netcoreapp2.1", ""); fileName = Path.Combine(fileName, $"{typeof(T).Name}.config"); } //fileName = string.Concat("/Config/", typeof(T).Name, ".config").Replace("/", "\\"); //if (fileName.StartsWith("\\")) //{ // fileName = fileName.TrimStart('\\'); //} //fileName = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName); } string cacheKey = fileName; IOptions <MemoryCacheOptions> option = new MemoryCacheOptions(); var myCache = new MemoryCache(option); configObj = myCache.Get <T>(cacheKey); if (configObj == null) { configObj = LoadFromXml <T>(fileName); myCache.Set(cacheKey, configObj); } return(configObj); }
public void ShouldSetCache() { // Arrange var expirationTimeSpan = TimeSpan.FromHours(1); var options = new MemoryCacheOptions(); var cache = new MemoryCache(options); var cacheEntryOptions = new MemoryCacheEntryOptions { SlidingExpiration = expirationTimeSpan }; // Act for (var i = 1; i <= 10; i++) { cache.Set($"{i}", new TestPayload(i), cacheEntryOptions); } // Assert cache.TryGetValue("1", out var result1); result1.Should().NotBeNull(); result1.Should().BeOfType <TestPayload>().Which.Id.Should().Be(1); cache.Count.Should().Be(10); }
public void GetOrAdd_ExpiresEntriesAfterOneMinute() { // Arrange var path = @"Views\Home\_ViewStart.cshtml"; var fileProvider = new TestFileProvider(); fileProvider.AddFile(path, "some content"); var clock = new Mock<ISystemClock>(); var utcNow = DateTimeOffset.UtcNow; clock.SetupGet(c => c.UtcNow) .Returns(() => utcNow); var options = new MemoryCacheOptions { Clock = clock.Object }; using (var chunkTreeCache = new DefaultChunkTreeCache(fileProvider, options)) { var chunkTree1 = new ChunkTree(); var chunkTree2 = new ChunkTree(); // Act 1 var result1 = chunkTreeCache.GetOrAdd(path, fileInfo => chunkTree1); // Assert 1 Assert.Same(chunkTree1, result1); // Act 2 utcNow = utcNow.AddSeconds(59); var result2 = chunkTreeCache.GetOrAdd(path, fileInfo => { throw new Exception("Shouldn't be called."); }); // Assert 2 Assert.Same(chunkTree1, result2); // Act 3 utcNow = utcNow.AddSeconds(65); var result3 = chunkTreeCache.GetOrAdd(path, fileInfo => chunkTree2); // Assert 3 Assert.Same(chunkTree2, result3); } }
static Cache() { var cacheOptions = new MemoryCacheOptions(); cacheOptions.ExpirationScanFrequency = TimeSpan.FromHours(1); cache = new MemoryCache(cacheOptions); }
private static IDistributedCacheTagHelperStorage GetStorage(MemoryCacheOptions options = null) { return new DistributedCacheTagHelperStorage(new MemoryDistributedCache(new MemoryCache(options ?? new MemoryCacheOptions()))); }
static WebSecurityUtil() { var cacheOptions = new MemoryCacheOptions(); cacheOptions.ExpirationScanFrequency = TimeSpan.FromMinutes(1); cache = new MemoryCache(cacheOptions); }