public void DifferentUsersWithSameRuleSet() { var cacheFactory = new CacheFactory { CacheName = "DifferentUsersWithSameRuleSet", MetadataCache = true }; var cache = cacheFactory.Create <string, string>(); UserAccount player1, player2; CreateTwoUsersWithSameSecurity(out player1, out player2); using (new SetUser(player1)) { cache.Add("first", "player1 value"); Assert.That(cache["first"], Is.EqualTo("player1 value"), "What we put in is what we get out"); } using (new SetUser(player2)) { string val; var found = cache.TryGetValue("first", out val); Assert.That(found, Is.True, "What the other user put in we get out"); Assert.That(val, Is.EqualTo("player1 value"), "What the other user put in we get out"); } }
public ActionResult CacheInfo(bool isOnlyPlaceHolder = true) { ICache cache = CacheFactory.Create(); cache.Clear(); return(View(cache.Count)); }
public RegionSSLTest() { var pathvar = Environment.GetEnvironmentVariable("PATH"); var openSslPath = Environment.CurrentDirectory + Config.OpenSSLPath; if (!Directory.Exists(openSslPath)) { throw new DirectoryNotFoundException("OpenSSL is a prerequisite for integration tests and the directory was not found."); } pathvar += ";" + openSslPath; var cryptoImplPath = Environment.CurrentDirectory + Config.CryptoImplPath; if (!File.Exists(cryptoImplPath + "\\cryptoImpl.dll")) { throw new System.IO.FileNotFoundException("cryptoImpl.dll was not found at " + cryptoImplPath); } pathvar += ";" + cryptoImplPath; Environment.SetEnvironmentVariable("PATH", pathvar); var cacheFactory = new CacheFactory(); cacheFactory.Set("ssl-enabled", "true"); cacheFactory.Set("ssl-keystore", Environment.CurrentDirectory + "\\ClientSslKeys\\client_keystore.password.pem"); cacheFactory.Set("ssl-keystore-password", "gemstone"); cacheFactory.Set("ssl-truststore", Environment.CurrentDirectory + "\\ClientSslKeys\\client_truststore.pem"); cacheOne_ = cacheFactory.Create(); }
static void Main(string[] args) { CacheConfig config = new CacheConfig(); //config.LoadConfig(""); config.CacheTime = 1800; config.Policy = CachePolicy.FIFO; config.PersPolicy = PersistencePolicy.Expire; ICache <int, int> cache = CacheFactory <int, int> .Create(config); cache.CacheRemoveListener += Cache_CacheRemoveListener; for (int i = 0; i < 10; i++) { Task.Factory.StartNew(() => { int num = i * 10; for (int j = num; j < num + 10000; j++) { cache.Add(j, j); } }); } Thread.Sleep(10000); int reslut = 0; if (cache.TryGetCache(10020, out reslut)) { Console.WriteLine(reslut); } Console.Read(); }
private CurrentHostContext(IHostConfig configuration, ContextSettings settings) { Audit = configuration.Runtime.Audit; Config = configuration; UserTokens = new List <string>(); var logger = LogFactory.CreateInstance(configuration.Runtime.LogInfo); var commandArgs = new CommandArgs(configuration.Runtime.Parameters); var cache = CacheFactory.Create(configuration.Caching); cache.ItemRemoved += (sender, args) => { Log.Debug("Item removed from cache: " + args.CacheKey + " Reason : " + args.RemoveReason); if (args.Value is AuthenticationOutput) { // User has been removed from cache. Login expired UserTokens.Remove(args.CacheKey); } }; CurrentContext.CreateDefault(logger, commandArgs, cache); //override the passwords if encrypted if (configuration.Certificate.Encryption != null) { var certificate = configuration.Certificate.Encryption.GetX509Certificate(); if (certificate != null) { DecryptPasswords(configuration, certificate); } } CommandFactory = settings.CommandFactory; Provider = GetDatabaseProviderInstance(configuration); }
static void Main(string[] args) { var cacheFactory = new CacheFactory() .Set("log-level", "none") .SetAuthInitialize(new ExampleAuthInitialize()); var cache = cacheFactory.Create(); var poolFactory = cache.GetPoolFactory() .AddLocator("localhost", 10334); poolFactory.Create("pool"); var regionFactory = cache.CreateRegionFactory(RegionShortcut.PROXY) .SetPoolName("pool"); var region = regionFactory.Create <string, string>("region"); region["a"] = "1"; region["b"] = "2"; var a = region["a"]; var b = region["b"]; Console.Out.WriteLine("a = " + a); Console.Out.WriteLine("b = " + b); cache.Close(); }
/// <summary> /// Create a new <see cref="CachingQueryRunner"/>. /// </summary> /// <param name="queryRunner"> /// The <see cref="IQueryRunner"/> that will actually generate the SQL. This cannot be null. /// </param> /// <param name="userRuleSetProvider"></param> /// <param name="querySqlBuilder"></param> /// <exception cref="ArgumentNullException"> /// <paramref name="queryRunner"/> cannot be null. /// </exception> public CachingQueryRunner([WithKey(Factory.NonCachedKey)] IQueryRunner queryRunner, IUserRuleSetProvider userRuleSetProvider, IQuerySqlBuilder querySqlBuilder) { if (queryRunner == null) { throw new ArgumentNullException("queryRunner"); } if (userRuleSetProvider == null) { throw new ArgumentNullException("userRuleSetProvider"); } QueryRunner = queryRunner; QuerySqlBuilder = querySqlBuilder; UserRuleSetProvider = userRuleSetProvider; // Create cache var fact = new CacheFactory { CacheName = "Query Result", MaxCacheEntries = CacheFactory.DefaultMaximumCacheSize }; Cache = fact.Create <CachingQueryRunnerKey, CachingQueryRunnerValue>( ); _cacheInvalidator = new CachingQueryRunnerInvalidator(Cache); }
protected void MergePhase1(Object objectToMerge, Object objectToDelete, ProceedWithMergeHook proceedHook, MergeFinishedCallback mergeFinishedCallback, bool addNewEntitiesToCache) { ICUDResult cudResult; MergeHandle mergeHandle; IDisposableCache childCache = CacheFactory.Create(CacheFactoryDirective.NoDCE, false, false, "MergeProcess.ORIGINAL"); try { mergeHandle = BeanContext.RegisterBean <MergeHandle>() // .PropertyValue("Cache", childCache) // .Finish(); cudResult = MergeController.MergeDeep(objectToMerge, mergeHandle); mergeHandle.Cache = null; } finally { childCache.Dispose(); childCache = null; } if (GuiThreadHelper.IsInGuiThread()) { MergePhase2(objectToMerge, objectToDelete, mergeHandle, cudResult, proceedHook, mergeFinishedCallback, addNewEntitiesToCache); } else { GuiThreadHelper.InvokeInGui(delegate() { MergePhase2(objectToMerge, objectToDelete, mergeHandle, cudResult, proceedHook, mergeFinishedCallback, addNewEntitiesToCache); }); } }
public static void Main(string[] args) { var cacheFactory = new CacheFactory() .Set("log-level", "none"); var cache = cacheFactory.Create(); Console.WriteLine("Registering for data serialization"); cache.TypeRegistry.RegisterPdxType(Order.CreateDeserializable); var poolFactory = cache.GetPoolFactory() .AddLocator("localhost", 10334); poolFactory.Create("pool"); var regionFactory = cache.CreateRegionFactory(RegionShortcut.PROXY) .SetPoolName("pool"); var orderRegion = regionFactory.Create <int, Order>("example_orderobject"); Console.WriteLine("Storing order object in the region"); const int orderKey = 65; var order = new Order(orderKey, "Donuts", 12); Console.WriteLine("order to put is " + order); orderRegion.Put(orderKey, order, null); Console.WriteLine("Successfully put order, getting now..."); var orderRetrieved = orderRegion.Get(orderKey, null); Console.WriteLine("Order key: " + orderKey + " = " + orderRetrieved); cache.Close(); }
void RunFeeder1() { CacheFactory cacheFactory = new CacheFactory(); Util.Log("Feeder connected to the Geode Distributed System"); Cache cache = cacheFactory.Create(); Util.Log("Created the Geode Cache"); RegionFactory regionFactory = cache.CreateRegionFactory(RegionShortcut.PROXY); Util.Log("Created the RegionFactory"); // Create the Region Programmatically. IRegion<object, object> region = regionFactory.Create<object, object>("DistRegionAck"); Util.Log("Created the Region Programmatically."); PendingEventCount(region, 0, true); for (int i = 10; i < 20; i++) { region[i] = i; } Thread.Sleep(10000); Util.Log("put on 10-20 keys done."); // Close the Geode Cache cache.Close(); Util.Log("Closed the Geode Cache"); }
public void TestClientCacheGetPdxReadSerialized() { using (var client = new GemfireClient()) { using (var cacheFactory = CacheFactory.Create() .SetProperty("log-level", "debug") .SetProperty("log-file", "TestClientCacheGetPdxReadSerialized.log")) { try { cacheFactory.PdxReadSerialized = true; using (var cache = cacheFactory.CreateCache()) { Assert.AreEqual(cache.GetPdxReadSerialized(), true); } cacheFactory.PdxReadSerialized = false; using (var otherCache = cacheFactory.CreateCache()) { Assert.AreEqual(otherCache.GetPdxReadSerialized(), false); } } catch (Exception e) { Console.WriteLine(e); throw; } } Assert.Pass(); } }
public void PutGetCustomSerializableTypes() { using (var cluster = new Cluster(CreateTestCaseDirectoryName(), 1, 1)) { Assert.True(cluster.Start()); Assert.Equal(cluster.Gfsh.create() .region() .withName("testRegion") .withType("REPLICATE") .execute(), 0); var cacheFactory = new CacheFactory() .Set("log-level", "none"); var cache = cacheFactory.Create(); cache.TypeRegistry.RegisterType(Order.CreateDeserializable, 0x42); var poolFactory = cache.GetPoolFactory() .AddLocator("localhost", cluster.Gfsh.LocatorPort); poolFactory.Create("pool"); var regionFactory = cache.CreateRegionFactory(RegionShortcut.PROXY) .SetPoolName("pool"); var orderRegion = regionFactory.Create <int, Order>("testRegion"); Assert.NotNull(orderRegion); const int orderKey = 65; var order = new Order(orderKey, "Donuts", 12); orderRegion.Put(orderKey, order, null); var orderRetrieved = orderRegion.Get(orderKey, null); Assert.Equal(order.ToString(), orderRetrieved.ToString()); cache.Close(); } }
public void Test_Reentrant_DifferentKey( ) { var factory = new CacheFactory { CacheName = "BlockIfPending", BlockIfPending = true }; var cache = factory.Create <int, string>( ); // Value function Func <int, string> valueFactory = null; valueFactory = key => { if (key == 1) { string value2; cache.TryGetOrAdd(2, out value2, valueFactory); Assert.That(value2, Is.EqualTo("Test2")); return("Test1"); } if (key == 2) { return("Test2"); } throw new Exception( ); }; string value1; cache.TryGetOrAdd(1, out value1, valueFactory); Assert.That(value1, Is.EqualTo("Test1")); }
public void Remove() { var cacheFactory = CacheFactory.Create() .SetProperty("log-level", "none") .SetProperty("log-file", "SessionStateCacheIntegrationTests.log"); var cache = (Cache)cacheFactory.CreateCache(); PoolFactory poolFactory = cache.PoolFactory.AddLocator("localhost", 10334); var pool = poolFactory.CreatePool("myPool"); var ssCache = new SessionStateCache(cache, _regionName); var options = new DistributedCacheEntryOptions(); DateTime localTime = DateTime.Now.AddDays(1); DateTimeOffset dateAndOffset = new DateTimeOffset(localTime, TimeZoneInfo.Local.GetUtcOffset(localTime)); options.AbsoluteExpiration = dateAndOffset; var testValue = new byte[] { 1, 2, 3, 4, 5 }; ssCache.Set("testKey", testValue, options); byte[] value = ssCache.Get("testKey"); ssCache.Remove("testKey"); value = ssCache.Get("testKey"); Assert.Null(value); }
public void Refresh() { var cacheFactory = CacheFactory.Create() .SetProperty("log-level", "none") .SetProperty("log-file", "SessionStateCacheIntegrationTests.log"); var cache = (Cache)cacheFactory.CreateCache(); PoolFactory poolFactory = cache.PoolFactory.AddLocator("localhost", 10334); var pool = poolFactory.CreatePool("myPool"); var ssCache = new SessionStateCache(cache, _regionName); var options = new DistributedCacheEntryOptions(); int numSeconds = 20; options.SlidingExpiration = new TimeSpan(0, 0, numSeconds); var testValue = new byte[] { 1, 2, 3, 4, 5 }; // Set a value ssCache.Set("testKey", testValue, options); // Wait half a timeout then refresh System.Threading.Thread.Sleep(numSeconds / 2 * 1000); ssCache.Refresh("testKey"); // Wait beyond the original expiration System.Threading.Thread.Sleep(numSeconds / 2 * 1000 + 1); // Ensure it's not expired byte[] value = ssCache.Get("testKey"); Assert.True(testValue.SequenceEqual(value)); }
private void SaveToCache() { var purchasingLimitKey = PurchaseRestrictionManagerFactory.GetCacheKey(_distributorId, _currentLoggedInCountry); CacheFactory.Create().Add(this, purchasingLimitKey, TimeSpan.FromMinutes(Settings.GetRequiredAppSetting( "PurchasingLimitsCacheMinutes", 30))); }
public static List <FavouriteSKU> GetDistributorFavouriteSKU(string distributorID, string locale) { ISimpleCache _cache = CacheFactory.Create(); var cacheKey = string.Format("Favour_{0}_{1}", distributorID.ToUpper(), Thread.CurrentThread.CurrentUICulture.Name); var result = _cache.Retrieve(_ => LoadFromService(distributorID, locale), cacheKey, TimeSpan.FromMinutes(FavouriteSKU_Cache_Minutes)); return(result ?? new List <FavouriteSKU>()); }
public void ExpireCache() { var currentLoggedInCounrtyCode = CultureInfo.CurrentCulture.Name.Substring(3); var purchasingLimitKey = string.Format("PL_{0}_{1}", _distributorId, currentLoggedInCounrtyCode); var _cache = CacheFactory.Create(); _cache.Expire(typeof(IPurchasingLimitManager), purchasingLimitKey); }
/// <summary> /// Create a new <see cref="CacheBase{TKey, TValue}"/>. /// </summary> /// <param name="name"> /// The name of the cache, used for logging and partitioning. This cannot be null, empty or whitespace. /// </param> /// <param name="distributed"> /// True if the cache is distributed, false otherwise. /// </param> /// <param name="logging"> /// True if the cache should provide logging details. /// </param> protected CacheBase(string name, bool distributed, bool logging) { CacheFactory factory = new CacheFactory { Distributed = distributed, Logging = logging }; _cache = factory.Create <TKey, TValue>(name); }
/// <summary> /// 设置用户的空间 /// </summary> /// <param name="PageSize"></param> /// <returns></returns> public static void SetUserSpace(string UserSpace) { ICache cache = CacheFactory.Create(); cache.Set <string>(UserService.CurrentUser.UserID.ToString(), "UserSpace", UserSpace); cache.SetExpire(UserService.CurrentUser.UserID.ToString(), "TopMenu"); cache.SetExpire(UserService.CurrentUser.UserID.ToString(), "LeftMenu"); }
private void SaveToCache() { var currentLoggedInCounrtyCode = CultureInfo.CurrentCulture.Name.Substring(3); var purchasingLimitKey = string.Format("PL_{0}_{1}", _distributorId, currentLoggedInCounrtyCode); var _cache = CacheFactory.Create(); _cache.Add(this, purchasingLimitKey, TimeSpan.FromMinutes(30)); }
public ResourceTriggerFilterPolicyCache(IEnumerable <IFilteredTargetHandlerFactory> handlerFactories) { using (Profiler.Measure("ResourceTriggerFilterPolicyCache Init")) { var cacheFactory = new CacheFactory() { IsolateTenants = true, ThreadSafe = true, CacheName = "ResourceTriggerFilterPolicyCache" }; // SHOULD BE METADATA? HandlerFactories = handlerFactories; _typePolicyMap = cacheFactory.Create <long, List <ResourceTriggerFilterDef> >(); // The policies that apply to a type including derived types _policyToFieldsMap = cacheFactory.Create <long, HashSet <long> >(); _policyTypeHandlerMap = cacheFactory.Create <long, IFilteredSaveEventHandler>(); _areWePrecachedYet = cacheFactory.Create <long, bool>(); } }
public void TestLeakCacheFactory() { var client = new GemfireClient(); using (var cacheFactory = CacheFactory.Create()) { Assert.Throws <InvalidOperationException>(() => client.Dispose()); } }
/// <summary> /// Instantiates <see cref="ObjectSecurityStrategy"/> with a cache based on the <paramref name="invalidationToken"/>. /// </summary> public static IObjectSecurityStrategy Create( [NotNull] ISecurityContextFactory securityContextFactory, [NotNull] InvalidationToken invalidationToken) { ArgumentUtility.CheckNotNull("securityContextFactory", securityContextFactory); ArgumentUtility.CheckNotNull("invalidationToken", invalidationToken); return(new ObjectSecurityStrategy(securityContextFactory, CacheFactory.Create <ISecurityPrincipal, AccessType[]> (invalidationToken))); }
public static GetSlowMovingSkuList LoadSlowMovingSkuInfo() { var cacheKey = string.Format("{0}{1}", SLOWMOVING_CACHE_PREFIX, "CN"); var slowmovingdetail = CacheFactory.Create().Retrieve(_ => GetSlowmovingskuDetail(), cacheKey, TimeSpan.FromMinutes(ANNOUNCEMENTINFO_CACHE_MINUTES)); return(slowmovingdetail); }
private readonly ICache <Tuple <long, TKey>, bool> _recentUpdatingUsers; // this doesn't need to be a cache I'm just lazy and using the expiration function. /// <summary> /// Constructor. /// </summary> /// <param name="innerCache">The inner cache.</param> /// <param name="cacheName">Name of the cache.</param> /// <param name="expirationInterval">The expiration interval.</param> /// <param name="globalThresholdTicks">The global threshold ticks.</param> /// <exception cref="System.ArgumentNullException">cacheName</exception> public DelayedInvalidateCache(ICache <TKey, TValue> innerCache, string cacheName, TimeSpan expirationInterval, TimeSpan globalThresholdTicks) { if (string.IsNullOrEmpty(cacheName)) { throw new ArgumentNullException(nameof(cacheName)); } _innerCache = innerCache; CacheName = cacheName; CacheFactory factory = new CacheFactory { ExpirationInterval = expirationInterval, IsolateTenants = false }; _recentCache = factory.Create <TKey, Tuple <TValue, DateTime> >(CacheName + " Delayed Invalidation Recent Cache"); _recentCache.ItemsRemoved += CacheOnItemsRemoved; _recentUpdatingUsers = factory.Create <Tuple <long, TKey>, bool>(CacheName + " Delayed Invalidation Recent Updating Users Cache"); _globalThresholdTicks = globalThresholdTicks; }
static void Main(string[] args) { var cacheFactory = new CacheFactory() .Set("log-level", "none"); var cache = cacheFactory.Create(); var poolFactory = cache.GetPoolFactory() .AddLocator("localhost", 10334); poolFactory.Create("pool"); var regionFactory = cache.CreateRegionFactory(RegionShortcut.PROXY) .SetPoolName("pool"); var region = regionFactory.Create <object, object>("partition_region"); Console.WriteLine("Storing id and username in the region"); string rtimmonsKey = "rtimmons"; string rtimmonsValue = "Robert Timmons"; string scharlesKey = "scharles"; string scharlesValue = "Sylvia Charles"; region.Put(rtimmonsKey, rtimmonsValue, null); region.Put(scharlesKey, scharlesValue, null); Console.WriteLine("Getting the user info from the region"); var user1 = region.Get(rtimmonsKey, null); var user2 = region.Get(scharlesKey, null); Console.WriteLine(rtimmonsKey + " = " + user1); Console.WriteLine(scharlesKey + " = " + user2); ArrayList keyArgs = new ArrayList(); keyArgs.Add(rtimmonsKey); keyArgs.Add(scharlesKey); var exc = Client.FunctionService <object> .OnRegion <object, object>(region); Client.IResultCollector <object> rc = exc.WithArgs <object>(keyArgs).Execute("ExampleMultiGetFunction"); ICollection <object> res = rc.GetResult(); Console.WriteLine("Function Execution Results:"); Console.WriteLine(" Count = {0}", res.Count); foreach (List <object> item in res) { foreach (object item2 in item) { Console.WriteLine(" value = {0}", item2.ToString()); } } cache.Close(); }
public void Check1( ) { CacheFactory fact = new CacheFactory { DelayedInvalidates = true }; var cache = fact.Create <string, string>("name"); Stopwatch sw = new Stopwatch( ); sw.Start( ); int callbackCount = 0; Func <string, string> callback = key1 => { Interlocked.Increment(ref callbackCount); Console.WriteLine(sw.ElapsedMilliseconds); return("value"); }; var user1 = Entity.Create <UserAccount>( ); var user2 = Entity.Create <UserAccount>( ); var user3 = Entity.Create <UserAccount>( ); using (new SetUser(user1)) { Console.WriteLine(RequestContext.GetContext( ).Identity.Id); } using (new SetUser(user2)) { Console.WriteLine(RequestContext.GetContext( ).Identity.Id); } UserAccount [] users = new [] { user1, user2 }; int userNumber = 0; // Fill cache string value; cache.TryGetOrAdd("a", out value, callback); Assert.That(callbackCount, Is.EqualTo(1)); TestHelpers.TestConcurrent(2, () => { int userIndex = Interlocked.Increment(ref userNumber) - 1; var user = users [userIndex]; Console.WriteLine("Running user {0}", userIndex); using (new SetUser(user)) { cache.Remove("a"); cache.TryGetOrAdd("a", out value, callback); } }); Assert.That(callbackCount, Is.EqualTo(2)); }
public void TestCreateFactory() { using (var client = new GemfireClient()) { using (var cacheFactory = CacheFactory.Create()) { Assert.IsNotNull(cacheFactory); } } }
public void Create_IEqualityComparerOverload() { var result = CacheFactory.Create <string, int> (_comparer); Assert.That(result, Is.TypeOf(typeof(Cache <string, int>))); var innerCache = PrivateInvoke.GetNonPublicField(result, "_dataStore"); Assert.That(innerCache, Is.TypeOf(typeof(SimpleDataStore <string, int>))); Assert.That(((SimpleDataStore <string, int>)innerCache).Comparer, Is.SameAs(_comparer)); }