Esempio n. 1
0
        public IRegion <int, string> getProductRegion()
        {
            Cache                 cache         = this.getCache();
            RegionFactory         regionFactory = cache.CreateRegionFactory(RegionShortcut.CACHING_PROXY);
            IRegion <int, string> r             = regionFactory.Create <int, string>("products");

            return(r);
        }
Esempio n. 2
0
        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");
        }
Esempio n. 3
0
        public static IRegion <TKey, TVal> CreateRegion(string name, RegionFactory attrs)
        {
            Init();
            DestroyRegion(name, true, false);
            IRegion <TKey, TVal> region = attrs.Create <TKey, TVal>(name);

            FwkAssert(region != null, "Region {0} was not created.", name);
            m_currRegion = region;
            return(region);
        }
Esempio n. 4
0
        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);
            }
        }
        public RequestReply(Cache cache)
        {
            this.cache = cache;
            if (this.cache.GetRegion <int, object>("request") == null)
            {
                RegionFactory         regionFactory1 = cache.CreateRegionFactory(RegionShortcut.CACHING_PROXY);
                IRegion <int, object> regionRequest  = regionFactory1.Create <int, object>("request");
            }

            if (this.cache.GetRegion <int, object>("reply") == null)
            {
                RegionFactory         regionFactory2 = cache.CreateRegionFactory(RegionShortcut.CACHING_PROXY);
                IRegion <int, object> regionReply    = regionFactory2.Create <int, object>("reply");

                regionReply.GetSubscriptionService().RegisterAllKeys();
                regionReply.AttributesMutator.SetCacheListener(new MyCacheListener(ref queue));
            }
        }
Esempio n. 7
0
        public async Task ProcessMessageAsync(byte[] message)
        {
            try
            {
                startTimeProcessing = DateTime.UtcNow;
                GatewayID           = Environment.GetEnvironmentVariable("IOTEDGE_DEVICEID");
                LoRaMessageWrapper loraMessage           = new LoRaMessageWrapper(message);
                byte[]             udpMsgForPktForwarder = new Byte[0];
                if (!loraMessage.IsLoRaMessage)
                {
                    udpMsgForPktForwarder = ProcessNonLoraMessage(loraMessage);
                }
                else
                {
                    if (RegionFactory.CurrentRegion == null)
                    {
                        RegionFactory.Create(loraMessage.PktFwdPayload.GetPktFwdMessage().Rxpks[0]);
                    }
                    //join message
                    if (loraMessage.LoRaMessageType == LoRaMessageType.JoinRequest)
                    {
                        udpMsgForPktForwarder = await ProcessJoinRequest(loraMessage);
                    }
                    //normal message
                    else if (loraMessage.LoRaMessageType == LoRaMessageType.UnconfirmedDataUp || loraMessage.LoRaMessageType == LoRaMessageType.ConfirmedDataUp)
                    {
                        udpMsgForPktForwarder = await ProcessLoraMessage(loraMessage);
                    }
                }

                //send reply to pktforwarder
                await UdpServer.UdpSendMessage(udpMsgForPktForwarder);
            }
            catch (Exception ex)
            {
                Logger.Log($"Error processing the message {ex.Message}, {ex.StackTrace}", Logger.LoggingLevel.Error);
            }
        }
        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);
            }
        }
Esempio n. 9
0
        private void SetupRegion(uint entryTTL, uint entryIdleTimeout,
                                 uint regionTTL, uint regionIdleTimeout)
        {
            const ExpirationAction action = ExpirationAction.Destroy;

            RegionFactory rf = CacheHelper.DCache.CreateRegionFactory(RegionShortcut.LOCAL);

            rf.SetEntryTimeToLive(action, entryTTL);
            rf.SetEntryIdleTimeout(action, entryIdleTimeout);
            rf.SetRegionTimeToLive(action, regionTTL);
            rf.SetRegionIdleTimeout(action, regionIdleTimeout);

            CacheHelper.Init();
            IRegion <object, object> region = CacheHelper.GetRegion <object, object>(m_regionName);

            if ((region != null) && !region.IsDestroyed)
            {
                region.GetLocalView().DestroyRegion();
                Assert.IsTrue(region.IsDestroyed, "IRegion<object, object> {0} was not destroyed.", m_regionName);
            }
            m_region = rf.Create <object, object>(m_regionName);
            Assert.IsNotNull(m_region, "IRegion<object, object> was not created.");
        }
        public async Task <byte[]> ProcessMessageAsync(byte[] message)
        {
            startTimeProcessing = DateTime.UtcNow;
            LoRaMessageWrapper loraMessage = new LoRaMessageWrapper(message);

            if (loraMessage.IsLoRaMessage)
            {
                if (RegionFactory.CurrentRegion == null)
                {
                    RegionFactory.Create(loraMessage.PktFwdPayload.GetPktFwdMessage().Rxpks[0]);
                }
                //join message
                if (loraMessage.LoRaMessageType == LoRaMessageType.JoinRequest)
                {
                    return(await ProcessJoinRequest(loraMessage));
                }
                //normal message
                else if (loraMessage.LoRaMessageType == LoRaMessageType.UnconfirmedDataUp || loraMessage.LoRaMessageType == LoRaMessageType.ConfirmedDataUp)
                {
                    return(await ProcessLoraMessage(loraMessage));
                }
            }
            return(null);
        }
Esempio n. 11
0
        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();
            }
        }
Esempio n. 12
0
        public void OverflowPutGetManagedSetInstance()
        {
            RegionFactory rf = CacheHelper.DCache.CreateRegionFactory(RegionShortcut.LOCAL);

            rf.SetCachingEnabled(true);
            rf.SetLruEntriesLimit(20);
            rf.SetInitialCapacity(1000);
            rf.SetDiskPolicy(DiskPolicyType.Overflows);

            Properties <string, string> sqliteProperties = new Properties <string, string>();

            sqliteProperties.Insert("PageSize", "65536");
            sqliteProperties.Insert("MaxFileSize", "512000000");
            String sqlite_dir = "SqLiteDir" + Process.GetCurrentProcess().Id.ToString();

            sqliteProperties.Insert("PersistenceDirectory", sqlite_dir);

            //rf.SetPersistenceManager(new Apache.Geode.Plugins.SQLite.SqLiteImpl<object, object>(), sqliteProperties);
            rf.SetPersistenceManager("SqLiteImpl", "createSqLiteInstance", sqliteProperties);

            CacheHelper.Init();
            IRegion <object, object> region = CacheHelper.GetRegion <object, object>("OverFlowRegion");

            if ((region != null) && !region.IsDestroyed)
            {
                region.GetLocalView().DestroyRegion();
                Assert.IsTrue(region.IsDestroyed, "IRegion<object, object> OverFlowRegion was not destroyed.");
            }
            region = rf.Create <object, object>("OverFlowRegion");
            Assert.IsNotNull(region, "IRegion<object, object> was not created.");
            ValidateAttributes(region);

            //Console.WriteLine("TEST-2");
            // put some values into the cache.
            DoNput(region, 100);
            //Console.WriteLine("TEST-2.1 All PUts Donee");

            CheckNumOfEntries(region, 100);

            //Console.WriteLine("TEST-3");
            // check whether value get evicted and token gets set as overflow
            CheckOverflowToken(region, 100, 20);
            // do some gets... printing what we find in the cache.
            DoNget(region, 100);
            TestEntryDestroy(region);
            TestGetOp(region, 100);

            //Console.WriteLine("TEST-4");
            // test to verify same region repeatedly to ensure that the persistece
            // files are created and destroyed correctly

            IRegion <object, object> subRegion;

            for (int i = 0; i < 1; i++)
            {
                subRegion = CreateSubRegion(region, "SubRegion", "Apache.Geode.Plugins.SqLite", "SqLiteImpl<object,object>.Create()");
                subRegion.DestroyRegion();
                Assert.IsTrue(subRegion.IsDestroyed, "Expected region to be destroyed");
                Assert.IsFalse(File.Exists(GetSqLiteFileName(sqlite_dir, "SubRegion")), "Persistence file present after region destroy");
            }
            //Console.WriteLine("TEST-5");
        }
Esempio n. 13
0
        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);
            }
        }
Esempio n. 14
0
        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);

                IRegion <int, string> region = regionFactory.Create <int, string>("exampleRegion");

                Console.WriteLine("Created the Region with generics support programmatically.");

                // Put an Entry (Key and Value pair) into the Region using the IDictionary interface.
                region[111] = "Value1";

                Console.WriteLine("Put the first Entry into the Region");

                // Put an Entry into the Region the traditional way.
                region[123] = "123";

                Console.WriteLine("Put the second Entry into the Region");

                PerformanceCounter pc = new PerformanceCounter("Memory", "Available Bytes");
                long freeMemory       = Convert.ToInt64(pc.NextValue());

                // Are we a 64 bit process and do we have 5 GB free memory available?
                if (IntPtr.Size == 8 && freeMemory > 5L * 1024L * 1024L * 1024L)
                {
                    Char   ch   = 'A';
                    string text = new string(ch, 1024 * 1024);
                    Console.WriteLine("Putting over 4 GB data locally...");
                    for (int item = 0; item < (5 * 1024 /* 5 GB */); item++)
                    {
                        region.GetLocalView()[item] = text;
                    }
                    Console.WriteLine("Put over 4 GB data locally");
                }
                else
                {
                    Console.WriteLine("Not putting over 4 GB data locally due to lack of memory capacity");
                }

                // Get Entries back out of the Region via the IDictionary interface.
                string result1 = region[111];

                Console.WriteLine("Obtained the first Entry from the Region");

                string result2 = region[123];

                Console.WriteLine("Obtained the second Entry from the Region");

                // Invalidate an Entry in the Region.
                region.Invalidate(111);

                Console.WriteLine("Invalidated the first Entry in the Region");

                // Destroy an Entry in the Region using the IDictionary interface.
                region.Remove(123);

                Console.WriteLine("Destroyed the second Entry in the Region");

                // Close the Geode Cache.
                cache.Close();

                Console.WriteLine("Closed the Geode Cache");
            }
            // An exception should not occur
            catch (GeodeException gfex)
            {
                Console.WriteLine("BasicOperations Geode Exception: {0}", gfex.Message);
            }
        }
Esempio n. 15
0
        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);
            }
        }
Esempio n. 16
0
        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);
            }
        }
Esempio n. 17
0
 /// <summary>
 /// Builds a graph of regions based on the basic blocks of the code.
 /// </summary>
 /// <param name="proc"></param>
 /// <returns></returns>
 public Tuple<DirectedGraph<Region>, Region> BuildRegionGraph(Procedure proc)
 {
     var btor = new Dictionary<Block, Region>();
     var regs = new DiGraph<Region>();
     var regionFactory = new RegionFactory();
     foreach (var b in proc.ControlGraph.Blocks)
     {
         var reg = regionFactory.Create(b);
         btor.Add(b, reg);
         regs.AddNode(reg);
     }
     foreach (var b in proc.ControlGraph.Blocks)
     {
         foreach (var s in b.Succ)
         {
             var from = btor[b];
             var to = btor[s];
             regs.AddEdge(from, to);
         }
     }
     return new Tuple<DirectedGraph<Region>, Region>(regs, btor[proc.EntryBlock]);
 }
Esempio n. 18
0
        static void Main(string[] args)
        {
            try
            {
                ReflectionBasedAutoSerializer autoSerializer = new ReflectionBasedAutoSerializer();
                Serializable.RegisterPdxSerializer(new ReflectionBasedAutoSerializer());
                CacheFactory cacheFactory = CacheFactory.CreateCacheFactory();
                cacheFactory.AddLocator("localhost", 10334);
                cacheFactory.SetPRSingleHopEnabled(true);
                cacheFactory.SetMaxConnections(-1);

                Cache cache = cacheFactory.Create();

                RegionFactory regionFactory = cache.CreateRegionFactory(RegionShortcut.PROXY);
                IRegion <int, SampleDataObject>     regionInstanceType = regionFactory.Create <int, SampleDataObject>("Region1");
                IDictionary <int, SampleDataObject> region             = regionInstanceType;

                // Putting one object in at a time
                for (int i = 0; i < 1000; i++)
                {
                    SampleDataObject sampleDataObject = new SampleDataObject("firstName single " + i, "lastName " + i, i);
                    region[i] = sampleDataObject;
                }

                //Bulk inserts
                Dictionary <int, SampleDataObject> bulk = new Dictionary <int, SampleDataObject>();
                for (int i = 0; i < 1000; i++)
                {
                    SampleDataObject sampleDataObject = new SampleDataObject("firstName bulk " + i, "lastName " + i, i);
                    bulk[i] = sampleDataObject;
                    if (i % 100 == 0)
                    {
                        regionInstanceType.PutAll(bulk);
                        bulk.Clear();
                    }
                }
                if (bulk.Count() > 0)
                {
                    regionInstanceType.PutAll(bulk);
                    bulk.Clear();
                }
                // iterating over the keys that should be in GemFire
                for (int i = 0; i < 1000; i++)
                {
                    SampleDataObject sampleDataObject = region[i];
                    Console.WriteLine("item - " + i + " : " + sampleDataObject);
                }

                //Simple method to get all of the keys if we want to iterate over keys.
                Console.WriteLine("Number of Object in GemFire " + regionInstanceType.Keys.Count);

                //Query GemFire for the data we need.   Don't forget to setup an index.
                QueryService <int, SampleDataObject> queryService = cache.GetQueryService <int, SampleDataObject>();
                Query <SampleDataObject>             query        = queryService.NewQuery("select * from /Region1 where id = $1");
                object[] queryParams = { 100 };
                ISelectResults <SampleDataObject> results = query.Execute(queryParams);

                foreach (SampleDataObject si in results)
                {
                    Console.WriteLine("result " + si);
                }
            }
            // An exception should not occur
            catch (GeodeException gfex)
            {
                Console.WriteLine("BasicOperations Geode Exception: {0}", gfex.Message);
            }
            Console.WriteLine("done");
        }