public LimitedSizeMemoryCache()
 {
     Cache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new MemoryCacheOptions()
     {
         SizeLimit = 1024
     });
 }
Beispiel #2
0
        public static void Main(string[] args)
        {
            // Runs several concurrent threads that access an item that periodically expires and is re-created.
            MemoryCache cache = new MemoryCache(new MemoryCacheOptions());
            string key = "MyKey";

            var options = new MemoryCacheEntryOptions().SetAbsoluteExpiration(TimeSpan.FromMilliseconds(50));

            var tasks = new List<Task>();
            for (int threads = 0; threads < 100; threads++)
            {
                var task = Task.Run(() =>
                {
                    for (int i = 0; i < 110000; i++)
                    {
                        object value;
                        if(!cache.TryGetValue(key, out value))
                        {
                            // Fake expensive object creation.
                            for (int j = 0; j < 1000000; j++)
                            {
                            }

                            cache.Set(key, new object(), options);
                        }
                    }
                });
                tasks.Add(task);
            }

            Console.WriteLine("Running");
            Task.WaitAll(tasks.ToArray());
            Console.WriteLine("Done");
        }
Beispiel #3
0
        public void AddCache()
        {
            var cacheConfig =
                (CacheType)Enum.Parse(typeof(CacheType), _configuration.GetSection("AppSettings")["CacheType"]);

            switch (cacheConfig)
            {
            case CacheType.InMemory:
                //net本地内存缓存
                _services.AddScoped <ICache, Infrastructure.Cache.MemoryCache>();
                _services.AddSingleton((Func <IServiceProvider, IMemoryCache>)(factory =>
                {
                    var cache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new MemoryCacheOptions());
                    return(cache);
                }));
                break;

            case CacheType.Redis:
                //redis 分布式缓存
                _services.AddScoped <ICache, RedisCache>();
                //autofac单例模式不能重连对象,只能自定义个类实现单例
                //services.AddSingleton<ConnectionMultiplexer>(provider =>
                //{
                //    var connection= ConnectionMultiplexer.Connect(Appsettings.app(new string[] { "AppSettings", "RedisCaching", "ConnectionString" }));
                //    return connection;
                //});
                break;
            }
        }
 /// <summary>Static constructor.</summary>
 static QueryCacheManager()
 {
     Cache = new MemoryCache(new MemoryCacheOptions());
     DefaultMemoryCacheEntryOptions = new MemoryCacheEntryOptions();
     CachePrefix = "Z.EntityFramework.Plus.QueryCacheManager;";
     CacheTags = new ConcurrentDictionary<string, List<string>>();
 }
 /// <inheritdoc />
 public MemoryCache(ILogger logger, string name, MemoryCacheOptions cacheOptions)
     : base(logger)
 {
     _name         = name;
     _cacheOptions = cacheOptions;
     _memoryCache  = new Microsoft.Extensions.Caching.Memory.MemoryCache(_cacheOptions);
 }
Beispiel #6
0
        public MethodResultCache(string methodName, int expirationPeriod = 30)
        {
            var options = new MemoryCacheOptions {
                ExpirationScanFrequency = TimeSpan.FromMinutes(expirationPeriod)
            };

            _cache = new Microsoft.Extensions.Caching.Memory.MemoryCache(options);
        }
Beispiel #7
0
        public void ClearCachedResults()
        {
            _cache.Dispose();
            var options = new MemoryCacheOptions {
                ExpirationScanFrequency = TimeSpan.FromMinutes(30)
            };

            _cache = new Microsoft.Extensions.Caching.Memory.MemoryCache(options);
        }
        public CacheSheetTest()
        {
            _spreadsheetRepository = ServiceFactory.CreateSpreadSheetRepository();
            _mockRepository        = ServiceFactory.CreateMockSpreadsheetRepository();
            var memoryCache = new MemoryCache(new MemoryCacheOptions());

            _cachedMockedDataRepository = new CachedDataRepository(_mockRepository, memoryCache, TimeSpan.FromSeconds(1));
            _cachedDataRepository       = new CachedDataRepository(_spreadsheetRepository, memoryCache, TimeSpan.FromSeconds(1));
        }
Beispiel #9
0
        public CqrsMemoryCache()
        {
            _cache = new MemoryCache(new MemoryCacheOptions() { ExpirationScanFrequency = new TimeSpan(0, 0, 15, 0) });

            _memoryCacheEntryOptions = new MemoryCacheEntryOptions()
            {
                SlidingExpiration = new TimeSpan(0, 0, 15, 0)
            };
        }
Beispiel #10
0
        public RScache()
        {
            memCache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new MemoryCacheOptions());
            folder   = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);

            // Combine the base folder with your specific folder....
            specificFolder = Path.Combine(folder, "drums");
            Directory.CreateDirectory(specificFolder);
            Directory.CreateDirectory(Path.Combine(folder, "localfiles"));
            localfiledirectory = Path.Combine(folder, "localfiles");
            localpathfile      = Path.Combine(localfiledirectory, "localfiles.json");
        }
        public async Task Get_Returns_Null_WhenNoRecordFound()
        {
            // Arrange
            var mockedStore = new Microsoft.Extensions.Caching.Memory.MemoryCache(new MemoryCacheOptions());
            var underTest   = new RegistrationsService(mockedStore);

            //Act
            var result = await underTest.GetRegistration(Guid.NewGuid().ToString());


            //Assert
            Assert.AreEqual(result, null);
        }
        public async Task Caches_per_url()
        {
            // setup
            var testMessageHandler = new TestMessageHandler();
            var cache = new MemoryCache(new MemoryCacheOptions());
            var client = new HttpClient(new InMemoryCacheHandler(testMessageHandler, null, null, cache));

            // execute for different URLs
            await client.GetAsync("http://unittest1");
            await client.GetAsync("http://unittest2");

            // validate
            testMessageHandler.NumberOfCalls.Should().Be(2);
        }
        public async Task Is_case_sensitive()
        {
            // setup
            var testMessageHandler = new TestMessageHandler();
            var cache = new MemoryCache(new MemoryCacheOptions());
            var client = new HttpClient(new InMemoryCacheHandler(testMessageHandler, null, null, cache));

            // execute for different URLs, only different by casing
            await client.GetAsync("http://unittest/foo.html");
            await client.GetAsync("http://unittest/FOO.html");

            // validate
            testMessageHandler.NumberOfCalls.Should().Be(2);
        }
 public MessageControllerTest(ITestOutputHelper output)
 {
     this.output = output;
     lookupRepo = new FakeLookupRepository();
     logger = new DivineLogger<FakeDataStore>(new FakeDataStore());
     cache = new MemoryCache(new MemoryCacheOptions());
     msgService = new FakeCommunicationService();
     var mockContext = new MockContext<IRepository<Member>>();
     membersRepo = new FakeMemberRepository(mockContext);
     var repositories = new DivineRepositories(attendanceRepo, lookupRepo, membersRepo, msgRepo);
     //divineBot = new TextDivineBot(repositories, msgService);
     mockContext.Arrange(x => (x.GetAllAsync())).Returns(Task.FromResult(membersList.AsQueryable()));
     messageCtrl = new MessageController(repositories, msgService, cache, logger, null);
 }
        public void ReturnsOnlyStaticUrlWhenPatternDoesntFindAnyMatches()
        {
            // Arrange
            var fileProvider = MakeFileProvider();
            var cache = new MemoryCache(new MemoryCacheOptions());
            var requestPathBase = PathString.Empty;
            var globbingUrlBuilder = new GlobbingUrlBuilder(fileProvider, cache, requestPathBase);

            // Act
            var urlList = globbingUrlBuilder.BuildUrlList("/site.css", "**/*.css", excludePattern: null);

            // Assert
            Assert.Collection(urlList, url => Assert.Equal("/site.css", url));
        }
Beispiel #16
0
        public void InvalidateCache()
        {
            var cache = new MemoryCache(_CacheOptions);

            foreach (var provider in Providers.Select(p => p.Value as CachedRateProvider).Where(p => p != null))
            {
                provider.CacheSpan   = CacheSpan;
                provider.MemoryCache = cache;
            }
            if (Providers.TryGetValue(CoinGeckoRateProvider.CoinGeckoName, out var coinAverage) && coinAverage is BackgroundFetcherRateProvider c)
            {
                c.RefreshRate  = CacheSpan;
                c.ValidatyTime = CacheSpan + TimeSpan.FromMinutes(1.0);
            }
        }
        public async Task Add_Returns_SavedRecordId()
        {
            // Arrange
            var mockedStore = new Microsoft.Extensions.Caching.Memory.MemoryCache(new MemoryCacheOptions());
            var underTest   = new RegistrationsService(mockedStore);

            // Act
            var createdRecord = await underTest.AddRegistration(new RegistrationRequest()
            {
                Locale = "en-GB"
            });

            //Assert
            Assert.IsNotNull(createdRecord.RegistrationId);
        }
        public async Task Gets_the_data_again_after_entry_is_gone_from_cache()
        {
            // setup
            var testMessageHandler = new TestMessageHandler();
            var cache = new MemoryCache(new MemoryCacheOptions());
            var client = new HttpClient(new InMemoryCacheHandler(testMessageHandler, null, null, cache));

            // execute twice
            await client.GetAsync("http://unittest");
            cache.Remove(new Uri("http://unittest"));
            await client.GetAsync("http://unittest");

            // validate
            testMessageHandler.NumberOfCalls.Should().Be(2);
        }
Beispiel #19
0
        public void TestMyExtension()
        {
            var cache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new MemoryCacheOptions());

            cache.MySet("user", new User {
                Name = "Foo"
            });
            var f = cache.MyGet <User>("user");

            Assert.Equal("Foo", f.Name);

            f.Name = "Bar";
            var b = cache.MyGet <User>("user");

            Assert.Equal("Foo", b.Name);
        }
        public void DedupesStaticUrlAndPatternMatches()
        {
            // Arrange
            var fileProvider = MakeFileProvider(MakeDirectoryContents("site.css", "blank.css"));
            var cache = new MemoryCache(new MemoryCacheOptions());
            var requestPathBase = PathString.Empty;
            var globbingUrlBuilder = new GlobbingUrlBuilder(fileProvider, cache, requestPathBase);

            // Act
            var urlList = globbingUrlBuilder.BuildUrlList("/site.css", "**/*.css", excludePattern: null);

            // Assert
            Assert.Collection(urlList,
                url => Assert.Equal("/site.css", url),
                url => Assert.Equal("/blank.css", url));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="RazorViewEngine" />.
 /// </summary>
 public MultiTemplateEngine(
     IRazorPageFactoryProvider pageFactory,
     IRazorPageActivator pageActivator,
     HtmlEncoder htmlEncoder,
     IOptions<RazorViewEngineOptions> optionsAccessor,
     ILoggerFactory loggerFactory)
 {
     _options = optionsAccessor.Value;
     _pageFactory = pageFactory;
     _pageActivator = pageActivator;
     _htmlEncoder = htmlEncoder;
     _logger = loggerFactory.CreateLogger<RazorViewEngine>();
     ViewLookupCache = new MemoryCache(new MemoryCacheOptions
     {
         CompactOnMemoryPressure = false
     });
 }
        public async Task Only_caches_get_results()
        {
            // setup
            var testMessageHandler = new TestMessageHandler();
            var cache = new MemoryCache(new MemoryCacheOptions());
            var client = new HttpClient(new InMemoryCacheHandler(testMessageHandler, null, null, cache));

            // execute twice for different methods
            await client.PostAsync("http://unittest", new StringContent(string.Empty));
            await client.PostAsync("http://unittest", new StringContent(string.Empty));
            await client.PutAsync("http://unittest", new StringContent(string.Empty));
            await client.PutAsync("http://unittest", new StringContent(string.Empty));
            await client.DeleteAsync("http://unittest");
            await client.DeleteAsync("http://unittest");

            // validate
            testMessageHandler.NumberOfCalls.Should().Be(6);
        }
Beispiel #23
0
        public void TestMemoryObject2()
        {
            var cache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new MemoryCacheOptions());

            var entry = cache.CreateEntry("user");

            entry.Value = new User {
                Name = "Foo"
            };


            cache.TryGetValue("user", out User f);
            Assert.Equal("Foo", f.Name);

            f.Name = "Bar";
            cache.TryGetValue("user", out User b);
            Assert.Equal("Bar", b.Name);
        }
Beispiel #24
0
        public void Contact()
        {
            // Arrange
            var config = new ConfigurationRoot(new List<IConfigurationProvider> {new MemoryConfigurationProvider(new MemoryConfigurationSource())});
            config["kEY1"] = "keyValue1";
            config["key2"] = "keyValue2";
            config["USERNAME"] = "******";
            var otherSettings = new OtherSettings { Numbers = new int[] { 234, 567 } };
            var options = new OptionsWrapper<OtherSettings>(otherSettings);
            var loggerFactory = new LoggerFactory();
            var logger = loggerFactory.CreateLogger<HomeController>();
            IMemoryCache cache = new MemoryCache(new MemoryCacheOptions());

            HomeController controller = new HomeController(config, options, logger, cache);

            // Act
            ViewResult result = controller.Contact() as ViewResult;

            // Assert
            Assert.Equal("keyValue1 SNeagu 234, 567", result.ViewBag.Message);
        }
Beispiel #25
0
        public void TestInitialize()
        {
            cache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new MemoryCacheOptions());
            List <string>  fpListOfKeys = new List <string>();
            List <Segment> segments     = new List <Segment>();
            Segment        segment      = new Segment {
                Latitude = 30, Longitude = 60, TimespanSeconds = 120
            };

            segments.Add(segment);
            testFlightPlan = new FlightPlan
            {
                FlightPlanId    = "123",
                InitialLocation = new FlightPlan.Location {
                    Longitude = 0, Latitude = 0, DateTime = DateTime.Parse("2020-05-30T12:00:00Z")
                },
                Segments = segments
            };
            fpListOfKeys.Add("123");
            cache.Set("flightListKeys", fpListOfKeys);
            cache.Set("123", testFlightPlan);
        }
Beispiel #26
0
        /// <summary>
        /// 将服务添加到容器
        /// </summary>
        /// <param name="services"></param>
        public IServiceProvider ConfigureServices(IServiceCollection services)
        {
            #region 部分服务注入-netcore自带方法
            //缓存注入
            services.AddSingleton <IMemoryCache>(factory => new MemoryCache(new MemoryCacheOptions()));
            //redis
            services.AddSingleton <IRedisCache, RedisCache>();
            //log日志注入
            services.AddSingleton <ILoggerHelper, LogHelper>();
            #endregion

            #region 初始化DB
            //services.AddScoped<DbContext>();
            #endregion

            #region CORS
            services.AddCors(c =>
            {
                ////↓↓↓↓↓↓↓注意正式环境不要使用这种全开放的处理↓↓↓↓↓↓↓↓↓↓
                //c.AddPolicy("AllRequests", policy =>
                //{
                //	policy
                //		.AllowAnyOrigin()//允许任何源
                //		.AllowAnyMethod()//允许任何方式
                //		.AllowAnyHeader()//允许任何头
                //		.AllowCredentials();//允许cookie
                //});
                ////↑↑↑↑↑↑↑注意正式环境不要使用这种全开放的处理↑↑↑↑↑↑↑↑↑↑

                //一般采用这种方法
                c.AddPolicy("LimitRequests", policy =>
                {
                    policy
                    .WithOrigins("http://*****:*****@iwenli.org", Url = "http://www.iwenli.org"
                        }
                    });
                    c.OrderActionsBy(m => m.RelativePath);
                });

                #region 读取xml信息
                var xmlPath = Path.Combine(basePath, "Demo.Core.xml");            //这个就是刚刚配置的xml文件名
                c.IncludeXmlComments(xmlPath, true);                              //默认的第二个参数是false,这个是controller的注释,记得修改

                var xmlModelPath = Path.Combine(basePath, "Demo.Core.Model.xml"); //这个就是Model层的xml文件名
                c.IncludeXmlComments(xmlModelPath);
                #endregion

                #region Token绑定到ConfigureServices
                //添加header验证信息
                //c.OperationFilter<SwaggerHeader>();

                var issuerName = (Configuration.GetSection("Audience"))["Issuer"];
                var security   = new Dictionary <string, IEnumerable <string> > {
                    { issuerName, new string[] { } },
                };
                c.AddSecurityRequirement(security);
                c.AddSecurityDefinition(issuerName, new ApiKeyScheme
                {
                    Description = "JWT授权(数据将在请求头中进行传输) 直接在下框中输入Bearer {token}(注意两者之间是一个空格)\"",
                    Name        = "Authorization",    //jwt默认的参数名称
                    In          = "header",           //jwt默认存放Authorization信息的位置(请求头中)
                    Type        = "apiKey"
                });
                #endregion
            });
            #endregion

            #region MVC + 注入全局异常捕获

            services.AddMvc(m =>
            {
                //全局异常过滤
                m.Filters.Add(typeof(GlobalExceptionsFilter));
            })
            .SetCompatibilityVersion(Microsoft.AspNetCore.Mvc.CompatibilityVersion.Version_2_2)
            //全局配置Json序列化处理
            .AddJsonOptions(options =>
            {
                //忽略循环引用
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                //不使用驼峰样式的key
                //options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                //设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });
            #endregion

            #region Token服务注册
            services.AddSingleton((Func <IServiceProvider, IMemoryCache>)(factory =>
            {
                var cache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new MemoryCacheOptions());
                return(cache);
            }));
            services.AddAuthorization(options =>
            {
                options.AddPolicy("Client", policy => policy.RequireRole("Client").Build());
                options.AddPolicy("Admin", policy => policy.RequireRole("Admin").Build());
                options.AddPolicy("AdminOrClient", policy => policy.RequireRole("Admin,Client").Build());
            });
            #endregion

            #region AutoFac
            //实例化 AutoFac 容器
            var builder = new ContainerBuilder();
            //注册要通过反射创建的组件
            builder.RegisterType <LogAop>();
            builder.RegisterType <MemoryCacheAop>();
            builder.RegisterType <RedisCacheAop>();
            //builder.RegisterType<AdvertisementServices>().As<IAdvertisementServices>();

            try
            {
                #region  引用项目,通过FileLoad
                var serviceDllFile  = Path.Combine(basePath, "Demo.Core.Service.dll");
                var serviceAssembly = Assembly.LoadFile(serviceDllFile);
                // AOP 开关,如果想要打开指定的功能,只需要在 appsettigns.json 对应对应 true 就行。
                var cacheType = new List <Type>();
                if (AppsettingsHelper.Get(new string[] { "AppSettings", "RedisCaching", "Enabled" }).ObjToBool())
                {
                    cacheType.Add(typeof(RedisCacheAop));
                }
                if (AppsettingsHelper.Get(new string[] { "AppSettings", "MemoryCachingAop", "Enabled" }).ObjToBool())
                {
                    cacheType.Add(typeof(MemoryCacheAop));
                }
                if (AppsettingsHelper.Get(new string[] { "AppSettings", "LogAop", "Enabled" }).ObjToBool())
                {
                    cacheType.Add(typeof(LogAop));
                }

                builder.RegisterAssemblyTypes(serviceAssembly)
                .AsImplementedInterfaces()
                .InstancePerLifetimeScope()
                .EnableInterfaceInterceptors()                         //引用Autofac.Extras.DynamicProxy;
                //如果你想注入两个,就这么写  InterceptedBy(typeof(BlogCacheAOP), typeof(BlogLogAOP));
                //如果想使用Redis缓存,请必须开启 redis 服务,端口号我的是6319,如果不一样还是无效,否则请使用memory缓存 BlogCacheAOP
                .InterceptedBy(cacheType.ToArray())                        //允许将拦截器服务的列表分配给注册。
                ;

                var repositoryDllFile  = Path.Combine(basePath, "Demo.Core.Repository.dll");
                var repositoryAssembly = Assembly.LoadFile(repositoryDllFile);
                builder.RegisterAssemblyTypes(repositoryAssembly).AsImplementedInterfaces();

                #endregion

                #region 直接引用项目
                //var servicveAssembly = Assembly.Load("Demo.Core.Service");
                //builder.RegisterAssemblyTypes(servicveAssembly).AsImplementedInterfaces();  //指定已扫描程序集中的类型注册为提供所有其实现的接口。
                //var repositoryAssembly = Assembly.Load("Demo.Core.Repository");
                //builder.RegisterAssemblyTypes(repositoryAssembly).AsImplementedInterfaces();
                #endregion

                #endregion
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }

            //将 services 填充 AutoFac 容器生成器
            builder.Populate(services);
            //使用已进行的组件等级创建新容器
            var applicationContainer = builder.Build();
            //第三方ico接管
            return(new AutofacServiceProvider(applicationContainer));
        }
 /// <inheritdoc />
 public override async Task ClearAsync()
 {
     _memoryCache.Dispose();
     _memoryCache = new Microsoft.Extensions.Caching.Memory.MemoryCache(_cacheOptions);
     await Task.FromResult(0);
 }
        public MemoryCache()
        {
            var cacheOptions = new MemoryCacheOptions();

            _memoryCache = new Microsoft.Extensions.Caching.Memory.MemoryCache(cacheOptions);
        }
        public void AddAndReplaceEntries_AreThreadSafe()
        {
            var cache = new MemoryCache(new MemoryCacheOptions
            {
                ExpirationScanFrequency = TimeSpan.Zero,
                SizeLimit            = 20,
                CompactionPercentage = 0.5
            });
            var cts = new CancellationTokenSource();

            var random = new Random();

            var task0 = Task.Run(() =>
            {
                while (!cts.IsCancellationRequested)
                {
                    var entrySize = random.Next(0, 5);
                    cache.Set(random.Next(0, 10), entrySize, new MemoryCacheEntryOptions {
                        Size = entrySize
                    });
                }
            });

            var task1 = Task.Run(() =>
            {
                while (!cts.IsCancellationRequested)
                {
                    var entrySize = random.Next(0, 5);
                    cache.Set(random.Next(0, 10), entrySize, new MemoryCacheEntryOptions {
                        Size = entrySize
                    });
                }
            });

            var task2 = Task.Run(() =>
            {
                while (!cts.IsCancellationRequested)
                {
                    var entrySize = random.Next(0, 5);
                    cache.Set(random.Next(0, 10), entrySize, new MemoryCacheEntryOptions {
                        Size = entrySize
                    });
                }
            });

            cts.CancelAfter(TimeSpan.FromSeconds(5));
            var task3 = Task.Delay(TimeSpan.FromSeconds(7));

            Task.WaitAll(task0, task1, task2, task3);

            Assert.Equal(TaskStatus.RanToCompletion, task0.Status);
            Assert.Equal(TaskStatus.RanToCompletion, task1.Status);
            Assert.Equal(TaskStatus.RanToCompletion, task2.Status);
            Assert.Equal(TaskStatus.RanToCompletion, task3.Status);

            var cacheSize = 0;

            for (var i = 0; i < 10; i++)
            {
                cacheSize += cache.Get <int>(i);
            }

            Assert.Equal(cacheSize, cache.Size);
            Assert.InRange(cache.Count, 0, 20);
        }
        public void OrdersGlobbedMatchResultsCorrectly(string staticUrl, FileNode dirStructure, string[] expectedPaths)
        {
            // Arrange
            var fileProvider = MakeFileProvider(dirStructure);
            var cache = new MemoryCache(new MemoryCacheOptions());
            var requestPathBase = PathString.Empty;
            var globbingUrlBuilder = new GlobbingUrlBuilder(fileProvider, cache, requestPathBase);

            // Act
            var urlList = globbingUrlBuilder.BuildUrlList(staticUrl, "**/*.*", excludePattern: null);

            // Assert
            var collectionAssertions = expectedPaths.Select<string, Action<string>>(expected =>
                actual => Assert.Equal(expected, actual));
            Assert.Collection(urlList, collectionAssertions.ToArray());
        }
        public async Task ProcessAsync_UsesExpiresSliding_ToExpireCacheEntryWithSlidingExpiration()
        {
            // Arrange - 1
            var currentTime = new DateTimeOffset(2010, 1, 1, 0, 0, 0, TimeSpan.Zero);
            var id = "unique-id";
            var childContent1 = "original-child-content";
            var clock = new Mock<ISystemClock>();
            clock.SetupGet(p => p.UtcNow)
                 .Returns(() => currentTime);
            var cache = new MemoryCache(new MemoryCacheOptions { Clock = clock.Object });
            var tagHelperContext1 = GetTagHelperContext(id);
            var tagHelperOutput1 = GetTagHelperOutput(childContent: childContent1);
            tagHelperOutput1.PreContent.SetContent("<cache>");
            tagHelperOutput1.PostContent.SetContent("</cache>");
            var cacheTagHelper1 = new CacheTagHelper(cache, new HtmlTestEncoder())
            {
                ViewContext = GetViewContext(),
                ExpiresSliding = TimeSpan.FromSeconds(30)
            };

            // Act - 1
            await cacheTagHelper1.ProcessAsync(tagHelperContext1, tagHelperOutput1);

            // Assert - 1
            Assert.Empty(tagHelperOutput1.PreContent.GetContent());
            Assert.Empty(tagHelperOutput1.PostContent.GetContent());
            Assert.True(tagHelperOutput1.IsContentModified);
            Assert.Equal(childContent1, tagHelperOutput1.Content.GetContent());

            // Arrange - 2
            currentTime = currentTime.AddSeconds(35);
            var childContent2 = "different-content";
            var tagHelperContext2 = GetTagHelperContext(id);
            var tagHelperOutput2 = GetTagHelperOutput(childContent: childContent2);
            tagHelperOutput2.PreContent.SetContent("<cache>");
            tagHelperOutput2.PostContent.SetContent("</cache>");
            var cacheTagHelper2 = new CacheTagHelper(cache, new HtmlTestEncoder())
            {
                ViewContext = GetViewContext(),
                ExpiresSliding = TimeSpan.FromSeconds(30)
            };

            // Act - 2
            await cacheTagHelper2.ProcessAsync(tagHelperContext2, tagHelperOutput2);

            // Assert - 2
            Assert.Empty(tagHelperOutput2.PreContent.GetContent());
            Assert.Empty(tagHelperOutput2.PostContent.GetContent());
            Assert.True(tagHelperOutput2.IsContentModified);
            Assert.Equal(childContent2, tagHelperOutput2.Content.GetContent());
        }
        public void ResolvesMatchedUrlsAgainstPathBase(string pathBase)
        {
            // Arrange
            var fileProvider = MakeFileProvider(MakeDirectoryContents("site.css", "blank.css"));
            var cache = new MemoryCache(new MemoryCacheOptions());
            var requestPathBase = new PathString(pathBase);
            var globbingUrlBuilder = new GlobbingUrlBuilder(fileProvider, cache, requestPathBase);

            // Act
            var urlList = globbingUrlBuilder.BuildUrlList(
                staticUrl: null,
                includePattern: "**/*.css",
                excludePattern: null);

            // Assert
            Assert.Collection(urlList,
                url => Assert.Equal($"{pathBase}/blank.css", url),
                url => Assert.Equal($"{pathBase}/site.css", url));
        }
Beispiel #33
0
        void InitExchanges()
        {
            // We need to be careful to only add exchanges which OnGetTickers implementation make only 1 request
            Providers.Add("binance", new ExchangeSharpRateProvider("binance", new ExchangeBinanceAPI(), true));
            Providers.Add("bittrex", new ExchangeSharpRateProvider("bittrex", new ExchangeBittrexAPI(), true));
            Providers.Add("poloniex", new ExchangeSharpRateProvider("poloniex", new ExchangePoloniexAPI(), true));
            Providers.Add("hitbtc", new ExchangeSharpRateProvider("hitbtc", new ExchangeHitBTCAPI(), true));
            Providers.Add("ndax", new ExchangeSharpRateProvider("ndax", new ExchangeNDAXAPI(), true));

            // Handmade providers
            Providers.Add(CoinGeckoRateProvider.CoinGeckoName, new CoinGeckoRateProvider(_httpClientFactory));
            Providers.Add(CoinAverageRateProvider.CoinAverageName, new CoinAverageRateProvider()
            {
                Exchange = CoinAverageRateProvider.CoinAverageName, HttpClient = _httpClientFactory?.CreateClient("EXCHANGE_COINAVERAGE"), Authenticator = _CoinAverageSettings
            });
            Providers.Add("kraken", new KrakenExchangeRateProvider()
            {
                HttpClient = _httpClientFactory?.CreateClient("EXCHANGE_KRAKEN")
            });
            Providers.Add("bylls", new ByllsRateProvider(_httpClientFactory?.CreateClient("EXCHANGE_BYLLS")));
            Providers.Add("bitbank", new BitbankRateProvider(_httpClientFactory?.CreateClient("EXCHANGE_BITBANK")));
            Providers.Add("bitpay", new BitpayRateProvider(_httpClientFactory?.CreateClient("EXCHANGE_BITPAY")));

            // Those exchanges make multiple requests when calling GetTickers so we remove them
            //DirectProviders.Add("gemini", new ExchangeSharpRateProvider("gemini", new ExchangeGeminiAPI()));
            //DirectProviders.Add("bitfinex", new ExchangeSharpRateProvider("bitfinex", new ExchangeBitfinexAPI()));
            //DirectProviders.Add("okex", new ExchangeSharpRateProvider("okex", new ExchangeOkexAPI()));
            //DirectProviders.Add("bitstamp", new ExchangeSharpRateProvider("bitstamp", new ExchangeBitstampAPI()));

            foreach (var provider in Providers.ToArray())
            {
                if (provider.Key == "cryptopia") // Shitty exchange, rate often unavailable, it spams the logs
                {
                    continue;
                }
                var prov = new BackgroundFetcherRateProvider(provider.Key, Providers[provider.Key]);
                if (provider.Key == CoinGeckoRateProvider.CoinGeckoName)
                {
                    prov.RefreshRate  = CacheSpan;
                    prov.ValidatyTime = CacheSpan + TimeSpan.FromMinutes(1.0);
                }
                else
                {
                    prov.RefreshRate  = TimeSpan.FromMinutes(1.0);
                    prov.ValidatyTime = TimeSpan.FromMinutes(5.0);
                }
                Providers[provider.Key] = prov;
            }

            var cache = new MemoryCache(_CacheOptions);

            foreach (var supportedExchange in GetCoinGeckoSupportedExchanges())
            {
                if (!Providers.ContainsKey(supportedExchange.Id))
                {
                    var coinAverage = new CoinGeckoRateProvider(_httpClientFactory)
                    {
                        Exchange = supportedExchange.Id
                    };
                    var cached = new CachedRateProvider(supportedExchange.Id, coinAverage, cache)
                    {
                        CacheSpan = CacheSpan
                    };
                    Providers.Add(supportedExchange.Id, cached);
                }
            }
            foreach (var supportedExchange in GetCoinAverageSupportedExchanges())
            {
                if (!Providers.ContainsKey(supportedExchange.Id))
                {
                    var coinAverage = new CoinGeckoRateProvider(_httpClientFactory)
                    {
                        Exchange = supportedExchange.Id
                    };
                    var cached = new CachedRateProvider(supportedExchange.Id, coinAverage, cache)
                    {
                        CacheSpan = CacheSpan
                    };
                    Providers.Add(supportedExchange.Id, cached);
                }
            }
        }
Beispiel #34
0
 public MemoryCacheTests()
 {
     _memoryCache = new MemoryCache(new MemoryCacheOptions());
 }
Beispiel #35
0
        public void ReturnsValueFromCache()
        {
            // Arrange
            var filePath = "/hello/world";
            var fileProvider = GetMockFileProvider(filePath);
            var memoryCache = new MemoryCache(new MemoryCacheOptions());
            memoryCache.Set(filePath, "FromCache");
            var fileVersionProvider = new FileVersionProvider(
                fileProvider,
                memoryCache,
                GetRequestPathBase());

            // Act
            var result = fileVersionProvider.AddFileVersionToPath(filePath);

            // Assert
            Assert.Equal("FromCache", result);
        }
Beispiel #36
0
 public MemoryCache()
 {
     _internal = new Microsoft.Extensions.Caching.Memory.MemoryCache(new MemoryCacheOptions());
 }
        public void HandlesCommaSeparatedPatterns(string includePattern, string[] expectedOutput)
        {
            // Arrange
            var fileProvider = MakeFileProvider(MakeDirectoryContents("site.css", "blank.js", "site2.txt", "site.js"));
            var cache = new MemoryCache(new MemoryCacheOptions());
            var requestPathBase = PathString.Empty;
            var globbingUrlBuilder = new GlobbingUrlBuilder(fileProvider, cache, requestPathBase);

            // Act
            var urlList = globbingUrlBuilder.BuildUrlList(
                staticUrl: null,
                includePattern: includePattern,
                excludePattern: null);

            // Assert
            Assert.Equal(expectedOutput, urlList, StringComparer.Ordinal);
        }
Beispiel #38
0
 /// <summary>
 /// Constructor.
 /// </summary>
 /// <param name="name">Unique name of the cache</param>
 public MemoryCache(string name)
     : base(name)
 {
     _memoryCache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new OptionsWrapper <MemoryCacheOptions>(new MemoryCacheOptions()));
 }
        public void UpdateCacheEntryOptions_SetsCachePreservationPriority()
        {
            // Arrange
            var priority = CacheItemPriority.High;
            var cache = new MemoryCache(new MemoryCacheOptions());
            var cacheTagHelper = new CacheTagHelper(cache, new HtmlTestEncoder())
            {
                Priority = priority
            };

            // Act
            var cacheEntryOptions = cacheTagHelper.GetMemoryCacheEntryOptions(new EntryLink());

            // Assert
            Assert.Equal(priority, cacheEntryOptions.Priority);
        }
        public void UpdateCacheEntryOptions_CopiesTriggersFromEntryLink()
        {
            // Arrange
            var expiresSliding = TimeSpan.FromSeconds(30);
            var expected = new[] { Mock.Of<IChangeToken>(), Mock.Of<IChangeToken>() };
            var cache = new MemoryCache(new MemoryCacheOptions());
            var cacheTagHelper = new CacheTagHelper(cache, new HtmlTestEncoder())
            {
                ExpiresSliding = expiresSliding
            };

            var entryLink = new EntryLink();
            entryLink.AddExpirationTokens(expected);

            // Act
            var cacheEntryOptions = cacheTagHelper.GetMemoryCacheEntryOptions(entryLink);

            // Assert
            Assert.Equal(expected, cacheEntryOptions.ExpirationTokens.ToArray());
        }
        public async Task ProcessAsync_ReturnsCachedValue_IfVaryByParamIsUnchanged()
        {
            // Arrange - 1
            var id = "unique-id";
            var childContent = "original-child-content";
            var cache = new MemoryCache(new MemoryCacheOptions());
            var tagHelperContext1 = GetTagHelperContext(id);
            var tagHelperOutput1 = GetTagHelperOutput(
                attributes: new TagHelperAttributeList(),
                childContent: childContent);
            var cacheTagHelper1 = new CacheTagHelper(cache, new HtmlTestEncoder())
            {
                VaryByQuery = "key1,key2",
                ViewContext = GetViewContext(),
            };
            cacheTagHelper1.ViewContext.HttpContext.Request.QueryString = new Http.QueryString(
                "?key1=value1&key2=value2");

            // Act - 1
            await cacheTagHelper1.ProcessAsync(tagHelperContext1, tagHelperOutput1);

            // Assert - 1
            Assert.Empty(tagHelperOutput1.PreContent.GetContent());
            Assert.Empty(tagHelperOutput1.PostContent.GetContent());
            Assert.True(tagHelperOutput1.IsContentModified);
            Assert.Equal(childContent, tagHelperOutput1.Content.GetContent());

            // Arrange - 2
            var tagHelperContext2 = GetTagHelperContext(id);
            var tagHelperOutput2 = GetTagHelperOutput(
                attributes: new TagHelperAttributeList(),
                childContent: "different-content");
            var cacheTagHelper2 = new CacheTagHelper(cache, new HtmlTestEncoder())
            {
                VaryByQuery = "key1,key2",
                ViewContext = GetViewContext(),
            };
            cacheTagHelper2.ViewContext.HttpContext.Request.QueryString = new Http.QueryString(
                "?key1=value1&key2=value2");

            // Act - 2
            await cacheTagHelper2.ProcessAsync(tagHelperContext2, tagHelperOutput2);

            // Assert - 2
            Assert.Empty(tagHelperOutput2.PreContent.GetContent());
            Assert.Empty(tagHelperOutput2.PostContent.GetContent());
            Assert.True(tagHelperOutput2.IsContentModified);
            Assert.Equal(childContent, tagHelperOutput2.Content.GetContent());
        }
        public async Task ProcessAsync_FlowsEntryLinkThatAllowsAddingTriggersToAddedEntry()
        {
            // Arrange
            var id = "some-id";
            var expectedContent = new DefaultTagHelperContent();
            expectedContent.SetContent("some-content");
            var tokenSource = new CancellationTokenSource();
            var cache = new MemoryCache(new MemoryCacheOptions());
            var cacheEntryOptions = new MemoryCacheEntryOptions()
                .AddExpirationToken(new CancellationChangeToken(tokenSource.Token));
            var tagHelperContext = new TagHelperContext(
                allAttributes: new TagHelperAttributeList(),
                items: new Dictionary<object, object>(),
                uniqueId: id);
            var tagHelperOutput = new TagHelperOutput(
                "cache",
                new TagHelperAttributeList { { "attr", "value" } },
                getChildContentAsync: useCachedResult =>
                {
                    TagHelperContent tagHelperContent;
                    if (!cache.TryGetValue("key1", out tagHelperContent))
                    {
                        tagHelperContent = expectedContent;
                        cache.Set("key1", tagHelperContent, cacheEntryOptions);
                    }

                    return Task.FromResult(tagHelperContent);
                });
            tagHelperOutput.PreContent.SetContent("<cache>");
            tagHelperOutput.PostContent.SetContent("</cache>");
            var cacheTagHelper = new CacheTagHelper(cache, new HtmlTestEncoder())
            {
                ViewContext = GetViewContext(),
            };
            var key = cacheTagHelper.GenerateKey(tagHelperContext);

            // Act - 1
            await cacheTagHelper.ProcessAsync(tagHelperContext, tagHelperOutput);
            IHtmlContent cachedValue;
            var result = cache.TryGetValue(key, out cachedValue);

            // Assert - 1
            Assert.Equal("HtmlEncode[[some-content]]", tagHelperOutput.Content.GetContent());
            Assert.True(result);

            // Act - 2
            tokenSource.Cancel();
            result = cache.TryGetValue(key, out cachedValue);

            // Assert - 2
            Assert.False(result);
            Assert.Null(cachedValue);
        }
        public async Task ProcessAsync_RecalculatesValueIfCacheKeyChanges()
        {
            // Arrange - 1
            var id = "unique-id";
            var childContent1 = "original-child-content";
            var cache = new MemoryCache(new MemoryCacheOptions());
            var tagHelperContext1 = GetTagHelperContext(id);
            var tagHelperOutput1 = GetTagHelperOutput(childContent: childContent1);
            tagHelperOutput1.PreContent.Append("<cache>");
            tagHelperOutput1.PostContent.SetContent("</cache>");
            var cacheTagHelper1 = new CacheTagHelper(cache, new HtmlTestEncoder())
            {
                VaryByCookie = "cookie1,cookie2",
                ViewContext = GetViewContext(),
            };
            cacheTagHelper1.ViewContext.HttpContext.Request.Headers["Cookie"] = "cookie1=value1;cookie2=value2";

            // Act - 1
            await cacheTagHelper1.ProcessAsync(tagHelperContext1, tagHelperOutput1);

            // Assert - 1
            Assert.Empty(tagHelperOutput1.PreContent.GetContent());
            Assert.Empty(tagHelperOutput1.PostContent.GetContent());
            Assert.True(tagHelperOutput1.IsContentModified);
            Assert.Equal(childContent1, tagHelperOutput1.Content.GetContent());

            // Arrange - 2
            var childContent2 = "different-content";
            var tagHelperContext2 = GetTagHelperContext(id);
            var tagHelperOutput2 = GetTagHelperOutput(childContent: childContent2);
            tagHelperOutput2.PreContent.SetContent("<cache>");
            tagHelperOutput2.PostContent.SetContent("</cache>");
            var cacheTagHelper2 = new CacheTagHelper(cache, new HtmlTestEncoder())
            {
                VaryByCookie = "cookie1,cookie2",
                ViewContext = GetViewContext(),
            };
            cacheTagHelper2.ViewContext.HttpContext.Request.Headers["Cookie"] = "cookie1=value1;cookie2=not-value2";

            // Act - 2
            await cacheTagHelper2.ProcessAsync(tagHelperContext2, tagHelperOutput2);

            // Assert - 2
            Assert.Empty(tagHelperOutput2.PreContent.GetContent());
            Assert.Empty(tagHelperOutput2.PostContent.GetContent());
            Assert.True(tagHelperOutput2.IsContentModified);
            Assert.Equal(childContent2, tagHelperOutput2.Content.GetContent());
        }
Beispiel #44
0
 public MemoryCache(IOptions <CachingOptions> options)
 {
     _options = options.Value;
     _cache   = new memory.MemoryCache(new memory.MemoryCacheOptions());
 }
        public void UpdateCacheEntryOptions_SetsAbsoluteExpiration_IfExpiresOnIsSet()
        {
            // Arrange
            var expiresOn = DateTimeOffset.UtcNow.AddMinutes(4);
            var cache = new MemoryCache(new MemoryCacheOptions());
            var cacheTagHelper = new CacheTagHelper(cache, new HtmlTestEncoder())
            {
                ExpiresOn = expiresOn
            };

            // Act
            var cacheEntryOptions = cacheTagHelper.GetMemoryCacheEntryOptions(new EntryLink());

            // Assert
            Assert.Equal(expiresOn, cacheEntryOptions.AbsoluteExpiration);
        }
        public void OvercapacityPurge_AreThreadSafe()
        {
            var cache = new MemoryCache(new MemoryCacheOptions
            {
                ExpirationScanFrequency = TimeSpan.Zero,
                SizeLimit            = 10,
                CompactionPercentage = 0.5
            });
            var cts           = new CancellationTokenSource();
            var limitExceeded = false;

            var task0 = Task.Run(() =>
            {
                while (!cts.IsCancellationRequested)
                {
                    if (cache.Size > 10)
                    {
                        limitExceeded = true;
                        break;
                    }
                    cache.Set(Guid.NewGuid(), Guid.NewGuid(), new MemoryCacheEntryOptions {
                        Size = 1
                    });
                }
            }, cts.Token);

            var task1 = Task.Run(() =>
            {
                while (!cts.IsCancellationRequested)
                {
                    if (cache.Size > 10)
                    {
                        limitExceeded = true;
                        break;
                    }
                    cache.Set(Guid.NewGuid(), Guid.NewGuid(), new MemoryCacheEntryOptions {
                        Size = 1
                    });
                }
            }, cts.Token);

            var task2 = Task.Run(() =>
            {
                while (!cts.IsCancellationRequested)
                {
                    if (cache.Size > 10)
                    {
                        limitExceeded = true;
                        break;
                    }
                    cache.Set(Guid.NewGuid(), Guid.NewGuid(), new MemoryCacheEntryOptions {
                        Size = 1
                    });
                }
            }, cts.Token);

            cts.CancelAfter(TimeSpan.FromSeconds(5));
            var task3 = Task.Delay(TimeSpan.FromSeconds(7));

            Task.WaitAll(task0, task1, task2, task3);

            Assert.Equal(TaskStatus.RanToCompletion, task0.Status);
            Assert.Equal(TaskStatus.RanToCompletion, task1.Status);
            Assert.Equal(TaskStatus.RanToCompletion, task2.Status);
            Assert.Equal(TaskStatus.RanToCompletion, task3.Status);
            Assert.Equal(cache.Count, cache.Size);
            Assert.InRange(cache.Count, 0, 10);
            Assert.False(limitExceeded);
        }
        public void UpdateCacheEntryOptions_PrefersAbsoluteExpirationSpecifiedOnEntryLinkOverExpiresOn()
        {
            // Arrange
            var expiresOn1 = DateTimeOffset.UtcNow.AddDays(12);
            var expiresOn2 = DateTimeOffset.UtcNow.AddMinutes(4);
            var cache = new MemoryCache(new MemoryCacheOptions());
            var cacheTagHelper = new CacheTagHelper(cache, new HtmlTestEncoder())
            {
                ExpiresOn = expiresOn1
            };

            var entryLink = new EntryLink();
            entryLink.SetAbsoluteExpiration(expiresOn2);

            // Act
            var cacheEntryOptions = cacheTagHelper.GetMemoryCacheEntryOptions(entryLink);

            // Assert
            Assert.Equal(expiresOn2, cacheEntryOptions.AbsoluteExpiration);
        }
Beispiel #48
0
        public void CheckFlights()
        {
            // Create new cache memory and it's keys.
            var cache = new Microsoft.Extensions.Caching.Memory.
                        MemoryCache(new MemoryCacheOptions());
            List <Server> serversList            = new List <Server>();
            List <string> keysList               = new List <string>();
            Dictionary <string, string> serverOf = new Dictionary <string, string>();

            cache.Set("servers", serversList);
            cache.Set("keys", keysList);
            cache.Set("serverOfIds", serverOf);

            // Check Post method of flight plans.
            FlightPlanController fpController = new FlightPlanController(cache)
            {
                ControllerContext = new ControllerContext
                {
                    HttpContext = new DefaultHttpContext()
                }
            };
            FlightPlan fp = new FlightPlan();

            // Fill flightPlan fields for posting it.
            fp.Passengers                = 200;
            fp.CompanyName               = "SwissAir";
            fp.InitialLocation           = new Location();
            fp.InitialLocation.Longitude = 35;
            fp.InitialLocation.Latitude  = 32;
            fp.InitialLocation.DateTime  = DateTime.UtcNow;
            fp.Segments = new List <Segment>();
            Segment seg = new Segment();

            seg.Longitude       = 36;
            seg.Latitude        = 33;
            seg.TimespanSeconds = 650;
            fp.Segments.Add(seg);
            // Post the preapared flightPlan.
            ActionResult resp = fpController.Post(fp);
            ObjectResult res  = resp as ObjectResult;

            // Check the status code of the response and check it equals
            // to the flight plan which was sent.
            Assert.AreEqual(res.StatusCode, 201);
            Assert.AreEqual(res.Value, fp);
            var iter = fpController.HttpContext.Response.Headers.Values.GetEnumerator();

            iter.MoveNext();
            // Get the interal flight id.
            string internalFlightId = iter.Current.ToArray()[0];

            // Check Post method of servers.
            ServersController serverController = new ServersController(cache);
            Server            testServer       = new Server();

            testServer.Id  = "test";
            testServer.Url = "http://www.testServer.com/";
            // Post the prepared server.
            resp = serverController.Post(testServer);
            res  = resp as ObjectResult;
            // Check the status code of the response and check it equals
            // to the server which was sent.
            Assert.AreEqual(res.StatusCode, 201);
            Assert.AreEqual(res.Value, testServer);

            // Inject fake MessegeHandler to HttpClient.
            // Create new HttpClient and override it's response method with a stub one.
            HttpClient client = new HttpClient(new HttpMessageHandlerStub());
            // Check get method of flights.
            FlightsController flightController = new FlightsController(cache, client)
            {
                ControllerContext = new ControllerContext
                {
                    HttpContext = new DefaultHttpContext()
                }
            };

            // Add sync_all to query.
            flightController.HttpContext.Request.QueryString = new QueryString("?sync_all");
            Task <ActionResult <List <Flight> > > respFlights = flightController.Get(DateTime.UtcNow);

            res = respFlights.Result.Result as ObjectResult;
            Assert.AreEqual(res.StatusCode, 200);
            // Check that we get two flights-
            // the first one is the one was sent earlier in this test.
            // the second one is a fake external flight which was generated by the stub.
            Assert.AreEqual(((List <Flight>)res.Value).Count, 2);
            Flight internalFlight = ((List <Flight>)res.Value)[0];
            Flight externalFlight = ((List <Flight>)res.Value)[1];

            Assert.AreEqual(internalFlight.FlightId, internalFlightId);
            Assert.AreEqual(internalFlight.IsExternal, false);
            Assert.AreEqual(externalFlight.FlightId, "FP00000000");
            Assert.AreEqual(externalFlight.IsExternal, true);
        }
        public void UpdateCacheEntryOptions_SetsAbsoluteExpiration_IfExpiresAfterIsSet()
        {
            // Arrange
            var expiresAfter = TimeSpan.FromSeconds(42);
            var cache = new MemoryCache(new MemoryCacheOptions());
            var cacheTagHelper = new CacheTagHelper(cache, new HtmlTestEncoder())
            {
                ExpiresAfter = expiresAfter
            };

            // Act
            var cacheEntryOptions = cacheTagHelper.GetMemoryCacheEntryOptions(new EntryLink());

            // Assert
            Assert.Equal(expiresAfter, cacheEntryOptions.AbsoluteExpirationRelativeToNow);
        }
Beispiel #50
0
 public Stats(MemoryCache memoryCache)
 {
     _memoryCache = memoryCache;
     _memoryCache.AddToStats(this);
 }
        public void UpdateCacheEntryOptions_SetsSlidingExpiration_IfExpiresSlidingIsSet()
        {
            // Arrange
            var expiresSliding = TimeSpan.FromSeconds(37);
            var cache = new MemoryCache(new MemoryCacheOptions());
            var cacheTagHelper = new CacheTagHelper(cache, new HtmlTestEncoder())
            {
                ExpiresSliding = expiresSliding
            };

            // Act
            var cacheEntryOptions = cacheTagHelper.GetMemoryCacheEntryOptions(new EntryLink());

            // Assert
            Assert.Equal(expiresSliding, cacheEntryOptions.SlidingExpiration);
        }
Beispiel #52
0
 public override void Clear()
 {
     _memoryCache.Dispose();
     _memoryCache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new OptionsWrapper <MemoryCacheOptions>(new MemoryCacheOptions()));
 }
        public void TrimsOnlySingleLeadingSlashOrTildeSlashFromPatterns(string prefix)
        {
            // Arrange
            var leadingSlashes = $"{prefix}{prefix}";
            var fileProvider = MakeFileProvider(MakeDirectoryContents("site.css", "blank.css"));
            var cache = new MemoryCache(new MemoryCacheOptions());
            var requestPathBase = PathString.Empty;
            var includePatterns = new List<string>();
            var excludePatterns = new List<string>();
            var matcher = MakeMatcher(includePatterns, excludePatterns);
            var globbingUrlBuilder = new GlobbingUrlBuilder(fileProvider, cache, requestPathBase);
            globbingUrlBuilder.MatcherBuilder = () => matcher;

            // Act
            var urlList = globbingUrlBuilder.BuildUrlList(
                staticUrl: null,
                includePattern: $"{leadingSlashes}**/*.css",
                excludePattern: $"{leadingSlashes}**/*.min.css");

            // Assert
            Assert.Collection(includePatterns, pattern => Assert.Equal($"{prefix}**/*.css", pattern));
            Assert.Collection(excludePatterns, pattern => Assert.Equal($"{prefix}**/*.min.css", pattern));
        }
Beispiel #54
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RazorViewEngine" />.
        /// </summary>
        public RazorViewEngine(
            IRazorPageFactoryProvider pageFactory,
            IRazorPageActivator pageActivator,
            HtmlEncoder htmlEncoder,
            IOptions<RazorViewEngineOptions> optionsAccessor,
            ILoggerFactory loggerFactory)
        {
            _options = optionsAccessor.Value;

            if (_options.ViewLocationFormats.Count == 0)
            {
                throw new ArgumentException(
                    Resources.FormatViewLocationFormatsIsRequired(nameof(RazorViewEngineOptions.ViewLocationFormats)),
                    nameof(optionsAccessor));
            }

            if (_options.AreaViewLocationFormats.Count == 0)
            {
                throw new ArgumentException(
                    Resources.FormatViewLocationFormatsIsRequired(nameof(RazorViewEngineOptions.AreaViewLocationFormats)),
                    nameof(optionsAccessor));
            }

            _pageFactory = pageFactory;
            _pageActivator = pageActivator;
            _htmlEncoder = htmlEncoder;
            _logger = loggerFactory.CreateLogger<RazorViewEngine>();
            ViewLookupCache = new MemoryCache(new MemoryCacheOptions
            {
                CompactOnMemoryPressure = false
            });
        }
Beispiel #55
-1
        public void Main()
        {
            _cacheEntryOptions = GetCacheEntryOptions();

            IMemoryCache cache = new MemoryCache(new MemoryCacheOptions());

            SetKey(cache, "0");

            PriodicallyReadKey(cache, TimeSpan.FromSeconds(1));

            PeriodciallyRemoveKey(cache, TimeSpan.FromSeconds(11));

            PeriodciallySetKey(cache, TimeSpan.FromSeconds(13));

            Console.ReadLine();
            Console.WriteLine("Shutting down");
        }