コード例 #1
0
 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)
     };
 }
コード例 #2
0
        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>());
        }
コード例 #3
0
ファイル: ExecuteShould.cs プロジェクト: vncpetrov/Mp3Music
        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);
        }
コード例 #4
0
        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"));
        }
コード例 #5
0
ファイル: ExecuteShould.cs プロジェクト: vncpetrov/Mp3Music
        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);
        }
コード例 #6
0
ファイル: ExecuteShould.cs プロジェクト: vncpetrov/Mp3Music
        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);
        }
コード例 #7
0
        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;
            }
        }
コード例 #8
0
        /// <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;
            }
        }
コード例 #9
0
        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);
        }
コード例 #10
0
        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);
        }
コード例 #11
0
        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));
        }
コード例 #12
0
        /// <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);
        }
コード例 #13
0
ファイル: TagInfoMap.cs プロジェクト: shivashankarp/Tag-Cache
        public TagInfoMap(CacheOptions cacheOptions)
        {
            _TagInfoByTag = new ConcurrentDictionary<string, WeakReference>();

            _IntervalTimer = new IntervalTimer(cacheOptions.TagMapScavengeInterval);
            _IntervalTimer.OnInterval += new Action(_ScavengeTagMap);
        }
コード例 #14
0
        /// <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);
        }
コード例 #15
0
        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"));
        }
コード例 #16
0
        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"));
        }
コード例 #17
0
        /// <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
            });
        }
コード例 #18
0
        /// <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
            });
        }
コード例 #19
0
        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);
        }
コード例 #20
0
        /// <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);
        }
コード例 #21
0
 public RabbitOptions()
 {
     Ssl      = new SslOptions();
     Cache    = new CacheOptions();
     Listener = new ListenerOptions();
     Template = new TemplateOptions();
 }
コード例 #22
0
        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);
        }
コード例 #23
0
        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);
        }
コード例 #24
0
ファイル: CacheOptions.cs プロジェクト: aTiKhan/Exceptionless
    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);
    }
コード例 #25
0
        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);
        }
コード例 #26
0
ファイル: CacheManagerTest.cs プロジェクト: lianggx/mystaging
 public CacheManagerTest()
 {
     CacheOptions options = new CacheOptions()
     {
         Cache = new Microsoft.Extensions.Caching.Redis.CSRedisCache(new CSRedis.CSRedisClient(ConstantUtil.REDIS_CONNECTION))
     };
     cacheManager = new CacheManager(options);
 }
コード例 #27
0
        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);
        }
コード例 #28
0
        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);
        }
コード例 #29
0
        public void NoExpirationFactory()
        {
            CacheOptions options = CacheOptions.NoExpiration;

            Assert.IsNull(options.AbsoluteExpirationTime);
            Assert.IsNull(options.SlidingExpirationTimeSpan);
            Assert.AreEqual(0, options.CustomOptions.Count);
        }
コード例 #30
0
        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;
 }
コード例 #32
0
ファイル: QueryProcessor.cs プロジェクト: sivanomula/Kledex
 public QueryProcessor(IHandlerResolver handlerResolver,
                       ICacheManager cacheManager,
                       IOptions <CacheOptions> cacheOptions)
 {
     _handlerResolver = handlerResolver;
     _cacheManager    = cacheManager;
     _cacheOptions    = cacheOptions.Value;
 }
コード例 #33
0
        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);
        }
コード例 #34
0
 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);
 }
コード例 #35
0
ファイル: SysCache.cs プロジェクト: mgagne-atman/Projects
        /// <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);
        }
コード例 #36
0
        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);
        }
コード例 #37
0
 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;
     }
 }
コード例 #38
0
 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"));
 }
コード例 #39
0
        protected override object GetValueFromCacheKey(string key, CacheOptions? cacheOptions)
        {
            if (DisabledDueToTesting) return null;

            if (cacheOptions != null && IsCacheStale(key))
            {
                return null;
            }

            return _cacheManager.GetData(key);
        }
コード例 #40
0
        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);
            }
        }
コード例 #41
0
        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"]);
        }
コード例 #42
0
ファイル: FileCacheProvider.cs プロジェクト: rhutchison/Nemo
 public FileCacheProvider(CacheOptions options = null)
     : base(options)
 {
     if (options != null && options.FilePath.NullIfEmpty() != null)
     {
         FilePath = options.FilePath;
     }
     else
     {
         FilePath = FileCacheProvider.DefaultFilePath;
     }
 }
コード例 #43
0
        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());
        }
コード例 #44
0
 /// <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);
     }
 }
コード例 #45
0
 public TaggedScavengedExpirableCacheStore(CacheOptions cacheOptions)
 {
     _CacheOptions = cacheOptions;
     _TagInfoMap = new TagInfoMap(_CacheOptions);
     _ScavengedExpirableCacheStore = new ScavengedExpirableCacheStore(_CacheOptions);
 }
コード例 #46
0
        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));
        }
コード例 #47
0
 /// <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());
 }
コード例 #48
0
        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);
        }
コード例 #49
0
ファイル: CacheStore.cs プロジェクト: shivashankarp/Tag-Cache
 public CacheStore(CacheOptions cacheOptions)
 {
     _CacheOptions = cacheOptions;
     _CacheItemMap = new ConcurrentDictionary<string, CacheItem>();
 }
コード例 #50
0
        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"));
        }
コード例 #51
0
        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);
        }
コード例 #52
0
        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);
        }
コード例 #53
0
ファイル: Core.cs プロジェクト: netintellect/NetOffice
        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;
                }
            }
        }
コード例 #54
0
        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"));
        }
コード例 #55
0
 protected abstract object GetValueFromCacheKey(string key, CacheOptions? cacheOptions);
コード例 #56
0
 protected abstract void AddToCache(string key, object value, CacheItemPriority normal, object o, TimeSpan timeSpan, CacheOptions? cacheOptions);
コード例 #57
0
        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"));
        }
コード例 #58
0
 public MemoryCacheProvider(CacheOptions options = null)
     : base(options)
 {
 }
コード例 #59
0
        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);
        }
コード例 #60
0
ファイル: Core.cs プロジェクト: netoffice/NetOffice
        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;
                }
            }
        }