public void Clear()
 {
     using (CreateCrossPlatLock(_storageCreationProperties))
     {
         CacheStore.Clear();
     }
 }
示例#2
0
        public void Fetch_OnSave_test()
        {
            var root          = Substitute.For <ISite>();
            var cacheRegistry = new CacheRegistry(new TestCacheConfig());
            var cacheStore    = new CacheStore();
            var cache         = new Cache(cacheStore, cacheRegistry, root);

            async Task <IEnumerable <TestItem> > Task(ICache c) => await System.Threading.Tasks.Task.Run(() => new[]
            {
                new TestItem {
                    ItemId = 1
                },
                new TestItem {
                    ItemId = 3
                },
                new TestItem {
                    ItemId = 2
                }
            }).ConfigureAwait(false);

            cacheRegistry.Add(Task)
            .Span(300)
            .OnSave(x => x.OrderBy(y => y.ItemId));

            var result = cache.Fetch <TestItem>().ToList();

            Assert.That(result, Is.Not.Null);
            Assert.That(result.First().ItemId, Is.EqualTo(1));
            Assert.That(result.Last().ItemId, Is.EqualTo(3));
        }
示例#3
0
        static void Main(string[] args)
        {
            const string baseDirectory = "c:\\tmp\\PersistantCache";

            //var diskCache = new BPlusTreeCache<Thing>(baseDirectory, 1);

            var diskCache = new EsentPersistentDictionary(baseDirectory);

            PersistentCache = new CacheStore <PersistentCache.CacheItem>(baseDirectory, "1", null, "00:00:10", diskCache);

            Console.WriteLine("Creating Data");
            const int itemsToUse = 1000000;

            var items = GenerateList(itemsToUse, 20);

            items.Shuffle();

            //var temp = new CacheItem[itemsToUse];
            //items.CopyTo(temp);
            //var reversedItems = temp.Reverse().ToList();

            var items2 = GenerateList(itemsToUse, 20);

            items2.Shuffle();

            RunPersistanceCacheTest(new List <List <CacheItem> >(2)
            {
                items, items2
            });

            Console.ReadKey();
        }
示例#4
0
 /// <summary>
 /// 清楚所有缓存
 /// </summary>
 public static void ClearCache()
 {
     foreach (var item in CacheStore)
     {
         CacheStore.Remove(item.Key);
     }
 }
示例#5
0
        private long CacheStoreCreate(long memPtr)
        {
            var cacheStore = CacheStore.CreateInstance(memPtr, _handleRegistry);

            if (_ignite != null)
            {
                cacheStore.Init(_ignite);
            }
            else
            {
                lock (_initActions)
                {
                    if (_ignite != null)
                    {
                        cacheStore.Init(_ignite);
                    }
                    else
                    {
                        _initActions.Add(cacheStore.Init);
                    }
                }
            }

            return(cacheStore.Handle);
        }
示例#6
0
        /// <summary>
        /// Agrega la cabecera con los datos de la carga útil necesarios para autenticar a un usuario en el servicio Aspen.
        /// </summary>
        /// <param name="request">Solicitud a donde se agrega la cabecera.</param>
        /// <param name="jwtEncoder">Instancia del codificador del contenido de la carga útil.</param>
        /// <param name="apiSecret">Secreto de la aplicación que se utiliza para codificar el contenido del carga útil.</param>
        /// <param name="token">El token de autenticación emitido para el usuario.</param>
        /// <param name="username">La identificación del usuario autenticado.</param>
        /// <param name="device">La información asociada con el dispositivo del usuario.</param>
        public void AddSignedPayloadHeader(
            IRestRequest request,
            IJwtEncoder jwtEncoder,
            string apiSecret,
            string token,
            string username,
            IDeviceInfo device = null)
        {
            Throw.IfNull(request, nameof(request));
            Throw.IfNull(jwtEncoder, nameof(jwtEncoder));
            Throw.IfNullOrEmpty(apiSecret, nameof(apiSecret));
            Throw.IfNullOrEmpty(token, nameof(token));
            Throw.IfNullOrEmpty(username, nameof(username));

            IDeviceInfo deviceInfo = device ?? CacheStore.Get <DeviceInfo>(CacheKeys.CurrentDevice) ?? DeviceInfo.Current;
            Dictionary <string, object> payload = new Dictionary <string, object>();

            ServiceLocator.Instance.PayloadClaimsManager.AddNonceClaim(payload, ServiceLocator.Instance.NonceGenerator.GetNonce());
            ServiceLocator.Instance.PayloadClaimsManager.AddEpochClaim(payload, ServiceLocator.Instance.EpochGenerator.GetSeconds());
            ServiceLocator.Instance.PayloadClaimsManager.AddTokenClaim(payload, token);
            ServiceLocator.Instance.PayloadClaimsManager.AddUsernameClaim(payload, username);
            ServiceLocator.Instance.PayloadClaimsManager.AddDeviceIdClaim(payload, deviceInfo.DeviceId);
            string jwt = jwtEncoder.Encode(payload, apiSecret);

            request.AddHeader(ServiceLocator.Instance.RequestHeaderNames.PayloadHeaderName, jwt);
        }
示例#7
0
        /// <summary>
        /// Agrega la cabecera con los datos de la carga útil necesarios para autenticar a un usuario en el servicio Aspen.
        /// </summary>
        /// <param name="request">Solicitud a donde se agrega la cabecera.</param>
        /// <param name="jwtEncoder">Instancia del codificador del contenido de la carga útil.</param>
        /// <param name="apiSecret">Secreto de la aplicación que se utiliza para codificar el contenido del carga útil.</param>
        /// <param name="userIdentity">La información que se utiliza para autenticar la solicitud en función de un usuario.</param>
        public void AddSigninPayloadHeader(
            IRestRequest request,
            IJwtEncoder jwtEncoder,
            string apiSecret,
            IUserIdentity userIdentity)
        {
            Throw.IfNull(request, nameof(request));
            Throw.IfNull(jwtEncoder, nameof(jwtEncoder));
            Throw.IfNullOrEmpty(apiSecret, nameof(apiSecret));
            Throw.IfNull(userIdentity, nameof(userIdentity));

            IDeviceInfo deviceInfo = userIdentity.Device ??
                                     CacheStore.Get <DeviceInfo>(CacheKeys.CurrentDevice) ??
                                     DeviceInfo.Current;

            request.AddHeader(ServiceLocator.Instance.RequestHeaderNames.DeviceInfoHeaderName, deviceInfo.ToJson());
            CacheStore.Add(CacheKeys.CurrentDevice, deviceInfo);

            Dictionary <string, object> payload = new Dictionary <string, object>();

            ServiceLocator.Instance.PayloadClaimsManager.AddNonceClaim(payload, ServiceLocator.Instance.NonceGenerator.GetNonce());
            ServiceLocator.Instance.PayloadClaimsManager.AddEpochClaim(payload, ServiceLocator.Instance.EpochGenerator.GetSeconds());
            ServiceLocator.Instance.PayloadClaimsManager.AddDocTypeClaim(payload, userIdentity.DocType);
            ServiceLocator.Instance.PayloadClaimsManager.AddDocNumberClaim(payload, userIdentity.DocNumber);
            ServiceLocator.Instance.PayloadClaimsManager.AddPasswordClaim(payload, userIdentity.Password);
            ServiceLocator.Instance.PayloadClaimsManager.AddDeviceIdClaim(payload, deviceInfo.DeviceId);
            string jwt = jwtEncoder.Encode(payload, apiSecret);

            request.AddHeader(ServiceLocator.Instance.RequestHeaderNames.PayloadHeaderName, jwt);
        }
示例#8
0
        public void Basic_Put_Get_Remove()
        {
            using (var store = new CacheStore(null))
            {
                var tbl1 = store["t1"];

                for (int i = 0; i < 1000; i++)
                {
                    var bo = new businessObject {
                        ID = i, Name = "Xroemson-{0}".Args(i), IsGood = i % 7 == 0
                    };
                    Assert.IsTrue(tbl1.Put((ulong)i, bo));
                }

                Assert.AreEqual(1000, tbl1.Count);

                Assert.IsTrue(tbl1.Remove(115));

                Assert.AreEqual(999, tbl1.Count);

                Assert.AreEqual("Xroemson-12", tbl1.Get(12).ValueAs <businessObject>().Name);
                Assert.AreEqual(null, tbl1.Get(115));
                Assert.AreEqual("Xroemson-999", tbl1.Get(999).ValueAs <businessObject>().Name);
                Assert.AreEqual(true, tbl1.Get(7).ValueAs <businessObject>().IsGood);
            }
        }
        public void CreatesCorrectPolicy(int seconds)
        {
            var basePolicy = new CacheStore(TimeSpan.FromSeconds(seconds));
            var xml        = basePolicy.GetXml().ToString();

            xml.Should().Be($"<cache-store duration=\"{seconds}\" />");
        }
示例#10
0
        public JsonResult Delete(int id)
        {
            CacheStore.Remove <Tutor>(id.ToString());
            string message = $"User has been removed successfully!";

            return(Json(message, JsonRequestBehavior.AllowGet));
        }
示例#11
0
        public void ComplexKeyHashingStrategy_1()
        {
            using (var store = new CacheStore(null))
            {
                var strat = new ComplexKeyHashingStrategy(store);

                strat.Put("t1", "A", new businessObject {
                    ID = 000, Name = "Adoyan", IsGood = true
                });
                strat.Put("t1", "B", new businessObject {
                    ID = 234, Name = "Borisenko", IsGood = false
                });
                strat.Put("t1", "C", new businessObject {
                    ID = 342, Name = "Carov", IsGood = true
                });
                strat.Put("t2", "A", new businessObject {
                    ID = 2000, Name = "2Adoyan", IsGood = true
                });
                strat.Put("t2", "B", new businessObject {
                    ID = 2234, Name = "2Borisenko", IsGood = false
                });
                strat.Put("t2", "C", new businessObject {
                    ID = 2342, Name = "2Carov", IsGood = true
                });

                Assert.AreEqual("Adoyan", ((businessObject)strat.Get("t1", "A")).Name);
                Assert.AreEqual("Borisenko", ((businessObject)strat.Get("t1", "B")).Name);
                Assert.AreEqual("Carov", ((businessObject)strat.Get("t1", "C")).Name);

                Assert.AreEqual("2Adoyan", ((businessObject)strat.Get("t2", "A")).Name);
                Assert.AreEqual("2Borisenko", ((businessObject)strat.Get("t2", "B")).Name);
                Assert.AreEqual("2Carov", ((businessObject)strat.Get("t2", "C")).Name);
            }
        }
示例#12
0
        public void Configuration_UnNamedStore()
        {
            var conf = LaconicConfiguration.CreateFromString(CONF_SRC);

            using (var app = new ServiceBaseApplication(null, conf.Root))
            {
                using (var store = new CacheStore("SomeStoreThat will be configured from default store without name"))
                {
                    store.Configure(null);

                    Assert.AreEqual(true, store.ParallelSweep);
                    Assert.AreEqual(true, store.InstrumentationEnabled);

                    Assert.AreEqual(1234567, store.TableOptions["doctor"].BucketCount);
                    Assert.AreEqual(7, store.TableOptions["doctor"].RecPerPage);
                    Assert.AreEqual(19, store.TableOptions["doctor"].LockCount);
                    Assert.AreEqual(193, store.TableOptions["doctor"].MaxAgeSec);
                    Assert.AreEqual(true, store.TableOptions["doctor"].ParallelSweep);

                    Assert.AreEqual(451000000, store.TableOptions["PATIENT"].BucketCount);
                    Assert.AreEqual(17, store.TableOptions["PATIENT"].RecPerPage);
                    Assert.AreEqual(1025, store.TableOptions["PATIENT"].LockCount);
                    Assert.AreEqual(739, store.TableOptions["PATIENT"].MaxAgeSec);
                    Assert.AreEqual(true, store.TableOptions["PATIENT"].ParallelSweep);
                }
            }
        }
示例#13
0
        public void Put_Expire_Get()
        {
            using (var store = new CacheStore(null))
            {
                var tbl1 = store["t1"];

                for (int i = 0; i < 1000; i++)
                {
                    var bo = new businessObject {
                        ID = i, Name = "Suvorov-{0}".Args(i), IsGood = i % 7 == 0
                    };
                    Assert.IsTrue(tbl1.Put((ulong)i, bo, i < 500 ? 5 : 100));
                }

                Assert.AreEqual(1000, tbl1.Count);

                //warning: this timeout depends on how fast the store will purge garbage
                for (var spin = 0; spin < 20 && tbl1.Count != 500; spin++)
                {
                    System.Threading.Thread.Sleep(1000);
                }

                Assert.AreEqual(500, tbl1.Count);

                Assert.AreEqual(null, tbl1.Get(1));
                Assert.AreEqual(null, tbl1.Get(499));
                Assert.AreEqual("Suvorov-500", tbl1.Get(500).ValueAs <businessObject>().Name);
                Assert.AreEqual("Suvorov-999", tbl1.Get(999).ValueAs <businessObject>().Name);
            }
        }
示例#14
0
        private long CacheStoreCreate(void *target, long memPtr)
        {
            return(SafeCall(() =>
            {
                var cacheStore = CacheStore.CreateInstance(memPtr, _handleRegistry);

                if (_ignite != null)
                {
                    cacheStore.Init(_ignite);
                }
                else
                {
                    lock (_initActions)
                    {
                        if (_ignite != null)
                        {
                            cacheStore.Init(_ignite);
                        }
                        else
                        {
                            _initActions.Add(cacheStore.Init);
                        }
                    }
                }

                return cacheStore.Handle;
            }, true));
        }
示例#15
0
        public void Basic_Put_Get_HitCount()
        {
            using (var store = new CacheStore(null))
            {
                var tbl1 = store["t1"];

                for (int i = 0; i < 100; i++)
                {
                    var bo = new businessObject {
                        ID = i, Name = "Froemson-{0}".Args(i), IsGood = i % 7 == 0
                    };
                    Assert.IsTrue(tbl1.Put((ulong)i, bo));
                }

                Assert.AreEqual(100, tbl1.Count);

                Assert.AreEqual("Froemson-12", tbl1.Get(12).ValueAs <businessObject>().Name);
                Assert.AreEqual("Froemson-12", store["t1", 12].ValueAs <businessObject>().Name);
                Assert.AreEqual(true, tbl1.Get(7).ValueAs <businessObject>().IsGood);

                Assert.AreEqual(1, tbl1.Get(0).HitCount);
                Assert.AreEqual(3, tbl1.Get(12).HitCount);
                Assert.AreEqual(2, tbl1.Get(7).HitCount);
            }
        }
示例#16
0
 public void Clear()
 {
     using (CreateCrossPlatLock(_storageCreationProperties))
     {
         CacheStore.Clear(ignoreExceptions: true);
     }
 }
 /// <summary>
 /// Extracts the token cache data from the persistent store
 /// </summary>
 /// <returns>an UTF-8 byte array of the unencrypted token cache</returns>
 /// <remarks>This method should be used with care. The data returned is unencrypted.</remarks>
 public byte[] LoadUnencryptedTokenCache()
 {
     using (CreateCrossPlatLock(_storageCreationProperties))
     {
         return(CacheStore.ReadData(ignoreExceptions: false));
     }
 }
        /// <summary>
        /// Before cache access
        /// </summary>
        /// <param name="args">Callback parameters from MSAL</param>
        internal void BeforeAccessNotification(TokenCacheNotificationArgs args)
        {
            _logger.LogInformation($"Before access");

            _logger.LogInformation($"Acquiring lock for token cache");

            // OK, we have two nested locks here. We need to maintain a clear ordering to avoid deadlocks.
            // 1. Use the CrossPlatLock which is respected by all processes and is used around all cache accesses.
            // 2. Use _lockObject which is used in UnregisterCache, and is needed for all accesses of _registeredCaches.
            CacheLock = CreateCrossPlatLock(_storageCreationProperties);

            _logger.LogInformation($"Before access, the store has changed");
            var cachedStoreData = CacheStore.ReadData();

            _logger.LogInformation($"Read '{cachedStoreData?.Length}' bytes from storage");

            lock (_lockObject)
            {
                try
                {
                    _logger.LogInformation($"Deserializing the store");
                    args.TokenCache.DeserializeMsalV3(cachedStoreData, shouldClearExistingCache: true);
                }
                catch (Exception e)
                {
                    _logger.LogError($"An exception was encountered while deserializing the {nameof(MsalCacheHelper)} : {e}");
                    _logger.LogError($"No data found in the store, clearing the cache in memory.");

                    // Clear the memory cache
                    Clear();
                    throw;
                }
            }
        }
 /// <summary>
 /// Saves an unencrypted, UTF-8 encoded byte array representing an MSAL token cache.
 /// The save operation will persist the data in a secure location, as configured in <see cref="StorageCreationProperties"/>
 /// </summary>
 public void SaveUnencryptedTokenCache(byte[] tokenCache)
 {
     using (CreateCrossPlatLock(_storageCreationProperties))
     {
         CacheStore.WriteData(tokenCache, ignoreExceptions: false);
     }
 }
示例#20
0
        public void Refresh()
        {
            try
            {
                if (null != this.RefreshStart)
                {
                    RefreshStart(this, new EventArgs());
                }
                Geocache selected = SelectedCache;
                m_disabledOrArchivedCount = 0;
                m_visibleCount            = 0;
                m_mineCount  = 0;
                m_foundCount = 0;

                if (m_app.AppConfig.ImperialUnits)
                {
                    m_distanceColumn.Title = Catalog.GetString("Mi");
                    distanceLabel.Text     = Catalog.GetString("Mi");
                }
                else
                {
                    m_distanceColumn.Title = Catalog.GetString("km");
                    distanceLabel.Text     = Catalog.GetString("km");
                }

                UpdateStatus();

                CacheStore.GlobalFilters.AddFilterCriteria(FilterList.KEY_STATUS,
                                                           new bool[] { foundCheck.Active, notFoundCheck.Active, mineCheck.Active,
                                                                        availCheck.Active, notAvailCheck.Active, archiveCheck.Active });
                cacheListTree.Model = null;
                if (m_list == null)
                {
                    m_list = new CacheStoreModel();
                }
                else
                {
                    m_list.Clear();
                }


                if (m_sort == null)
                {
                    m_sort = new TreeModelSort(new TreeModelAdapter(m_list));
                    m_sort.SetSortFunc(3, TitleCompare);
                    m_sort.SetSortFunc(2, DistanceCompare);
                    m_sort.SetSortFunc(0, SymbolCompare);
                    m_sort.DefaultSortFunc = DistanceCompare;
                }
                CacheStore.ReadCache += HandleCacheStoreReadCache;
                CacheStore.Complete  += HandleCacheStoreComplete;
                CacheStore.GetUnfilteredCaches(m_app.CentreLat, m_app.CentreLon, m_app.OwnerIDs.ToArray());
                CacheStore.ReadCache -= HandleCacheStoreReadCache;
                CacheStore.Complete  -= HandleCacheStoreComplete;
            }
            catch (Exception e)
            {
                OCMApp.ShowException(e);
            }
        }
示例#21
0
        public void CacheStoreCanAddAnEntryWithExpirationTime()
        {
            // Arrange
            var keyName       = "MyKeyName";
            var keyValue      = "MyKeyValue";
            var secondsToWait = 2;

            // Expire Configuration
            Dictionary <string, TimeSpan> expirationConfiguration = new Dictionary <string, TimeSpan>()
            {
                { "MyKeyName", TimeSpan.Parse($"00:00:0{secondsToWait}") }
            };

            // Act
            ICacheStore _cache = new CacheStore(_memoryCache, expirationConfiguration);

            _cache.Add <string>(keyName, keyValue);
            var cacheValue = _memoryCache.Get(keyName);

            Thread.Sleep(secondsToWait * 1000);
            var cacheValueAfterExpireTime = _memoryCache.Get <string>(keyName);

            // Assert
            Assert.NotNull(cacheValue);
            Assert.Equal(keyValue, cacheValue);
            Assert.Null(cacheValueAfterExpireTime);
        }
示例#22
0
        private void AddInjectionAssembly(string assemblyName)
        {
            ReflectionAssemblyResolver assemblyInjectionCode = null;

            if (CacheStore.Exists <ReflectionAssemblyResolver>("injection|" + assemblyName))
            {
                assemblyInjectionCode = CacheStore.Get <ReflectionAssemblyResolver>("injection|" + assemblyName);
            }
            else
            {
                assemblyInjectionCode = new ReflectionAssemblyResolver(assemblyName);
                CacheStore.Add <ReflectionAssemblyResolver>("injection|" + assemblyName, assemblyInjectionCode);
            }

            var nodeAssembly = new TreeNode {
                Text = Path.GetFileName(assemblyName), Tag = assemblyInjectionCode
            };

            List <Type> types = assemblyInjectionCode.FindTypes <ICInject>();

            for (int i = 0; i < types.Count; i++)
            {
                OnBindInjectors(assemblyInjectionCode, types[i], nodeAssembly, true);
            }

            // don't show the assembly if it does not have any injectors
            if (types.Count > 0)
            {
                _rootInjection.Nodes.Add(nodeAssembly);
                treeInjectionCode.ExpandAll();
            }

            _injectorAssemblyLoaded = true;
            SendMessageToPlugins(EventType.InjectionAssemblyLoaded, null, null, assemblyName);
        }
示例#23
0
        public void Configuration_NamedStore()
        {
            var conf = LaconicConfiguration.CreateFromString(CONF_SRC);

            using (var app = new ServiceBaseApplication(null, conf.Root))
            {
                using (var store = new CacheStore("BANKING"))
                {
                    store.Configure(null);

                    Assert.AreEqual(789001, store.TableOptions["Account"].BucketCount);
                    Assert.AreEqual(23, store.TableOptions["Account"].RecPerPage);
                    Assert.AreEqual(149, store.TableOptions["Account"].LockCount);
                    Assert.AreEqual(12000, store.TableOptions["Account"].MaxAgeSec);
                    Assert.AreEqual(true, store.TableOptions["Account"].ParallelSweep);

                    Assert.AreEqual(1023, store.TableOptions["BaLaNCE"].BucketCount);
                    Assert.AreEqual(3, store.TableOptions["BaLaNCE"].RecPerPage);
                    Assert.AreEqual(11, store.TableOptions["BaLaNCE"].LockCount);
                    Assert.AreEqual(230000, store.TableOptions["BaLaNCE"].MaxAgeSec);
                    Assert.AreEqual(false, store.TableOptions["BaLaNCE"].ParallelSweep);

                    var tbl = store["AccoUNT"];
                    Assert.AreEqual(789001, tbl.BucketCount);
                    Assert.AreEqual(23, tbl.RecPerPage);
                    Assert.AreEqual(789001 * 23, tbl.Capacity);
                    Assert.AreEqual(149, tbl.LockCount);
                    Assert.AreEqual(12000, tbl.MaxAgeSec);
                    Assert.AreEqual(true, tbl.ParallelSweep);
                }
            }
        }
示例#24
0
        public void Get_Does_Not_See_AbsoluteExpired()
        {
            using (var store = new CacheStore(null))
            {
                var tbl1 = store["t1"];

                var utcNow = App.TimeSource.UTCNow;
                var utcExp = utcNow.AddSeconds(5);


                var bo1 = new businessObject {
                    ID = 1, Name = "Suvorov-1", IsGood = true
                };
                Assert.IsTrue(tbl1.Put(1, bo1, maxAgeSec: int.MaxValue, absoluteExpirationUTC: utcExp));

                var bo2 = new businessObject {
                    ID = 2, Name = "Meduzer-2", IsGood = false
                };
                Assert.IsTrue(tbl1.Put(2, bo2));



                Assert.AreEqual(2, tbl1.Count);

                System.Threading.Thread.Sleep(15000);// this timeout depends on store sweep thread speed, 15 sec span should be enough

                Assert.AreEqual(1, tbl1.Count);

                Assert.IsNull(tbl1.Get(1));                                                // expired
                Assert.AreEqual("Meduzer-2", tbl1.Get(2).ValueAs <businessObject>().Name); //still there
            }
        }
示例#25
0
 static HomeController()
 {
     Id = 1;
     //Adding Intial Record
     CacheStore.Add(Id.ToString(), new Tutor {
         Id = 1, Name = "Rahul Malviya", Email = "*****@*****.**", Topics = "AngularJS Assignment", Price = 1000
     });
 }
示例#26
0
        public void CacheStoreCanBeCreatedByInjection()
        {
            // Arrange-Act
            CacheStore myCache = new CacheStore(_memoryCache);

            // Assert
            Assert.NotNull(myCache);
        }
示例#27
0
        public void CacheStoreCanBeCreatedWithNullParameters()
        {
            // Arrange-Act
            CacheStore myCache = new CacheStore(null, null);

            // Assert
            Assert.NotNull(myCache);
        }
示例#28
0
        private void AddTargetAssembly(string assemblyName)
        {
            MonoAssemblyResolver assemblyTarget = null;

            if (CacheStore.Exists <MonoAssemblyResolver>("mono|" + assemblyName))
            {
                assemblyTarget = CacheStore.Get <MonoAssemblyResolver>("mono|" + assemblyName);
            }
            else
            {
                assemblyTarget = new MonoAssemblyResolver(assemblyName);
                CacheStore.Add <MonoAssemblyResolver>("mono|" + assemblyName, assemblyTarget);
            }

            // add in the dictionary
            if (_targetAssemblies.ContainsKey(assemblyName) == false)
            {
                _targetAssemblies.Add(assemblyName, assemblyTarget);
            }

            // attach message received event
            assemblyTarget.OnMessageReceived += resolver_OnMessageReceived;

            // add node
            var nodeAssembly = new TreeNode
            {
                Text = Path.GetFileName(assemblyName),
                Tag  = new BindItem {
                    Assembly = assemblyTarget, Method = null
                }
            };

            _rootTarget.Nodes.Add(nodeAssembly);

            List <TypeDefinition> types = assemblyTarget.FindClasses();

            for (int i = 0; i < types.Count; i++)
            {
                if (types[i].HasMethods)
                {
                    var nodeClass = new TreeNode
                    {
                        Text = types[i].Name,
                        Tag  = types[i]
                    };

                    nodeAssembly.Nodes.Add(nodeClass);

                    OnBindMethodsDefinitions(assemblyTarget, types[i], nodeClass);
                }
            }

            treeTarget.CollapseAll();

            _targetAssemblyLoaded = true;

            SendMessageToPlugins(EventType.TargetAssemblyLoaded, null, null, assemblyName);
        }
示例#29
0
 private void CacheTest_Load(object sender, EventArgs e)
 {
     store = new CacheStore("Test Ztore1");
     store.InstrumentationEnabled = true;
     store.TableOptions.Register(new TableOptions(TBL, TableCapacity.Default));    //.DBServer_128GB) );
     //store.TableOptions.Register( new TableOptions(TBL2, TableCapacity.M100,1024) );
     //store.TableOptions.Register( new TableOptions(TBL3, TableCapacity.M100,1024) );
     //store.TableOptions.Register( new TableOptions(TBL4, TableCapacity.M100,1024) );
 }
示例#30
0
文件: Metabank.cs 项目: rstonkus/azos
        /// <summary>
        /// Opens metabase from the specified file system instance at the specified metabase root path
        /// </summary>
        /// <param name="bootApplication">IApplication chassis which this metabank boots from</param>
        /// <param name="skyApplication">ISkyApplication chassis which this metabank installs in</param>
        /// <param name="fileSystem">
        /// An instance of a file system that stores the metabase files
        /// Note: This file system is typically a component of Boot application, not the sky app which is being mounted.
        /// Metabank does NOT dispose the FS, as it is an external resource relative to metabank
        /// </param>
        /// <param name="fsSessionParams">File system connection parameter</param>
        /// <param name="rootPath">A path to the directory within the file system that contains metabase root data</param>
        internal Metabank(IApplication bootApplication,
                          ISkyApplication skyApplication,
                          IFileSystem fileSystem,
                          FileSystemSessionConnectParams fsSessionParams,
                          string rootPath) : base(bootApplication.NonNull(nameof(bootApplication)))
        {
            this.m_SkyApplication = skyApplication.NonNull(nameof(skyApplication));

            if (fileSystem is LocalFileSystem && fsSessionParams == null)
            {
                fsSessionParams = new FileSystemSessionConnectParams();
            }

            if (fileSystem == null || fsSessionParams == null)
            {
                throw new MetabaseException(StringConsts.ARGUMENT_ERROR + "Metabank.ctor(fileSystem|fsSessionParams==null)");
            }

            using (var session = ctorFS(fileSystem, fsSessionParams, rootPath))
            {
                m_CommonLevelConfig = getConfigFromFile(session, CONFIG_COMMON_FILE).Root;

                m_RootConfig = getConfigFromFile(session, CONFIG_SECTION_LEVEL_FILE).Root;
                includeCommonConfig(m_RootConfig);
                m_RootConfig.ResetModified();

                m_RootAppConfig  = getConfigFromFile(session, CONFIG_SECTION_LEVEL_ANY_APP_FILE).Root;
                m_PlatformConfig = getConfigFromFile(session, CONFIG_PLATFORMS_FILE).Root;
                m_NetworkConfig  = getConfigFromFile(session, CONFIG_NETWORKS_FILE).Root;
                m_ContractConfig = getConfigFromFile(session, CONFIG_CONTRACTS_FILE).Root;
            }
            m_Catalogs = new Registry <Catalog>();
            var cacheStore = new CacheStore(this, "AC.Metabank");

            //No app available - nowhere to configure: //cacheStore.Configure(null);

            /*
             * cacheStore.TableOptions.Register( new TableOptions(APP_CATALOG, 37, 3) );
             * cacheStore.TableOptions.Register( new TableOptions(BIN_CATALOG, 37, 7) );
             * cacheStore.TableOptions.Register( new TableOptions(REG_CATALOG, 37, 17) );
             * superseded by the cacheStore.DefaultTableOptions below:
             */
            cacheStore.DefaultTableOptions = new TableOptions("*", 37, 17);
            //reg catalog needs more space
            cacheStore.TableOptions.Register(new TableOptions(REG_CATALOG, 571, 37));

            cacheStore.InstrumentationEnabled = false;

            m_Cache = new ComplexKeyHashingStrategy(cacheStore);

            new AppCatalog(this);
            new BinCatalog(this);
            new SecCatalog(this);
            new RegCatalog(this);

            ConfigAttribute.Apply(this, m_RootConfig);
        }
示例#31
0
        static void Main(string[] args)
        {
            PersistentCache = new CacheStore<Thing>("c:\\tmp\\PersistantCache", "1", null, "00:00:10");

            Console.WriteLine("Creating Data");
            const int itemsToUse = 2000000;

            var items = GenerateList(itemsToUse, 20);
            items.Shuffle();

            //var temp = new CacheItem[itemsToUse];
            //items.CopyTo(temp);
            //var reversedItems = temp.Reverse().ToList();

            var items2 = GenerateList(itemsToUse, 20);
            items2.Shuffle();

            RunPersistanceCacheTest(new List<List<CacheItem>>(2) { items, items2 });

            Console.ReadKey();
        }
 public AccountCreationServiceImpl(ChronokeeperService chronokeeperService, CacheStore<Guid, Account> accountCacheStore) {
    this.chronokeeperService = chronokeeperService;
    this.accountCacheStore = accountCacheStore;
 }
 public ClientLogImportingServiceImpl(ChronokeeperService chronokeeperService, CacheStore<Guid, ClientLog> clientLogCacheStore, ZipArchiveToMapConverter zipArchiveToMapConverter) {
    this.chronokeeperService = chronokeeperService;
    this.clientLogCacheStore = clientLogCacheStore;
    this.zipArchiveToMapConverter = zipArchiveToMapConverter;
 }
示例#34
0
 public void Initialize() {
    clientLogCacheStore = new MicroLiteCacheStore<Guid, ClientLog>(platformCacheConfiguration.DatabaseSessionFactory);
 }
示例#35
0
 public void Initialize() {
    accountCacheStore = new MicroLiteCacheStore<Guid, Account>(platformCacheConfiguration.DatabaseSessionFactory);
    accountCache = cacheInitializer.NearCache("account-cache", accountCacheStore);
    accountIdByUsernameCache = cacheInitializer.NearCache<string, Guid>("account-id-by-username-cache");
    accessTokenCache = cacheInitializer.NearCache<string, Guid>("access-token-cache");
 }