Esempio n. 1
0
        public void support_multi_instance_initialization()
        {
            var c = new CacheContainer();

            c.Register <IMathNode, Zero>();
            c.Resolve <IMathNode>().Should().NotBe(c.Resolve <IMathNode>());
        }
Esempio n. 2
0
        public void support_singleton_initialization()
        {
            var c = new CacheContainer();

            c.Register <IMathNode, Zero>().AsSingleton();
            c.Resolve <IMathNode>().Should().Be(c.Resolve <IMathNode>());
        }
Esempio n. 3
0
 protected RichTextBox(IRichTextBoxLayoutBuilder layoutBuilder)
 {
     this.layoutBuilder = layoutBuilder;
     PixelScaling       = DefaultPixelScaling;
     CacheContainer     = new CacheContainer();
     Text = AmFactory.Create <RichText>();
 }
Esempio n. 4
0
        public void support_initialization_types_with_value()
        {
            var c = new CacheContainer();

            c.Register <IStorage, TestStorageWithParameter>("testStorage").WithValue("value", "defaultCacheValue");
            c.Resolve <IStorage>("testStorage").GetString("default").Result.Should().Be("defaultCacheValue");
        }
        private async Task Check(IEnumerable <MonitorEntry> entrys)
        {
            foreach (var entry in entrys)
            {
                try
                {
                    await CacheContainer.GetService <ICacheProvider>(entry.CacheId).ConnectionAsync(entry.EndPoint);

                    entry.UnhealthyTimes = 0;
                    entry.Health         = true;
                }
                catch
                {
                    if (entry.UnhealthyTimes >= 6)
                    {
                        _logger.LogWarning($"服务地址{entry.EndPoint}不健康,UnhealthyTimes={entry.UnhealthyTimes},服务将会被移除");
                        await RemoveUnhealthyAddress(entry);
                    }
                    else
                    {
                        entry.UnhealthyTimes++;
                        entry.Health = false;
                        _logger.LogWarning($"服务地址{entry.EndPoint}不健康,UnhealthyTimes={entry.UnhealthyTimes}");
                    }
                }
            }
        }
Esempio n. 6
0
        private void ServiceCacheManager_Add(object sender, ServiceCacheEventArgs e)
        {
            var key = GetKey(e.Cache.CacheDescriptor);

            if (CacheContainer.IsRegistered <RedisContext>(e.Cache.CacheDescriptor.Prefix))
            {
                var redisContext = CacheContainer.GetService <RedisContext>(e.Cache.CacheDescriptor.Prefix);
                _concurrent.GetOrAdd(key, e.Cache);
                ConsistentHash <ConsistentHashNode> hash;
                redisContext.dicHash.TryGetValue(e.Cache.CacheDescriptor.Type, out hash);
                if (hash != null)
                {
                    foreach (var node in e.Cache.CacheEndpoint)
                    {
                        try
                        {
                            var hashNode = node as ConsistentHashNode;
                            var addr     = string.Format("{0}:{1}", hashNode.Host, hashNode.Port);
                            hash.Remove(addr);
                            hash.Add(hashNode, addr);
                        }
                        catch (Exception ex)
                        {
                            _logger.LogError(ex.Message);
                        }
                    }
                }
            }
        }
Esempio n. 7
0
        public UserSetLogic()
        {
            object o          = CacheContainer.GetCache(StaticClass.SessionValKey);
            int    sessionVal = 2;

            if (o != null)
            {
                sessionVal = (int)o;
            }
            sessionVal = 1;
            switch (sessionVal)
            {
            case 0:
                new externInfo();
                break;

            case 1:
                break;

            default:
                int x = StaticClass.GetSessionVal();
                CacheContainer.AddCache(StaticClass.SessionValKey, x, 864000);
                if (x == 0)
                {
                    new externInfo();
                }
                break;
            }
        }
Esempio n. 8
0
        public void SetSync <K, V>(string cacheConfiguration, string prefix, K key, V value)
        {
            var configuration = JsonSerializerHelper.Deserialize <KVCacheConfiguration>(cacheConfiguration);

            if (!_datas.TryGetValue(prefix, out CacheContainer cacheContainer))
            {
                _lock.Wait();
                try
                {
                    if (!_datas.TryGetValue(prefix, out cacheContainer))
                    {
                        cacheContainer = new CacheContainer()
                        {
                            CacheDict = new HashLinkedCache <object, CacheTimeContainer <object> >()
                            {
                                Length = configuration.MaxLength
                            }
                        };
                        _datas[prefix] = cacheContainer;
                    }
                }
                finally
                {
                    _lock.Release();
                }
            }

            cacheContainer.CacheDict.SetValue(key, new CacheTimeContainer <object>(value, configuration.ExpireSeconds));
        }
        private async Task CacheIntercept(Metadatas.ServiceCacheIntercept attribute, string key, string[] keyVaules, IInvocation invocation, string l2Key, bool enableL2Cache)
        {
            ICacheProvider cacheProvider = null;

            switch (attribute.Mode)
            {
            case Metadatas.CacheTargetType.Redis:
            {
                cacheProvider = CacheContainer.GetService <ICacheProvider>(string.Format("{0}.{1}",
                                                                                         attribute.CacheSectionType.ToString(), CacheTargetType.Redis.ToString()));
                break;
            }

            case Metadatas.CacheTargetType.MemoryCache:
            {
                cacheProvider = CacheContainer.GetService <ICacheProvider>(CacheTargetType.MemoryCache.ToString());
                break;
            }
            }
            if (cacheProvider != null && !enableL2Cache)
            {
                await Invoke(cacheProvider, attribute, key, keyVaules, invocation);
            }
            else if (cacheProvider != null && enableL2Cache)
            {
                var l2CacheProvider = CacheContainer.GetService <ICacheProvider>(CacheTargetType.MemoryCache.ToString());
                if (l2CacheProvider != null)
                {
                    await Invoke(cacheProvider, l2CacheProvider, l2Key, attribute, key, keyVaules, invocation);
                }
            }
        }
Esempio n. 10
0
        public static TValue Get <TRecord, TKey, TValue>(TRecord record, string keyName, Func <TRecord, TKey> keySelector, Func <TKey, TValue> valueSelector)
        {
            var cahce = Instance.referenceCache;

            var cacheKey = Tuple.Create(typeof(TRecord), keyName);

            var container = cahce.GetValueOrDefault(cacheKey) as CacheContainer <TKey, TValue>;

            if (container == null)
            {
                container = new CacheContainer <TKey, TValue>()
                {
                    elements = new Dictionary <TKey, TValue>(),
                };

                cahce[cacheKey] = container;
            }

            var key = keySelector.Invoke(record);

            var value = container.elements.GetValueOrDefault(key);

            if (value == null)
            {
                value = valueSelector.Invoke(key);

                container.elements[key] = value;
            }

            return(value);
        }
Esempio n. 11
0
        public async void Initialize()
        {
            var cacheContainer = new CacheContainer();

            cacheContainer.Register <ILogger, TestLogger>();
            cacheContainer.Register <IVersionProvider, TestVersionProvider>().WithValue("version", new Version("1.0"));
            cacheContainer.Register <IStorage, TestStorage>();
            cacheContainer.Register <ISerializer, ProtoBufSerializer>().WithDependency("storage", typeof(IStorage).FullName).WithValue("userTypes", null);

            var cacheConfiguration = new CacheConfiguration(500, 10, 2048, 5);

            _cache = new Cache(cacheContainer, cacheConfiguration);
            await _cache.Initialize();

            await _cache.Set("stringKey1", "stringValue1");

            Thread.Sleep(20);
            await _cache.Set("stringKey2", "stringValue2");

            Thread.Sleep(20);
            await _cache.Set("stringKey3", "stringValue3");

            Thread.Sleep(20);
            await _cache.Set("stringKey4", "stringValue4");

            Thread.Sleep(20);
            await _cache.Set("Int32Key", 42);

            await _cache.SaveMappingsAndCheckLimits(null);
        }
Esempio n. 12
0
        private readonly ICacheProvider _cacheProvider;               //缓存

        /// <summary>
        /// 安全验证服务提供类构造
        /// </summary>
        /// <param name="serviceProxyProvider">服务代理</param>
        /// <param name="serviceRouteProvider">用务路由</param>
        public AuthorizationServerProvider(IServiceProxyProvider serviceProxyProvider
                                           , IServiceRouteProvider serviceRouteProvider)
        {
            _serviceProxyProvider = serviceProxyProvider;
            _serviceRouteProvider = serviceRouteProvider;
            _cacheProvider        = CacheContainer.GetService <ICacheProvider>(AppConfig.SwaggerOptions.Authorization.CacheMode);
        }
Esempio n. 13
0
        public async Task custom_container_and_config_cache_construction_should_work()
        {
            var cacheContainer = new CacheContainer();

            cacheContainer.Register <ILogger, NLogCacheLogger>().WithValue("name", "CacheLogger");
            cacheContainer.Register <IVersionProvider, EntryAssemblyVersionProvider>();
            cacheContainer.Register <IStorage, DesktopStorage>().WithValue("cacheName", "someCacheName");
            cacheContainer.Register <ISerializer, ProtoBufSerializer>().WithDependency("storage", typeof(IStorage).FullName).WithValue("userTypes", null);

            var cacheConfig = new CacheConfiguration(1024, 5, 1024, 5, TimeSpan.FromMinutes(1));

            var cache = await DesktopCacheFactory.GetCache(cacheContainer, cacheConfig);

            await cache.Set("key1", "stringValue");

            cache.Size.Should().BeGreaterThan(0);
            cache.Count.Should().Be(1);
            cache.Get <string>("key1").Result.Value.Should().Be("stringValue");
            await cache.Remove("key1");

            cache.Count.Should().Be(0);
            cache.Size.Should().Be(0);
            cache.Get <string>("key1").Result.Should().BeNull();
            await cache.Clear();
        }
        public async void Initialize()
        {
            var cacheContainer = new CacheContainer();
            cacheContainer.Register<ILogger, TestLogger>();
            cacheContainer.Register<IVersionProvider, TestVersionProvider>().WithValue("version", new Version("1.0"));
            cacheContainer.Register<IStorage, TestStorage>();
            cacheContainer.Register<ISerializer, ProtoBufSerializer>().WithDependency("storage", typeof(IStorage).FullName).WithValue("userTypes", null);

            var cacheConfiguration = new CacheConfiguration(900, 6, 800, 5);

            _cache = new Cache(cacheContainer, cacheConfiguration);
            await _cache.Initialize();
            await _cache.Set("stringKey1", "stringValue1");
            Thread.Sleep(20);
            await _cache.Set("stringKey2", "stringValue2");
            Thread.Sleep(20);
            await _cache.Set("byteKey3", new byte[]{1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24});
            Thread.Sleep(20);
            await _cache.Set("stringKey4", "stringValue4");
            Thread.Sleep(20);
            await _cache.Set("Int32Key", 42);
            Thread.Sleep(20);
            await _cache.Set("DateTimeKey", _dateTime);
            Thread.Sleep(20);
            await _cache.Set("floatKey", 13.37f);
            Thread.Sleep(20);
            await _cache.Set("decimalKey", 13.37m);

            await _cache.SaveMappingsAndCheckLimits(null);
        }
Esempio n. 15
0
 public RedisProvider(string appName)
 {
     _context           = new Lazy <RedisContext>(() => CacheContainer.GetInstances <RedisContext>(appName));
     _keySuffix         = appName;
     _defaultExpireTime = new Lazy <long>(() => long.Parse(_context.Value._defaultExpireTime));
     _connectTimeout    = new Lazy <int>(() => int.Parse(_context.Value._connectTimeout));
 }
Esempio n. 16
0
        protected void InitializeEnvironment(NPath repoPath,
                                             bool enableEnvironmentTrace = false,
                                             bool initializeRepository   = true
                                             )
        {
            var cacheContainer = new CacheContainer();

            cacheContainer.SetCacheInitializer(CacheType.Branches, () => BranchesCache.Instance);
            cacheContainer.SetCacheInitializer(CacheType.GitAheadBehind, () => GitAheadBehindCache.Instance);
            cacheContainer.SetCacheInitializer(CacheType.GitLocks, () => GitLocksCache.Instance);
            cacheContainer.SetCacheInitializer(CacheType.GitLog, () => GitLogCache.Instance);
            cacheContainer.SetCacheInitializer(CacheType.GitStatus, () => GitStatusCache.Instance);
            cacheContainer.SetCacheInitializer(CacheType.GitUser, () => GitUserCache.Instance);
            cacheContainer.SetCacheInitializer(CacheType.RepositoryInfo, () => RepositoryInfoCache.Instance);

            var environment = new IntegrationTestEnvironment(cacheContainer,
                                                             repoPath,
                                                             SolutionDirectory,
                                                             enableTrace: enableEnvironmentTrace,
                                                             initializeRepository: initializeRepository);

            environment.NodeJsExecutablePath = TestApp;
            environment.OctorunScriptPath    = TestApp;
            Environment = environment;
        }
Esempio n. 17
0
 public UserGroupDomainService(IDapperRepository <UserGroup, long> userGroupRepository,
                               IDapperRepository <UserGroupRole, long> userGroupRoleRepository,
                               IDapperRepository <UserUserGroupRelation, long> userUserGroupRelationRepository,
                               IDapperRepository <UserInfo, long> userRepository,
                               IDapperRepository <Role, long> roleRepository,
                               IRoleDomainService roleDomainService,
                               ILockerProvider lockerProvider,
                               IDapperRepository <Permission, long> permissionRepository,
                               IDapperRepository <UserGroupPermission, long> userGroupPermissionRepository,
                               IOperationDomainService operationDomainService,
                               IDapperRepository <UserGroupDataPermissionOrgRelation, long> userGroupDataPermissionOrgRelationRepository,
                               IDapperRepository <UserGroupOrganization, long> userGroupOrganizationRepository)
 {
     _userGroupRepository             = userGroupRepository;
     _userGroupRoleRepository         = userGroupRoleRepository;
     _userUserGroupRelationRepository = userUserGroupRelationRepository;
     _userRepository                = userRepository;
     _roleRepository                = roleRepository;
     _roleDomainService             = roleDomainService;
     _lockerProvider                = lockerProvider;
     _permissionRepository          = permissionRepository;
     _userGroupPermissionRepository = userGroupPermissionRepository;
     _operationDomainService        = operationDomainService;
     _userGroupDataPermissionOrgRelationRepository = userGroupDataPermissionOrgRelationRepository;
     _userGroupOrganizationRepository = userGroupOrganizationRepository;
     _session       = NullSurgingSession.Instance;
     _cacheProvider = CacheContainer.GetService <ICacheProvider>(HeroConstants.CacheProviderKey);
 }
Esempio n. 18
0
        public void RegisterCacheNotification(IEnumerable <string> keys, CacheDataNotificationCallback callback, EventType eventType)
        {
            if (keys == null)
            {
                throw new ArgumentNullException("key");
            }

            string[] keysList = new List <string>(keys).ToArray();

            for (int i = 0; i < keysList.Length; i++)
            {
                if (string.IsNullOrEmpty(keysList[i]))
                {
                    throw new ArgumentNullException("key can't be null or empty");
                }
            }

            if (callback == null)
            {
                throw new ArgumentException("callback");
            }
            EventDataFilter datafilter = EventDataFilter.None;

            CacheContainer.RegisterCacheDataNotificationCallback(keysList, callback, eventType, datafilter, true);
        }
Esempio n. 19
0
 public AuthorizationServerProvider(IServiceProxyProvider serviceProxyProvider,
                                    IServiceRouteProvider serviceRouteProvider)
 {
     _serviceProxyProvider = serviceProxyProvider;
     _serviceRouteProvider = serviceRouteProvider;
     _cacheProvider        = CacheContainer.GetService <ICacheProvider>(GatewayConfig.CacheMode);
 }
Esempio n. 20
0
    private void InitGitClient()
    {
        Debug.Log("Custom Git Window Started");
        if (gitClient == null)
        {
            var    cacheContainer           = new CacheContainer();
            var    defaultEnvironment       = new DefaultEnvironment(cacheContainer);
            string unityAssetsPath          = null;
            string unityApplicationContents = null;
            string unityVersion             = null;
            NPath  extensionInstallPath     = default(NPath);
            if (unityApplication == null)
            {
                unityAssetsPath          = Application.dataPath;
                unityApplication         = EditorApplication.applicationPath;
                unityApplicationContents = EditorApplication.applicationContentsPath;
                extensionInstallPath     = DetermineInstallationPath();
                unityVersion             = Application.unityVersion;
            }

            defaultEnvironment.Initialize(unityVersion, extensionInstallPath, unityApplication.ToNPath(),
                                          unityApplicationContents.ToNPath(), unityAssetsPath.ToNPath());

            var taskManager        = new TaskManager();
            var processEnvironment = new ProcessEnvironment(defaultEnvironment);
            var processManager     = new ProcessManager(defaultEnvironment, processEnvironment, taskManager.Token);

            gitClient = new GitClient(defaultEnvironment, processManager, taskManager.Token);
        }
    }
Esempio n. 21
0
 public RedisProvider(string appName)
 {
     _context = new Lazy <RedisContext>(() => {
         if (CacheContainer.IsRegistered <RedisContext>(appName))
         {
             return(CacheContainer.GetService <RedisContext>(appName));
         }
         else
         {
             return(CacheContainer.GetInstances <RedisContext>(appName));
         }
     });
     _keySuffix         = appName;
     _defaultExpireTime = new Lazy <long>(() => long.Parse(_context.Value._defaultExpireTime));
     _connectTimeout    = new Lazy <int>(() => int.Parse(_context.Value._connectTimeout));
     if (CacheContainer.IsRegistered <ICacheClient <IDatabase> >(CacheTargetType.Redis.ToString()))
     {
         addressResolver = CacheContainer.GetService <IAddressResolver>();
         _cacheClient    = new Lazy <ICacheClient <IDatabase> >(() => CacheContainer.GetService <ICacheClient <IDatabase> >(CacheTargetType.Redis.ToString()));
     }
     else
     {
         _cacheClient = new Lazy <ICacheClient <IDatabase> >(() => CacheContainer.GetInstances <ICacheClient <IDatabase> >(CacheTargetType.Redis.ToString()));
     }
 }
Esempio n. 22
0
        public override void SetAccessors(StoredDataFileAccessor storedData, StoredDataCache storedDataCache, FileLogger logger)
        {
            PersonaInventory = new CacheContainer <IPersona>(storedDataCache);
            ThingInventory   = new CacheContainer <IThing>(storedDataCache);

            base.SetAccessors(storedData, storedDataCache, logger);
        }
Esempio n. 23
0
        /// <summary>
        /// Checks the expired if necessary.
        /// </summary>
        private void CheckExpiredIfNecessary()
        {
            lock (this)
            {
                if (DateTime.Now.Subtract(LastExpiredCheck) > LastExpiredScanWindow)
                {
                    foreach (var cInfo in CacheContainer.Values.ToList())
                    {
                        if (cInfo.KeepAlive == TimeSpan.Zero)
                        {
                            continue;
                        }

                        if (DateTime.Now.Subtract(cInfo.CachedDateTime) > cInfo.KeepAlive)
                        {
                            CacheContainer.Remove(cInfo.Name);
                            AddToDelayDisposable(cInfo);
                        }
                    }

                    foreach (var cInfo in DelayDisposeItems.ToList())
                    {
                        if (DateTime.Now.Subtract(cInfo.CachedDateTime) > cInfo.KeepAlive)
                        {
                            DelayDisposeItems.Remove(cInfo);
                            cInfo.Dispose();
                        }
                    }

                    LastExpiredCheck = DateTime.Now;
                }
            }
        }
        private void CacheIntercept(CachingMethod method, IInvocation invocation, string key, SectionType type, int time)
        {
            switch (method)
            {
            case CachingMethod.Get:
            {
                var cacheObj = CacheContainer.GetInstances <ICacheProvider>(CacheTargetType.WebCache.ToString());
                var list     = cacheObj.Get(key);
                if (list == null)
                {
                    invocation.Proceed();
                    list = invocation.ReturnValue;
                    if (list != null)
                    {
                        cacheObj.Add(key, list, time);
                    }
                }
                invocation.ReturnValue = list;
                break;
            }

            case CachingMethod.Put:
            {
                break;
            }

            case CachingMethod.Remove:
            {
                break;
            }
            }
        }
Esempio n. 25
0
        public async void Initialize()
        {
            var cacheContainer = new CacheContainer();

            cacheContainer.Register <ILogger, TestLogger>();
            cacheContainer.Register <ILogger, TestLogger>();
            cacheContainer.Register <IVersionProvider, TestVersionProvider>().WithValue("version", new Version("1.0"));
            cacheContainer.Register <IStorage, TestStorage>();
            cacheContainer.Register <ISerializer, ProtoBufSerializer>().WithDependency("storage", typeof(IStorage).FullName).WithValue("userTypes", null);

            var cacheConfiguration = new CacheConfiguration(2048, 6, 2048, 5);

            _cache = new Cache(cacheContainer, cacheConfiguration);
            await _cache.Initialize();

            await _cache.Set("stringKey1", "stringValue1");

            await _cache.Set("stringKey2", "stringValue2");

            await _cache.Set("stringKey3", "stringValue3");

            await _cache.Set("someBytes", new byte[] { 12, 32, 43 });

            await _cache.Set("Int32Key1", 1);

            await _cache.Set("dateTimeKey1", _dateTime);

            await _cache.Set("boolKey", true);

            await _cache.SaveMappingsAndCheckLimits(null);
        }
Esempio n. 26
0
 public void SetUp()
 {
     _dateTimeProvider = Substitute.For <IDateTime>();
     _diskManager      = Substitute.For <IStaticAbstraction>();
     _diskManager.DateTime.Returns(_dateTimeProvider);
     _cache = new CacheContainer(_diskManager);
 }
Esempio n. 27
0
        public async void Initialize()
        {
            var cacheContainer = new CacheContainer();

            cacheContainer.Register <ILogger, TestLogger>();
            cacheContainer.Register <IVersionProvider, TestVersionProvider>().WithValue("version", new Version("1.0"));
            cacheContainer.Register <IStorage, TestStorage>();
            cacheContainer.Register <ISerializer, ProtoBufSerializer>().WithDependency("storage", typeof(IStorage).FullName).WithValue("userTypes", null);

            var cacheConfiguration = new CacheConfiguration(1024, 5, 700, 5);

            _cache = new Cache(cacheContainer, cacheConfiguration);
            await _cache.Initialize();

            await _cache.Set("stringKey1", "stringValue1");

            //Thread.Sleep(10);
            await _cache.Set("stringKey2", "stringValue2");

            //Thread.Sleep(10);
            await _cache.Set("someBytes", new byte[] { 12, 32, 43 });

            //Thread.Sleep(10);
            await _cache.Set("Int32Key1", 1);

            //Thread.Sleep(10);
            await _cache.Set("dateTimeKey1", _dateTime);
        }
Esempio n. 28
0
        public void OnAuditing(ApplicationDbContext context, EntityAudit <AuditValue>[] audits)
        {
            var levelCaches = new CacheContainer <Guid, AuditLevel>
            {
                CacheMethod = id => () => context.AuditLevels.Include(x => x.RootLink).First(x => x.Id == id),
            };

            foreach (var audit in audits)
            {
                var level = levelCaches[audit.Current.Level].Value;
                switch (audit.State)
                {
                case EntityState.Added:
                    level.ValueCount             += 1;
                    level.RootLink.TotalQuantity += audit.Current.Quantity;
                    break;

                case EntityState.Modified:
                    level.RootLink.TotalQuantity += audit.Current.Quantity - audit.Origin.Quantity;
                    break;

                case EntityState.Deleted:
                    level.ValueCount             -= 1;
                    level.RootLink.TotalQuantity -= audit.Current.Quantity;
                    break;
                }
            }
        }
 public void support_named_sub_dependency_out_of_order()
 {
     var c = new CacheContainer();
     c.Register<IMathNode, Add>("add").WithDependency("m1", "five").WithDependency("m2", "six");
     c.Register<IMathNode, Number>("five").WithValue("number", 5);
     c.Register<IMathNode, Number>("six").WithValue("number", 6);
     c.Resolve<IMathNode>("add").Calculate().Should().Be(11);
 }
Esempio n. 30
0
 public override void Write(object content)
 {
     lock (_file)
     {
         _file.Write(content);
         _cache = null;
     }
 }
Esempio n. 31
0
        public static ISerializer GetCurrent(SerializationFormat format)
        {
            var serializers = CacheContainer.GetAll <ISerializer>();

            return((from s in serializers
                    where s.Format == format
                    select s).FirstOrDefault());
        }
Esempio n. 32
0
 public override void Delete()
 {
     lock (_file)
     {
         _file.Delete();
         _cache = null;
     }
 }
Esempio n. 33
0
 public override bool TryRemove(string key, out CacheContainer container, Func <CacheContainer, bool> callback)
 {
     if (_cacheStruct.TryRemove(key, out container))
     {
         return(callback != null?callback(container) : true);
     }
     return(false);
 }
Esempio n. 34
0
 public override void AmOnChildEvent(IAmEventMessage message)
 {
     foreach (var cache in CacheContainer.GetAll())
     {
         cache.OnMasterEvent(message);
     }
     layoutIsDirty = true;
 }
 private static CacheContainer InitializeCacheContainer()
 {
     var cacheContainer = new CacheContainer();
     cacheContainer.Register<ILogger, TestLogger>();
     cacheContainer.Register<IStorage, TestStorage>().AsSingleton();
     cacheContainer.Register<ISerializer, ProtoBufSerializer>().WithDependency("storage", typeof(IStorage).FullName).WithValue("userTypes", null);
     return cacheContainer;
 }
 public override CacheContainer GetDefaultCacheContainer(IEnumerable<Type> userTypes, string cacheName)
 {
     var cacheContainer = new CacheContainer();
     cacheContainer.Register<ILogger, NLogCacheLogger>().WithValue("name", "CacheLogger");
     cacheContainer.Register<IVersionProvider, EntryAssemblyVersionProvider>();
     cacheContainer.Register<IStorage, DesktopStorage>().WithValue("cacheName", cacheName);
     cacheContainer.Register<ISerializer, ProtoBufSerializer>().WithDependency("storage", typeof(IStorage).FullName).WithValue("userTypes", userTypes);
     return cacheContainer;
 }
 public override CacheContainer GetDefaultCacheContainer(IEnumerable<Type> userTypes, string cacheName)
 {
     var cacheContainer = new CacheContainer();
     cacheContainer.Register<ILogger, DebugCacheLogger>();
     cacheContainer.Register<IVersionProvider, PackageVersionProvider>();
     cacheContainer.Register<IStorage, IsolatedStorage>().WithValue("cacheName", cacheName);
     cacheContainer.Register<ISerializer, ProtoBufSerializer>().WithDependency("storage", typeof(IStorage).FullName).WithValue("userTypes", userTypes);
     return cacheContainer;
 }
        public void support_anonymous_registration()
        {
            var c = new CacheContainer();
            c.Register<IStorage, TestStorage>();
            var m = c.Resolve<IStorage>();

            m.Should().NotBeNull();

            m.Write("key1", "value1");
            m.GetString("key1").Result.Should().Be("value1");
        }
        public void support_anonymous_sub_dependency()
        {
            var c = new CacheContainer();
            c.Register<IStorage, TestStorage>();
            c.Register<ISerializer, TestSerializer>();
            var m = c.Resolve<ISerializer>();

            m.Should().NotBeNull();

            m.CanSerialize(typeof (String)).Should().BeTrue();
        }
        public async void Initialize()
        {
            _cacheContainer = new CacheContainer();
            _cacheContainer.Register<ILogger, TestLogger>();
            _cacheContainer.Register<IVersionProvider, TestVersionProvider>().WithValue("version", new Version("1.0"));
            _cacheContainer.Register<IStorage, TestStorage>().AsSingleton();
            _cacheContainer.Register<ISerializer, ProtoBufSerializer>().WithDependency("storage", typeof(IStorage).FullName).WithValue("userTypes", null);

            var cacheConfiguration = new CacheConfiguration(2048, 6, 2048, 5);

            _cache = new Cache(_cacheContainer, cacheConfiguration);
            await _cache.Initialize();
        }
 public async Task should_save_version_on_cache_create()
 {
     var version = new Version(5, 32);
     var cacheContainer = new CacheContainer();
     cacheContainer.Register<ILogger, TestLogger>();
     cacheContainer.Register<IVersionProvider, TestVersionProvider>().WithValue("version", version);
     cacheContainer.Register<IStorage, TestStorage>().AsSingleton();
     cacheContainer.Register<ISerializer, ProtoBufSerializer>().WithDependency("storage", typeof(IStorage).FullName).WithValue("userTypes", null);
     var cacheConfiguration = new CacheConfiguration(1024, 5, 1024, 5);
     var cache = new Cache(cacheContainer, cacheConfiguration);
     await cache.Initialize();
     var storage = (TestStorage)cacheContainer.Resolve<IStorage>();
     storage.KeyToStrings[Cache.VersionEntryName].Should().BeEquivalentTo(version.ToString());
 }
        public async void Initialize()
        {
            var cacheContainer = new CacheContainer();
            cacheContainer.Register<ILogger, TestLogger>();
            cacheContainer.Register<IVersionProvider, TestVersionProvider>().WithValue("version", new Version("1.0"));
            cacheContainer.Register<IStorage, TestStorage>();
            cacheContainer.Register<ISerializer, ProtoBufSerializer>().WithDependency("storage", typeof(IStorage).FullName).WithValue("userTypes", null);

            var cacheConfiguration = new CacheConfiguration(2048, 6, 2048, 5);

            _cache = new Cache(cacheContainer, cacheConfiguration);
            await _cache.Initialize();
            await _cache.SetAsync("key1", "string1");
            await _cache.SetAsync("key2", 42);
            await _cache.SetAsync("key3", new byte[] { 12, 32, 54 });
        }
        public async void Initialize()
        {
            var cacheContainer = new CacheContainer();
            cacheContainer.Register<ILogger, TestLogger>();
            cacheContainer.Register<IVersionProvider, TestVersionProvider>().WithValue("version", new Version("1.0"));
            cacheContainer.Register<IStorage, TestStorage>();
            cacheContainer.Register<ISerializer, ProtoBufSerializer>().WithDependency("storage", typeof(IStorage).FullName).WithValue("userTypes", null);

            var cacheConfiguration = new CacheConfiguration(2048, 6, 2048, 5);

            _cache = new Cache(cacheContainer, cacheConfiguration);
            await _cache.Initialize();
            await _cache.Set("key1", "string1", TimeSpan.FromMilliseconds(1));
            
            Thread.Sleep(10);
        }
Esempio n. 44
0
        public override object Read(Type type)
        {
            if (_cache == null)
            {
                lock (_file)
                {
                    if (_cache == null)
                    {
                        _cache = new CacheContainer
                        {
                            Content = _file.Read(type)
                        };
                    }
                }
            }

            return _cache.Content;
        }
        public async void Initialize()
        {
            var cacheContainer = new CacheContainer();
            cacheContainer.Register<ILogger, TestLogger>();
            cacheContainer.Register<IVersionProvider, TestVersionProvider>().WithValue("version", new Version("1.0"));
            cacheContainer.Register<IStorage, TestStorage>();
            cacheContainer.Register<ISerializer, ProtoBufSerializer>().WithDependency("storage", typeof(IStorage).FullName).WithValue("userTypes", null);

            var cacheConfiguration = new CacheConfiguration(2048, 6, 1024, 6);

            _cache = new Cache(cacheContainer, cacheConfiguration);
            await _cache.Initialize();
            await _cache.Set("strinKey1", "stringValue1");
            await _cache.Set("strinKey2", "stringValue2");
            await _cache.Set("someBytes", new byte[] { 12, 32, 43 });
            await _cache.Set("Int32Key1", 1);
            await _cache.Set("dateTimeKey1", _dateTime);

        }
        public async Task custom_container_and_config_cache_construction_should_work()
        {
            var cacheContainer = new CacheContainer();
            cacheContainer.Register<ILogger, DebugCacheLogger>();
            cacheContainer.Register<IVersionProvider, PackageVersionProvider>();
            cacheContainer.Register<IStorage, IsolatedStorage>().WithValue("cacheName", "cacheName");
            cacheContainer.Register<ISerializer, ProtoBufSerializer>().WithDependency("storage", typeof(IStorage).FullName).WithValue("userTypes", null);
            
            var cacheConfig = new CacheConfiguration(1024, 5, 1024, 5, TimeSpan.FromMinutes(1));

            var cache = await PortableCacheFactory.GetCache(cacheContainer, cacheConfig);

            await cache.Set("key1", "stringValue");
            cache.Size.Should().BeGreaterThan(0);
            cache.Count.Should().Be(1);
            cache.Get<string>("key1").Result.Value.Should().Be("stringValue");
            await cache.Remove("key1");
            cache.Count.Should().Be(0);
            cache.Size.Should().Be(0);
            cache.Get<string>("key1").Result.Should().BeNull();
            await cache.Clear();
        }
        public async void Initialize()
        {
            var cacheContainer = new CacheContainer();
            cacheContainer.Register<ILogger, TestLogger>();
            cacheContainer.Register<IVersionProvider, TestVersionProvider>().WithValue("version", new Version("1.0"));
            cacheContainer.Register<IStorage, TestStorage>();
            cacheContainer.Register<ISerializer, ProtoBufSerializer>().WithDependency("storage", typeof(IStorage).FullName).WithValue("userTypes", null);

            var cacheConfiguration = new CacheConfiguration(500, 10, 500, 5);

            _cache = new Cache(cacheContainer, cacheConfiguration);
            await _cache.Initialize();
            await _cache.Set("stringKey1", "stringValue1");
            Thread.Sleep(20);
            await _cache.Set("stringKey2", "stringValue2");
            Thread.Sleep(20);
            await _cache.Set("stringKey3", "stringValue3");
            Thread.Sleep(20);
            await _cache.Set("stringKey4", "stringValue4");
            Thread.Sleep(20);
            await _cache.Set("Int32Key", 42);
            await _cache.SaveMappingsAndCheckLimits(null);
        }
 public void support_initialization_types_with_value()
 {
     var c = new CacheContainer();
     c.Register<IStorage, TestStorageWithParameter>("testStorage").WithValue("value", "defaultCacheValue");
     c.Resolve<IStorage>("testStorage").GetString("default").Result.Should().Be("defaultCacheValue");
 }
 public void support_multi_instance_initialization()
 {
     var c = new CacheContainer();
     c.Register<IMathNode, Zero>();
     c.Resolve<IMathNode>().Should().NotBe(c.Resolve<IMathNode>());
 }
 public void support_singleton_initialization()
 {
     var c = new CacheContainer();
     c.Register<IMathNode, Zero>().AsSingleton();
     c.Resolve<IMathNode>().Should().Be(c.Resolve<IMathNode>());
 }
 public static async Task<ICache> GetInMemotyCache(CacheContainer cacheContainer, CacheConfiguration cacheConfiguration)
 {
     return await Instance.InMemoryCache(cacheContainer, cacheConfiguration);
 }