Exemplo n.º 1
1
		public void Setup()
		{
			_container = new MocksAndStubsContainer();	

			_applicationSettings = _container.ApplicationSettings;
			_context = _container.UserContext;

			_settingsRepository = _container.SettingsRepository;
			_userRepository = _container.UserRepository;
			_pageRepository = _container.PageRepository;

			_settingsService = _container.SettingsService;
			_userService = _container.UserService;
			_pageCache = _container.PageViewModelCache;
			_listCache = _container.ListCache;
			_siteCache = _container.SiteCache;
			_cache = _container.MemoryCache;
			_container.ClearCache();

			_pageService = _container.PageService;
			_wikiImporter = new WikiImporterMock();
			_pluginFactory = _container.PluginFactory;
			_searchService = _container.SearchService;

			// There's no point mocking WikiExporter (and turning it into an interface) as 
			// a lot of usefulness of these tests would be lost when creating fake Streams and zip files.
			_wikiExporter = new WikiExporter(_applicationSettings, _pageService, _settingsRepository, _pageRepository, _userRepository, _pluginFactory);
			_wikiExporter.ExportFolder = AppDomain.CurrentDomain.BaseDirectory;

			_toolsController = new ToolsController(_applicationSettings, _userService, _settingsService, _pageService,
													_searchService, _context, _listCache, _pageCache, _wikiImporter, 
													_pluginFactory, _wikiExporter);
		}
Exemplo n.º 2
0
        public DocumentCacher(InMemoryRavenConfiguration configuration)
        {
            this.configuration = configuration;
            cachedSerializedDocuments = CreateCache();

            MemoryStatistics.RegisterLowMemoryHandler(this);
        }
Exemplo n.º 3
0
        /// <summary>
        /// The constructor.
        /// </summary>
        /// <param name="physicalMemoryLimitPercentage">The cache memory limit, as a percentage of the total system memory.</param>
        /// <param name="performanceDataManager">The performance data manager.</param>
        internal MemCache(int physicalMemoryLimitPercentage, PerformanceDataManager performanceDataManager)
        {
            // Sanitize
            if (physicalMemoryLimitPercentage <= 0)
            {
                throw new ArgumentException("cannot be <= 0", "physicalMemoryLimitPercentage");
            }
            if (performanceDataManager == null)
            {
                throw new ArgumentNullException("performanceDataManager");
            }

            var cacheMemoryLimitMegabytes = (int)(((double)physicalMemoryLimitPercentage / 100) * (new ComputerInfo().TotalPhysicalMemory / 1048576)); // bytes / (1024 * 1024) for MB;

            _cacheName = "Dache";
            _cacheConfig = new NameValueCollection();
            _cacheConfig.Add("pollingInterval", "00:00:05");
            _cacheConfig.Add("cacheMemoryLimitMegabytes", cacheMemoryLimitMegabytes.ToString());
            _cacheConfig.Add("physicalMemoryLimitPercentage", physicalMemoryLimitPercentage.ToString());

            _memoryCache = new TrimmingMemoryCache(_cacheName, _cacheConfig);
            _internDictionary = new Dictionary<string, string>(100);
            _internReferenceDictionary = new Dictionary<string, int>(100);

            _performanceDataManager = performanceDataManager;

            // Configure per second timer to fire every 1000 ms starting 1000ms from now
            _perSecondTimer = new Timer(PerSecondOperations, null, 1000, 1000);
        }
Exemplo n.º 4
0
 private GameBot()
 {
     _userRequests = new MemoryCache(nameof(_userRequests));
     _refreshGamesTimer = new Timer(2000);
     _refreshGamesTimer.Start();
     _refreshGamesTimer.Elapsed += RefreshGamesTimerOnElapsed;
 }
Exemplo n.º 5
0
        /// <summary>
        /// GetFlight with MemoryCache (5 sek)
        /// </summary>
        private static List <Flight> GetFlight1(string departure)
        {
            string cacheItemName = "FlightSet_" + departure;

            // Zugriff auf Cache-Eintrag
            System.Runtime.Caching.MemoryCache cache = System.Runtime.Caching.MemoryCache.Default;
            List <Flight> flightSet = cache[cacheItemName] as List <Flight>;

            if (flightSet == null) // Element ist NICHT im Cache
            {
                CUI.Print($"{DateTime.Now.ToLongTimeString()}: Cache missed", ConsoleColor.Red);
                using (var ctx = new WWWingsContext())
                {
                    ctx.Log();
                    // Load flights
                    flightSet = ctx.FlightSet.Where(x => x.Departure == departure).ToList();
                }
                // Store flights in cache
                CacheItemPolicy policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = DateTime.Now.AddSeconds(5);
                //or: policy.SlidingExpiration = new TimeSpan(0,0,0,5);
                cache.Set(cacheItemName, flightSet, policy);
            }
            else // Data is already in cache
            {
                CUI.Print($"{DateTime.Now.ToLongTimeString()}: Cache hit", ConsoleColor.Green);
            }
            return(flightSet);
        }
Exemplo n.º 6
0
        public void AddOrGetExisting()
        {
            var cache2 = new CacheTest();
            var cache3 = new CacheTest();
            var cache4 = new CacheTest();

            System.Runtime.Caching.MemoryCache cache = System.Runtime.Caching.MemoryCache.Default;

            int cache1_1 = cache.AddOrGetExisting("cache1", 1);
            int cache1_2 = cache.AddOrGetExisting("cache1", 2);

            int cache2_1 = cache.AddOrGetExisting("cache2", i => cache2.Increment());
            int cache2_2 = cache.AddOrGetExisting("cache2", i => cache2.Increment());

            int cache3_1 = cache.AddOrGetExisting("cache3", i => cache3.Increment(), new CacheItemPolicy());
            int cache3_2 = cache.AddOrGetExisting("cache3", i => cache3.Increment(), new CacheItemPolicy());

            int cache4_1 = cache.AddOrGetExisting("cache4", i => cache4.Increment(), new DateTimeOffset(new DateTime(2100, 01, 01)));
            int cache4_2 = cache.AddOrGetExisting("cache4", i => cache4.Increment(), new DateTimeOffset(new DateTime(2100, 01, 01)));

            Assert.AreEqual(1, cache1_1);
            Assert.AreEqual(1, cache1_2);

            Assert.AreEqual(1, cache2_1);
            Assert.AreEqual(1, cache2_2);

            Assert.AreEqual(1, cache3_1);
            Assert.AreEqual(1, cache3_2);

            Assert.AreEqual(1, cache4_1);
            Assert.AreEqual(1, cache4_2);
        }
        public void ShouldExpireCacheAfterConfigurableTime()
        {
            const string PolicyKey = "MDM.Market";

            var appSettings = new NameValueCollection();
            appSettings["CacheItemPolicy.Expiration." + PolicyKey] = "8";

            var configManager = new Mock<IConfigurationManager>();
            configManager.Setup(x => x.AppSettings).Returns(appSettings);

            ICacheItemPolicyFactory policyFactory = new AbsoluteCacheItemPolicyFactory(PolicyKey, configManager.Object);
            var policyItem = policyFactory.CreatePolicy();

            var marketName = "ABC market";
            var marketKey = "Market-1";
            var cache = new MemoryCache("MDM.Market");
            cache.Add(marketKey, marketName, policyItem);

            // Should get cache item
            Assert.AreEqual(marketName, cache[marketKey]);

            // Keep on accessing cache, it should expire approximately with in 10 iterations
            int count = 0;
            while (cache[marketKey] != null && count < 10)
            {
                count++;
                Thread.Sleep(TimeSpan.FromSeconds(1));
            }

            Console.WriteLine("Cache has expired in {0} seconds:", count);
            // should not be in the cache after configuratble time
            Assert.IsNull(cache[marketKey]);
        }
        public void ShouldCreateAbsoluteCacheItemPolicyBasedOnTheConfiguration()
        {
            const string PolicyKey = "MDM.Market";

            var appSettings = new NameValueCollection();
            appSettings["CacheItemPolicy.Expiration." + PolicyKey] = "8";

            var configManager = new Mock<IConfigurationManager>();
            configManager.Setup(x => x.AppSettings).Returns(appSettings);

            ICacheItemPolicyFactory policyFactory = new AbsoluteCacheItemPolicyFactory(PolicyKey, configManager.Object);
            var policyItem = policyFactory.CreatePolicy();

            var marketName = "ABC market";
            var marketKey = "Market-1";
            var cache = new MemoryCache("MDM.Market");
            cache.Add(marketKey, marketName, policyItem);

            // Should get cache item
            Assert.AreEqual(marketName, cache[marketKey]);

            // wait until the expiry time
            Thread.Sleep(TimeSpan.FromSeconds(10));

            // should not be in the cache
            Assert.IsNull(cache[marketKey]);
        }
		public EmailOutputChannel(OutputSetting setting, IStatsTemplate template)
				: base(setting)
		{
			this.template = template;
			emailSetting = (EmailOutputSetting)setting;
			cache = MemoryCache.Default;
		}
Exemplo n.º 10
0
        public ExpiringCache(ILogger log, Func<string, ICurrentWorkingDirectory, IRepositoryStatus> factory)
        {
            _log = log;
            _factory = factory;

            _cache = GetCache();
        }
Exemplo n.º 11
0
 public override void Initialise()
 {
     if (_cache == null)
     {
         _cache = sys.MemoryCache.Default;
     }
 }
            public void ExistingObject_IncrementByOneAndSetExpirationDate()
            {
                // Arrange
                var key = new SimpleThrottleKey("test", "key");
                var limiter = new Limiter()
                    .Limit(1)
                    .Over(100);
                var cache = new MemoryCache("testing_cache");
                var repository = new MemoryThrottleRepository(cache);
                string id = repository.CreateThrottleKey(key, limiter);

                var cacheItem = new MemoryThrottleRepository.ThrottleCacheItem()
                {
                    Count = 1,
                    Expiration = new DateTime(2030, 1, 1)
                };

                cache
                    .Set(id, cacheItem, cacheItem.Expiration);

                // Act
                repository.AddOrIncrementWithExpiration(key, limiter);

                // Assert
                var item = (MemoryThrottleRepository.ThrottleCacheItem)cache.Get(id);
                Assert.Equal(2L, item.Count);
                Assert.Equal(new DateTime(2030, 1, 1), item.Expiration);
            }
Exemplo n.º 13
0
 internal MemCache(CacheCommon cacheCommon) : base(cacheCommon) {
     // config initialization is done by Init.
     Assembly asm = Assembly.Load("System.Runtime.Caching, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL");
     Type t = asm.GetType("System.Runtime.Caching.MemoryCache", true, false);
     _cacheInternal = HttpRuntime.CreateNonPublicInstance(t, new object[] {"asp_icache", null, true}) as MemoryCache;
     _cachePublic = HttpRuntime.CreateNonPublicInstance(t, new object[] {"asp_pcache", null, true}) as MemoryCache;
 }
        public CacheTestSetupHelper()
        {
            _cacheReference = new MemoryCache("unit-tester");

            var metadata = new ProviderMetadata("cache", new Uri("cache://"), false, true);
            var frameworkContext = new FakeFrameworkContext();

            var schemaRepositoryFactory = new SchemaRepositoryFactory(
                metadata,
                new NullProviderRevisionRepositoryFactory<EntitySchema>(metadata, frameworkContext),
                frameworkContext,
                new DependencyHelper(metadata, new CacheHelper(CacheReference)));

            var revisionRepositoryFactory = new EntityRevisionRepositoryFactory(
                metadata,
                frameworkContext,
                new DependencyHelper(metadata, new CacheHelper(CacheReference)));

            var entityRepositoryFactory = new EntityRepositoryFactory(
                metadata,
                revisionRepositoryFactory,
                schemaRepositoryFactory,
                frameworkContext,
                new DependencyHelper(metadata, new CacheHelper(CacheReference)));
            var unitFactory = new ProviderUnitFactory(entityRepositoryFactory);
            var readonlyUnitFactory = new ReadonlyProviderUnitFactory(entityRepositoryFactory);
            ProviderSetup = new ProviderSetup(unitFactory, metadata, frameworkContext, new NoopProviderBootstrapper(), 0);
            ReadonlyProviderSetup = new ReadonlyProviderSetup(readonlyUnitFactory, metadata, frameworkContext, new NoopProviderBootstrapper(), 0);
        }
Exemplo n.º 15
0
 public override void Initialise()
 {
     if (_cache == null)
     {
         _cache = new sys.MemoryCache(Assembly.GetExecutingAssembly().FullName);
     }
 }
Exemplo n.º 16
0
 public override void Initialise()
 {
     if (_cache == null)
     {
         _cache = new sys.MemoryCache(Assembly.GetExecutingAssembly().FullName);
     }
 }
Exemplo n.º 17
0
 public MemoryAdapter(CacheSettings cacheSettings)
 {
     CacheSettings = cacheSettings;
     _memoryCache = new MemoryCache(cacheSettings.Name);
     _expirationType = cacheSettings.ExpirationType;
     _minutesToExpire = cacheSettings.TimeToLive;
 }
Exemplo n.º 18
0
 private RuntimeCacheProvider()
 {
     if (HttpContext.Current == null)
     {
         _memoryCache = new MemoryCache("in-memory");
     }
 }
Exemplo n.º 19
0
 //private static DataCacheFactory _factory;
 static MatchingService()
 {
     //DataCacheFactory factory = new DataCacheFactory();
     //_cache = factory.GetCache("default");
     _cache = MemoryCache.Default;
     //Debug.Assert(_cache == null);
 }
 void IMemoryCacheManager.ReleaseCache(MemoryCache memoryCache)
 {
     if (memoryCache == null)
     {
         throw new ArgumentNullException("memoryCache");
     }
     long sizeUpdate = 0L;
     lock (this._lock)
     {
         if (this._cacheInfos != null)
         {
             MemoryCacheInfo info = null;
             if (this._cacheInfos.TryGetValue(memoryCache, out info))
             {
                 sizeUpdate = -info.Size;
                 this._cacheInfos.Remove(memoryCache);
             }
         }
     }
     if (sizeUpdate != 0L)
     {
         ApplicationManager applicationManager = HostingEnvironment.GetApplicationManager();
         if (applicationManager != null)
         {
             applicationManager.GetUpdatedTotalCacheSize(sizeUpdate);
         }
     }
 }
            public void RetrieveValidThrottleCountFromRepostitory()
            {
                // Arrange
                var key = new SimpleThrottleKey("test", "key");
                var limiter = new Limiter()
                    .Limit(1)
                    .Over(100);
                var cache = new MemoryCache("testing_cache");
                var repository = new MemoryThrottleRepository(cache);
                string id = repository.CreateThrottleKey(key, limiter);

                var cacheItem = new MemoryThrottleRepository.ThrottleCacheItem()
                {
                    Count = 1,
                    Expiration = new DateTime(2030, 1, 1)
                };

                repository.AddOrIncrementWithExpiration(key, limiter);

                // Act
                var count = repository.GetThrottleCount(key, limiter);

                // Assert
                Assert.Equal(count, 1);
            }
Exemplo n.º 22
0
        public Instance(Configuration configuration, string domain, Index index = null)
        {
            // Set instance on configuration
            Configuration = configuration;

            // Init things
            ObjDb = new Db(Configuration.Object.Database.ConnectionString); // Database
            CacheObj = new MemoryCache("instance-obj-" + domain); // Cache
            //CacheQ = new MemoryCache("instance-q-" + domain); // Cache

            if (null == index) {
                // Create new index
                Index = new Index(Configuration.Schema);

                // Build base index
                var retry = new RetryPolicy<DbRetryStrategy>(3, new TimeSpan(0, 0, 1));
                using (var rdr = ObjDb.Query("SELECT [uid],[type],[serial],[properties] FROM [obj] WHERE [oid] NOT IN (SELECT [predecessor] FROM [obj])").ExecuteReaderWithRetry(retry)) {
                    while (rdr.Read()) {
                        Index.Set((string)rdr["uid"], (string)rdr["type"], (long)rdr["serial"], (string)rdr["properties"]);
                    }
                }
            } else {
                Index = index;
            }

            // Init mode
            Mode = Amos.ImplementationMode.Mode.Select(Configuration.Mode, this);
        }
 internal CacheMemoryMonitor(MemoryCache memoryCache, int cacheMemoryLimitMegabytes) {
     _memoryCache = memoryCache;
     _gen2Count = GC.CollectionCount(2);
     _cacheSizeSamples = new long[SAMPLE_COUNT];
     _cacheSizeSampleTimes = new DateTime[SAMPLE_COUNT];
     InitMemoryCacheManager();
     InitDisposableMembers(cacheMemoryLimitMegabytes);
 }
Exemplo n.º 24
0
 private void GenerateAndBindNrlCache()
 {
     MemoryCache memoryCache = new MemoryCache("NrlCache");
     Kernel.Bind<INrlCache>()
         .To<NrlCache>()
         .InSingletonScope()
         .WithConstructorArgument("memoryCache", memoryCache);
 }
Exemplo n.º 25
0
 public GameBroadcastListener(int port = 21234)
 {
     Port = port;
     IsListening = false;
     // Expected: System.InvalidOperationException
     // Additional information: The requested Performance Counter is not a custom counter, it has to be initialized as ReadOnly.
     GameCache = new MemoryCache("gamebroadcastlistenercache");
 }
 static ObjectServiceExceptionStore()
 {
     timeoutSeconds = 3600;
     cacheName = "ObjectSerficeExceptionStore";
     cache = CacheManager.GetCache(cacheName);
     policy = new CacheItemPolicy();
     policy.AbsoluteExpiration = DateTime.Now + TimeSpan.FromSeconds(timeoutSeconds);
 }
Exemplo n.º 27
0
		protected override void TestSetup()
		{
			memoryCacheReference = MemoryCache.Default;
			CacheBuilder.For<ObjectWithMultipleParameters>()
				.CacheMethod(x => x.Calculate(0, null, 0))
				.AsImplemented();
			component = CacheBuilder.BuildFactory().Create<ObjectWithMultipleParameters>();
		}
Exemplo n.º 28
0
        static SimpleDataRepository()
        {
            const string DIRECTORY = "C:\\x\\cacheit";

            var objectCache = new MemoryCache("{7D8DAD94-A0EF-4168-ACB5-2574DC000F26}");
            Directory directory = new CacheDirectory(objectCache, DIRECTORY);
            simpleDataIndex = new SimpleDataIndex(Items, directory);
        }
Exemplo n.º 29
0
        public MemoryCacheProvider(string name)
        {
            Name = name;
            m_memoryCache = new MemoryCache(Name);

            m_policy = new CacheItemPolicy();
            m_policy.SlidingExpiration = TimeSpan.FromHours(1);
        }
Exemplo n.º 30
0
 public LookUp(ArrayList fingerList, int gender, byte[] probeTemplate, MemoryCache cache, CancellationToken ct)
 {
     _fingerList     = fingerList;
     _gender         = gender;
     _probeTemplate  = probeTemplate;
     _cache          = cache;
     _ct             = ct;
 }
Exemplo n.º 31
0
        public MemoryCache(System.Runtime.Caching.MemoryCache cache)
        {
            this.cache = cache;

            DefaultCacheCapabilities = cache.DefaultCacheCapabilities;

            Name = cache.Name;
        }
Exemplo n.º 32
0
 protected override void InitialiseInternal()
 {
     if (_cache == null)
     {
         Log.Debug("MemoryCache.Initialise - initialising with cacheName: {0}", CacheConfiguration.Current.DefaultCacheName);
         _cache = new sys.MemoryCache(CacheConfiguration.Current.DefaultCacheName);
     }
 }
Exemplo n.º 33
0
 public void ClearCache()
 {
     lock (_locker)
     {
         _cacheInfraestructure.Dispose();
         _cacheInfraestructure = new MemoryCache(CacheName);
     }
 }
Exemplo n.º 34
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RedisCache"/> class.
 /// </summary>
 /// <param name="name">The name.</param>
 /// <param name="hostname">The hostname.</param>
 public RedisCache(string name, string hostname = "localhost")
     : base(name)
 {
     _redis = ConnectionMultiplexer.Connect(hostname);
     _redis.PreserveAsyncOrder = false;
     _redisDb = _redis.GetDatabase();
     _level1Cache = new MemoryCache(name);
 }
Exemplo n.º 35
0
 protected override void InitialiseInternal()
 {
     if (_cache == null)
     {
         //Log.Debug("MemoryCache.Initialise - initialising with cacheName: {0}", CacheConfiguration.Current.DefaultCacheName);
         _cache = new sys.MemoryCache(CacheConfiguration.Current.DefaultCacheName);
     }
 }
Exemplo n.º 36
0
        public void HandleLowMemory()
        {
            var oldCache = cachedSerializedDocuments;

            cachedSerializedDocuments = CreateCache();

            oldCache.Dispose();
        }
Exemplo n.º 37
0
 public override void Initialise()
 {
     if (_cache == null)
     {
         //Log.Debug("MemoryCache.Initialise - initialising with cacheName: {0}", CacheConfiguration.Current.DefaultCacheName);
         // _cache = new sys.MemoryCache(CacheConfiguration.Current.DefaultCacheName);
         _cache = sys.MemoryCache.Default;
     }
 }
Exemplo n.º 38
0
        public void ClearCache()
        {
            var newCache = new MemCache("CacheService");
            var oldCache = _cache;

            _cache = newCache;

            oldCache.Dispose();
        }
Exemplo n.º 39
0
        private static System.Runtime.Caching.MemoryCache GetInstance()
        {
            if (_cache == null)
            {
                _cache = new System.Runtime.Caching.MemoryCache("privateCache");
            }

            return(_cache);
        }
Exemplo n.º 40
0
        public static object Value(string key)
        {
            string NewKey = TransformKey(key);

            System.Runtime.Caching.MemoryCache cache = System.Runtime.Caching.MemoryCache.Default;
            if (cache.Contains(NewKey))
            {
                return(cache[NewKey]);
            }
            return(string.Empty);
        }
Exemplo n.º 41
0
        /// <summary>
        /// Clears the cache.
        /// </summary>
        public void Flush()
        {
            lock (_lockObj)
            {
                if (_cache != null)
                {
                    _cache.Dispose();
                    _ttls.Clear();
                }

                _cache = new System.Runtime.Caching.MemoryCache("stackredis.l1.objmemcache");
            }
        }
Exemplo n.º 42
0
        public MemoryCache(string region, IDictionary <string, string> properties)
        {
            this.region =
                string.IsNullOrEmpty(region) ?
                Guid.NewGuid().ToString() :
                region;

            cache = new System.Runtime.Caching.MemoryCache(this.region);
            Configure(properties);

            rootCacheKey = GenerateRootCacheKey();
            StoreRootCacheKey();
        }
Exemplo n.º 43
0
        public MemoryCache(int expiry)
        {
#if NET451
            _cache         = System.Runtime.Caching.MemoryCache.Default;
            _policyFactory = () => new CacheItemPolicy();
#else
            _cacheOptions = new MemoryCacheEntryOptions
            {
                SlidingExpiration = TimeSpan.FromMinutes(expiry)
            };
            _cache = new Microsoft.Extensions.Caching.Memory.MemoryCache(new MemoryCacheOptions());
#endif
        }
Exemplo n.º 44
0
            public MemoryCache(string regionName, IDictionary <string, string> properties)
            {
                this.regionName = regionName;
                this.policy     = new CacheItemPolicy()
                {
                    SlidingExpiration = GetExpiration(properties),
                    Priority          = GetPriority(properties)
                };

                this.cache        = System.Runtime.Caching.MemoryCache.Default;
                this.rootCacheKey = GenerateRootCacheKey();

                this.policy.ChangeMonitors.Add(
                    this.cache.CreateCacheEntryChangeMonitor(new[] { rootCacheKey }, regionName)
                    );
            }
        // getPersonTkn() - Get a person's token.
        public static token getPersonTkn()
        {
            // Extract my tokenID
            string myTokenID = HttpContext.Current.Request.Headers["majama60"];

            // Get token object from cache
            System.Runtime.Caching.MemoryCache memCache = System.Runtime.Caching.MemoryCache.Default;
            var res = memCache.Get(myTokenID);

            if (res == null)
            {
                return(null);
            }
            else
            {
                token myToken = (token)res;
                return(myToken);
            }
        }
Exemplo n.º 46
0
        public static IEnumerable <DTO.LocationDTO> GetLocations()
        {
            HttpClient client = ApiLocationClient();
            var        cache  = new System.Runtime.Caching.MemoryCache("locations");

            var cacheItemPolicy = new CacheItemPolicy()
            {
                //Set your Cache expiration.
                AbsoluteExpiration = DateTime.Now.AddDays(1)
            };
            IEnumerable <DTO.LocationDTO> result;

            if (cache["locations"] == null)
            {
                result             = GetLocationsFromervice(client);;
                cache["locations"] = result;
            }
            else
            {
                result = (IEnumerable <DTO.LocationDTO>)cache["locations"];
            }

            return(result);
        }
Exemplo n.º 47
0
        public CacheRepository(IRepository repository, IEventStore eventStore)
        {
            if (repository == null)
            {
                throw new ArgumentNullException("repository");
            }
            if (eventStore == null)
            {
                throw new ArgumentNullException("eventStore");
            }

            _repository    = repository;
            _eventStore    = eventStore;
            _cache         = System.Runtime.Caching.MemoryCache.Default;
            _policyFactory = () => new CacheItemPolicy
            {
                SlidingExpiration = new TimeSpan(0, 0, 15, 0),
                RemovedCallback   = x =>
                {
                    object o;
                    _locks.TryRemove(x.CacheItem.Key, out o);
                }
            };
        }
Exemplo n.º 48
0
 /// <summary>
 ///     初始化一个<see cref="MemoryCache" />实例。
 /// </summary>
 /// <param name="region"></param>
 public MemoryCache(string region)
 {
     _cache  = new System.Runtime.Caching.MemoryCache(region);
     _region = region;
 }
 public MemoryCacheManagement()
 {
     _cache = MemoryCache.Default;
 }
Exemplo n.º 50
0
 /// <summary>
 /// Инициализирует новый экземпляр класса <see cref="MemoryCacheProvider"/>.
 /// </summary>
 /// <param name="cache">
 /// The cache.
 /// </param>
 public MemoryCacheProvider(System.Runtime.Caching.MemoryCache cache)
 {
     this._cache = cache;
 }
Exemplo n.º 51
0
 public static void Set(string key, object o, int timeout)
 {
     System.Runtime.Caching.MemoryCache cache = System.Runtime.Caching.MemoryCache.Default;
     cache.Add(TransformKey(key), o, DateTime.Now.AddMinutes(timeout));
 }
Exemplo n.º 52
0
 public static bool Exists(string key)
 {
     System.Runtime.Caching.MemoryCache cache = System.Runtime.Caching.MemoryCache.Default;
     return(cache.Contains(TransformKey(key)));
 }
Exemplo n.º 53
0
 public MemoryCache(System.Runtime.Caching.MemoryCache memoryCache)
 {
     _regionCache = new RegionCache(memoryCache);
 }
Exemplo n.º 54
0
 public MemoryCache(string name) : base()
 {
     _memoryCache = new System.Runtime.Caching.MemoryCache(name);
 }
 public override void ClearAll()
 {
     _cache.Dispose();
     _cache = System.Runtime.Caching.MemoryCache.Default;
 }
Exemplo n.º 56
0
 public MemoryCacheProvider(string name = "Default", NameValueCollection config = null)
 {
     Cache = new System.Runtime.Caching.MemoryCache(name, config);
 }
Exemplo n.º 57
0
 public MemoryCache(string cacheName)
 {
     _cache = new System.Runtime.Caching.MemoryCache(cacheName);
 }
Exemplo n.º 58
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MemoryCache"/> class.
 /// </summary>
 public MemoryCache()
 {
     this.cache = System.Runtime.Caching.MemoryCache.Default;
 }
Exemplo n.º 59
0
 public MemoryCacheProvider()
 {
     _cache = System.Runtime.Caching.MemoryCache.Default;
 }
Exemplo n.º 60
0
 MemoryCache()
 {
     _cache           = System.Runtime.Caching.MemoryCache.Default;
     _defaultSettings = new Settings();
 }