public void AbsoluteExpitationTest() { int count = 0; Func<DateTime> dataProvider = () => { count++; return DateTime.Now; }; IDataProvider<DateTime> provider = new MemoryCacheProvider<DateTime>("DateTime1", dataProvider, TimeSpan.FromSeconds(5), ObjectCache.NoSlidingExpiration); var now = DateTime.Now; var dt = provider.Data; while(true) { Thread.Sleep(100); var d = provider.Data; if(d != dt) { Assert.True(DateTime.Now - now <= TimeSpan.FromSeconds(10)); break; } Assert.Equal(1, count); } }
public async Task ReadShouldCacheForTheTimeSpanProvided() { #region Setup var memory = new MemoryCacheProvider(TimeSpan.FromSeconds(5)); HttpContent empty = new StringContent(string.Empty); HttpRequestMessage request = new HttpRequestMessage(); request.Method = HttpMethod.Get; HttpResponseMessage response = new HttpResponseMessage(); response.Content = testContent; this.http.Setup(h => h.SendOriginalAsync()).Returns(() => Task.FromResult(response)); this.http.SetupGet(h => h.OriginalRequest).Returns(request); #endregion HttpContent result = await memory.Read(testUri, this.http.Object); Assert.AreEqual(testContent, result); response.Content = empty; result = await memory.Read(testUri, this.http.Object); Assert.AreEqual(testContent, result); await Task.Delay(5000); result = await memory.Read(testUri, this.http.Object); Assert.AreEqual(empty, result); }
public void MonitorExceptionTest() { using ( var provider = new MemoryCacheProvider( "Test" ).AsAsyncProvider() ) { var cacheService = new CacheService( provider ); var monitor = new CacheServiceMonitorWithException(); cacheService.RegisterMonitor( monitor ); Task.Run( (Func<Task>) (async () => { await cacheService.FetchOrAdd<string>( (string) "Test", (Func<Task<string>>) (() => (Task<string>) Task.Run( (Func<string>) (() => (string) "Test") )), (Caching.CachePolicy) Caching.CachePolicy.Expires( (TimeSpan) TimeSpan.FromHours( (double) 1 ) ) ); await cacheService.FetchOrAdd<string>( (string) "Test", (Func<Task<string>>) (() => (Task<string>) Task.Run( (Func<string>) (() => (string) "Test") )), (Caching.CachePolicy) Caching.CachePolicy.Expires( (TimeSpan) TimeSpan.FromHours( (double) 1 ) ) ); await Task.Delay( 100 ); await cacheService.FetchOrAdd<string>( (string) "Test", (Func<Task<string>>) (() => (Task<string>) Task.Run( (Func<string>) (() => (string) "Test") )), (Caching.CachePolicy) Caching.CachePolicy.Expires( (TimeSpan) TimeSpan.FromHours( (double) 1 ) ) ); await cacheService.FetchOrAdd<string>( (string) "Test", (Func<Task<string>>) (() => (Task<string>) Task.Run( (Func<string>) (() => (string) "Test") )), (Caching.CachePolicy) Caching.CachePolicy.Expires( (TimeSpan) TimeSpan.FromHours( (double) 1 ) ) ); }) ).Wait(); Assert.AreEqual( monitor.Misses, 1 ); Assert.AreEqual( monitor.Hits, 3 ); } }
static OutputCache() { DefaultOptions = OutputCacheOptions.None; var providerSettings = new CacheSettingsManager().RetrieveOutputCacheProviderSettings(); if (providerSettings == null || providerSettings.Type == null) { Instance = new MemoryCacheProvider(); } else { try { Instance = (OutputCacheProvider)Activator.CreateInstance(Type.GetType(providerSettings.Type)); Instance.Initialize(providerSettings.Name, providerSettings.Parameters); } catch (Exception ex) { throw new ConfigurationErrorsException( string.Format("Unable to instantiate and initialize OutputCacheProvider of type '{0}'. Make sure you are specifying the full type name.", providerSettings.Type), ex ); } } }
public async Task TemplateEngineShouldUseSameNamingConventionForBinding() { var cacheProvider = new MemoryCacheProvider(); var handlerFactory = new Mock<IHelperHandlerFactory>(); handlerFactory.Setup(f => f.Create()).Returns(Enumerable.Empty<IHelperHandler>()); var namingRule = new NamingRule(); var schemaProvider = new HandlebarsViewSchemaProvider(null, new MemberLocatorFromNamingRule(namingRule)); var codeGenerator = new JsonSchemaCodeGenerator(namingRule); const string input = "<p>{{name}}</p><p>{{first_name}}</p>"; var templateInfo = new StringTemplateInfo("views/test", input); var schema = await schemaProvider.GetSchemaFromTemplateAsync(templateInfo).ConfigureAwait(false); var modelType = codeGenerator.Compile(schema); var viewEngine = new VeilViewEngine(cacheProvider, handlerFactory.Object, namingRule); var view = await viewEngine.CreateViewAsync(templateInfo, modelType).ConfigureAwait(false); var model = Activator.CreateInstance(modelType); modelType.GetProperty("Name").SetValue(model, "{{name}}"); modelType.GetProperty("FirstName").SetValue(model, "{{first_name}}"); var writer = new StringWriter(); view.Render(model, new RenderingContext(writer)); var stringResult = writer.ToString(); Assert.AreEqual(input, stringResult); }
public void Provider_Initializes_Correctly() { using (var provider = new MemoryCacheProvider<string, string>()) { Assert.IsNotNull(provider); } }
public void SlidingExpirationTest() { int count = 0; Func<DateTime> dataProvider = () => { count++; return DateTime.Now; }; IDataProvider<DateTime> provider = new MemoryCacheProvider<DateTime>("DateTime2", dataProvider, ObjectCache.NoSlidingExpiration, TimeSpan.FromSeconds(2)); var dt = provider.Data; DateTime d = provider.Data; for(int i = 0; i < 10; i++) { Thread.Sleep(300); Assert.Equal(dt, d); Assert.Equal(1, count); } Thread.Sleep(TimeSpan.FromSeconds(3)); d = provider.Data; Assert.Equal(2, count); Assert.NotEqual(dt, d); }
public void FixtureSetup() { XmlConfigurator.Configure(); props = new Dictionary<string, string>(); props.Add("expiration", 120.ToString()); props.Add("priority", 0.ToString()); provider = new MemoryCacheProvider(); }
public void should_not_throw() { var cacheProvider = new MemoryCacheProvider(); Maybe<Boo> value = null; cacheProvider.Invoking(c => { value = c.Find<Boo>("key"); }). ShouldNotThrow(); value.HasValue.Should(). BeFalse(); }
public void Removes_Function_Correctly() { var provider = new MemoryCacheProvider<string, string>() { { "key1", new CachedValue<string>("value1") }, { "key2", new CachedValue<string>("value2") }, { "key3", new CachedValue<string>("value3") }, }; Assert.AreEqual(3, provider.Count()); provider.Remove("key1"); Assert.AreEqual(2, provider.Count()); provider.Remove(new List<string> { "key2", "key3" }); Assert.AreEqual(0, provider.Count()); }
public void Enumerable_Function_Correctly() { var provider = new MemoryCacheProvider<string, string>() { { "key1", new CachedValue<string>("value1") }, { "key2", new CachedValue<string>("value2") }, { "key3", new CachedValue<string>("value3") }, }; foreach (var item in provider) { Assert.AreEqual(item.Value, provider.Get(item.Key)); } // for code coverage sake var enumerator = ((System.Collections.IEnumerable)provider).GetEnumerator(); }
public void GetItemCanAddToCache() { // Arrange var cache = new MemoryCacheProvider(this.fixture.AppConfiguration.TerminologySqlSettings); const string Key = "key"; var dt = DateTime.Now; var obj = new TestObject { Text = "Test", Stamp = dt }; // Act var tmp = cache.GetItem(Key, () => obj); var cached = cache.GetItem(Key) as TestObject; // Assert Assert.NotNull(cached); Assert.Equal(dt, cached.Stamp); }
public void GetItemCanAddToCache() { // Arrange var cache = new MemoryCacheProvider(this.fixture.AppConfiguration.TerminologySqlSettings); const string Key = "key"; var dt = DateTime.Now; var obj = new TestObject { Text = "Test", Stamp = dt }; // Act var tmp = cache.GetItem(Key, () => obj); var cached = cache.GetItem(Key).OfType <TestObject>(); // Assert cached.HasValue.Should().BeTrue(); cached.Single().Stamp.Should().Be(dt); }
public void AddTest() { var provider = new MemoryCacheProvider(); var cacheKey = new CacheKey("AddTest" + DateTime.Now.Ticks); var value = "Test Value " + DateTime.Now; var cachePolicy = new CachePolicy(); bool result = provider.Add(cacheKey, value, cachePolicy); result.Should().BeTrue(); // look in underlying MemoryCache string innerKey = MemoryCacheProvider.GetKey(cacheKey); var cachedValue = MemoryCache.Default.Get(innerKey); cachedValue.Should().NotBeNull(); cachedValue.Should().Be(value); }
public void Put_should_put_item_into_configured_MemoryCacheImplementation() { IMemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions()); string key = Guid.NewGuid().ToString(); object value = new object(); MemoryCacheProvider provider = new MemoryCacheProvider(memoryCache); Ttl ttl = new Ttl(TimeSpan.FromSeconds(10)); provider.Put(key, value, ttl); object got; memoryCache.TryGetValue(key, out got); got.Should().BeSameAs(value); }
/// <summary>Initializes a new instance of the <see cref="LinqCompileCacheDecorator"/> class.</summary> /// <param name="handler">The handler.</param> /// <param name="cacheProvider"></param> /// <param name="cachePolicy">The cache policy.</param> /// <param name="metrics">The metrics.</param> /// <param name="connectionInformation">The connection information.</param> public LinqCompileCacheDecorator( ILinqCompiler handler, MemoryCacheProvider cacheProvider, ICachePolicy <ILinqCompiler> cachePolicy, IMetrics metrics, IConnectionInformation connectionInformation) { _handler = handler; _cacheActions = Policy.Cache <Action <object, object> >(cacheProvider, new SlidingTtl(cachePolicy.SlidingExpiration) , OnCacheGetAction, OnCacheMissAction, (context, s) => { }, (context, s, arg3) => { }, (context, s, arg3) => { }); var name = handler.GetType().Name; _counterActionCacheHit = metrics.Counter($"{connectionInformation.QueueName}.{name}.LinqActionCacheHitCounter", Units.Items); _counterActionCacheMiss = metrics.Counter($"{connectionInformation.QueueName}.{name}.LinqActionCacheMissCounter", Units.Items); _counterActionCacheUnique = metrics.Counter($"{connectionInformation.QueueName}.{name}.LinqActionUniqueFlaggedCounter", Units.Items); }
public void Get_should_return_instance_previously_stored_in_cache() { IMemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions()); string key = Guid.NewGuid().ToString(); object value = new object(); using (ICacheEntry entry = memoryCache.CreateEntry(key)) { entry.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(10); entry.Value = value; } MemoryCacheProvider provider = new MemoryCacheProvider(memoryCache); (bool cacheHit, object payload) = provider.TryGet(key); cacheHit.Should().BeTrue(); payload.Should().BeSameAs(value); }
protected override void Act() { var memoryCacheProvider = new MemoryCacheProvider { MemoryCache = new MemoryCache("IsolatedForUnitTest") }; var educationOrganizationCache = new EducationOrganizationCache( memoryCacheProvider, edfiOdsInstanceIdentificationProvider, edOrgValueMapper, educationOrganizationIdentifiersProvider, synchronousInitialization: true); //Two Calls educationOrganizationCache.GetEducationOrganizationIdentifiers(suppliedEdOrgValueMap.EducationOrganizationId); actualEdOrgIds = educationOrganizationCache.GetEducationOrganizationIdentifiers(suppliedEdOrgValueMap.EducationOrganizationId); }
public static AsyncPolicyWrap <HttpResponseMessage> GetRequestPolicy(IMemoryCache memoryCache = null, int cacheSeconds = 0, int additionalRetries = 0, int requestTimeoutSeconds = 100) { AsyncCachePolicy cache = null; if (memoryCache != null) { var memoryCacheProvider = new MemoryCacheProvider(memoryCache); cache = Policy.CacheAsync(memoryCacheProvider, TimeSpan.FromSeconds(cacheSeconds)); } int[] httpStatusCodesWorthRetrying = { StatusCodes.Status408RequestTimeout, StatusCodes.Status429TooManyRequests, //StatusCodes.Status500InternalServerError, StatusCodes.Status502BadGateway, StatusCodes.Status503ServiceUnavailable, StatusCodes.Status504GatewayTimeout }; var waitAndRetryPolicy = Policy .Handle <HttpRequestException>() //HttpClient Timeout or CancellationToken .Or <TimeoutRejectedException>() .OrResult <HttpResponseMessage>(r => httpStatusCodesWorthRetrying.Contains((int)r.StatusCode)) .WaitAndRetryAsync(additionalRetries, retryAttempt => TimeSpan.FromSeconds(1)); //https://github.com/App-vNext/Polly/wiki/Timeout var requestTimeout = Policy.TimeoutAsync(TimeSpan.FromSeconds(requestTimeoutSeconds)); //https://github.com/App-vNext/Polly/wiki/PolicyWrap AsyncPolicyWrap <HttpResponseMessage> policyWrap = null; if (cache != null) { policyWrap = cache.WrapAsync(waitAndRetryPolicy).WrapAsync(requestTimeout); } else { policyWrap = waitAndRetryPolicy.WrapAsync(requestTimeout); } return(policyWrap); }
public void InitResetCache() { cache.CacheProvider.Dispose(); var provider = new MemoryCacheProvider( new MemoryCache( new MemoryCacheOptions())); cache = new CachingService(provider); dummyData = new List<Product>(); dummyData.Add(new Product("product-01", "High Back Leather Chair", 34475.00m)); dummyData.Add(new Product("product-02", "Mid Back Leather Chair", 24475.00m)); dummyData.Add(new Product("product-03", "Low Back Leather Chair", 14475.00m)); dummyData.Add(new Product("product-04", "Visitor Chair", 24400.00m)); dummyData.Add(new Product("product-05", "Lecture hall chair", 7475.00m)); }
public NewCombinedFeedSource(IEnumerable <IAmACommunityMember> tamarins) { EnsureHttpClient(); Tamarins = tamarins; if (retryPolicy == null) { // cache in memory for an hour var memoryCache = new MemoryCache(new MemoryCacheOptions()); var memoryCacheProvider = new MemoryCacheProvider(memoryCache); cachePolicy = Policy.CacheAsync(memoryCacheProvider, TimeSpan.FromHours(1), OnCacheError); // retry policy with max 2 retries, delay by x*x^1.2 where x is retry attempt // this will ensure we don't retry too quickly retryPolicy = Policy.Handle <FeedReadFailedException>() .WaitAndRetryAsync(2, retry => TimeSpan.FromSeconds(retry * Math.Pow(1.2, retry))); } }
static void Main(string[] args) { var tc = new CustomTest(); ITest tc1 = tc; ITestBase <CustomTest> tb = new TestBase <CustomTest>(); var tb1 = (ITestBase <Test>)tb; var s1 = "Admin"; var s2 = "Employee"; var c1 = s1.GetHashCode(); var c2 = s2.GetHashCode(); var config = new ConfigurationOptions(); config.Password = "******"; //ICacheProvider cacheProvider = new RedisCacheProvider("localhost:6379,password=zhaokun"); ICacheProvider cacheProvider = new MemoryCacheProvider(); CacheManager.SetCacheProvider(cacheProvider); CacheManager.GetGlobalCache().Set("test", "test"); CacheManager.GetCache <Program>().Set("test", "test"); CacheManager.GetCache <Program>().Set("test1", "test"); CacheManager.GetCache <Program>().Set("test2", "test"); CacheManager.GetCache <Program>().Set("test3", "test"); CacheManager.GetCache(nameof(Program)).Set("test", "test1"); System.Console.WriteLine(CacheManager.GetGlobalCache().Get <string>("test")); System.Console.WriteLine(CacheManager.GetCache(nameof(Program)).Get <string>("test")); TestMethod1(); TestMethod2(); TestMethod3(); TestMethod4(); //TestMethod5(); System.Console.ReadKey(); }
public static void AddCacheManager <TCacheProvider>(this IServiceCollection services) where TCacheProvider : ICacheProvider { services.AddMemoryCache(); var cacheProviderType = typeof(TCacheProvider); var serviceProvider = services.BuildServiceProvider(); var logger = serviceProvider.GetService <ILogger <CacheManager> >(); if (cacheProviderType.IsAssignableFrom(typeof(IMemoryCacheProvider))) { var memoryCache = serviceProvider.GetService <IMemoryCache>(); var memoryCacheProvider = new MemoryCacheProvider(memoryCache); services.AddSingleton <IMemoryCacheProvider>(imp => memoryCacheProvider); services.AddSingleton <ICacheManager>(imp => new CacheManager(logger, memoryCacheProvider)); return; } throw new CacheProviderNaoImplementadoException(); }
protected override void Arrange() { _edfiOdsInstanceIdentificationProvider = Stub <IEdFiOdsInstanceIdentificationProvider>(); _usiValueMapper = Stub <IUniqueIdToUsiValueMapper>(); _suppliedUsiValueMap = new PersonIdentifiersValueMap { UniqueId = Guid.NewGuid() .ToString(), Usi = 10, Id = Guid.NewGuid() // Id is also provided by the USI value mapper }; A.CallTo(() => _usiValueMapper.GetUniqueId(A <string> ._, A <int> ._)) .Returns(_suppliedUsiValueMap); _personIdentifiersProvider = Stub <IPersonIdentifiersProvider>(); A.CallTo(() => _personIdentifiersProvider.GetAllPersonIdentifiers(A <string> ._)) .Returns(Task.Run(() => (IEnumerable <PersonIdentifiersValueMap>) new PersonIdentifiersValueMap[0])); SetupCaching(); void SetupCaching() { var memorycacheoption = A.Fake <IOptions <MemoryCacheOptions> >(); MemoryCache memoryCache = new MemoryCache(memorycacheoption); _memoryCacheProvider = new MemoryCacheProvider(memoryCache); _usiCache = new PersonUniqueIdToUsiCache( _memoryCacheProvider, _edfiOdsInstanceIdentificationProvider, _usiValueMapper, _personIdentifiersProvider, TimeSpan.Zero, TimeSpan.Zero, synchronousInitialization: true); PersonUniqueIdToUsiCache.GetCache = () => _usiCache; } }
public void Set_then_expire() { var key = Guid.NewGuid().ToString(); var value = Guid.NewGuid(); var cache = new MemoryCacheProvider("region6"); cache.Overwrite(key, value); cache.Expire(key); Guid value2; var exist = cache.TryGet(key, out value2); Assert.IsFalse(exist); Assert.AreEqual(value2, Guid.Empty); cache.ExpireAll(); Assert.AreEqual(cache.Count(), 0); }
/// <summary> /// Retrieves the new bearer token. /// </summary> /// <param name="authenticationSettings">The authentication settings.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// authenticationSettings.ClientId /// or /// authenticationSettings.ClientSecret /// or /// authenticationSettings.Url /// or /// authenticationSettings.Password /// or /// authenticationSettings.Username /// or /// authenticationSettings.TenantName /// </exception> public static AccessTokenResponse RetrieveNewBearToken(Oauth2AuthenticationSettings authenticationSettings) { if (string.IsNullOrEmpty(authenticationSettings.ClientId)) { throw new ArgumentNullException("authenticationSettings.ClientId"); } if (string.IsNullOrEmpty(authenticationSettings.ClientSecret)) { throw new ArgumentNullException("authenticationSettings.ClientSecret"); } if (string.IsNullOrEmpty(authenticationSettings.Url)) { throw new ArgumentNullException("authenticationSettings.Url"); } if (string.IsNullOrEmpty(authenticationSettings.Password)) { throw new ArgumentNullException("authenticationSettings.Password"); } if (string.IsNullOrEmpty(authenticationSettings.Username)) { throw new ArgumentNullException("authenticationSettings.Username"); } if (string.IsNullOrEmpty(authenticationSettings.TenantName)) { throw new ArgumentNullException("authenticationSettings.TenantName"); } var oauthClient = new OAuth2Client(new Uri(authenticationSettings.Url + "token"), authenticationSettings.ClientId, authenticationSettings.ClientSecret); var accessTokenResponse = oauthClient.RequestAccessTokenUserName(authenticationSettings.Username, authenticationSettings.Password, authenticationSettings.TenantName); string key = string.Concat("AuthHash:", EncryptionHelper.Md5Encryption.GetMd5Hash(string.Concat(authenticationSettings.TenantName, authenticationSettings.Username))); //Cache Token in Memory var memoryCachingService = new MemoryCacheProvider(); memoryCachingService.SetCache(key, accessTokenResponse, SecurityTokenConstants.TokenLifeTime); return(accessTokenResponse); }
public void AddWithExistingTagTest() { var provider = new MemoryCacheProvider(); string key = "AddTest" + DateTime.Now.Ticks; string[] tags = new[] { "a", "b" }; var cacheKey = new CacheKey(key, tags); var value = "Test Value " + DateTime.Now; var cachePolicy = new CachePolicy(); bool result = provider.Add(cacheKey, value, cachePolicy); result.Should().BeTrue(); // make sure cache key is in underlying MemoryCache var cacheTag = new CacheTag("a"); string tagKey = MemoryCacheProvider.GetTagKey(cacheTag); tagKey.Should().NotBeNullOrEmpty(); var cachedTag = MemoryCache.Default.Get(tagKey); cachedTag.Should().NotBeNull(); // add second value with same tag string key2 = "AddTest2" + DateTime.Now.Ticks; string[] tags2 = new[] { "a", "c" }; var cacheKey2 = new CacheKey(key2, tags2); var value2 = "Test Value 2 " + DateTime.Now; var cachePolicy2 = new CachePolicy(); bool result2 = provider.Add(cacheKey2, value2, cachePolicy2); result2.Should().BeTrue(); // tag 'a' should have same value var cachedTag2 = MemoryCache.Default.Get(tagKey); cachedTag2.Should().NotBeNull(); cachedTag2.Should().Be(cachedTag); }
/// <summary> /// 创建缓存实例 /// </summary> /// <param name="providerType">缓存类型</param> /// <returns></returns> public static ICacheProvider GetCacheInstance(CacheProviderType providerType) { ICacheProvider cacheProvider = new MemoryCacheProvider(); switch (providerType) { case CacheProviderType.LOCALMEMORYCACHE: cacheProvider = new MemoryCacheProvider(); break; case CacheProviderType.MEMCACHEDCACHE: cacheProvider = new MemcachedCacheProvider(); break; case CacheProviderType.ServiceStackREDIS: cacheProvider = new RedisCacheProvider(); break; } return(cacheProvider); }
static void setup() { retryPolicy = Policy .Handle <Exception>() .OrResult <HttpResponseMessage>(r => !r.IsSuccessStatusCode) .RetryAsync(2, (ex, retryCnt) => { Console.WriteLine($"Retry count {retryCnt}"); }); var myCache = new MemoryCache(new MemoryCacheOptions()); MemoryCacheProvider memoryCacheProvider = new MemoryCacheProvider(myCache); cachePolicy = Policy.CacheAsync <HttpResponseMessage>(memoryCacheProvider, TimeSpan.FromMinutes(5)); policyWrap = Policy.WrapAsync <HttpResponseMessage>(cachePolicy, retryPolicy); }
public void Put_should_put_item_using_passed_sliding_ttl_maxvalue() { IMemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions()); string key = "anything"; object value = new object(); MemoryCacheProvider provider = new MemoryCacheProvider(memoryCache); TimeSpan maxSlidingExpiration = TimeSpan.MaxValue; Ttl ttl = new Ttl(maxSlidingExpiration, true); provider.Put(key, value, ttl); object got; memoryCache.TryGetValue(key, out got); got.Should().BeSameAs(value); }
public static void Caching() { ErrorProneCode errorProneCode = new ErrorProneCode(); var memoryCache = new MemoryCache(new MemoryCacheOptions()); var memoryCacheProvider = new MemoryCacheProvider(memoryCache); #region caching CachePolicy <int> cachePolicy = Policy.Cache <int>(memoryCacheProvider, TimeSpan.FromSeconds(1.5)); for (int loop = 1; loop <= 10; loop++) { int result = cachePolicy.Execute(context => errorProneCode.GetSomeNumberThatMightBeCacheable(), new Context("ContextKey")); Console.WriteLine($"result={result}. cachePolicy executed {loop} time(s). GetSomeNumberThatMightBeCacheable method really called {result} time(s)."); Thread.Sleep(500); } #endregion }
private void CacheSonarrQualityProfiles(MemoryCacheProvider cacheProvider) { try { Log.Info("Executing GetSettings call to Sonarr for quality profiles"); var sonarrSettingsService = new SettingsServiceV2 <SonarrSettings>(new SettingsJsonRepository(new DbConfiguration(new SqliteFactory()), new MemoryCacheProvider())); var sonarrSettings = sonarrSettingsService.GetSettings(); if (sonarrSettings.Enabled) { Log.Info("Begin executing GetProfiles call to Sonarr for quality profiles"); SonarrApi sonarrApi = new SonarrApi(); var profiles = sonarrApi.GetProfiles(sonarrSettings.ApiKey, sonarrSettings.FullUri); cacheProvider.Set(CacheKeys.SonarrQualityProfiles, profiles); Log.Info("Finished executing GetProfiles call to Sonarr for quality profiles"); } } catch (Exception ex) { Log.Error(ex, "Failed to cache Sonarr quality profiles!"); } }
public async Task Returns_True_When_Item_Of_Correct_Type_Is_In_Cache() { // Arrange var cacheMock = new Mock <IMemoryCache>(); cacheMock.Setup(m => m.TryGetValue("key1", out It.Ref <object> .IsAny)) .Returns(new TryGetValueReturns((object key, out object item) => { item = "abc321"; return(true); })); var provider = new MemoryCacheProvider(cacheMock.Object, null); // Act var result = await provider.TryGet <string>("key1"); // Assert Assert.True(result.Succeeded); Assert.Equal("abc321", result.Value); }
public async Task Returns_False_When_Item_Is_Of_Wrong_Type() { // Arrange var cacheMock = new Mock <IMemoryCache>(); cacheMock.Setup(m => m.TryGetValue("key1", out It.Ref <object> .IsAny)) .Returns(new TryGetValueReturns((object key, out object item) => { item = 1.0; return(true); })); var provider = new MemoryCacheProvider(cacheMock.Object, null); // Act var result = await provider.TryGet <string>("key1"); // Assert Assert.False(result.Succeeded); Assert.Null(result.Value); }
private void CacheCouchPotatoQualityProfiles(MemoryCacheProvider cacheProvider) { try { Log.Info("Executing GetSettings call to CouchPotato for quality profiles"); var cpSettingsService = new SettingsServiceV2 <CouchPotatoSettings>(new SettingsJsonRepository(new DbConfiguration(new SqliteFactory()), new MemoryCacheProvider())); var cpSettings = cpSettingsService.GetSettings(); if (cpSettings.Enabled) { Log.Info("Begin executing GetProfiles call to CouchPotato for quality profiles"); CouchPotatoApi cpApi = new CouchPotatoApi(); var profiles = cpApi.GetProfiles(cpSettings.FullUri, cpSettings.ApiKey); cacheProvider.Set(CacheKeys.CouchPotatoQualityProfiles, profiles); Log.Info("Finished executing GetProfiles call to CouchPotato for quality profiles"); } } catch (Exception ex) { Log.Error(ex, "Failed to cache CouchPotato quality profiles!"); } }
public void CreateChangeMonitorTest() { string key = DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture); string[] tags = new[] { "a", "b" }; var cacheKey = new CacheKey(key, tags); cacheKey.Should().NotBeNull(); var monitor = MemoryCacheProvider.CreateChangeMonitor(cacheKey); monitor.Should().NotBeNull(); monitor.CacheKeys.Should().HaveCount(2); var cacheTag = new CacheTag("a"); string tagKey = MemoryCacheProvider.GetTagKey(cacheTag); tagKey.Should().NotBeNullOrEmpty(); monitor.CacheKeys.Should().Contain(tagKey); }
public AppSettings() { try { var memoryCacheProvider = MemoryCacheProvider.GetInstance(); var declaringTypeFullName = MethodBase.GetCurrentMethod()?.DeclaringType?.FullName; var filePathKey = $"{declaringTypeFullName}{@".FilePath"}"; var filePath = (object)memoryCacheProvider.Get(filePathKey); if (null == filePath) { AppSettingsRepository?.MergeAndCopyToUserDirectory(this); memoryCacheProvider.Put(filePathKey, FilePath, TimeSpan.FromDays(1)); } if (null != FileName && null != UserProfileDirectory) { FilePath = (string)(filePath ?? Path.Combine(UserProfileDirectory, FileName)); } var useGlobalDatabaseConnectionSettingsKey = $"{declaringTypeFullName}{@".UseGlobalDatabaseConnectionSettings"}"; var useGlobalDatabaseConnectionSettings = (object)memoryCacheProvider.Get(useGlobalDatabaseConnectionSettingsKey); if (null == useGlobalDatabaseConnectionSettings) { memoryCacheProvider.Put(useGlobalDatabaseConnectionSettingsKey, UseGlobalDatabaseConnectionSettings, TimeSpan.FromDays(1)); if (UseGlobalDatabaseConnectionSettings) { var appSettingsModel = new NetAppCommon.AppSettings.Models.AppSettings(); ConnectionString = appSettingsModel.ConnectionString; AppSettingsRepository?.MergeAndSave(this); } } } catch (Exception e) { _log4Net.Error($"\n{e.GetType()}\n{e.InnerException?.GetType()}\n{e.Message}\n{e.StackTrace}\n", e); } }
protected override void Act() { var memoryCacheProvider = new MemoryCacheProvider { MemoryCache = new MemoryCache("IsolatedForUnitTest") }; var educationOrganizationCache = new EducationOrganizationCache( memoryCacheProvider, edfiOdsInstanceIdentificationProvider, edOrgValueMapper, educationOrganizationIdentifiersProvider, synchronousInitialization: true); // Synchronous initialization should result in values being supplied by the edorg identifier provider result // Launch 50 threads to try and obtain the USI var listLock = new object(); var tasks = new List <Task>(); for (var i = 0; i < 50; i++) { tasks.Add( Task.Run( () => { var educationOrganizationIdentifiers = educationOrganizationCache.GetEducationOrganizationIdentifiers( suppliedEducationOrganizationIdentifiers.EducationOrganizationId); lock (listLock) { actualEducationOrganizationIdentifiers.Add(educationOrganizationIdentifiers); } })); } Task.WaitAll(tasks.ToArray()); }
public void Adds_Function_Correctly() { var collection = new List<KeyValuePair<string, CachedValue<string>>> { new KeyValuePair<string, CachedValue<string>>("key2", new CachedValue<string>("value2")), new KeyValuePair<string, CachedValue<string>>("key3", new CachedValue<string>("value3")), }; using (var provider = new MemoryCacheProvider<string, string>()) { provider.Add("key1", new CachedValue<string>("value2")); provider.Add("key1", new CachedValue<string>("value1")); provider.Add(collection); Assert.AreEqual(3, provider.Count()); Assert.AreEqual("value1", provider.Get("key1").Value); Assert.IsTrue(provider.Get("non-existant").IsExpired); foreach (var value in provider.Get(new List<string> { "key2", "key3" })) { Assert.IsTrue(collection.Any(item => item.Value.Value == value.Value)); } } }
public void Put_should_put_item_using_passed_sliding_ttl_zero() { IMemoryCache memoryCache = new MemoryCache(new MemoryCacheOptions()); string key = "anything"; object value = new object(); MemoryCacheProvider provider = new MemoryCacheProvider(memoryCache); TimeSpan minExpiration = TimeSpan.FromMilliseconds(1); // This is the minimum permitted sliding ttl for .NetStandard Ttl ttl = new Ttl(minExpiration, false); provider.Put(key, value, ttl); Thread.Sleep(TimeSpan.FromMilliseconds(10)); object got; memoryCache.TryGetValue(key, out got); got.Should().BeNull(); }
public void CreatePolicySlidingTest() { string key = DateTime.Now.Ticks.ToString(CultureInfo.InvariantCulture); string[] tags = new[] { "a", "b" }; var cacheKey = new CacheKey(key, tags); cacheKey.Should().NotBeNull(); var slidingExpiration = TimeSpan.FromMinutes(5); var cachePolicy = CachePolicy.WithSlidingExpiration(slidingExpiration); cachePolicy.Should().NotBeNull(); var policy = MemoryCacheProvider.CreatePolicy(cacheKey, cachePolicy); policy.Should().NotBeNull(); policy.SlidingExpiration.Should().Be(slidingExpiration); policy.ChangeMonitors.Should().NotBeNull(); policy.ChangeMonitors.Should().HaveCount(1); policy.ChangeMonitors.Should().ContainItemsAssignableTo <CacheEntryChangeMonitor>(); }
private static async Task <string> Execute(string input, string templateId, object model, Type modelType) { var cacheProvider = new MemoryCacheProvider(); var handlerFactory = new Mock <IHelperHandlerFactory>(); var namingRule = new NamingRule(); var templateInfo = new StringTemplateInfo(templateId, input); var viewEngine = new VeilViewEngine(cacheProvider, handlerFactory.Object, namingRule); var view = await viewEngine.CreateViewAsync(templateInfo, modelType) .ConfigureAwait(false); var builder = new StringBuilder(); using (var writer = new StringWriter(builder)) { var context = new RenderingContext(writer); view.Render(model, context); } return(builder.ToString()); }
private static void Cache() { ICacheManager cache = new MemoryCacheProvider(); int[] array = { 1, 2, 3 }; //cache.Set("cache","Test",60); //string str = cache.Get<string>("cache"); //Console.Write(str); //cache.Remove("cache"); //string str2 = cache.Get<string>("cache"); //Console.Write("空:"+str2); cache.Set("cacheTest", array, 60); var arr = cache.Get<int[]>("cacheTest"); Console.Write(arr[1]); }
public async Task EscapeNullStringLateBinding() { var cacheProvider = new MemoryCacheProvider(); var handlerFactory = new Mock<IHelperHandlerFactory>(); handlerFactory.Setup(f => f.Create()).Returns(Enumerable.Empty<IHelperHandler>()); var namingRule = new NamingRule(); const string input = "<p>{{{name}}}</p>"; var templateInfo = new StringTemplateInfo("views/test", input); var viewEngine = new VeilViewEngine(cacheProvider, handlerFactory.Object, namingRule); var view = await viewEngine.CreateViewAsync(templateInfo, typeof(object)).ConfigureAwait(false); var model = new TestModel(); var writer = new StringWriter(); view.Render(model, new RenderingContext(writer)); var stringResult = writer.ToString(); Assert.AreEqual("<p></p>", stringResult); }
private static async Task<string> Execute(string input, string templateId, object model, Type modelType) { var cacheProvider = new MemoryCacheProvider(); var handlerFactory = new Mock<IHelperHandlerFactory>(); var namingRule = new NamingRule(); var templateInfo = new StringTemplateInfo(templateId, input); var viewEngine = new VeilViewEngine(cacheProvider, handlerFactory.Object, namingRule); var view = await viewEngine.CreateViewAsync(templateInfo, modelType, StaticModelBinder.Create(modelType)) .ConfigureAwait(false); var builder = new StringBuilder(); using (var writer = new StringWriter(builder)) { var context = new RenderingContext(writer); view.Render(model, context); } return builder.ToString(); }
public void should_return_value() { var cacheProvider = new MemoryCacheProvider(); cacheProvider.Put("key", new Boo { Num = 13 }, 5.Seconds()); var value = cacheProvider.Get<Boo>("key"); value.Num.Should(). Be(13); }
public void Setup() { provider = new MemoryCacheProvider(); }
public void should_fail() { var cacheProvider = new MemoryCacheProvider(); cacheProvider.Put("key", new Boo { Num = 13 }, 5.Seconds()); cacheProvider.Remove("key"); cacheProvider.Find<Boo>("key"). HasValue.Should(). BeFalse(); }
public void IsByDefaultCachingEverything() { var memory = new MemoryCacheProvider(TimeSpan.FromMinutes(1)); Assert.IsTrue(memory.ProvidesCacheForRequest(new Uri("http://localhost/"))); }
public void ResetTest() { Func<DateTime> dataProvider = () => DateTime.Now; IDataProvider<DateTime> provider = new MemoryCacheProvider<DateTime>("DateTime3", dataProvider, ObjectCache.NoSlidingExpiration, TimeSpan.FromSeconds(20)); var dt = provider.Data; for (int i = 0; i < 20; i++) { Thread.Sleep(500); var d = provider.Data; Assert.Equal(dt, d); } Assert.Equal(DataProviderStatus.Ready, provider.Status.Value); provider.Reset(); Assert.Equal(DataProviderStatus.NotReady, provider.Status.Value); Assert.NotEqual(dt, provider.Data); }
public void should_throw() { var cacheProvider = new MemoryCacheProvider(); cacheProvider.Invoking(c => c.Get<Boo>("key")). ShouldThrow<InvalidOperationException>(); }
public void MemoryCache() { using ( var provider = new MemoryCacheProvider( "Test" ) ) { var cacheService = new CacheService( provider ); var tasks = new List<Task>(); //测试并发创建值 for ( int i = 0; i < 1000; i++ ) { Func<int, Task> task = async ( j ) => { await Task.Yield(); var value = await cacheService.FetchOrAdd( "Test", ValueFactory, CachePolicy.Expires( TimeSpan.FromHours( 1 ) ) ); Assert.AreEqual( value, _value ); }; tasks.Add( task( i ) ); } Task.WaitAll( tasks.ToArray() ); //测试从缓存读取 for ( int i = 0; i < 1000; i++ ) { Func<int, Task> task = async ( j ) => { await Task.Yield(); var value = await cacheService.FetchOrAdd( "Test", ValueFactory, CachePolicy.Expires( TimeSpan.FromHours( 1 ) ) ); Assert.AreEqual( value, _value ); }; tasks.Add( task( i ) ); } Task.WaitAll( tasks.ToArray() ); //清除缓存 cacheService.Clear(); _value = null; //测试创建新值 for ( int i = 0; i < 1000; i++ ) { Func<int, Task> task = async ( j ) => { await Task.Yield(); var value = await cacheService.FetchOrAdd( "Test", ValueFactory, CachePolicy.Expires( TimeSpan.FromHours( 1 ) ) ); Assert.AreEqual( value, _value ); }; tasks.Add( task( i ) ); } Task.WaitAll( tasks.ToArray() ); cacheService.Clear(); { _value = null; var value = cacheService.FetchOrAdd( "Test", ValueFactory, CachePolicy.Expires( TimeSpan.FromHours( 1 ) ) ).Result; Assert.IsNotNull( _value ); Assert.AreEqual( _value, value ); } } }
public void ExcepionTest() { using ( var provider = new MemoryCacheProvider( "Test" ).AsAsyncProvider() ) { var cacheService = new CacheService( provider ); Task.Run( (Func<Task>) (async () => { bool exception_catched = false; try { await cacheService.FetchOrAdd<string>( (string) "Test", (Func<Task<string>>) this.ValueFactoryWithException, (Caching.CachePolicy) Caching.CachePolicy.Expires( (TimeSpan) TimeSpan.FromHours( (double) 1 ) ) ); } catch { exception_catched = true; } Assert.IsTrue( exception_catched ); var value = await cacheService.FetchOrAdd<string>( (string) "Test", (Func<Task<string>>) this.ValueFactory, (Caching.CachePolicy) Caching.CachePolicy.Expires( (TimeSpan) TimeSpan.FromHours( (double) 1 ) ) ); Assert.AreEqual( (string) value, _value ); }) ).Wait(); } }
public void should_absolutly_expired() { var cacheProvider = new MemoryCacheProvider(); cacheProvider.Put("key", new Boo { Num = 13 }, 5.Seconds()); Thread.Sleep(3000); cacheProvider.Get<Boo>("key"); Thread.Sleep(3000); Assert.Throws<InvalidOperationException>(() => cacheProvider.Get<Boo>("key"), "Объект должен быть удален из кеша."); }
public void should_fail() { var cacheProvider = new MemoryCacheProvider(); cacheProvider.Put("key", new Boo { Num = 13 }, 100.Milliseconds()); Thread.Sleep(500); cacheProvider.Find<Boo>("key"). HasValue.Should(). BeFalse(); }
public void Setup() { Cache = new MemoryCacheProvider(); F = new Fixture(); Key = "Test"; }