public void NewAPI() { // 1. Create a cache CacheFactory cacheFactory = CacheFactory.CreateCacheFactory(); cacheFactory.SetSubscriptionEnabled(true); Cache cache = cacheFactory.Create(); GemStone.GemFire.Cache.PoolFactory poolFactory = GemStone.GemFire.Cache.PoolManager.CreateFactory(); poolFactory.AddServer("localhost", 40404); poolFactory.SetSubscriptionEnabled(true); poolFactory.Create("examplePool"); // 2. Create default region attributes using region factory RegionFactory regionFactory = cache.CreateRegionFactory(RegionShortcut.CACHING_PROXY); regionFactory.SetPoolName("examplePool"); // 3. Create region Region region = regionFactory.Create("exampleregion"); region.RegisterRegex("Keys-*", false, null, true); }
static void Main(string[] args) { var properties = new Properties <string, string>(); properties.Insert("security-client-auth-library", "client"); properties.Insert("security-client-auth-factory", "client.DummyAuthInitialize.Create"); var cacheFactory = CacheFactory.CreateCacheFactory(properties) .AddServer("localhost", 2000) .SetPdxReadSerialized(false) .SetSubscriptionEnabled(true) .SetMinConnections(1) .SetMaxConnections(2); var cache = cacheFactory.Create(); string regionName = "Test"; var region = cache.CreateRegionFactory(RegionShortcut.PROXY).Create <string, string>(regionName); var values = new Dictionary <string, string>(); region.GetAll(region.Keys, values, new Dictionary <string, Exception>()); foreach (var value in values) { Console.Out.WriteLine($"[get] {value}"); } cache.Close(); }
void RunFeeder1() { CacheFactory cacheFactory = CacheFactory.CreateCacheFactory(); 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 RunFeeder() { // Create a Geode Cache Programmatically. CacheFactory cacheFactory = CacheFactory.CreateCacheFactory(); Cache cache = cacheFactory.SetSubscriptionEnabled(true).Create(); Console.WriteLine("Created the Geode Cache"); RegionFactory regionFactory = cache.CreateRegionFactory(RegionShortcut.PROXY); // Created the Region Programmatically. IRegion <string, string> region = regionFactory.Create <string, string>("exampleRegion"); Console.WriteLine("Created the Region Programmatically."); // create two keys with value string key1 = "Key-1"; string value1 = "Value-1"; region[key1] = value1; string key2 = "Key-2"; string value2 = "Value-2"; region[key2] = value2; Console.WriteLine("Created Key-1 and Key-2 in region. Durable interest was registered only for Key-1."); // Close the Geode Cache cache.Close(); Console.WriteLine("Closed the Geode Cache"); }
public void RunMultiuserSecurityExample() { // Create client's Authentication Intializer and Credentials using api ( Same can be set to gfcpp.properties & comment following code ). Properties <string, string> secProp = Properties <string, string> .Create <string, string>(); //By setting this property client will send credential in encrypted form. //to do this one need to setup OpenSSL. //secProp.Insert("security-client-dhalgo", "Blowfish:128"); // Connect to the GemFire Distributed System using the settings from the gfcpp.properties file by default. // Create a GemFire Cache. CacheFactory cacheFactory = CacheFactory.CreateCacheFactory(null) .AddServer("192.168.1.121", 40404); Cache cache = cacheFactory.SetMultiuserAuthentication(true).Create(); Console.WriteLine("Created the GemFire Cache"); RegionFactory regionFactory = cache.CreateRegionFactory(RegionShortcut.PROXY); IRegion <string, string> region = regionFactory.Create <string, string>("exampleRegion"); Console.WriteLine("Created the Region Programmatically."); runWithUserRoot(cache); runWithUserWriter(cache); runWithUserReader(cache); Console.In.ReadLine(); cache.Close(); Console.WriteLine("Client disconnected from the GemFire Distributed System"); }
static void Main(string[] args) { try { // Create a Geode Cache. CacheFactory cacheFactory = CacheFactory.CreateCacheFactory(); Cache cache = cacheFactory.SetSubscriptionEnabled(true).Create(); Console.WriteLine("Created the Geode Cache"); //test on first distributem system TestDistributedSystem(cache, "localhost", 40404, "poolName1", "exampleRegion1"); //test on second distributed system TestDistributedSystem(cache, "localhost", 40405, "poolName2", "exampleRegion2"); // Close the Geode Cache. cache.Close(); Console.WriteLine("Closed the Geode Cache"); } // An exception should not occur catch (GeodeException gfex) { Console.WriteLine("DistributedSystem Geode Exception: {0}", gfex.Message); } }
static void Main() { // Register the user-defined serializable type. Serializable.RegisterType(AccountHistory.CreateInstance); Serializable.RegisterType(BankAccount.CreateInstance); // Create a GemFire Cache Programmatically. CacheFactory cacheFactory = CacheFactory.CreateCacheFactory(null); Cache cache = cacheFactory.SetSubscriptionEnabled(true).Create(); Console.WriteLine("Created the GemFire Cache"); RegionFactory regionFactory = cache.CreateRegionFactory(RegionShortcut.LOCAL); Console.WriteLine("Created Region Factory"); // Create the example Region programmatically. Region region = regionFactory .Create("BankAccounts"); Console.WriteLine("Created the Region Programmatically."); // Place some instances of BankAccount cache region. BankAccount baKey = new BankAccount(2309, 123091); AccountHistory ahVal = new AccountHistory(); ahVal.AddLog("Created account"); region.Put(baKey, ahVal); Console.WriteLine("Put an AccountHistory in cache keyed with BankAccount."); // Display the BankAccount information. Console.WriteLine(baKey.ToString()); // Call custom behavior on instance of AccountHistory. ahVal.ShowAccountHistory(); // Get a value out of the region. AccountHistory history = region.Get(baKey) as AccountHistory; if (history != null) { Console.WriteLine("Found AccountHistory in the cache."); history.ShowAccountHistory(); history.AddLog("debit $1,000,000."); region.Put(baKey, history); Console.WriteLine("Updated AccountHistory in the cache."); } // Look up the history again. history = region.Get(baKey) as AccountHistory; if (history != null) { Console.WriteLine("Found AccountHistory in the cache."); history.ShowAccountHistory(); } // Close the cache. cache.Close(); }
public Cache getCache() { CacheFactory cacheFactory = CacheFactory.CreateCacheFactory(); cacheFactory.AddLocator("192.168.0.100", 10334); Cache cache = cacheFactory.SetSubscriptionEnabled(true).Create(); return(cache); }
void RunDurableClient(int expectedPendingQSize) { Properties <string, string> pp = Properties <string, string> .Create <string, string>(); pp.Insert("durable-client-id", "DurableClientId"); pp.Insert("durable-timeout", "30"); CacheFactory cacheFactory = CacheFactory.CreateCacheFactory(pp); Cache cache = cacheFactory.SetSubscriptionEnabled(true) .SetSubscriptionAckInterval(5000) .SetSubscriptionMessageTrackingTimeout(5000) .Create(); Util.Log("Created the Geode Cache Programmatically"); RegionFactory regionFactory = cache.CreateRegionFactory(RegionShortcut.CACHING_PROXY); IRegion <object, object> region = regionFactory.Create <object, object>("DistRegionAck"); Util.Log("Created the DistRegionAck Region Programmatically"); QueryService <object, object> qService = cache.GetQueryService <object, object>(); CqAttributesFactory <object, object> cqFac = new CqAttributesFactory <object, object>(); ICqListener <object, object> cqLstner = new MyCqListener1 <object, object>(); cqFac.AddCqListener(cqLstner); CqAttributes <object, object> cqAttr = cqFac.Create(); Util.Log("Attached CqListener"); String query = "select * from /DistRegionAck"; CqQuery <object, object> qry = qService.NewCq("MyCq", query, cqAttr, true); Util.Log("Created new CqQuery"); qry.Execute(); Util.Log("Executed new CqQuery"); Thread.Sleep(10000); PendingEventCount(region, expectedPendingQSize, false); //Send ready for Event message to Server( only for Durable Clients ). //Server will send queued events to client after recieving this. cache.ReadyForEvents(); Util.Log("Sent ReadyForEvents message to server"); Thread.Sleep(10000); // Close the Geode Cache with keepalive = true. Server will queue events for // durable registered keys and will deliver all events when client will reconnect // within timeout period and send "readyForEvents()" PendingEventCount(region, 0, true); cache.Close(true); Util.Log("Closed the Geode Cache with keepalive as true"); }
public void RunDurableClient() { // Create durable client's properties using api. Properties <string, string> durableProp = Properties <string, string> .Create <string, string>(); durableProp.Insert("durable-client-id", "DurableClientId"); durableProp.Insert("durable-timeout", "300"); // Create a Geode Cache programmatically. CacheFactory cacheFactory = CacheFactory.CreateCacheFactory(durableProp); Cache cache = cacheFactory.SetSubscriptionEnabled(true) .Create(); Console.WriteLine("Created the Geode Cache"); // Create the example Region programmatically. RegionFactory regionFactory = cache.CreateRegionFactory(RegionShortcut.CACHING_PROXY); IRegion <string, string> region = regionFactory.Create <string, string>("exampleRegion"); Console.WriteLine("Created the generic Region programmatically."); // Plugin the CacheListener with afterRegionLive. "afterRegionLive()" will be called // after all the queued events are recieved by client AttributesMutator <string, string> attrMutator = region.AttributesMutator; attrMutator.SetCacheListener(new DurableCacheListener <string, string>()); Console.WriteLine("DurableCacheListener set to region."); // For durable Clients, Register Intrest can be durable or non durable ( default ), // Unregister Interest APIs remain same. string [] keys = new string[] { "Key-1" }; region.GetSubscriptionService().RegisterKeys(keys, true, true); Console.WriteLine("Called Register Interest for Key-1 with isDurable as true"); //Send ready for Event message to Server( only for Durable Clients ). //Server will send queued events to client after recieving this. cache.ReadyForEvents(); Console.WriteLine("Sent ReadyForEvents message to server"); //wait for some time to recieve events System.Threading.Thread.Sleep(1000); // Close the Geode Cache with keepalive = true. Server will queue events for // durable registered keys and will deliver all events when client will reconnect // within timeout period and send "readyForEvents()" cache.Close(true); Console.WriteLine("Closed the Geode Cache with keepalive as true"); }
static void Main(string[] args) { try { //Create a Geode Cache using CacheFactory. By default it will connect to "localhost" at port 40404". Cache cache = CacheFactory.CreateCacheFactory().Create(); Console.WriteLine("Created the Geode Cache"); //Set Attributes for the region. RegionFactory regionFactory = cache.CreateRegionFactory(RegionShortcut.CACHING_PROXY); //Create exampleRegion IRegion <int, string> region = regionFactory.Create <int, string>("exampleRegion"); Console.WriteLine("Created exampleRegion"); // PutAll Entries (Key and Value pairs) into the Region. Dictionary <int, string> entryMap = new Dictionary <int, string>(); for (Int32 item = 0; item < 100; item++) { int key = item; string value = item.ToString(); entryMap.Add(key, value); } region.PutAll(entryMap); Console.WriteLine("PutAll 100 entries into the Region"); //GetAll Entries back out of the Region List <int> keys = new List <int>(); for (int item = 0; item < 100; item++) { int key = item; keys.Add(key); } Dictionary <int, string> values = new Dictionary <int, string>(); region.GetAll(keys.ToArray(), values, null, true); Console.WriteLine("Obtained 100 entries from the Region"); // Close the Geode Cache. cache.Close(); Console.WriteLine("Closed the Geode Cache"); } // An exception should not occur catch (GeodeException gfex) { Console.WriteLine("PutAllGetAllOperations Geode Exception: {0}", gfex.Message); } }
static void Main(string[] args) { try { CacheFactory cacheFactory = CacheFactory.CreateCacheFactory().SetSubscriptionEnabled(true); Cache cache = cacheFactory.Create(); Console.WriteLine("Created the Geode Cache"); RequestReply requestReply = new RequestReply(cache); Response res = requestReply.Put(777, "Hello World"); Console.Write("Response=" + res); } catch (GeodeException gfex) { Console.WriteLine("BasicOperations Geode Exception: {0}", gfex.Message); } }
public static void InitConfig(Properties <string, string> config, string cacheXml, bool PdxReadSerialized) { string gfcppPropsFile = Util.AssemblyDir + "/gfcpp.properties"; if (File.Exists(gfcppPropsFile)) { Properties <string, string> newConfig = new Properties <string, string>(); newConfig.Load(gfcppPropsFile); if (config != null) { newConfig.AddAll(config); } config = newConfig; } //ConnectConfig(dsName, config); if (m_cache == null || m_cache.IsClosed) { try { CacheHelper <TKey, TVal> .m_doDisconnect = false; CacheFactory cf = CacheFactory.CreateCacheFactory(config); if (cacheXml != null && cacheXml.Length > 0) { FwkInfo("seting cache-xml-file {0}", cacheXml); cf = cf.Set("cache-xml-file", cacheXml); } if (PdxReadSerialized) { FwkInfo("seting PdxReadSerialized {0}", PdxReadSerialized); cf = CacheFactory.CreateCacheFactory(config) .SetPdxReadSerialized(PdxReadSerialized); } m_cache = cf.Create(); } catch (CacheExistsException) { m_cache = CacheFactory.GetAnyInstance(); } } m_dsys = m_cache.DistributedSystem; }
// Initialize the distributed system, setup the cache, register callbacks // and user-defined classes and create the region. public static void DSInit(string[] args) { Console.WriteLine("{0}Connecting to GemFire{0}", Environment.NewLine); // Register the ComplexNumber type Serializable.RegisterType(ComplexNumber.Create); // Register the Portfolio and Position classes for Query Serializable.RegisterType(Portfolio.CreateDeserializable); Serializable.RegisterType(Position.CreateDeserializable); // Register the ExampleObject for putall and interop Serializable.RegisterType(ExampleObject.CreateDeserializable); string xmlPath; // Create a cache if (args != null && args.Length > 1) { throw new ApplicationException(string.Format("Usage: CacheRunner " + "[<XML file name>]{0}\tXML file name is optional " + "and the default is {1}.", Environment.NewLine, DefaultXMLPath)); } else if (args != null && args.Length == 1) { xmlPath = args[0]; } else { xmlPath = DefaultXMLPath; } CacheFactory cacheFactory = CacheFactory.CreateCacheFactory(null); m_cache = cacheFactory.Set("cache-xml-file", xmlPath).Create(); Region[] rootRegions = m_cache.RootRegions(); if (rootRegions != null && rootRegions.Length > 0) { SetRegion(rootRegions[rootRegions.Length - 1]); } else { throw new ApplicationException("No root regions found."); } }
public void RunSecurityExampleWithGetPermission() { // Create client's Authentication Intializer and Credentials using api ( Same can be set to gfcpp.properties & comment following code ). Properties <string, string> properties = Properties <string, string> .Create <string, string>(); properties.Insert("security-client-auth-factory", "Apache.Geode.Templates.Cache.Security.UserPasswordAuthInit.Create"); properties.Insert("security-client-auth-library", "Apache.Geode.Templates.Cache.Security"); properties.Insert("cache-xml-file", "XMLs/clientSecurity.xml"); properties.Insert("security-username", "reader1"); properties.Insert("security-password", "reader1"); CacheFactory cacheFactory = CacheFactory.CreateCacheFactory(properties); Cache cache = cacheFactory.Create(); Console.WriteLine("Created the Geode Cache"); // Get the example Region from the Cache which is declared in the Cache XML file. IRegion <string, string> region = cache.GetRegion <string, string>("exampleRegion"); Console.WriteLine("Obtained the Region from the Cache"); string getResult1 = region["key-3"]; string getResult2 = region["key-4"]; bool exceptiongot = false; try { region["key-5"] = "val-5"; } catch (NotAuthorizedException ex) { Console.WriteLine("Got expected UnAuthorizedException: {0}", ex.Message); exceptiongot = true; } if (exceptiongot == false) { Console.WriteLine("Example FAILED: Did not get expected NotAuthorizedException"); } cache.Close(); }
public ProductBrowser() { InitializeComponent(); Serializable.RegisterType(Product.CreateInstance); /* * Initialize Cache system properties */ Apache.Geode.Client.Properties prop = Apache.Geode.Client.Properties.Create(); prop.Insert("log-file", logFile); prop.Insert("log-level", logLevel); prop.Insert("name", "ProductCache"); CacheFactory cacheFactory = CacheFactory.CreateCacheFactory(prop); try { /* * Create the GemFire Client cache */ Cache cache = cacheFactory.SetSubscriptionEnabled(true).Create(); /* * Specify required region attributes */ RegionFactory regionFactory = cache.CreateRegionFactory(RegionShortcut.CACHING_PROXY); /* * Create the region and register interest in all keys */ prodRegion = regionFactory .SetCachingEnabled(true) .SetCacheListener(this) .Create("product"); prodRegion.RegisterAllKeys(); } catch (Exception e) { MessageBox.Show("Error during client initialization. " + e.Message); } }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); WebApiConfig.Register(GlobalConfiguration.Configuration); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); Properties <string, string> properties = new Properties <string, string>(); properties.Load("c:\\dev\\gemfire-dotnetsession\\SampleWebApp\\geode.properties"); properties.Insert("cache-xml-file", "c:\\dev\\gemfire-dotnetsession\\SampleWebApp\\cache.xml"); properties.Insert("appdomain-enabled", "true"); var cacheFactory = CacheFactory.CreateCacheFactory(properties); Cache = cacheFactory.Create(); Serializable.RegisterPdxSerializer(new GetItemExclusiveSerializer(new SessionStateStoreDataSerializer())); }
public void RunSecurityExampleWithAllPermission() { // Create client's Authentication Intializer and Credentials using api ( Same can be set to gfcpp.properties & comment following code ). Properties <string, string> properties = Properties <string, string> .Create <string, string>(); properties.Insert("security-client-auth-factory", "Apache.Geode.Templates.Cache.Security.UserPasswordAuthInit.Create"); properties.Insert("security-client-auth-library", "Apache.Geode.Templates.Cache.Security"); properties.Insert("cache-xml-file", "XMLs/clientSecurity.xml"); properties.Insert("security-username", "root"); properties.Insert("security-password", "root"); CacheFactory cacheFactory = CacheFactory.CreateCacheFactory(properties); Cache cache = cacheFactory.Create(); Console.WriteLine("Created the Geode Cache"); // Get the example Region from the Cache which is declared in the Cache XML file. IRegion <string, string> region = cache.GetRegion <string, string>("exampleRegion"); Console.WriteLine("Obtained the Region from the Cache"); //put region["key-1"] = "val-1"; region["key-2"] = "val-2"; //get string getResult = region["key-1"]; //invalidate key region.Invalidate("key-1"); //Remove key region.Remove("key-2"); //close caache cache.Close(); }
/// <summary> /// 获得远程字符串 /// </summary> public static string GetDomainStr(string key, string uriPath) { var cacheHelper = CacheFactory.CreateCacheFactory(); var result = cacheHelper.Get(key) as string; if (result == null) { var client = new WebClient(); try { client.Encoding = Encoding.UTF8; result = client.DownloadString(uriPath); } catch { result = "暂时无法连接!"; } cacheHelper.Insert(key, result, new TimeSpan(0, 60, 0)); } return(result); }
static void Main(string[] args) { try { CacheFactory cacheFactory = CacheFactory.CreateCacheFactory().SetSubscriptionEnabled(true); Cache cache = cacheFactory.Create(); Console.WriteLine("Created the Geode Cache"); RegionFactory regionFactory = cache.CreateRegionFactory(RegionShortcut.CACHING_PROXY); IRegion <string, string> region = regionFactory.Create <string, string>("exampleRegion"); region.GetSubscriptionService().RegisterAllKeys(); Console.WriteLine("RegisterAllKeys to exampleRegion"); QueryService <string, string> qrySvc = cache.GetQueryService <string, string>(); CqAttributesFactory <string, string> cqFac = new CqAttributesFactory <string, string>(); ICqListener <string, string> cqLstner = new MyCqListener <string, string>(); cqFac.AddCqListener(cqLstner); CqAttributes <string, string> cqAttr = cqFac.Create(); CqQuery <string, string> qry = qrySvc.NewCq("MyCq", "select * from /exampleRegion p where p.toString = '1'", cqAttr, false); ICqResults <string> results = qry.ExecuteWithInitialResults(); Console.WriteLine("Execute CQ: Initial ResultSet returned {0} rows", results.Size); while (true) { System.Threading.Thread.Sleep(5000); string val1 = null; string val2 = null; region.TryGetValue("1", ref val1); region.TryGetValue("2", ref val2); Console.WriteLine("exampleRegion['1']: {0}", val1); Console.WriteLine("exampleRegion['2']: {0}", val2); } } catch (GeodeException gfex) { Console.WriteLine("Geode Exception: {0}", gfex.Message); } }
static void Main() { try { // Create a GemFire Cache. CacheFactory cacheFactory = CacheFactory.CreateCacheFactory(null); Cache cache = cacheFactory.Create(); Console.WriteLine("Created the GemFire Cache"); RegionFactory regionFactory = cache.CreateRegionFactory(RegionShortcut.LOCAL); // Create the example Region programmatically. region = regionFactory.Create("exampledsregion"); // Put some entries Console.WriteLine("{0}Putting entries", Environment.NewLine); PutStr(strKey, strValue); PutInt(intKey, intValue); // Get the entries Console.WriteLine("{0}Getting entries", Environment.NewLine); string getStr = GetStr(strKey); int getInt = GetInt(intKey); // Close cache cache.Close(); Console.WriteLine("Closed the cache."); } catch (Exception ex) { Console.WriteLine("{0}An exception occurred: {1}", Environment.NewLine, ex); Console.WriteLine("---[ Press <Enter> to End the Application ]---"); Console.ReadLine(); } }
static void Main(string[] args) { try { CacheFactory cacheFactory = CacheFactory.CreateCacheFactory(); Cache cache = cacheFactory.SetSubscriptionEnabled(true).AddServer("localhost", 50505).AddServer("localhost", 40404).Create(); Console.WriteLine("Created the Geode Cache"); IRegion <string, string> region = cache.CreateRegionFactory(RegionShortcut.CACHING_PROXY).Create <string, string>("partition_region"); Console.WriteLine("Created the Region"); region.GetSubscriptionService().RegisterAllKeys(); for (int i = 0; i < 34; i++) { region["KEY--" + i] = "VALUE--" + i; } object[] routingObj = new object[17]; int j = 0; for (int i = 0; i < 34; i++) { if (i % 2 == 0) { continue; } routingObj[j] = "KEY--" + i; j++; } Console.WriteLine("routingObj count= {0}.", routingObj.Length); bool args0 = true; //test data dependant function execution //test get function with result Execution <object> exc = FunctionService <object> .OnRegion <string, string>(region); IResultCollector <object> rc = exc.WithArgs <bool>(args0).WithFilter <object>(routingObj).Execute(getFuncName); ICollection <object> executeFunctionResult = rc.GetResult(); List <object> resultList = new List <object>(); foreach (List <object> item in executeFunctionResult) { foreach (object subitem in item) { resultList.Add(subitem); } } Console.WriteLine("on region: result count= {0}.", resultList.Count); for (int i = 0; i < resultList.Count; i++) { Console.WriteLine("on region:get:result[{0}]={1}.", i, (string)resultList[i]); } //test date independant fucntion execution on one server //test get function with result exc = FunctionService <object> .OnServer(cache); ArrayList args1 = new ArrayList(); for (int i = 0; i < routingObj.Length; i++) { Console.WriteLine("routingObj[{0}]={1}.", i, (string)routingObj[i]); args1.Add(routingObj[i]); } rc = exc.WithArgs <ArrayList>(args1).Execute(getFuncIName); executeFunctionResult = rc.GetResult(); Console.WriteLine("on one server: result count= {0}.", executeFunctionResult.Count); List <object> resultList1 = new List <object>(); foreach (List <object> item in executeFunctionResult) { foreach (object subitem in item) { resultList1.Add(subitem); } } if (resultList1.Count != 17) { Console.WriteLine("result count check failed on one server:get:"); } for (int i = 0; i < resultList1.Count; i++) { Console.WriteLine("on one server:get:result[{0}]={1}.", i, (string)resultList1[i]); } //test date independant fucntion execution on all servers //test get function with result exc = FunctionService <object> .OnServers(cache); rc = exc.WithArgs <ArrayList>(args1).Execute(getFuncIName); executeFunctionResult = rc.GetResult(); Console.WriteLine("on all servers: result count= {0}.", executeFunctionResult.Count); List <object> resultList2 = new List <object>(); foreach (List <object> item in executeFunctionResult) { foreach (object subitem in item) { resultList2.Add(subitem); } } if (resultList2.Count != 34) { Console.WriteLine("result count check failed on all servers"); } for (int i = 0; i < resultList2.Count; i++) { Console.WriteLine("on all servers:result[{0}]={1}.", i, (string)resultList2[i]); } // Close the Geode Cache. cache.Close(); Console.WriteLine("Closed the Geode Cache"); } // An exception should not occur catch (GeodeException gfex) { Console.WriteLine("ExecuteFunctions Geode Exception: {0}", gfex.Message); } }
public void XmlCacheCreationWithOverflow() { Cache cache = null; IRegion <object, object> region1; IRegion <object, object> region2; IRegion <object, object> region3; IRegion <object, object>[] rootRegions; //Region<object, object>[] subRegions; ICollection <IRegion <object, object> > subRegions; /*string host_name = "XML_CACHE_CREATION_TEST";*/ const UInt32 totalSubRegionsRoot1 = 2; const UInt32 totalRootRegions = 3; try { CacheHelper.CloseCache(); Util.Log("Creating cache with the configurations provided in valid_overflowAttr.xml"); string cachePath = CacheHelper.TestDir + Path.DirectorySeparatorChar + "valid_overflowAttr.xml"; cache = CacheFactory.CreateCacheFactory().Set("cache-xml-file", cachePath).Create(); Util.Log("Successfully created the cache."); rootRegions = cache.RootRegions <object, object>(); Assert.IsNotNull(rootRegions); Assert.AreEqual(totalRootRegions, rootRegions.Length); Util.Log("Root regions in Cache: "); foreach (IRegion <object, object> rg in rootRegions) { Util.Log('\t' + rg.Name); } region1 = rootRegions[0]; //subRegions = region1.SubRegions(true); subRegions = region1.SubRegions(true); Assert.IsNotNull(subRegions); Assert.AreEqual(subRegions.Count, totalSubRegionsRoot1); Util.Log("SubRegions for the root region: "); foreach (IRegion <object, object> rg in subRegions) { Util.Log('\t' + rg.Name); } Util.Log("Testing if the nesting of regions is correct..."); region2 = rootRegions[1]; subRegions = region2.SubRegions(true); string childName; string parentName; foreach (IRegion <object, object> rg in subRegions) { childName = rg.Name; IRegion <object, object> parent = rg.ParentRegion; parentName = parent.Name; if (childName == "SubSubRegion221") { Assert.AreEqual("SubRegion22", parentName); } } region3 = rootRegions[2]; //subRegions = region1.SubRegions(true); subRegions = region3.SubRegions(true); Assert.IsNotNull(subRegions); Assert.AreEqual(subRegions.Count, totalSubRegionsRoot1); Util.Log("SubRegions for the root region: "); foreach (IRegion <object, object> rg in subRegions) { Util.Log('\t' + rg.Name); } Apache.Geode.Client.RegionAttributes <object, object> attrs = region1.Attributes; //Util.Log("Attributes of root region Root1 are: "); bool cachingEnabled = attrs.CachingEnabled; Assert.IsTrue(cachingEnabled); uint lruEL = attrs.LruEntriesLimit; Assert.AreEqual(35, lruEL); int concurrency = attrs.ConcurrencyLevel; Assert.AreEqual(10, concurrency); int initialCapacity = attrs.InitialCapacity; Assert.AreEqual(25, initialCapacity); int regionIdleTO = attrs.RegionIdleTimeout; Assert.AreEqual(20, regionIdleTO); ExpirationAction action1 = attrs.RegionIdleTimeoutAction; Assert.AreEqual(ExpirationAction.Destroy, action1); DiskPolicyType type = attrs.DiskPolicy; Assert.AreEqual(DiskPolicyType.Overflows, type); string persistenceDir, maxPageCount, pageSize; string lib = attrs.PersistenceLibrary; string libFun = attrs.PersistenceFactory; Util.Log(" persistence library1 = " + lib); Util.Log(" persistence function1 = " + libFun); Properties <string, string> pconfig = attrs.PersistenceProperties; Assert.IsNotNull(pconfig, "Persistence properties should not be null for root1."); persistenceDir = (string)pconfig.Find("PersistenceDirectory"); maxPageCount = (string)pconfig.Find("MaxPageCount"); pageSize = (string)pconfig.Find("PageSize"); Assert.IsNotNull(persistenceDir, "Persistence directory should not be null."); Assert.AreNotEqual(0, persistenceDir.Length, "Persistence directory should not be empty."); Assert.IsNotNull(maxPageCount, "Persistence MaxPageCount should not be null."); Assert.AreNotEqual(0, maxPageCount.Length, "Persistence MaxPageCount should not be empty."); Assert.IsNotNull(pageSize, "Persistence PageSize should not be null."); Assert.AreNotEqual(0, pageSize.Length, "Persistence PageSize should not be empty."); Util.Log("****Attributes of Root1 are correctly set****"); Apache.Geode.Client.RegionAttributes <object, object> attrs2 = region2.Attributes; string lib2 = attrs2.PersistenceLibrary; string libFun2 = attrs2.PersistenceFactory; Util.Log(" persistence library2 = " + lib2); Util.Log(" persistence function2 = " + libFun2); Properties <string, string> pconfig2 = attrs2.PersistenceProperties; Assert.IsNotNull(pconfig2, "Persistence properties should not be null for root2."); persistenceDir = (string)pconfig2.Find("PersistenceDirectory"); maxPageCount = (string)pconfig2.Find("MaxPageCount"); maxPageCount = (string)pconfig2.Find("PageSize"); Assert.IsNotNull(persistenceDir, "Persistence directory should not be null."); Assert.AreNotEqual(0, persistenceDir.Length, "Persistence directory should not be empty."); Assert.IsNotNull(maxPageCount, "Persistence MaxPageCount should not be null."); Assert.AreNotEqual(0, maxPageCount.Length, "Persistence MaxPageCount should not be empty."); Assert.IsNotNull(pageSize, "Persistence PageSize should not be null."); Assert.AreNotEqual(0, pageSize.Length, "Persistence PageSize should not be empty."); Util.Log("****Attributes of Root2 are correctly set****"); Apache.Geode.Client.RegionAttributes <object, object> attrs3 = region3.Attributes; //Util.Log("Attributes of root region Root1 are: "); Assert.IsTrue(attrs3.CachingEnabled); Assert.AreEqual(35, attrs3.LruEntriesLimit); Assert.AreEqual(10, attrs3.ConcurrencyLevel); Assert.AreEqual(25, attrs3.InitialCapacity); Assert.AreEqual(20, attrs3.RegionIdleTimeout); Assert.AreEqual(ExpirationAction.Destroy, attrs3.RegionIdleTimeoutAction); Assert.AreEqual(DiskPolicyType.Overflows, attrs3.DiskPolicy); Util.Log(" persistence library1 = " + attrs3.PersistenceLibrary); Util.Log(" persistence function1 = " + attrs3.PersistenceFactory); Properties <string, string> pconfig3 = attrs.PersistenceProperties; Assert.IsNotNull(pconfig3, "Persistence properties should not be null for root1."); Assert.IsNotNull(pconfig3.Find("PersistenceDirectory"), "Persistence directory should not be null."); Assert.AreNotEqual(0, pconfig3.Find("PersistenceDirectory").Length, "Persistence directory should not be empty."); Assert.IsNotNull(pconfig3.Find("MaxPageCount"), "Persistence MaxPageCount should not be null."); Assert.AreNotEqual(0, pconfig3.Find("MaxPageCount").Length, "Persistence MaxPageCount should not be empty."); Assert.IsNotNull(pconfig3.Find("PageSize"), "Persistence PageSize should not be null."); Assert.AreNotEqual(0, pconfig3.Find("PageSize"), "Persistence PageSize should not be empty."); Util.Log("****Attributes of Root1 are correctly set****"); region1.DestroyRegion(null); region2.DestroyRegion(null); region3.DestroyRegion(null); if (!cache.IsClosed) { cache.Close(); } ////////////////////////////testing of cache.xml completed/////////////////// Util.Log("Create cache with the configurations provided in the invalid_overflowAttr1.xml."); Util.Log("Non existent XML; exception should be thrown"); try { cachePath = CacheHelper.TestDir + Path.DirectorySeparatorChar + "non-existent.xml"; cache = CacheFactory.CreateCacheFactory().Set("cache-xml-file", cachePath).Create(); Assert.Fail("Creation of cache with non-existent.xml should fail!"); } catch (CacheXmlException ex) { Util.Log("Expected exception with non-existent.xml: {0}", ex); } Util.Log("This is a well-formed xml....attributes not provided for persistence manager. exception should be thrown"); try { cachePath = CacheHelper.TestDir + Path.DirectorySeparatorChar + "invalid_overflowAttr1.xml"; cache = CacheFactory.CreateCacheFactory().Set("cache-xml-file", cachePath).Create(); Assert.Fail("Creation of cache with invalid_overflowAttr1.xml should fail!"); } catch (IllegalStateException ex) { Util.Log("Expected exception with invalid_overflowAttr1.xml: {0}", ex); } ///////////////testing of invalid_overflowAttr1.xml completed/////////////////// Util.Log("Create cache with the configurations provided in the invalid_overflowAttr2.xml."); Util.Log("This is a well-formed xml....attribute values is not provided for persistence library name......should throw an exception"); try { cachePath = CacheHelper.TestDir + Path.DirectorySeparatorChar + "invalid_overflowAttr2.xml"; cache = CacheFactory.CreateCacheFactory().Set("cache-xml-file", cachePath).Create(); Assert.Fail("Creation of cache with invalid_overflowAttr2.xml should fail!"); } catch (CacheXmlException ex) { Util.Log("Expected exception with invalid_overflowAttr2.xml: {0}", ex); } ///////////////testing of invalid_overflowAttr2.xml completed/////////////////// Util.Log("Create cache with the configurations provided in the invalid_overflowAttr3.xml."); Util.Log("This is a well-formed xml....but region-attributes for persistence invalid......should throw an exception"); try { cachePath = CacheHelper.TestDir + Path.DirectorySeparatorChar + "invalid_overflowAttr3.xml"; cache = CacheFactory.CreateCacheFactory().Set("cache-xml-file", cachePath).Create(); Assert.Fail("Creation of cache with invalid_overflowAttr3.xml should fail!"); } catch (CacheXmlException ex) { Util.Log("Expected exception with invalid_overflowAttr3.xml: {0}", ex); } ///////////////testing of invalid_overflowAttr3.xml completed/////////////////// } catch (Exception ex) { Assert.Fail("Caught exception: {0}", ex); } finally { if (cache != null && !cache.IsClosed) { cache.Close(); } } }
static void Main(string[] args) { try { // Create a Geode Cache Programmatically. CacheFactory cacheFactory = CacheFactory.CreateCacheFactory(); Cache cache = cacheFactory.SetSubscriptionEnabled(true).Create(); Console.WriteLine("Created the Geode Cache"); RegionFactory regionFactory = cache.CreateRegionFactory(RegionShortcut.CACHING_PROXY); // Create the example Region programmatically. IRegion <string, Portfolio> region = regionFactory.Create <string, Portfolio>("Portfolios"); Console.WriteLine("Created the Region Programmatically."); // Register our Serializable/Cacheable Query objects, viz. Portfolio and Position. Serializable.RegisterTypeGeneric(Portfolio.CreateDeserializable); Serializable.RegisterTypeGeneric(Position.CreateDeserializable); Console.WriteLine("Registered Serializable Query Objects"); // Populate the Region with some Portfolio objects. Portfolio port1 = new Portfolio(1 /*ID*/, 10 /*size*/); Portfolio port2 = new Portfolio(2 /*ID*/, 20 /*size*/); Portfolio port3 = new Portfolio(3 /*ID*/, 30 /*size*/); region["Key1"] = port1; region["Key2"] = port2; region["Key3"] = port3; Console.WriteLine("Populated some Portfolio Objects"); // Get the QueryService from the Cache. QueryService <string, Portfolio> qrySvc = cache.GetQueryService <string, Portfolio>(); Console.WriteLine("Got the QueryService from the Cache"); // Execute a Query which returns a ResultSet. Query <Portfolio> qry = qrySvc.NewQuery("SELECT DISTINCT * FROM /Portfolios"); ISelectResults <Portfolio> results = qry.Execute(); Console.WriteLine("ResultSet Query returned {0} rows", results.Size); // Execute a Query which returns a StructSet. QueryService <string, Struct> qrySvc1 = cache.GetQueryService <string, Struct>(); Query <Struct> qry1 = qrySvc1.NewQuery("SELECT DISTINCT ID, status FROM /Portfolios WHERE ID > 1"); ISelectResults <Struct> results1 = qry1.Execute(); Console.WriteLine("StructSet Query returned {0} rows", results1.Size); // Iterate through the rows of the query result. int rowCount = 0; foreach (Struct si in results1) { rowCount++; Console.WriteLine("Row {0} Column 1 is named {1}, value is {2}", rowCount, si.Set.GetFieldName(0), si[0].ToString()); Console.WriteLine("Row {0} Column 2 is named {1}, value is {2}", rowCount, si.Set.GetFieldName(0), si[1].ToString()); } // Execute a Region Shortcut Query (convenience method). results = region.Query <Portfolio>("ID = 2"); Console.WriteLine("Region Query returned {0} rows", results.Size); // Execute the Region selectValue() API. object result = region.SelectValue("ID = 3"); Console.WriteLine("Region selectValue() returned an item:\n {0}", result.ToString()); // Execute the Region existsValue() API. bool existsValue = region.ExistsValue("ID = 4"); Console.WriteLine("Region existsValue() returned {0}", existsValue ? "true" : "false"); //Execute the parameterized query //Populate the parameter list (paramList) for the query. //TODO:remove once query service is generic QueryService <string, Struct> pqrySvc = cache.GetQueryService <string, Struct>(); Query <Struct> pquery = pqrySvc.NewQuery("SELECT DISTINCT ID, status FROM /Portfolios WHERE ID > $1 and status=$2"); object[] paramList = new object[2]; paramList[0] = 1; //param-1 paramList[1] = "active"; //param-2 ISelectResults <Struct> pqresults = pquery.Execute(paramList); Console.WriteLine("Parameterized Query returned {0} rows", pqresults.Size); // Iterate through the rows of the query result. rowCount = 0; foreach (Struct st in pqresults) { rowCount++; Console.WriteLine("Row {0} Column 1 is named {1}, value is {2}", rowCount, st.Set.GetFieldName(0), st[0].ToString()); Console.WriteLine("Row {0} Column 2 is named {1}, value is {2}", rowCount, st.Set.GetFieldName(0), st[1].ToString()); } // Close the Geode Cache. cache.Close(); Console.WriteLine("Closed the Geode Cache"); } // An exception should not occur catch (GeodeException gfex) { Console.WriteLine("RemoteQuery Geode Exception: {0}", gfex.Message); } }
static void Main(string[] args) { try { // Create a Geode Cache CacheFactory cacheFactory = CacheFactory.CreateCacheFactory(); Cache cache = cacheFactory.Create(); Console.WriteLine("Created the Geode cache."); RegionFactory regionFactory = cache.CreateRegionFactory(RegionShortcut.CACHING_PROXY); Console.WriteLine("Created the RegionFactory."); // Create the example Region IRegion <string, string> region = regionFactory.Create <string, string>("exampleRegion"); Console.WriteLine("Created the region with generics support."); // Get the cache transaction manager from the cache. CacheTransactionManager txManager = cache.CacheTransactionManager; // Starting a transaction txManager.Begin(); Console.WriteLine("Transaction started."); region["Key1"] = "Value1"; region["Key2"] = "Value2"; Console.WriteLine("Put two entries into the region"); try { // Prepare the transaction txManager.Prepare(); Console.WriteLine("Transaction Prepared"); // Commit the transaction txManager.Commit(); Console.WriteLine("Transaction Committed"); } catch (CommitConflictException e) { Console.WriteLine("CommitConflictException encountered. Exception: {0}", e.Message); } if (region.ContainsKey("Key1")) { Console.WriteLine("Obtained the first entry from the Region"); } if (region.ContainsKey("Key2")) { Console.WriteLine("Obtained the second entry from the Region"); } //start a new transaction txManager.Begin(); Console.WriteLine("Transaction Started"); // Put a new entry region["Key3"] = "Value3"; Console.WriteLine("Put the third entry into the Region"); // remove the first key region.Remove("Key1", null); Console.WriteLine("remove the first entry"); txManager.Prepare(); Console.WriteLine("Transaction Prepared"); txManager.Rollback(); Console.WriteLine("Transaction Rollbacked"); if (region.ContainsKey("Key1")) { Console.WriteLine("Obtained the first entry from the Region"); } if (region.ContainsKey("Key2")) { Console.WriteLine("Obtained the second entry from the Region"); } if (region.ContainsKey("Key3")) { Console.WriteLine("ERROR: Obtained the third entry from the Region."); } cache.Close(); Console.WriteLine("Closed the Geode Cache"); } // An exception should not occur catch (GeodeException gfex) { Console.WriteLine("Transactions Geode Exception: {0}", gfex.Message); } }
static void Main(string[] args) { try { // Create a Geode Cache through XMLs/clientDelta.xml Properties <string, string> prop = Properties <string, string> .Create <string, string>(); prop.Insert("cache-xml-file", "XMLs/clientDelta.xml"); CacheFactory cacheFactory = CacheFactory.CreateCacheFactory(prop); Cache cache = cacheFactory.Create(); Console.WriteLine("Created the Geode Cache"); // Get the example Region from the Cache which is declared in the Cache XML file. IRegion <string, DeltaExample> region = cache.GetRegion <string, DeltaExample>("exampleRegion"); Console.WriteLine("Obtained the Region from the Cache"); Serializable.RegisterTypeGeneric(DeltaExample.create); //Creating Delta Object. DeltaExample ptr = new DeltaExample(10, 15, 20); //Put the delta object. This will send the complete object to the server. region["Key1"] = ptr; Console.WriteLine("Completed put for a delta object"); //Changing state of delta object. ptr.setField1(9); //Put delta object again. Since delta flag is set true it will calculate //Delta and send only Delta to the server. region["Key1"] = ptr; Console.WriteLine("Completed put with delta"); //Locally invalidating the key. region.GetLocalView().Invalidate("Key1"); //Fetching the value from server. DeltaExample retVal = (DeltaExample)region["Key1"]; //Verification if (retVal.getField1() != 9) { throw new GeodeException("First field should have been 9"); } if (retVal.getField2() != 15) { throw new GeodeException("Second field should have been 15"); } if (retVal.getField3() != 20) { throw new GeodeException("Third field should have been 20"); } Console.WriteLine("Delta has been successfully applied at server"); // Close the Geode Cache. cache.Close(); Console.WriteLine("Closed the Geode Cache"); } // An exception should not occur catch (GeodeException gfex) { Console.WriteLine("Delta Geode Exception: {0}", gfex.Message); } }
static void Main(string[] args) { try { // Create a Geode Cache. Apache.Geode.Client.CacheFactory cacheFactory = CacheFactory.CreateCacheFactory(); Cache cache = cacheFactory.Set("cache-xml-file", "XMLs/clientHACache.xml") .AddServer("localhost", 40404) .AddServer("localhost", 40405) .SetSubscriptionRedundancy(1) .SetSubscriptionEnabled(true) .Create(); Console.WriteLine("Created the Geode Cache"); // Get the example Region from the Cache which is declared in the Cache XML file. IRegion <object, int> region = cache.GetRegion <object, int>("/exampleRegion"); Console.WriteLine("Obtained the generic Region from the Cache"); // Register and Unregister Interest on Region for Some Keys. object [] keys = new object[] { 123, "Key-123" }; region.GetSubscriptionService().RegisterKeys(keys); region.GetSubscriptionService().RegisterRegex("Keys.*"); Console.WriteLine("Called RegisterKeys() and RegisterRegex()"); region[123] = 1; region["Key-123"] = 2; Console.WriteLine("Called put() on Region"); Console.WriteLine("Waiting for updates on keys"); Thread.Sleep(10000); int count = 0; //try to get the entries for keys destroyed by server. try { int value1 = region[123]; Console.WriteLine("UNEXPECTED: First get should not have succeeded"); } catch (KeyNotFoundException) { Console.WriteLine("gfex.Message: Verified that key1 has been destroyed"); count++; } try { int value2 = region["Key-123"]; Console.WriteLine("UNEXPECTED: Second get should not have succeeded"); } catch (KeyNotFoundException) { Console.WriteLine("gfex.Message: Verified that key2 has been destroyed"); count++; } if (count == 2) { Console.WriteLine("Verified all updates"); } else { Console.WriteLine("Could not verify all updates"); } region.GetSubscriptionService().UnregisterKeys(keys); region.GetSubscriptionService().UnregisterRegex("Keys.*"); Console.WriteLine("Unregistered keys"); // Close the Geode Cache. cache.Close(); Console.WriteLine("Closed the Geode Cache"); } // An exception should not occur catch (GeodeException gfex) { Console.WriteLine("HACache Geode Exception: {0}", gfex.Message); } }
static void Main(string[] args) { try { //Create CacheFactory using the user specified properties or from the gfcpp.properties file by default. Properties <string, string> prp = Properties <string, string> .Create <string, string>(); prp.Insert("cache-xml-file", "XMLs/clientPoolCqQuery.xml"); CacheFactory cacheFactory = CacheFactory.CreateCacheFactory(prp); Console.WriteLine("Created CacheFactory"); // Create a Geode Cache with the "clientPoolCqQuery.xml" Cache XML file. Cache cache = cacheFactory.Create(); Console.WriteLine("Created the Geode Cache"); // Get the Portfolios Region from the Cache which is declared in the Cache XML file. IRegion <string, Portfolio> region = cache.GetRegion <string, Portfolio>("Portfolios"); Console.WriteLine("Obtained the Region from the Cache"); // Register our Serializable/Cacheable Query objects, viz. Portfolio and Position. Serializable.RegisterTypeGeneric(Portfolio.CreateDeserializable); Serializable.RegisterTypeGeneric(Position.CreateDeserializable); Console.WriteLine("Registered Serializable Query Objects"); // Populate the Region with some Portfolio objects. Portfolio port1 = new Portfolio(1 /*ID*/, 10 /*size*/); Portfolio port2 = new Portfolio(2 /*ID*/, 20 /*size*/); Portfolio port3 = new Portfolio(3 /*ID*/, 30 /*size*/); region["Key1"] = port1; region["Key2"] = port2; region["Key3"] = port3; Console.WriteLine("Populated some Portfolio Objects"); Pool pp = PoolManager.Find("examplePool"); // Get the QueryService from the Pool QueryService <string, object> qrySvc = pp.GetQueryService <string, object>(); Console.WriteLine("Got the QueryService from the Cache"); //create CqAttributes with listener CqAttributesFactory <string, object> cqFac = new CqAttributesFactory <string, object>(); ICqListener <string, object> cqLstner = new MyCqListener <string, object>(); cqFac.AddCqListener(cqLstner); CqAttributes <string, object> cqAttr = cqFac.Create(); //create a new cqQuery CqQuery <string, object> qry = qrySvc.NewCq("MyCq", "select * from /Portfolios" + " p where p.ID!=2", cqAttr, false); // Execute a CqQuery with Initial Results ICqResults <object> results = qry.ExecuteWithInitialResults(); Console.WriteLine("ResultSet Query returned {0} rows", results.Size); //make changes to generate cq events region["Key2"] = port1; region["Key3"] = port2; region["Key1"] = port3; SelectResultsIterator <object> iter = results.GetIterator(); while (iter.HasNext) { object item = iter.Next(); if (item != null) { Struct st = item as Struct; string key = st["key"] as string;; Console.WriteLine("Got key " + key); Portfolio port = st["value"] as Portfolio; if (port == null) { Position pos = st["value"] as Position; if (pos == null) { string cs = st["value"] as string; if (cs == null) { Console.WriteLine("Query got other/unknown object."); } else { Console.WriteLine("Query got string : {0}.", cs); } } else { Console.WriteLine("Query got Position object with secId {0}, shares {1}.", pos.SecId, pos.SharesOutstanding); } } else { Console.WriteLine("Query got Portfolio object with ID {0}, pkid {1}.", port.ID, port.Pkid); } } } //Stop the cq qry.Stop(); //Close the cq qry.Close(); // Close the Geode Cache. cache.Close(); Console.WriteLine("Closed the Geode Cache"); } // An exception should not occur catch (GeodeException gfex) { Console.WriteLine("PoolCqQuery Geode Exception: {0}", gfex.Message); } }
static void Main(string[] args) { bool verbose = false; if (args.Length == 1 && args[0] == "-v") { verbose = true; } try { // Connect to the GemFire Distributed System using the settings from the gfcpp.properties file by default. Properties prop = Properties.Create(); prop.Insert("cache-xml-file", "clientCqQuery.xml"); CacheFactory cacheFactory = CacheFactory.CreateCacheFactory(prop); Cache cache = cacheFactory.SetSubscriptionEnabled(true) .Create(); Console.WriteLine("Created the GemFire Cache"); // Get the Portfolios Region from the Cache which is declared in the Cache XML file. Region region = cache.GetRegion("Portfolios"); Console.WriteLine("Obtained the Region from the Cache"); region.GetAttributesMutator().SetCacheListener(new MyCacheListener(verbose)); // Register our Serializable/Cacheable Query objects, viz. Portfolio and Position. Serializable.RegisterType(Portfolio.CreateDeserializable); Serializable.RegisterType(Position.CreateDeserializable); //Register all keys region.RegisterAllKeys(); Console.WriteLine("Registered Serializable Query Objects"); // Populate the Region with some Portfolio objects. Portfolio port1 = new Portfolio(1 /*ID*/, 10 /*size*/); Portfolio port2 = new Portfolio(2 /*ID*/, 20 /*size*/); Portfolio port3 = new Portfolio(3 /*ID*/, 30 /*size*/); region.Put("Key1", port1); region.Put("Key2", port2); region.Put("Key3", port3); Console.WriteLine("Populated some Portfolio Objects"); // Get the QueryService from the Cache. QueryService qrySvc = cache.GetQueryService(); Console.WriteLine("Got the QueryService from the Cache"); //create CqAttributes with listener CqAttributesFactory cqFac = new CqAttributesFactory(); ICqListener cqLstner = new MyCqListener(0, verbose); cqFac.AddCqListener(cqLstner); CqAttributes cqAttr = cqFac.Create(); //create a new cqQuery CqQuery qry = qrySvc.NewCq(cqNames[0], queryStrings[0], cqAttr, true); // Execute a CqQuery with Initial Results ICqResults results = qry.ExecuteWithInitialResults(); Console.WriteLine("ResultSet Query returned {0} rows", results.Size); SelectResultsIterator iter = results.GetIterator(); while (iter.HasNext) { IGFSerializable item = iter.Next(); if (item != null) { Struct st = item as Struct; CacheableString key = st["key"] as CacheableString; Console.WriteLine("Got key " + key.Value); Portfolio port = st["value"] as Portfolio; if (port == null) { Position pos = st["value"] as Position; if (pos == null) { CacheableString cs = st["value"] as CacheableString; if (cs == null) { Console.WriteLine("Query got other/unknown object."); } else { Console.WriteLine("Query got string : {0}.", cs.Value); } } else { Console.WriteLine("Query got Position object with secId {0}, shares {1}.", pos.SecId, pos.SharesOutstanding); } } else { Console.WriteLine("Query got Portfolio object with ID {0}, pkid {1}.", port.ID, port.Pkid); } } } //Stop the cq qry.Stop(); //Restart the cq qry.Execute(); for (int i = 1; i < cqNames.Length; i++) { ICqListener cqLstner1 = new MyCqListener(i, verbose); cqFac.AddCqListener(cqLstner1); cqAttr = cqFac.Create(); qry = qrySvc.NewCq(cqNames[i], queryStrings[i], cqAttr, true); } qry = qrySvc.GetCq(cqNames[6]); cqAttr = qry.GetCqAttributes(); ICqListener[] vl = cqAttr.getCqListeners(); Console.WriteLine("number of listeners for cq[{0}] is {1}", cqNames[6], vl.Length); qry = qrySvc.GetCq(cqNames[0]); CqAttributesMutator cqam = qry.GetCqAttributesMutator(); for (int i = 0; i < vl.Length; i++) { cqam.AddCqListener(vl[i]); } //Stop the cq qry.Stop(); //Start all Cq Query qrySvc.ExecuteCqs(); for (int i = 0; i < cqNames.Length; i++) { Console.WriteLine("get info for cq[{0}]:", cqNames[i]); CqQuery cqy = qrySvc.GetCq(cqNames[i]); CqStatistics cqStats = cqy.GetStatistics(); Console.WriteLine("Cq[{0}]: CqStatistics: numInserts[{1}], numDeletes[{2}], numUpdates[{3}], numEvents[{4}]", cqNames[i], cqStats.numInserts(), cqStats.numDeletes(), cqStats.numUpdates(), cqStats.numEvents()); } CqServiceStatistics serviceStats = qrySvc.GetCqStatistics(); Console.WriteLine("numCqsActive={0}, numCqsCreated={1}, numCqsClosed={2}, numCqsStopped={3}, numCqsOnClient={4}", serviceStats.numCqsActive(), serviceStats.numCqsCreated(), serviceStats.numCqsClosed(), serviceStats.numCqsStopped(), serviceStats.numCqsOnClient()); while (true) { Console.WriteLine("*******Type \'q\' to quit !!!! ******"); ConsoleKeyInfo ckey; ckey = Console.ReadKey(true); if (ckey.Key == ConsoleKey.Q) { break; } } //Stop all cqs qrySvc.StopCqs(); for (int i = 0; i < cqNames.Length; i++) { Console.WriteLine("get info for cq[{0}]:", cqNames[i]); CqQuery cqy = qrySvc.GetCq(cqNames[i]); cqAttr = qry.GetCqAttributes(); vl = cqAttr.getCqListeners(); Console.WriteLine("number of listeners for cq[{0}] is {1}", cqNames[i], vl.Length); CqStatistics cqStats = cqy.GetStatistics(); Console.WriteLine("Cq[{0}]: CqStatistics: numInserts[{1}], numDeletes[{2}], numUpdates[{3}], numEvents[{4}]", cqNames[i], cqStats.numInserts(), cqStats.numDeletes(), cqStats.numUpdates(), cqStats.numEvents()); } //Close all cqs qrySvc.CloseCqs(); Console.WriteLine("numCqsActive={0}, numCqsCreated={1}, numCqsClosed={2}, numCqsStopped={3}, numCqsOnClient={4}", serviceStats.numCqsActive(), serviceStats.numCqsCreated(), serviceStats.numCqsClosed(), serviceStats.numCqsStopped(), serviceStats.numCqsOnClient()); // Close the GemFire Cache. cache.Close(); Console.WriteLine("Closed the GemFire Cache"); } // An exception should not occur catch (GemFireException gfex) { Console.WriteLine("CqQuery GemFire Exception: {0}", gfex.Message); } }
static void Main(string[] args) { try { // Create a Geode Cache Programmatically. CacheFactory cacheFactory = CacheFactory.CreateCacheFactory(); Cache cache = cacheFactory.SetSubscriptionEnabled(true) .AddServer("localhost", 50505) .Create(); Console.WriteLine("Created the Geode Cache"); RegionFactory regionFactory = cache.CreateRegionFactory(RegionShortcut.PROXY); // Create the example Region programmatically. IRegion <string, Portfolio> region = regionFactory.Create <string, Portfolio>("Portfolios"); Console.WriteLine("Created the Region Programmatically."); // Register our Serializable/Cacheable Query objects, viz. Portfolio and Position. Serializable.RegisterTypeGeneric(Portfolio.CreateDeserializable); Serializable.RegisterTypeGeneric(Position.CreateDeserializable); Console.WriteLine("Registered Serializable Query Objects"); // Populate the Region with some Portfolio objects. Portfolio port1 = new Portfolio(1 /*ID*/, 10 /*size*/); Portfolio port2 = new Portfolio(2 /*ID*/, 20 /*size*/); Portfolio port3 = new Portfolio(3 /*ID*/, 30 /*size*/); region["Key1"] = port1; region["Key2"] = port2; region["Key3"] = port3; Console.WriteLine("Populated some Portfolio Objects"); // Get the QueryService from the Cache. QueryService <string, object> qrySvc = cache.GetQueryService <string, object>(); Console.WriteLine("Got the QueryService from the Cache"); //create CqAttributes with listener CqAttributesFactory <string, object> cqFac = new CqAttributesFactory <string, object>(); ICqListener <string, object> cqLstner = new MyCqListener <string, object>(); cqFac.AddCqListener(cqLstner); CqAttributes <string, object> cqAttr = cqFac.Create(); //create a new cqQuery CqQuery <string, object> qry = qrySvc.NewCq("MyCq", "select * from /Portfolios" + " p where p.ID!=2", cqAttr, false); // Execute a CqQuery with Initial Results ICqResults <object> results = qry.ExecuteWithInitialResults(); Console.WriteLine("ResultSet Query returned {0} rows", results.Size); //make changes to generate cq events region["Key2"] = port1; region["Key3"] = port2; region["Key1"] = port3; SelectResultsIterator <object> iter = results.GetIterator(); while (iter.HasNext) { object item = iter.Next(); if (item != null) { Struct st = item as Struct; string key = st["key"] as string; Console.WriteLine("Got key " + key); Portfolio port = st["value"] as Portfolio; if (port == null) { Position pos = st["value"] as Position; if (pos == null) { string cs = st["value"] as string; if (cs == null) { Console.WriteLine("Query got other/unknown object."); } else { Console.WriteLine("Query got string : {0}.", cs); } } else { Console.WriteLine("Query got Position object with secId {0}, shares {1}.", pos.SecId, pos.SharesOutstanding); } } else { Console.WriteLine("Query got Portfolio object with ID {0}, pkid {1}.", port.ID, port.Pkid); } } } //Stop the cq qry.Stop(); //Close the cq qry.Close(); // Close the Geode Cache. cache.Close(); Console.WriteLine("Closed the Geode Cache"); } // An exception should not occur catch (GeodeException gfex) { Console.WriteLine("CqQuery Geode Exception: {0}", gfex.Message); } }