private void InitializeOptions() { MinZoomLevel = 3; MaxZoomLevel = 18; CenterPoint = new GeoPoint(52.1205333, 11.6276237); ZoomLevel = 12; ShowSearchPanel = false; UseSprings = true; ZoomTrackbarOptions = new ZoomTrackbarOptions() { Orientation = MapZoomTrackbarOrientation.Horizontal, Margin = new Thickness(10), VerticalAlignment = NavigationElementVerticalAlignment.Bottom }; ScrollButtonsOptions = new ScrollButtonsOptions() { Visible = false }; ScalePanelOptions = new ScalePanelOptions() { ShowMilesScale = false, Margin = new Thickness(0, -30, 0, 5), VerticalAlignment = NavigationElementVerticalAlignment.Bottom }; CoordinatesPanelOptions = new CoordinatesPanelOptions() { Visible = false }; CacheOptions = new CacheOptions() { Directory = System.IO.Path.GetTempPath(), KeepInterval = TimeSpan.FromHours(1) }; }
private async Task <CacheValue <T> > TryGet <T>(string key, CacheOptions options) { // first try and retrieve from local cache if (options?.LocalTimeout != null) { var localCacheValue = _localCache.TryGet <T>(key); if (localCacheValue.HasValue) { return(localCacheValue); } } // second try and retrieve from distributed cache if (options?.DistributedTimeout != null) { var distributedCacheValue = await _distributedCache.TryGet <T>(key); if (distributedCacheValue.HasValue) { // set in local cache if (options.LocalTimeout != null) { _localCache.Set(key, new CacheValue <T>(distributedCacheValue.Value), options.LocalTimeout.Value); } return(distributedCacheValue); } } return(new CacheValue <T>()); }
public async Task NotCallThePassedQueryServiceWhenItsResultIsCached() { var queryServiceStub = new Mock <IQueryService <QueryStub, object> >(); var cacheManagerStub = new Mock <ICacheManager>(); cacheManagerStub.Setup(cm => cm.Exists(It.IsAny <string>())) .Returns(true); var optionsStub = new CacheOptions(false, int.MaxValue); var userContextStub = new Mock <IUserContext>(); // Arrange CacheQueryServiceProxy <QueryStub, object> sut = new CacheQueryServiceProxy <QueryStub, object>( queryService: queryServiceStub.Object, cacheManager: cacheManagerStub.Object, options: optionsStub, userContext: userContextStub.Object); // Act string actualResult = (string)await sut.ExecuteAsync(new QueryStub()); // Assert queryServiceStub.Verify( q => q.ExecuteAsync(It.IsAny <QueryStub>()), Times.Never); }
public void PopulateRecoversFromExceptionsSafely() { try { Cache.Populate("key", delegate(string key, out CacheOptions options) { throw new Exception("Boom!"); }); Assert.Fail("Expected an exception to be thrown by the populator."); } catch (Exception ex) { // Expected. Assert.AreEqual("Boom!", ex.Message); } // Try again to ensure we have recovered. // Note: This helps to ensure that our exception cleanup logic works // for caches that do more sophisticated locking during population. Assert.AreEqual("value", Cache.Populate("key", delegate(string key, out CacheOptions options) { options = new CacheOptions(); Assert.AreEqual("key", key); return("value"); })); Assert.IsTrue(Cache.ContainsKey("key")); Assert.AreEqual("value", Cache.Get("key")); }
public async Task CacheTheQueryResultIfIsNotInTheCache() { var queryServiceStub = new QueryServiceStub(); var cacheManagerStub = new Mock <ICacheManager>(); cacheManagerStub.Setup(cm => cm.Exists(It.IsAny <string>())) .Returns(false); var optionsStub = new CacheOptions(false, int.MaxValue); var userContextStub = new Mock <IUserContext>(); // Arrange CacheQueryServiceProxy <QueryStub, object> sut = new CacheQueryServiceProxy <QueryStub, object>( queryService: queryServiceStub, cacheManager: cacheManagerStub.Object, options: optionsStub, userContext: userContextStub.Object); // Act await sut.ExecuteAsync(new QueryStub()); // Assert cacheManagerStub.Verify(cm => cm.Add( It.IsAny <string>(), It.IsAny <object>(), It.IsAny <int>()), Times.Once); }
public async Task ReturnQueryResultFromCacheIfExistsInTheCache() { string expectedResult = "Returned from cache"; var queryServiceStub = new QueryServiceStub(); var cacheManagerStub = new Mock <ICacheManager>(); cacheManagerStub.Setup(cm => cm.Exists(It.IsAny <string>())) .Returns(true); cacheManagerStub.Setup(cm => cm.Get <object>(It.IsAny <string>())) .Returns(expectedResult); var optionsStub = new CacheOptions(false, int.MaxValue); var userContextStub = new Mock <IUserContext>(); // Arrange CacheQueryServiceProxy <QueryStub, object> sut = new CacheQueryServiceProxy <QueryStub, object>( queryService: queryServiceStub, cacheManager: cacheManagerStub.Object, options: optionsStub, userContext: userContextStub.Object); // Act string actualResult = (string)await sut.ExecuteAsync(new QueryStub()); // Assert Assert.AreEqual(expectedResult, actualResult); }
public static void EnsureValid(this CacheOptions options) { if (options == null) { ThrowMissingConfiguration(nameof(LiGetOptions.Cache)); } if (!options.Enabled) { return; } if (options.UpstreamIndex == null) { ThrowMissingConfiguration( nameof(LiGetOptions.Cache), nameof(CacheOptions.UpstreamIndex)); } if (options.PackagesPath == null) { ThrowMissingConfiguration( nameof(LiGetOptions.Cache), nameof(CacheOptions.PackagesPath)); } if (options.PackageDownloadTimeoutSeconds <= 0) { options.PackageDownloadTimeoutSeconds = 600; } }
/// <summary> /// Applies the <see cref="CachePolicy"/> options to the given <paramref name="response"/>. /// </summary> /// <param name="response">The current <see cref="HttpResponseMessage"/>.</param> protected virtual void SetCacheOptions(HttpResponseMessage response) { if (response == null) { throw new ArgumentNullException("response"); } CacheOptions options = this.Policy.Options; CacheControlHeaderValue cacheControl = response.Headers.CacheControl ?? new CacheControlHeaderValue(); bool hasCacheOptions = false; if ((options & CacheOptions.NoStore) != 0) { hasCacheOptions = true; cacheControl.NoStore = true; ForceNoCache(response); } if ((options & CacheOptions.NoCache) != 0) { hasCacheOptions = true; cacheControl.NoCache = true; ForceNoCache(response); } if ((options & CacheOptions.MustRevalidate) != 0) { hasCacheOptions = true; cacheControl.MustRevalidate = true; } if ((options & CacheOptions.ProxyRevalidate) != 0) { hasCacheOptions = true; cacheControl.ProxyRevalidate = true; } if ((options & CacheOptions.NoTransform) != 0) { hasCacheOptions = true; cacheControl.NoTransform = true; } if ((options & CacheOptions.Private) != 0) { hasCacheOptions = true; cacheControl.Private = true; } if ((options & CacheOptions.Public) != 0) { hasCacheOptions = true; cacheControl.Public = true; } if (hasCacheOptions) { response.Headers.CacheControl = cacheControl; } }
public async Task DispatchesThroughPipelineOnCacheHitWithThrottling() { // Arrange Mock <ICacheKeyProvider> cacheKeyProvider = new Mock <ICacheKeyProvider>(); Mock <ICommandDispatcher> underlyingCommandDispatcher = new Mock <ICommandDispatcher>(); Mock <ICacheOptionsProvider> cacheOptionsProvider = new Mock <ICacheOptionsProvider>(); Mock <ICacheAdapter> cacheWrapper = new Mock <ICacheAdapter>(); CacheOptions options = new CacheOptions(typeof(SimpleCommand), TimeSpan.FromMinutes(5), 1); SimpleCommand command = new SimpleCommand(); SimpleResult cachedResult = new SimpleResult { ANumber = 2 }; cacheOptionsProvider.Setup(x => x.Get(It.IsAny <ICommand>())).Returns(options); cacheKeyProvider.Setup(x => x.CacheKey(It.IsAny <ICommand>())).Returns("akey"); cacheWrapper.Setup(x => x.Set("akey", It.IsAny <object>(), TimeSpan.FromMinutes(5))).Returns(Task.FromResult(0)); underlyingCommandDispatcher.Setup(x => x.DispatchAsync(command, It.IsAny <CancellationToken>())).ReturnsAsync(new CommandResult <SimpleResult>(cachedResult, false)); CachedCommandDispatcher dispatcher = new CachedCommandDispatcher(cacheKeyProvider.Object, underlyingCommandDispatcher.Object, cacheOptionsProvider.Object, cacheWrapper.Object); // Act var result = await dispatcher.DispatchAsync(command, default(CancellationToken)); // Assert underlyingCommandDispatcher.Verify(x => x.DispatchAsync(command, It.IsAny <CancellationToken>()), Times.Once, "Underlying dispatched was not called"); cacheWrapper.Verify(x => x.Set("akey", cachedResult, TimeSpan.FromMinutes(5)), Times.Once, "Result was not set in cache"); Assert.Equal(2, result.Result.ANumber); }
public async Task DoesntDispatchThroughPipelineOnCacheHit() { // Arrange Mock <ICacheKeyProvider> cacheKeyProvider = new Mock <ICacheKeyProvider>(); Mock <ICommandDispatcher> underlyingCommandDispatcher = new Mock <ICommandDispatcher>(); Mock <ICacheOptionsProvider> cacheOptionsProvider = new Mock <ICacheOptionsProvider>(); Mock <ICacheAdapter> cacheWrapper = new Mock <ICacheAdapter>(); CacheOptions options = new CacheOptions(typeof(SimpleCommand), TimeSpan.FromMinutes(5)); SimpleCommand command = new SimpleCommand(); SimpleResult cachedResult = new SimpleResult { ANumber = 2 }; cacheWrapper.Setup(x => x.Get <SimpleResult>(It.IsAny <string>())).ReturnsAsync(cachedResult); cacheOptionsProvider.Setup(x => x.Get(It.IsAny <ICommand>())).Returns(options); cacheKeyProvider.Setup(x => x.CacheKey(It.IsAny <ICommand>())).Returns("akey"); CachedCommandDispatcher dispatcher = new CachedCommandDispatcher(cacheKeyProvider.Object, underlyingCommandDispatcher.Object, cacheOptionsProvider.Object, cacheWrapper.Object); // Act var result = await dispatcher.DispatchAsync(command, default(CancellationToken)); // Assert underlyingCommandDispatcher.Verify(x => x.DispatchAsync(command, It.IsAny <CancellationToken>()), Times.Never); Assert.Equal(2, result.Result.ANumber); }
public void Populate_ForwardsToInnerCache() { CacheOptions options = CacheOptions.AbsoluteExpiration(DateTime.UtcNow); Populator populator = delegate(string key, out CacheOptions populatedOptions) { populatedOptions = options; Assert.AreEqual("key", key); return("value"); }; Expect.Call(mockInnerCache.Populate("partition:key", null)) .Constraints(Is.Equal("partition:key"), Is.NotSame(populator)) .Do((PopulateDelegate) delegate(string actualKey, Populator actualPopulator) { CacheOptions populatedOptions; object populatedValue = actualPopulator(actualKey, out populatedOptions); Assert.AreEqual("value", populatedValue); Assert.AreEqual(options, populatedOptions); return("value"); }); Mocks.ReplayAll(); Assert.AreEqual("value", Cache.Populate("key", populator)); }
/// <summary> /// 更改ocelot的存储方式为使用redis /// </summary> /// <param name="ocelotBuilder"></param> /// <returns></returns> public static IOcelotBuilder AddRedisCache(this IOcelotBuilder ocelotBuilder, Action <CacheOptions> options) { //获取数据 CacheOptions cacheOptions = new CacheOptions(); options?.Invoke(cacheOptions); //验证仓储服务是否注册 if (ocelotBuilder.Services.BuildServiceProvider().GetService <IRedisOperationHelp>() == null) { if (cacheOptions != null && cacheOptions.RedisOptions != null) { ocelotBuilder.Services.AddRedisRepository(cacheOptions.RedisOptions); } else { throw new ApplicationException("当前检查没有配置Redis仓储服务"); } } //更改扩展方式 ocelotBuilder.Services.RemoveAll(typeof(IOcelotCache <FileConfiguration>)); ocelotBuilder.Services.RemoveAll(typeof(IOcelotCache <CachedResponse>)); ocelotBuilder.Services.TryAddSingleton <IOcelotCache <FileConfiguration>, OcelotRedisManagerCache <FileConfiguration> >(); ocelotBuilder.Services.TryAddSingleton <IOcelotCache <CachedResponse>, OcelotRedisManagerCache <CachedResponse> >(); ocelotBuilder.Services.RemoveAll(typeof(IFileConfigurationRepository)); //重写提取Ocelot配置信息 ocelotBuilder.Services.AddSingleton(RedisConfigurationProvider.Get); ocelotBuilder.Services.AddSingleton <IFileConfigurationRepository, RedisConfigurationRepository>(); return(ocelotBuilder); }
public TagInfoMap(CacheOptions cacheOptions) { _TagInfoByTag = new ConcurrentDictionary<string, WeakReference>(); _IntervalTimer = new IntervalTimer(cacheOptions.TagMapScavengeInterval); _IntervalTimer.OnInterval += new Action(_ScavengeTagMap); }
/// <summary> /// 更改ocelot的存储方式为使用EF /// </summary> /// <param name="ocelotBuilder"></param> /// <returns></returns> public static IOcelotBuilder AddOcelotEFCache(this IOcelotBuilder ocelotBuilder, Action <CacheOptions> options) { //获取数据 CacheOptions cacheOptions = new CacheOptions(); options?.Invoke(cacheOptions); OcelotEFOption eFOptions = new OcelotEFOption(); cacheOptions?.EFOptions.Invoke(eFOptions); #region 注入仓储 ocelotBuilder.Services.AddRepository(); ocelotBuilder.Services.AddEFOption(ocelot => { ocelot.ConfigureDbContext = eFOptions.ConfigureDbContext; ocelot.ReadOnlyConnectionString = eFOptions.ReadOnlyConnectionString; // ocelot.UseEntityFramework <OcelotDbContent, SlaveOcelotDbContent>(); ocelot.IsOpenMasterSlave = eFOptions.IsOpenMasterSlave; }); #endregion //更改扩展方式 ocelotBuilder.Services.RemoveAll(typeof(IFileConfigurationRepository)); //重写提取Ocelot配置信息 ocelotBuilder.Services.AddSingleton(EFConfigurationProvider.Get); ocelotBuilder.Services.AddSingleton <IFileConfigurationRepository, EFConfigurationRepository>(); return(ocelotBuilder); }
public void CleanupPurgesExpiredEntries() { Cache.Set("key1", "value1", CacheOptions.AbsoluteExpiration(DateTime.UtcNow)); Cache.Set("key2", "value2", CacheOptions.AbsoluteExpiration(DateTime.MinValue)); Cache.Set("key3", "value3", CacheOptions.AbsoluteExpiration(DateTime.MaxValue)); Cache.Set("key4", "value4", CacheOptions.SlidingExpiration(TimeSpan.Zero)); Cache.Set("key5", "value5", CacheOptions.NoExpiration); Thread.Sleep(100); // Cause keys to expire Cache.Cleanup(); // Note: Order of ContainsKey / Get matters because ContainsKey // doesn't auto-expire values like Get does. Assert.IsFalse(Cache.ContainsKey("key1")); Assert.AreEqual(null, Cache.Get("key1")); Assert.IsFalse(Cache.ContainsKey("key2")); Assert.AreEqual(null, Cache.Get("key2")); Assert.IsTrue(Cache.ContainsKey("key3")); Assert.AreEqual("value3", Cache.Get("key3")); Assert.IsFalse(Cache.ContainsKey("key4")); Assert.AreEqual(null, Cache.Get("key4")); Assert.IsTrue(Cache.ContainsKey("key5")); Assert.AreEqual("value5", Cache.Get("key5")); }
public void BackgroundCleanupIsInitiatedWhenIntervalIsSet() { CacheOptions options = CacheOptions.SlidingExpiration(new TimeSpan(0, 0, 0, 0, 50)); // Initially values are not getting purged because the interval is 0. Cache.Set("key", "value", options); Thread.Sleep(300); Assert.IsTrue(Cache.ContainsKey("key")); // Cleanup manually to demonstrate that the value should go away. Cache.Cleanup(); Assert.IsFalse(Cache.ContainsKey("key")); // Now enable auto-cleanup Cache.CleanupIntervalInMilliseconds = 100; Assert.AreEqual(100, Cache.CleanupIntervalInMilliseconds); // Add some values and watch them get purged periodically. Cache.Set("key", "value", options); Thread.Sleep(300); Assert.IsFalse(Cache.ContainsKey("key")); Cache.Set("key", "value", options); Thread.Sleep(300); Assert.IsFalse(Cache.ContainsKey("key")); // Now stop the cleanup and notice that they don't get purged anymore. Cache.CleanupIntervalInMilliseconds = 0; Cache.Set("key", "value", options); Thread.Sleep(300); Assert.IsTrue(Cache.ContainsKey("key")); }
/// <inheritdoc /> public void Set(string key, byte[] value, CacheOptions options) { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } Connect(); var creationTime = DateTimeOffset.UtcNow; var absoluteExpiration = GetAbsoluteExpiration(creationTime, options); _cache.ScriptEvaluate(LunaConstants.SetScript, new RedisKey[] { _instance + key }, new RedisValue[] { absoluteExpiration?.Ticks ?? LunaConstants.NotPresent, options.SlidingExpiration?.Ticks ?? LunaConstants.NotPresent, GetExpirationInSeconds(creationTime, absoluteExpiration, options) ?? LunaConstants.NotPresent, value }); }
/// <inheritdoc /> public async Task SetAsync(string key, byte[] value, CacheOptions options, CancellationToken token = default) { if (key == null) { throw new ArgumentNullException(nameof(key)); } if (value == null) { throw new ArgumentNullException(nameof(value)); } if (options == null) { throw new ArgumentNullException(nameof(options)); } token.ThrowIfCancellationRequested(); await ConnectAsync(token); var creationTime = DateTimeOffset.UtcNow; var absoluteExpiration = GetAbsoluteExpiration(creationTime, options); await _cache.ScriptEvaluateAsync(LunaConstants.SetScript, new RedisKey[] { _instance + key }, new RedisValue[] { absoluteExpiration?.Ticks ?? LunaConstants.NotPresent, options.SlidingExpiration?.Ticks ?? LunaConstants.NotPresent, GetExpirationInSeconds(creationTime, absoluteExpiration, options) ?? LunaConstants.NotPresent, value }); }
public override async Task SetAsync <T>( string key, T obj, CacheOptions <T> options = null ) { await base.SetAsync(key, obj, options); var oldRedis = await IRedisGatewayService.GetAsync <T>(key); await IRedisGatewayService.SetAsync(key, obj); if (oldRedis == null) { return; } var oldMd5 = oldRedis.ToJsonMd5(); var newMd5 = obj.ToJsonMd5(); if (oldMd5 == newMd5) { return; } await IRedisCacheBus.RemoveAsync(key); }
/// <summary> /// 实用redis存储替换IInternalConfigurationRepository的服务 /// </summary> /// <param name="ocelotBuilder"></param> /// <returns></returns> public static IOcelotBuilder AddRedisProvider(this IOcelotBuilder ocelotBuilder, Action <CacheOptions> options) { //获取数据 CacheOptions cacheOptions = new CacheOptions(); options?.Invoke(cacheOptions); //检验是否注入redis仓储 if (ocelotBuilder.Services.BuildServiceProvider().GetService <IRedisOperationHelp>() == null) { if (cacheOptions.RedisOptions == null) { throw new ArgumentNullException(nameof(cacheOptions.RedisOptions)); } //注入redis仓储 ocelotBuilder.Services.AddRedisRepository(cacheOptions.RedisOptions); } //更改扩展方式 ocelotBuilder.Services.RemoveAll(typeof(IInternalConfigurationRepository)); //重写ocelot每次请求获取配置的服务 ocelotBuilder.Services.AddSingleton <IInternalConfigurationRepository, RedisInternalConfigurationRepository>(); return(ocelotBuilder); }
public RabbitOptions() { Ssl = new SslOptions(); Cache = new CacheOptions(); Listener = new ListenerOptions(); Template = new TemplateOptions(); }
public override async Task <HashSet <string> > GetSetAsync( string key, Func <IEnumerable <string> > factory = null ) { var result = IMemoryCacheService.Get <HashSet <string> >(key); if (result != null) { return(result); } var values = await IRedisGatewayService.GetSetAsync <string>(key); if (!values.HasContent()) { values = factory.Invoke().ToHashSet(); } await IRedisGatewayService.SetSetAsync(key, values); result = values.ToHashSet(); if (_UseCacheAside) { var entryOptions = new CacheOptions <HashSet <string> >(expirationType: CacheExpirationType.NotRemoveable); IMemoryCacheService.Set(key, result, entryOptions); } return(result); }
public TResult Retrieve <TResult>(string name, Func <TResult> callback, CacheOptions cacheOptions = null) { TResult model = Get <TResult>(name); if (model == null) { object miniLock = MiniLocks.GetOrAdd(name, k => new object()); lock (miniLock) { model = Get <TResult>(name); if (model == null) { model = callback(); if (model != null) { Set(name, model, cacheOptions); } } object temp; if (MiniLocks.TryGetValue(name, out temp) && (temp == miniLock)) { MiniLocks.TryRemove(name, out temp); } } } return(model); }
public static CacheOptions ReadFromConfiguration(IConfiguration config, AppOptions appOptions) { var options = new CacheOptions(); options.Scope = appOptions.AppScope; options.ScopePrefix = !String.IsNullOrEmpty(options.Scope) ? options.Scope + "-" : String.Empty; string cs = config.GetConnectionString("Cache"); options.Data = cs.ParseConnectionString(); options.Provider = options.Data.GetString(nameof(options.Provider)); var providerConnectionString = !String.IsNullOrEmpty(options.Provider) ? config.GetConnectionString(options.Provider) : null; if (!String.IsNullOrEmpty(providerConnectionString)) { options.Data.AddRange(providerConnectionString.ParseConnectionString()); } options.ConnectionString = options.Data.BuildConnectionString(new HashSet <string> { nameof(options.Provider) }); return(options); }
public void AbsoluteExpirationFactory() { CacheOptions options = CacheOptions.AbsoluteExpiration(new DateTime(1970, 1, 3)); Assert.AreEqual(new DateTime(1970, 1, 3), options.AbsoluteExpirationTime); Assert.IsNull(options.SlidingExpirationTimeSpan); Assert.AreEqual(0, options.CustomOptions.Count); }
public CacheManagerTest() { CacheOptions options = new CacheOptions() { Cache = new Microsoft.Extensions.Caching.Redis.CSRedisCache(new CSRedis.CSRedisClient(ConstantUtil.REDIS_CONNECTION)) }; cacheManager = new CacheManager(options); }
public void SlidingExpirationTime_GetterAndSetter() { CacheOptions options = new CacheOptions(); Assert.IsNull(options.SlidingExpirationTimeSpan); options.SlidingExpirationTimeSpan = new TimeSpan(1, 2, 3); Assert.AreEqual(new TimeSpan(1, 2, 3), options.SlidingExpirationTimeSpan); }
public void AbsoluteExpirationTime_GetterAndSetter() { CacheOptions options = new CacheOptions(); Assert.IsNull(options.AbsoluteExpirationTime); options.AbsoluteExpirationTime = new DateTime(1970, 1, 3); Assert.AreEqual(new DateTime(1970, 1, 3), options.AbsoluteExpirationTime); }
public void NoExpirationFactory() { CacheOptions options = CacheOptions.NoExpiration; Assert.IsNull(options.AbsoluteExpirationTime); Assert.IsNull(options.SlidingExpirationTimeSpan); Assert.AreEqual(0, options.CustomOptions.Count); }
public void GetUtcExpirationTimeRelativeToNow_WithAbsoluteExpirationTime() { CacheOptions options = new CacheOptions(); options.AbsoluteExpirationTime = new DateTime(1970, 1, 3, 0, 0, 0, DateTimeKind.Utc); Assert.AreEqual(new DateTime(1970, 1, 3, 0, 0, 0, DateTimeKind.Utc), options.GetUtcExpirationTimeRelativeToNow()); }
public LocalFileStreamMemoryCacheWorker(ILogger <LocalFileStreamMemoryCacheWorker> logger, OptionsConfigurableMemoryCache optionsConfigurableMemoryCache, IOptions <CacheOptions> cacheOptions) { _logger = logger; _cacheOptions = cacheOptions.Value; _memoryCache = optionsConfigurableMemoryCache.Cache; }
public QueryProcessor(IHandlerResolver handlerResolver, ICacheManager cacheManager, IOptions <CacheOptions> cacheOptions) { _handlerResolver = handlerResolver; _cacheManager = cacheManager; _cacheOptions = cacheOptions.Value; }
public ScavengedExpirableCacheStore(CacheOptions cacheOptions) { Guard.Assert(cacheOptions.MaxCacheItemCount > 0, "invalid cache item count"); Guard.Assert(cacheOptions.ScavengePercentage > 0, "invalid scavenge percentage"); _CacheOptions = cacheOptions; _ExpirableCacheStore = new ExpirableCacheStore(_CacheOptions); }
public CatalogInvalidatorTest(ITestOutputHelper helper) { logProvider = new XunitLoggerProvider(helper); logger = logProvider.CreateLogger <CatalogInvalidator>("CatalogInvalidatorTest"); config = new CacheOptions(); store = new Mock <ICatalogScanStore>(MockBehavior.Strict); reader = new Mock <ICatalogReader>(MockBehavior.Strict); }
/// <inheritdoc /> protected override void InternalSet(string key, object value, CacheOptions options) { DateTime absoluteExpirationOption = options.AbsoluteExpirationTime.HasValue ? options.AbsoluteExpirationTime.Value : ASPNetCache.NoAbsoluteExpiration; TimeSpan slidingExpirationOption = options.SlidingExpirationTimeSpan.HasValue ? options.SlidingExpirationTimeSpan.Value : ASPNetCache.NoSlidingExpiration; innerCache.Insert(key, value, null, absoluteExpirationOption, slidingExpirationOption); }
public ExpirableCacheStore(CacheOptions cacheOptions) { _CacheOptions = cacheOptions; _CacheStore = new CacheStore(_CacheOptions); Guard.Assert(cacheOptions.ExpirationPollInterval.TotalSeconds >= 1.0, "expiration poll time interval must be at least one second long"); _IntervalTimer = new IntervalTimer(cacheOptions.ExpirationPollInterval); _IntervalTimer.OnInterval += new Action(_IntervalTimer_OnInterval); }
public PublicFile(string path, CacheOptions cacheOptions, params AccessControlEntry[] accessControl) { if (path == null) throw new ArgumentNullException("path"); _path = path; _cacheOptions = cacheOptions; if (accessControl != null) { _accessControl = accessControl; } }
public void GetOrPopulate_ForwardsToThePopulatorButForgetsTheResult() { Assert.AreEqual("value", Cache.GetOrPopulate("key", delegate(string key, out CacheOptions options) { options = new CacheOptions(); Assert.AreEqual("key", key); return "value"; })); Assert.IsNull(Cache.Get("key")); }
protected override object GetValueFromCacheKey(string key, CacheOptions? cacheOptions) { if (DisabledDueToTesting) return null; if (cacheOptions != null && IsCacheStale(key)) { return null; } return _cacheManager.GetData(key); }
protected override void AddToCache(string key, object value, CacheItemPriority normal, object o, TimeSpan timeSpan, CacheOptions? cacheOptions) { if (DisabledDueToTesting) return; _cacheManager.Add(key, value, CacheItemPriority.Normal, null, new AbsoluteTime(timeSpan)); if (cacheOptions != null && IsCacheStale(key)) { ClearStaleFlag(key); } }
public void CustomOptions_EmptyUntilValuesAreAdded() { CacheOptions options = new CacheOptions(); Assert.AreEqual(0, options.CustomOptions.Count); options.AddCustomOption("foo", "bar"); options.AddCustomOption("xyzzy", "yiff"); Assert.AreEqual(2, options.CustomOptions.Count); Assert.AreEqual("bar", options.CustomOptions["foo"]); Assert.AreEqual("yiff", options.CustomOptions["xyzzy"]); }
public FileCacheProvider(CacheOptions options = null) : base(options) { if (options != null && options.FilePath.NullIfEmpty() != null) { FilePath = options.FilePath; } else { FilePath = FileCacheProvider.DefaultFilePath; } }
public void SetCachePolicy_SetsExpiresAndPragma_IfNoCacheOrNoStore(CacheOptions options) { // Arrange this.policy.Options = options; // Act this.provider.SetCachePolicy(this.response); // Assert Assert.Equal("no-cache", this.response.Headers.Pragma.ToString()); IEnumerable<string> expires; this.response.Content.Headers.TryGetValues("Expires", out expires); Assert.Equal("0", expires.Single()); }
/// <summary> /// Sets the Cache-Control header and optionally the Expires and Vary headers. /// </summary> /// <param name="response"></param> /// <param name="cacheOptions">A <see cref="CacheOptions"/> object to specify the cache settings.</param> public static void SetCacheOptions(this IResponse response, CacheOptions cacheOptions) { if (cacheOptions == null) { return; } if (cacheOptions.Disable) { response.Headers.CacheControl = "no-cache, no-store, must-revalidate"; response.Headers.Pragma = "no-cache"; response.Headers.Expires = "0"; return; } response.Headers.CacheControl = cacheOptions.ToHeaderString(); if (cacheOptions.AbsoluteExpiry.HasValue) { response.Headers.Expires = cacheOptions.AbsoluteExpiry.Value.ToString("R"); } if (cacheOptions.VaryByHeaders != null && cacheOptions.VaryByHeaders.Count > 0) { response.Headers.Vary = string.Join(", ", cacheOptions.VaryByHeaders); } }
public TaggedScavengedExpirableCacheStore(CacheOptions cacheOptions) { _CacheOptions = cacheOptions; _TagInfoMap = new TagInfoMap(_CacheOptions); _ScavengedExpirableCacheStore = new ScavengedExpirableCacheStore(_CacheOptions); }
public void SetCachePolicy_SetsCacheOptions(CacheOptions options, Func<HttpResponseMessage, bool> expected) { this.policy.Options = options; this.policy.MaxAge = null; // Act this.provider.SetCachePolicy(this.response); // Assert Assert.True(expected(this.response)); }
/// <summary> /// Always forces the image to be cached even if it wasn't modified by the resizing module. /// No disables caching even if it was. /// </summary> public static ImageUrlBuilder Cache(this ImageUrlBuilder builder, CacheOptions cacheOption = CacheOptions.Default) { return builder.SetParameter(MiscCommands.Cache, cacheOption.ToString().ToLowerInvariant()); }
public void AbsoluteExpirationTest() { CacheOptions cacheOptions = new CacheOptions() { Expiration = CacheExpiration.Absolute, CacheDuration = TimeSpan.FromSeconds(2D) }; DictionaryMemoryCache<string, Cat> actual = new DictionaryMemoryCache<string, Cat>(TestLoadByStringCatCloneMethod, cacheOptions); Cat cat1 = actual[_Key1]; Cat cat2 = actual[_Key2]; Assert.IsNotNull(cat1); Assert.IsNotNull(cat2); Guid originalCat1UniqueId = cat1.UniqueId; Guid originalCat2UniqueId = cat2.UniqueId; Cat cat1TakeTwo = actual[_Key1]; Cat cat2TakeTwo = actual[_Key2]; Assert.IsNotNull(cat1TakeTwo); Assert.IsNotNull(cat2TakeTwo); Assert.AreSame(cat1, cat1TakeTwo); Assert.AreSame(cat2, cat2TakeTwo); Assert.AreEqual<Guid>(originalCat1UniqueId, cat1TakeTwo.UniqueId); Assert.AreEqual<Guid>(originalCat2UniqueId, cat2TakeTwo.UniqueId); System.Threading.Thread.Sleep(TimeSpan.FromSeconds(3D)); Cat cat1TakeThree = actual[_Key1]; Cat cat2TakeThree = actual[_Key2]; Assert.IsNotNull(cat1TakeThree); Assert.IsNotNull(cat2TakeThree); Assert.AreEqual<string>(cat1.Name, cat1TakeThree.Name); Assert.AreEqual<int>(cat1.ClawLength, cat1TakeThree.ClawLength); Assert.AreEqual<string>(cat2.Name, cat2TakeThree.Name); Assert.AreEqual<int>(cat2.ClawLength, cat2TakeThree.ClawLength); Assert.AreNotEqual<Guid>(originalCat1UniqueId, cat1TakeThree.UniqueId); Assert.AreNotEqual<Guid>(originalCat2UniqueId, cat2TakeThree.UniqueId); }
public CacheStore(CacheOptions cacheOptions) { _CacheOptions = cacheOptions; _CacheItemMap = new ConcurrentDictionary<string, CacheItem>(); }
public void PopulateOverwritesTheExistingValueWhenPresent() { Cache.Set("key", "EXISTING"); Assert.AreEqual("value", Cache.Populate("key", delegate(string key, out CacheOptions options) { options = new CacheOptions(); Assert.AreEqual("key", key); return "value"; })); Assert.IsTrue(Cache.ContainsKey("key")); Assert.AreEqual("value", Cache.Get("key")); }
public void ImmediateExpirationTest() { CacheOptions cacheOptions = new CacheOptions() { Expiration = CacheExpiration.Immediate }; DictionaryMemoryCache<string, Cat> actual = new DictionaryMemoryCache<string, Cat>(TestLoadByStringCatMethod); Cat cat = actual[_Key1]; Assert.IsNotNull(cat); Cat cat1TakeTwo = actual[_Key2]; Assert.IsNotNull(cat1TakeTwo); Assert.AreNotSame(cat, cat1TakeTwo); Assert.AreNotEqual<Guid>(cat.UniqueId, cat1TakeTwo.UniqueId); }
public void SlidingExpirationTest() { CacheOptions cacheOptions = new CacheOptions() { Expiration = CacheExpiration.Sliding, CacheDuration = TimeSpan.FromSeconds(2D) }; SingleItemMemoryCache<Cat> actual = new SingleItemMemoryCache<Cat>(TestLoadCatMethod, cacheOptions); Cat cat = actual.GetItem(); Assert.IsNotNull(cat); Guid originalUniqueId = cat.UniqueId; for (int counter = 0; counter < 5; counter++) { System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1D)); Cat cat2 = actual.GetItem(); Assert.IsNotNull(cat2); Assert.AreSame(cat, cat2); Assert.AreEqual<Guid>(originalUniqueId, cat2.UniqueId); } System.Threading.Thread.Sleep(TimeSpan.FromSeconds(3D)); Cat cat3 = actual.GetItem(); Assert.IsNotNull(cat3); Assert.AreNotSame(cat, cat3); Assert.AreNotEqual<Guid>(originalUniqueId, cat3.UniqueId); }
public void Initialize(CacheOptions cacheOptions) { Settings.CacheOptions = cacheOptions; _initalized = true; bool isLocked = false; try { Monitor.Enter(_factoryListLock); isLocked = true; Console.WriteLine("NetOffice Core.Initialize() NO Version:{1} DeepLevel:{0}", Settings.EnableDeepLoading, this.GetType().Assembly.GetName().Version); foreach (var item in _tryLoadAssemblyNames) TryLoadAssembly(item); if (!_assemblyResolveEventConnected) { AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve); _assemblyResolveEventConnected = true; } ClearCache(); AddNetOfficeAssemblies(); AddDependentNetOfficeAssemblies(); Console.WriteLine("Factory contains {0} assemblies", _factoryList.Count); Console.WriteLine("NetOffice Core.Initialize() passed"); } catch (Exception throwedException) { DebugConsole.Default.WriteException(throwedException); throw (throwedException); } finally { if (isLocked) { Monitor.Exit(_factoryListLock); isLocked = false; } } }
public void PopulateReturnsNullAndDoesAbsolutelyNothingElseIfThePopulatorReturnsNull() { Assert.IsNull(Cache.Populate("key", delegate(string key, out CacheOptions options) { options = new CacheOptions(); Assert.AreEqual("key", key); return null; })); Assert.IsFalse(Cache.ContainsKey("key")); Assert.IsNull(Cache.Get("key")); }
protected abstract object GetValueFromCacheKey(string key, CacheOptions? cacheOptions);
protected abstract void AddToCache(string key, object value, CacheItemPriority normal, object o, TimeSpan timeSpan, CacheOptions? cacheOptions);
public void PopulateRecoversFromExceptionsSafely() { try { Cache.Populate("key", delegate(string key, out CacheOptions options) { throw new Exception("Boom!"); }); Assert.Fail("Expected an exception to be thrown by the populator."); } catch (Exception ex) { // Expected. Assert.AreEqual("Boom!", ex.Message); } // Try again to ensure we have recovered. // Note: This helps to ensure that our exception cleanup logic works // for caches that do more sophisticated locking during population. Assert.AreEqual("value", Cache.Populate("key", delegate(string key, out CacheOptions options) { options = new CacheOptions(); Assert.AreEqual("key", key); return "value"; })); Assert.IsTrue(Cache.ContainsKey("key")); Assert.AreEqual("value", Cache.Get("key")); }
public MemoryCacheProvider(CacheOptions options = null) : base(options) { }
public void ImmediateExpirationTest() { CacheOptions cacheOptions = new CacheOptions() { Expiration = CacheExpiration.Immediate }; SingleItemMemoryCache<Cat> actual = new SingleItemMemoryCache<Cat>(TestLoadCatMethod, cacheOptions); Cat cat = actual.GetItem(); Assert.IsNotNull(cat); Guid expectedUniqueId = cat.UniqueId; Cat cat2 = actual.GetItem(); Assert.IsNotNull(cat2); Assert.AreNotSame(cat, cat2); Assert.AreNotEqual<Guid>(expectedUniqueId, cat2.UniqueId); int expectedClawLength = 7; cat.ClawLength = expectedClawLength; Assert.AreNotEqual<int>(expectedClawLength, cat2.ClawLength); }
public void Initialize(CacheOptions cacheOptions) { Settings.CacheOptions = cacheOptions; _initalized = true; bool isLocked = false; try { DateTime startTime = DateTime.Now; Monitor.Enter(_factoryListLock); isLocked = true; Console.WriteLine("NetOffice Core.Initialize() NO Version:{1} DeepLevel:{0}", Settings.EnableDeepLoading, _coreVersion); foreach (var item in _tryLoadAssemblyNames) TryLoadAssembly(item); ClearCache(); AddNetOfficeAssemblies(); AddDependentNetOfficeAssemblies(); InitializedTime = DateTime.Now - startTime; Console.WriteLine("Core contains {0} assemblies", _factoryList.Count); Console.WriteLine("NetOffice Core.Initialize() passed in {0} milliseconds", InitializedTime.TotalMilliseconds); } catch (Exception throwedException) { DebugConsole.Default.WriteException(throwedException); throw; } finally { if (isLocked) { Monitor.Exit(_factoryListLock); isLocked = false; } } }