public void StepOneQE(string locators, bool isPdx)
        {
            m_isPdx = isPdx;
            try
            {
                var poolFail    = CacheHelper.DCache.GetPoolManager().CreateFactory().Create("_TESTFAILPOOL_", CacheHelper.DCache);
                var qsFail      = poolFail.GetQueryService();
                var qryFail     = qsFail.NewQuery <object>("select distinct * from /" + QERegionName);
                var resultsFail = qryFail.Execute();
                Assert.Fail("Since no endpoints defined, so exception expected");
            }
            catch (IllegalStateException ex)
            {
                Util.Log("Got expected exception: {0}", ex);
            }
            catch (Exception e) {
                Util.Log("Caught unexpected exception: {0}", e);
                throw e;
            }

            CacheHelper.CreateTCRegion_Pool <object, object>(QERegionName, true, true,
                                                             null, locators, "__TESTPOOL1_", true);
            IRegion <object, object> region = CacheHelper.GetVerifyRegion <object, object>(QERegionName);

            if (!m_isPdx)
            {
                Portfolio p1 = new Portfolio(1, 100);
                Portfolio p2 = new Portfolio(2, 100);
                Portfolio p3 = new Portfolio(3, 100);
                Portfolio p4 = new Portfolio(4, 100);

                region["1"] = p1;
                region["2"] = p2;
                region["3"] = p3;
                region["4"] = p4;
            }
            else
            {
                PortfolioPdx p1 = new PortfolioPdx(1, 100);
                PortfolioPdx p2 = new PortfolioPdx(2, 100);
                PortfolioPdx p3 = new PortfolioPdx(3, 100);
                PortfolioPdx p4 = new PortfolioPdx(4, 100);

                region["1"] = p1;
                region["2"] = p2;
                region["3"] = p3;
                region["4"] = p4;
            }

            var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();

            Query <object>          qry     = qs.NewQuery <object>("select distinct * from /" + QERegionName);
            ISelectResults <object> results = qry.Execute();
            Int32 count = results.Size;

            Assert.AreEqual(4, count, "Expected 4 as number of portfolio objects.");

            // Bring down the region
            region.GetLocalView().DestroyRegion();
        }
        public virtual bool VerifyRS(ISelectResults <object> resultset, int expectedRows)
        {
            if (resultset == null)
            {
                return(false);
            }

            int foundRows = 0;

            SelectResultsIterator <object> sr = resultset.GetIterator();

            while (sr.HasNext)
            {
                //TVal ser = (TVal)sr.Next();
                Object ser = sr.Next();
                if (ser == null)
                {
                    Util.Log("QueryHelper.VerifyRS: Object is null.");
                    return(false);
                }

                foundRows++;
            }
            Util.Log("QueryHelper.VerifyRS: found rows {0}, expected {1}",
                     foundRows, expectedRows);
            return(foundRows == expectedRows);
        }
        public void StepTwoFailover()
        {
            CacheHelper.StartJavaServerWithLocators(2, "GFECS2", 1);
            Util.Log("Cacheserver 2 started.");

            IAsyncResult       killRes = null;
            KillServerDelegate ksd     = new KillServerDelegate(KillServer);

            var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();

            for (int i = 0; i < 10000; i++)
            {
                Query <object> qry = qs.NewQuery <object>("select distinct * from /" + QueryRegionNames[0]);

                ISelectResults <object> results = qry.Execute();

                if (i == 10)
                {
                    killRes = ksd.BeginInvoke(null, null);
                }

                Int32 resultSize = results.Size;

                if (i % 100 == 0)
                {
                    Util.Log("Iteration upto {0} done, result size is {1}", i, resultSize);
                }

                Assert.AreEqual(4, resultSize, "Result size is not 4!");
            }

            killRes.AsyncWaitHandle.WaitOne();
            ksd.EndInvoke(killRes);
        }
Exemple #4
0
        /// <summary>
        /// Run a query on server for native client to force deserialization
        /// on server and thereby check serialization/deserialization compability
        /// between native clients and java server.
        /// </summary>
        public void DoRunQuery()
        {
            Assert.IsNotNull(m_cKeys, "DoGets: null keys array.");
            Assert.IsNotNull(m_region, "DoGets: null region.");

            // for a type that cannot be handled by server, delete these values
            // before next query that will cause problem
            Type valType = GetValueType();

            if (CacheableHelper.IsUnhandledType(m_cValues[0].TypeId))
            {
                Util.Log("DoRunQuery: deleting entries with value type {0}", valType);
                for (int keyIndex = 0; keyIndex < m_cKeys.Length; keyIndex++)
                {
                    m_region.Remove(m_cKeys[keyIndex].CacheableKey); // Destroy() -> Remove()
                }
            }
            else
            {
                var                     qs      = CacheHelper.DCache.GetPoolManager().Find(m_region.Attributes.PoolName).GetQueryService();
                Query <object>          qry     = qs.NewQuery <object>("SELECT * FROM " + m_region.FullPath);
                ISelectResults <object> results = qry.Execute();
                // not really interested in results but loop through them neverthless
                Util.Log("DoRunQuery: obtained {0} results", results.Size);
                int numResults = 0;
                foreach (object res in results)
                {
                    ++numResults;
                }
                Assert.AreEqual(results.Size, numResults,
                                "Expected the number of results to match the size of ISelectResults");
            }
            Util.Log("DoQuery completed for keyType [{0}], valType [{1}].",
                     m_cKeys[0].CacheableKey.GetType(), valType);
        }
        public void StepOneQE(string locators)
        {
            CacheHelper.CreateTCRegion_Pool <object, object>(QERegionName, true, true,
                                                             null, locators, "__TESTPOOL1_", true);
            IRegion <object, object> region = CacheHelper.GetVerifyRegion <object, object>(QERegionName);

            string[] /*sta*/ cnm = { "C#aaa", "C#bbb", "C#ccc", "C#ddd" };
            //CacheableStringArray cnm = CacheableStringArray.Create(sta);
            Portfolio p1 = new Portfolio(1, 2, cnm);
            Portfolio p2 = new Portfolio(2, 2, cnm);
            Portfolio p3 = new Portfolio(3, 2, cnm);
            Portfolio p4 = new Portfolio(4, 2, cnm);

            region["1"] = p1;
            region["2"] = p2;
            region["3"] = p3;
            region["4"] = p4;

            var                     qs      = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();
            Query <object>          qry     = qs.NewQuery <object>("select * from /" + QERegionName + "  p where p.ID!=3");
            ISelectResults <object> results = qry.Execute();

            Util.Log("Results size {0}.", results.Size);

            SelectResultsIterator <object> iter = results.GetIterator();

            while (iter.HasNext)
            {
                /*IGeodeSerializable*/ object item = iter.Next();
                Portfolio port = item as Portfolio;
                if (port == null)
                {
                    Position pos = item as Position;
                    if (pos == null)
                    {
                        //CacheableString cs = item as CacheableString;
                        string cs = item as string;
                        if (cs == null)
                        {
                            Util.Log("Query got other/unknown object.");
                        }
                        else
                        {
                            Util.Log("Query got string : {0}.", cs);
                        }
                    }
                    else
                    {
                        Util.Log("Query got Position object with secId {0}, shares {1}.", pos.SecId, pos.SharesOutstanding);
                    }
                }
                else
                {
                    Util.Log("Query got Portfolio object with ID {0}, pkid {1}.", port.ID, port.Pkid);
                }
            }
            // Bring down the region
            region.GetLocalView().DestroyRegion();
        }
Exemple #6
0
        // Run the given query
        public static void RunQuery(string query, bool isRegionQuery)
        {
            try
            {
                ISelectResults results = null;

                if (isRegionQuery)
                {
                    results = m_region.Query(query);
                }
                else
                {
                    QueryService qs  = m_cache.GetQueryService("examplePool");
                    Query        qry = qs.NewQuery(query);
                    results = qry.Execute();
                }
                if (results is ResultSet)
                {
                    uint index = 1;
                    foreach (IGFSerializable result in results)
                    {
                        Console.WriteLine("\tResult {0}: {1}", index, result);
                        index++;
                    }
                }
                else
                {
                    StructSet ss = (StructSet)results;
                    Console.Write("Columns:");
                    uint   index = 0;
                    string colName;
                    while ((colName = ss.GetFieldName(index)) != null)
                    {
                        Console.Write('\t' + colName);
                        index++;
                    }
                    Console.WriteLine();
                    index = 1;
                    foreach (Struct si in results)
                    {
                        Console.Write("\tResult {0}: ");
                        while (si.HasNext())
                        {
                            Console.Write(si.Next() + " || ");
                        }
                        Console.WriteLine();
                        index++;
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception while running the query [{0}]: {1}",
                                  query, ex.Message);
            }
        }
Exemple #7
0
        public void StepTwoQE()
        {
            var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();

            Util.Log("Going to execute the query");
            Query <object>          qry     = qs.NewQuery <object>("select distinct * from /" + QERegionName);
            ISelectResults <object> results = qry.Execute();
            var count = results.Size;

            Assert.AreEqual(4, count, "Expected 4 as number of portfolio objects.");
        }
Exemple #8
0
        public virtual bool VerifySS(ISelectResults <object> structset, int expectedRows,
                                     int expectedFields)
        {
            if (structset == null)
            {
                if (expectedRows == 0 && expectedFields == 0)
                {
                    return(true); //quite possible we got a null set back.
                }
                return(false);
            }

            int foundRows = 0;

            foreach (Struct si in structset)
            {
                foundRows++;

                if (si == null)
                {
                    Util.Log("QueryHelper.VerifySS: Struct is null.");
                    return(false);
                }

                int foundFields = 0;
                for (int cols = 0; cols < si.Count; cols++)
                {
                    //ISerializable field = si[cols];
                    object field = si[cols];
                    foundFields++;
                }

                if (foundFields != expectedFields)
                {
                    Util.Log("QueryHelper.VerifySS: found fields {0}, expected"
                             + " fields {1}.", foundFields, expectedFields);
                    return(false);
                }
            }
            if (foundRows != expectedRows)
            {
                Util.Log("QueryHelper.VerifySS: rows fields {0}, expected rows {1}.",
                         foundRows, expectedRows);
                return(false);
            }
            return(true);
        }
Exemple #9
0
        public void StepFourSS()
        {
            bool ErrorOccurred = false;

            QueryHelper <object, object> qh = QueryHelper <object, object> .GetHelper(CacheHelper.DCache);

            var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();

            int qryIdx = 0;

            foreach (QueryStrings qrystr in QueryStatics.StructSetQueries)
            {
                if (qrystr.Category != QueryCategory.Unsupported)
                {
                    qryIdx++;
                    continue;
                }

                Util.Log("Evaluating unsupported query index {0}.", qryIdx);

                Query <object> query = qs.NewQuery <object>(qrystr.Query);

                try
                {
                    ISelectResults <object> results = query.Execute();

                    Util.Log("Query exception did not occur for index {0}.", qryIdx);
                    ErrorOccurred = true;
                    qryIdx++;
                }
                catch (GeodeException)
                {
                    // ok, exception expected, do nothing.
                    qryIdx++;
                }
                catch (Exception)
                {
                    Util.Log("Query unexpected exception occurred for index {0}.", qryIdx);
                    ErrorOccurred = true;
                    qryIdx++;
                }
            }

            Assert.IsFalse(ErrorOccurred, "Query expected exceptions did not occur.");
        }
Exemple #10
0
        public override void DoTask(int iters, object data)
        {
            Int32 localcnt = m_cnt;

            Interlocked.Increment(ref m_cnt);
            int  offset = Util.Rand(100);
            int  count  = offset;
            long startTime;

            while (Running && (iters-- != 0))
            {
                startTime = InitPerfStat.perfstat[localcnt].StartQuery();
                ISelectResults <object> sptr = m_region.Query <object>(m_queryString, 600);
                InitPerfStat.perfstat[localcnt].EndQuery(startTime, false);
                count++;
            }
            Interlocked.Add(ref m_iters, count - offset);
        }
Exemple #11
0
        public void StepSixRQ()
        {
            bool ErrorOccurred = false;

            IRegion <object, object> region = CacheHelper.GetRegion <object, object>(QueryRegionNames[0]);

            int qryIdx = 0;

            foreach (QueryStrings qrystr in QueryStatics.RegionQueries)
            {
                if ((qrystr.Category != QueryCategory.Unsupported) || (qryIdx == 3))
                {
                    qryIdx++;
                    continue;
                }

                Util.Log("Evaluating unsupported query index {0}.", qryIdx);

                try
                {
                    ISelectResults <object> results = region.Query <object>(qrystr.Query);

                    Util.Log("Query # {0} expected exception did not occur", qryIdx);
                    ErrorOccurred = true;
                    qryIdx++;
                }
                catch (QueryException)
                {
                    // ok, exception expected, do nothing.
                    qryIdx++;
                }
                catch (Exception)
                {
                    ErrorOccurred = true;
                    Util.Log("FAIL: Query # {0} unexpected exception occured", qryIdx);
                    qryIdx++;
                }
            }

            Assert.IsFalse(ErrorOccurred, "Query expected exceptions did not occur.");
        }
Exemple #12
0
        public virtual bool VerifyRS(ISelectResults <object> resultset, int expectedRows)
        {
            if (resultset == null)
            {
                return(false);
            }

            int foundRows = 0;

            foreach (var ser in resultset)
            {
                if (ser == null)
                {
                    Util.Log("QueryHelper.VerifyRS: Object is null.");
                    return(false);
                }

                foundRows++;
            }
            Util.Log("QueryHelper.VerifyRS: found rows {0}, expected {1}",
                     foundRows, expectedRows);
            return(foundRows == expectedRows);
        }
Exemple #13
0
        public void StepThreeSS()
        {
            bool ErrorOccurred = false;

            QueryHelper <object, object> qh = QueryHelper <object, object> .GetHelper(CacheHelper.DCache);

            var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();

            int qryIdx = 0;

            foreach (QueryStrings qrystr in QueryStatics.StructSetQueries)
            {
                if (qrystr.Category == QueryCategory.Unsupported)
                {
                    Util.Log("Skipping query index {0} because it is unsupported.", qryIdx);
                    qryIdx++;
                    continue;
                }

                if (m_isPdx == true)
                {
                    if (qryIdx == 12 || qryIdx == 4 || qryIdx == 7 || qryIdx == 22 || qryIdx == 30 || qryIdx == 34)
                    {
                        Util.Log("Skipping query index {0} for pdx because it has function.", qryIdx);
                        qryIdx++;
                        continue;
                    }
                }

                Util.Log("Evaluating query index {0}. {1}", qryIdx, qrystr.Query);

                Query <object> query = qs.NewQuery <object>(qrystr.Query);

                ISelectResults <object> results = query.Execute();

                int expectedRowCount = qh.IsExpectedRowsConstantSS(qryIdx) ?
                                       QueryStatics.StructSetRowCounts[qryIdx] : QueryStatics.StructSetRowCounts[qryIdx] * qh.PortfolioNumSets;

                if (!qh.VerifySS(results, expectedRowCount, QueryStatics.StructSetFieldCounts[qryIdx]))
                {
                    ErrorOccurred = true;
                    Util.Log("Query verify failed for query index {0}.", qryIdx);
                    qryIdx++;
                    continue;
                }

                StructSet <object> ss = results as StructSet <object>;
                if (ss == null)
                {
                    Util.Log("Zero records found for query index {0}, continuing.", qryIdx);
                    qryIdx++;
                    continue;
                }

                uint  rows   = 0;
                Int32 fields = 0;
                foreach (Struct si in ss)
                {
                    rows++;
                    fields = (Int32)si.Count;
                }

                Util.Log("Query index {0} has {1} rows and {2} fields.", qryIdx, rows, fields);

                qryIdx++;
            }

            Assert.IsFalse(ErrorOccurred, "One or more query validation errors occurred.");
        }
Exemple #14
0
        public void StepFourPQSS()
        {
            bool ErrorOccurred = false;

            QueryHelper <object, object> qh = QueryHelper <object, object> .GetHelper(CacheHelper.DCache);

            var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();

            int qryIdx = 0;

            foreach (QueryStrings qrystr in QueryStatics.StructSetParamQueries)
            {
                if (qrystr.Category != QueryCategory.Unsupported)
                {
                    qryIdx++;
                    continue;
                }

                Util.Log("Evaluating unsupported query index {0}.", qryIdx);

                Query <object> query = qs.NewQuery <object>(qrystr.Query);

                //Populate the param list
                object[] paramList = new object[QueryStatics.NoOfQueryParamSS[qryIdx]];

                Int32 numVal = 0;
                for (Int32 ind = 0; ind < QueryStatics.NoOfQueryParamSS[qryIdx]; ind++)
                {
                    //Util.Log("NIL::PQRS:: QueryStatics.QueryParamSetSS[{0},{1}] = {2}", qryIdx, ind, QueryStatics.QueryParamSetSS[qryIdx, ind]);

                    try
                    {
                        numVal         = Convert.ToInt32(QueryStatics.QueryParamSetSS[qryIdx][ind]);
                        paramList[ind] = numVal;
                        //Util.Log("NIL::PQRS:: Interger Args:: paramList[0] = {1}", ind, paramList[ind]);
                    }
                    catch (FormatException)
                    {
                        //Console.WriteLine("Param string is not a sequence of digits.");
                        paramList[ind] = (System.String)QueryStatics.QueryParamSetSS[qryIdx][ind];
                        //Util.Log("NIL::PQRS:: Interger Args:: paramList[0] = {1}", ind, paramList[ind].ToString());
                    }
                }

                try
                {
                    ISelectResults <object> results = query.Execute(paramList);

                    Util.Log("Query exception did not occur for index {0}.", qryIdx);
                    ErrorOccurred = true;
                    qryIdx++;
                }
                catch (GeodeException)
                {
                    // ok, exception expected, do nothing.
                    qryIdx++;
                }
                catch (Exception)
                {
                    Util.Log("Query unexpected exception occurred for index {0}.", qryIdx);
                    ErrorOccurred = true;
                    qryIdx++;
                }
            }

            Assert.IsFalse(ErrorOccurred, "Query expected exceptions did not occur.");
        }
Exemple #15
0
        public void StepThreePQSS()
        {
            bool ErrorOccurred = false;

            QueryHelper <object, object> qh = QueryHelper <object, object> .GetHelper(CacheHelper.DCache);

            var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();

            int qryIdx = 0;

            foreach (QueryStrings qrystr in QueryStatics.StructSetParamQueries)
            {
                if (qrystr.Category == QueryCategory.Unsupported)
                {
                    Util.Log("Skipping query index {0} because it is unsupported.", qryIdx);
                    qryIdx++;
                    continue;
                }

                Util.Log("Evaluating query index {0}. {1}", qryIdx, qrystr.Query);

                if (m_isPdx == true)
                {
                    if (qryIdx == 16)
                    {
                        Util.Log("Skipping query index {0} for pdx because it has function.", qryIdx);
                        qryIdx++;
                        continue;
                    }
                }

                Query <object> query = qs.NewQuery <object>(qrystr.Query);

                //Populate the param list, paramList for parameterized query
                object[] paramList = new object[QueryStatics.NoOfQueryParamSS[qryIdx]];

                Int32 numVal = 0;
                for (Int32 ind = 0; ind < QueryStatics.NoOfQueryParamSS[qryIdx]; ind++)
                {
                    //Util.Log("NIL::PQRS:: QueryStatics.QueryParamSetSS[{0},{1}] = {2}", qryIdx, ind, QueryStatics.QueryParamSetSS[qryIdx, ind]);

                    try
                    {
                        numVal         = Convert.ToInt32(QueryStatics.QueryParamSetSS[qryIdx][ind]);
                        paramList[ind] = numVal;
                        //Util.Log("NIL::PQRS:: Interger Args:: paramList[0] = {1}", ind, paramList[ind]);
                    }
                    catch (FormatException)
                    {
                        //Console.WriteLine("Param string is not a sequence of digits.");
                        paramList[ind] = (System.String)QueryStatics.QueryParamSetSS[qryIdx][ind];
                        //Util.Log("NIL::PQRS:: Interger Args:: paramList[0] = {1}", ind, paramList[ind].ToString());
                    }
                }

                ISelectResults <object> results = query.Execute(paramList);

                int expectedRowCount = qh.IsExpectedRowsConstantPQSS(qryIdx) ?
                                       QueryStatics.StructSetPQRowCounts[qryIdx] : QueryStatics.StructSetPQRowCounts[qryIdx] * qh.PortfolioNumSets;

                if (!qh.VerifySS(results, expectedRowCount, QueryStatics.StructSetPQFieldCounts[qryIdx]))
                {
                    ErrorOccurred = true;
                    Util.Log("Query verify failed for query index {0}.", qryIdx);
                    qryIdx++;
                    continue;
                }

                StructSet <object> ss = results as StructSet <object>;
                if (ss == null)
                {
                    Util.Log("Zero records found for query index {0}, continuing.", qryIdx);
                    qryIdx++;
                    continue;
                }

                uint  rows   = 0;
                Int32 fields = 0;
                foreach (Struct si in ss)
                {
                    rows++;
                    fields = (Int32)si.Count;
                }

                Util.Log("Query index {0} has {1} rows and {2} fields.", qryIdx, rows, fields);

                qryIdx++;
            }

            Assert.IsFalse(ErrorOccurred, "One or more query validation errors occurred.");
        }
Exemple #16
0
        public void StepThreeRQ()
        {
            bool ErrorOccurred = false;

            IRegion <object, object> region = CacheHelper.GetRegion <object, object>(QueryRegionNames[0]);

            int qryIdx = 0;

            foreach (QueryStrings qrystr in QueryStatics.RegionQueries)
            {
                if (qrystr.Category == QueryCategory.Unsupported)
                {
                    Util.Log("Skipping query index {0} because it is unsupported.", qryIdx);
                    qryIdx++;
                    continue;
                }

                Util.Log("Evaluating query index {0}. {1}", qryIdx, qrystr.Query);

                if (m_isPdx)
                {
                    if (qryIdx == 18)
                    {
                        Util.Log("Skipping query index {0} because it is unsupported for pdx type.", qryIdx);
                        qryIdx++;
                        continue;
                    }
                }

                ISelectResults <object> results = region.Query <object>(qrystr.Query);

                if (results.Size != (ulong)QueryStatics.RegionQueryRowCounts[qryIdx])
                {
                    ErrorOccurred = true;
                    Util.Log("FAIL: Query # {0} expected result size is {1}, actual is {2}", qryIdx,
                             QueryStatics.RegionQueryRowCounts[qryIdx], results.Size);
                    qryIdx++;
                    continue;
                }
                qryIdx++;
            }

            Assert.IsFalse(ErrorOccurred, "One or more query validation errors occurred.");

            try
            {
                ISelectResults <object> results = region.Query <object>("");
                Assert.Fail("Expected IllegalArgumentException exception for empty predicate");
            }
            catch (IllegalArgumentException ex)
            {
                Util.Log("got expected IllegalArgumentException exception for empty predicate:");
                Util.Log(ex.Message);
            }


            try
            {
                ISelectResults <object> results = region.Query <object>(QueryStatics.RegionQueries[0].Query, TimeSpan.FromSeconds(2200000));
                Assert.Fail("Expected IllegalArgumentException exception for invalid timeout");
            }
            catch (IllegalArgumentException ex)
            {
                Util.Log("got expected IllegalArgumentException exception for invalid timeout:");
                Util.Log(ex.Message);
            }


            try
            {
                ISelectResults <object> results = region.Query <object>("bad predicate");
                Assert.Fail("Expected QueryException exception for wrong predicate");
            }
            catch (QueryException ex)
            {
                Util.Log("got expected QueryException exception for wrong predicate:");
                Util.Log(ex.Message);
            }
        }
        void runWithUserRoot(Cache cache)
        {
            Console.WriteLine("------------------------------------------------------------");
            Console.WriteLine("Logging in as root.  Should have access to reads and writes ");
            Console.WriteLine("------------------------------------------------------------");

            //user "root" 's credential
            Properties <string, object> credentials = Properties <string, object> .Create <string, object>();

            //user = "******" has permission to do put/get both
            credentials.Insert("security-username", "root");
            credentials.Insert("security-password", "root");

            // Create user cache by passing credentials
            IRegionService userCache1 = cache.CreateAuthenticatedView(credentials);

            Console.WriteLine("Created the Region Programmatically. 2");
            // Create region using usercache
            IRegion <string, string> userRegion1 = userCache1.GetRegion <string, string>("exampleRegion");

            //doing operation on behalf of user "root"
            userRegion1["key-1"] = "val-1";

            string result = userRegion1["key-1"];

            // commented 1/2015 for Morgan Stanley since they do not use functions
            //to execute function on server

            /*
             * Execution<object> exc = FunctionService<object>.OnServer(userCache1);
             *
             * bool getResult = true;
             * ArrayList args1 = new ArrayList();
             * args1.Add("key-1");
             *
             * try
             * {
             * IResultCollector<object> rc = exc.WithArgs<ArrayList>(args1).Execute(
             * getFuncIName, getResult);
             * ICollection<object> 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);
             *    }
             * }
             *
             * for (int i = 0; i < resultList1.Count; i++)
             * {
             *    Console.WriteLine("on one server:get:result[{0}]={1}.", i, (string)resultList1[i]);
             * }
             * }
             * catch (Exception e)
             * {
             * Console.WriteLine(e);
             * }
             *
             * */


            //to execute Query

            // Get the QueryService from the Cache.
            QueryService <string, string> qrySvc = userCache1.GetQueryService <string, string>();

            Console.WriteLine("Got the QueryService from the user Cache");

            // Execute a Query which returns a ResultSet.
            Query <string>          qry     = qrySvc.NewQuery("SELECT DISTINCT * FROM /exampleRegion");
            ISelectResults <string> results = qry.Execute();

            Console.WriteLine("ResultSet Query returned {0} rows", results.Size);

            userCache1.Close();

            Console.WriteLine("User root done put/get ops successfully");
        }
Exemple #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");
        }
Exemple #19
0
        private void RunQuery(ref int queryCnt)
        {
            FwkInfo("In Security.RunQuery");

            try
            {
                ResetKey(EntryCount);
                int         numOfKeys = GetUIntValue(EntryCount);
                QueryHelper qh        = QueryHelper.GetHelper();
                int         setSize   = qh.PortfolioSetSize;
                if (numOfKeys < setSize)
                {
                    setSize = numOfKeys;
                }
                int          index = Util.Rand(QueryStrings.RSsize);
                DateTime     startTime;
                DateTime     endTime;
                TimeSpan     elapsedTime;
                QueryService qs = CacheHelper.DCache.GetQueryService();
                ResetKey(LargeSetQuery);
                ResetKey(UnsupportedPRQuery);
                bool         isLargeSetQuery      = GetBoolValue(LargeSetQuery);
                bool         isUnsupportedPRQuery = GetBoolValue(UnsupportedPRQuery);
                QueryStrings currentQuery         = QueryStatics.ResultSetQueries[index];
                if (AllowQuery(currentQuery.Category, currentQuery.IsLargeResultset,
                               isLargeSetQuery, isUnsupportedPRQuery))
                {
                    string query = currentQuery.Query;
                    FwkInfo("Security.RunQuery: ResultSet Query Category [{0}], " +
                            "String [{1}].", currentQuery.Category, query);
                    Query qry = qs.NewQuery(query);
                    startTime = DateTime.Now;
                    ISelectResults results = qry.Execute(600);
                    endTime     = DateTime.Now;
                    elapsedTime = endTime - startTime;
                    FwkInfo("Security.RunQuery: Time Taken to execute" +
                            " the query [{0}]: {1}ms", query, elapsedTime.TotalMilliseconds);
                    ++queryCnt;
                }
                index        = Util.Rand(QueryStrings.SSsize);
                currentQuery = QueryStatics.StructSetQueries[index];
                if (AllowQuery(currentQuery.Category, currentQuery.IsLargeResultset,
                               isLargeSetQuery, isUnsupportedPRQuery))
                {
                    string query = currentQuery.Query;
                    FwkInfo("Security.RunQuery: StructSet Query Category [{0}], " +
                            "String [{1}].", currentQuery.Category, query);
                    Query qry = qs.NewQuery(query);
                    startTime = DateTime.Now;
                    ISelectResults results = qry.Execute(600);
                    endTime     = DateTime.Now;
                    elapsedTime = endTime - startTime;
                    FwkInfo("Security.RunQuery: Time Taken to execute" +
                            " the query [{0}]: {1}ms", query, elapsedTime.TotalMilliseconds);
                    ++queryCnt;
                }
            }
            catch (Exception ex)
            {
                FwkException("Security.RunQuery: Caught Exception: {0}", ex);
            }
            FwkInfo("Security.RunQuery complete.");
        }
    public void StepThreeRS()
    {
      bool ErrorOccurred = false;

      QueryHelper<object, object> qh = QueryHelper<object, object>.GetHelper(CacheHelper.DCache);

      var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();

      int qryIdx = 0;

      foreach (QueryStrings qrystr in QueryStatics.ResultSetQueries)
      {
        if (qrystr.Category == QueryCategory.Unsupported)
        {
          Util.Log("Skipping query index {0} because it is unsupported.", qryIdx);
          qryIdx++;
          continue;
        }

        if (m_isPdx == true)
        {
          if (qryIdx == 2 || qryIdx == 3 || qryIdx == 4)
          {
            Util.Log("Skipping query index {0} for Pdx because it is function type.", qryIdx);
            qryIdx++;
            continue;
          }
        }

        Util.Log("Evaluating query index {0}. Query string {1}", qryIdx, qrystr.Query);

        Query<object> query = qs.NewQuery<object>(qrystr.Query);

        ISelectResults<object> results = query.Execute();

        int expectedRowCount = qh.IsExpectedRowsConstantRS(qryIdx) ?
          QueryStatics.ResultSetRowCounts[qryIdx] : QueryStatics.ResultSetRowCounts[qryIdx] * qh.PortfolioNumSets;

        if (!qh.VerifyRS(results, expectedRowCount))
        {
          ErrorOccurred = true;
          Util.Log("Query verify failed for query index {0}.", qryIdx);
          qryIdx++;
          continue;
        }

        ResultSet<object> rs = results as ResultSet<object>;

        foreach (object item in rs)
        {
          if (!m_isPdx)
          {
            Portfolio port = item as Portfolio;
            if (port == null)
            {
              Position pos = item as Position;
              if (pos == null)
              {
                string cs = item.ToString();
                if (cs == null)
                {
                  Util.Log("Query got other/unknown object.");
                }
                else
                {
                  Util.Log("Query got string : {0}.", cs);
                }
              }
              else
              {
                Util.Log("Query got Position object with secId {0}, shares {1}.", pos.SecId, pos.SharesOutstanding);
              }
            }
            else
            {
              Util.Log("Query got Portfolio object with ID {0}, pkid {1}.", port.ID, port.Pkid);
            }
          }
          else
          {
            PortfolioPdx port = item as PortfolioPdx;
            if (port == null)
            {
              PositionPdx pos = item as PositionPdx;
              if (pos == null)
              {
                string cs = item.ToString();
                if (cs == null)
                {
                  Util.Log("Query got other/unknown object.");
                }
                else
                {
                  Util.Log("Query got string : {0}.", cs);
                }
              }
              else
              {
                Util.Log("Query got Position object with secId {0}, shares {1}.", pos.secId, pos.getSharesOutstanding);
              }
            }
            else
            {
              Util.Log("Query got Portfolio object with ID {0}, pkid {1}.", port.ID, port.Pkid);
            }
          }
        }

        qryIdx++;
      }

      Assert.IsFalse(ErrorOccurred, "One or more query validation errors occurred.");
    }
Exemple #21
0
        private string Process(string expr)
        {
            Match match = regex.Match(expr);

            if (match.Success)
            {
                string[] args    = StringUtils.DelimitedListToStringArray(expr, " ");
                string   command = args[0];
                string   arg1    = (args.Length >= 2 ? args[1] : null);
                string   arg2    = (args.Length == 3 ? args[2] : null);

                if (IsMatch("query", command))
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("[");
                    string         query     = expr.Trim().Substring(command.Length);
                    ISelectResults resultSet = region.Query(query);


                    for (uint i = 0; i < resultSet.Size; i++)
                    {
                        sb.Append(resultSet[i].ToString());
                        if (i != resultSet.Size - 1)
                        {
                            sb.Append(",");
                        }
                    }
                    sb.Append("]");
                    return(sb.ToString());
                }

                // parse commands w/o arguments
                if (IsMatch("exit", command))
                {
                    threadActive = false;
                    return("Node exiting...");
                }
                if (IsMatch("help", command))
                {
                    return(help);
                }
                if (IsMatch("size", command))
                {
                    return("" + region.Size);
                }
                if (IsMatch("clear", command))
                {
                    region.Clear();
                    return("Clearing grid...");
                }
                if (IsMatch("keys", command))
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("[");
                    ICacheableKey[] keys = region.GetKeys();
                    for (int i = 0; i < keys.Length; i++)
                    {
                        sb.Append(keys[i]);
                        if (i != keys.Length - 1)
                        {
                            sb.Append(",");
                        }
                    }
                    sb.Append("]");
                    return(sb.ToString());
                }
                if (IsMatch("values", command))
                {
                    StringBuilder sb = new StringBuilder();
                    sb.Append("[");
                    IGFSerializable[] values = region.GetValues();
                    for (int i = 0; i < values.Length; i++)
                    {
                        sb.Append(values[i]);
                        if (i != values.Length - 1)
                        {
                            sb.Append(",");
                        }
                    }
                    sb.Append("]");
                    return(sb.ToString());
                }
                if (IsMatch("map", command))
                {
                    RegionEntry[] regionEntries = region.GetEntries(false);
                    if (regionEntries.Length == 0)
                    {
                        return("[]");
                    }
                    StringBuilder sb = new StringBuilder();
                    foreach (RegionEntry regionEntry in regionEntries)
                    {
                        sb.Append("[").Append(regionEntry.Key.ToString()).Append("=").Append(
                            regionEntry.Value.ToString()).Append("]");
                    }
                    return(sb.ToString());
                }


                //commands w/ 1 arg
                if (IsMatch("containsKey", command))
                {
                    return("" + region.ContainsKey(arg1));
                }
                if (IsMatch("containsValue", command))
                {
                    return("not yet implemented");
                    //return "" + region.ExistsValue(arg1);
                }
                if (IsMatch("get", command))
                {
                    IGFSerializable cValue = region.Get(arg1);
                    if (cValue == null)
                    {
                        return("null");
                    }
                    return(cValue.ToString());
                }
                if (IsMatch("remove", command))
                {
                    return("not yet implemented");
                }

                // commands w/ 2 args
                if (IsMatch("put", command))
                {
                    IGFSerializable oldValue = region.Get(arg1);
                    region.Put(arg1, arg2);
                    if (oldValue == null)
                    {
                        return("null");
                    }
                    return("old value = [" + oldValue.ToString() + "]");
                }
                return("unknown command [" + command + "] - type 'help' for available commands");
            }
            return("unknown command [" + expr + "] -  type 'help' for available commands");
        }
        void runWithUserRoot(Cache cache)
        {
            Console.WriteLine("Created the Region Programmatically. 0");
            //user "root" 's credential
            Properties <string, object> credentials = Properties <string, object> .Create <string, object>();

            //user = "******" has permission to do put/get both
            credentials.Insert("security-username", "root");
            credentials.Insert("security-password", "root");

            Console.WriteLine("Created the Region Programmatically. 1");
            // Create user cache by passing credentials
            IRegionService userCache1 = cache.CreateAuthenticatedView(credentials);

            Console.WriteLine("Created the Region Programmatically. 2");
            // Create region using usercache
            IRegion <string, string> userRegion1 = userCache1.GetRegion <string, string>("partition_region");

            //doing operation on behalf of user "root"
            userRegion1["key-1"] = "val-1";

            string result = userRegion1["key-1"];

            //to execute function on server
            Execution <object> exc = FunctionService <object> .OnServer(userCache1);

            ArrayList args1 = new ArrayList();

            args1.Add("key-1");

            IResultCollector <object> rc = exc.WithArgs <ArrayList>(args1).Execute(getFuncIName);
            ICollection <object>      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);
                }
            }

            for (int i = 0; i < resultList1.Count; i++)
            {
                Console.WriteLine("on one server:get:result[{0}]={1}.", i, (string)resultList1[i]);
            }

            //to execute Query

            // Get the QueryService from the Cache.
            QueryService <string, string> qrySvc = userCache1.GetQueryService <string, string>();

            Console.WriteLine("Got the QueryService from the user Cache");

            // Execute a Query which returns a ResultSet.
            Query <string>          qry     = qrySvc.NewQuery("SELECT DISTINCT * FROM /partition_region");
            ISelectResults <string> results = qry.Execute();

            Console.WriteLine("ResultSet Query returned {0} rows", results.Size);

            userCache1.Close();

            Console.WriteLine("User root done put/get ops successfully");
        }
        static void Main(string[] args)
        {
            try
            {
                CacheFactory cacheFactory = CacheFactory.CreateCacheFactory();

                Console.WriteLine("Connected to the Geode Distributed System");

                // Create a Geode Cache with the "clientPdxRemoteQuery.xml" Cache XML file.
                Cache cache = cacheFactory.Set("cache-xml-file", "XMLs/clientPdxRemoteQuery.xml").Create();

                Console.WriteLine("Created the Geode Cache");

                // Get the example Region from the Cache which is declared in the Cache XML file.
                IRegion <string, PortfolioPdx> region = cache.GetRegion <string, PortfolioPdx>("Portfolios");

                Console.WriteLine("Obtained the Region from the Cache");

                // Register our Serializable/Cacheable Query objects, viz. Portfolio and Position.
                Serializable.RegisterPdxType(PortfolioPdx.CreateDeserializable);
                Serializable.RegisterPdxType(PositionPdx.CreateDeserializable);

                Console.WriteLine("Registered Serializable Query Objects");

                // Populate the Region with some PortfolioPdx objects.
                PortfolioPdx port1 = new PortfolioPdx(1 /*ID*/, 10 /*size*/);
                PortfolioPdx port2 = new PortfolioPdx(2 /*ID*/, 20 /*size*/);
                PortfolioPdx port3 = new PortfolioPdx(3 /*ID*/, 30 /*size*/);
                region["Key1"] = port1;
                region["Key2"] = port2;
                region["Key3"] = port3;

                Console.WriteLine("Populated some PortfolioPdx Objects");

                //find the pool
                Pool pool = PoolManager.Find("examplePool");

                // Get the QueryService from the pool
                QueryService <string, PortfolioPdx> qrySvc = pool.GetQueryService <string, PortfolioPdx>();

                Console.WriteLine("Got the QueryService from the Pool");

                // Execute a Query which returns a ResultSet.
                Query <PortfolioPdx>          qry     = qrySvc.NewQuery("SELECT DISTINCT * FROM /Portfolios");
                ISelectResults <PortfolioPdx> results = qry.Execute();

                Console.WriteLine("ResultSet Query returned {0} rows", results.Size);

                // Execute a Query which returns a StructSet.
                QueryService <string, Struct> qrySvc1 = pool.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(1), si[1].ToString());
                }

                // Execute a Region Shortcut Query (convenience method).
                results = region.Query <PortfolioPdx>("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");

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

                Console.WriteLine("Closed the Geode Cache");
            }
            // An exception should not occur
            catch (GeodeException gfex)
            {
                Console.WriteLine("PdxRemoteQuery Geode Exception: {0}", gfex.Message);
            }
        }
Exemple #24
0
        public void StepThreePQRS()
        {
            bool ErrorOccurred = false;

            QueryHelper <object, object> qh = QueryHelper <object, object> .GetHelper(CacheHelper.DCache);

            var qs = CacheHelper.DCache.GetPoolManager().Find("__TESTPOOL1_").GetQueryService();

            int qryIdx = 0;

            foreach (QueryStrings paramqrystr in QueryStatics.ResultSetParamQueries)
            {
                if (paramqrystr.Category == QueryCategory.Unsupported)
                {
                    Util.Log("Skipping query index {0} because it is unsupported.", qryIdx);
                    qryIdx++;
                    continue;
                }

                Util.Log("Evaluating query index {0}. {1}", qryIdx, paramqrystr.Query);

                Query <object> query = qs.NewQuery <object>(paramqrystr.Query);

                //Populate the parameter list (paramList) for the query.
                object[] paramList = new object[QueryStatics.NoOfQueryParam[qryIdx]];
                int      numVal    = 0;
                for (int ind = 0; ind < QueryStatics.NoOfQueryParam[qryIdx]; ind++)
                {
                    //Util.Log("NIL::PQRS:: QueryStatics.QueryParamSet[{0},{1}] = {2}", qryIdx, ind, QueryStatics.QueryParamSet[qryIdx][ind]);

                    try
                    {
                        numVal         = Convert.ToInt32(QueryStatics.QueryParamSet[qryIdx][ind]);
                        paramList[ind] = numVal;
                        //Util.Log("NIL::PQRS::361 Interger Args:: paramList[0] = {1}", ind, paramList[ind]);
                    }
                    catch (FormatException)
                    {
                        //Console.WriteLine("Param string is not a sequence of digits.");
                        paramList[ind] = (System.String)QueryStatics.QueryParamSet[qryIdx][ind];
                        //Util.Log("NIL::PQRS:: Interger Args:: routingObj[0] = {1}", ind, routingObj[ind].ToString());
                    }
                }

                ISelectResults <object> results = query.Execute(paramList);

                //Varify the result
                int expectedRowCount = qh.IsExpectedRowsConstantPQRS(qryIdx) ?
                                       QueryStatics.ResultSetPQRowCounts[qryIdx] : QueryStatics.ResultSetPQRowCounts[qryIdx] * qh.PortfolioNumSets;

                if (!qh.VerifyRS(results, expectedRowCount))
                {
                    ErrorOccurred = true;
                    Util.Log("Query verify failed for query index {0}.", qryIdx);
                    qryIdx++;
                    continue;
                }

                ResultSet <object> rs = results as ResultSet <object>;

                foreach (object item in rs)
                {
                    if (!m_isPdx)
                    {
                        Portfolio port = item as Portfolio;
                        if (port == null)
                        {
                            Position pos = item as Position;
                            if (pos == null)
                            {
                                string cs = item as string;
                                if (cs == null)
                                {
                                    Util.Log("Query got other/unknown object.");
                                }
                                else
                                {
                                    Util.Log("Query got string : {0}.", cs);
                                }
                            }
                            else
                            {
                                Util.Log("Query got Position object with secId {0}, shares {1}.", pos.SecId, pos.SharesOutstanding);
                            }
                        }
                        else
                        {
                            Util.Log("Query got Portfolio object with ID {0}, pkid {1}.", port.ID, port.Pkid);
                        }
                    }
                    else
                    {
                        PortfolioPdx port = item as PortfolioPdx;
                        if (port == null)
                        {
                            PositionPdx pos = item as PositionPdx;
                            if (pos == null)
                            {
                                string cs = item as string;
                                if (cs == null)
                                {
                                    Util.Log("Query got other/unknown object.");
                                }
                                else
                                {
                                    Util.Log("Query got string : {0}.", cs);
                                }
                            }
                            else
                            {
                                Util.Log("Query got PositionPdx object with secId {0}, shares {1}.", pos.secId, pos.getSharesOutstanding);
                            }
                        }
                        else
                        {
                            Util.Log("Query got PortfolioPdx object with ID {0}, pkid {1}.", port.ID, port.Pkid);
                        }
                    }
                }

                qryIdx++;
            }

            Assert.IsFalse(ErrorOccurred, "One or more query validation errors occurred.");
        }
Exemple #25
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);
            }
        }
Exemple #26
0
        static void Main(string[] args)
        {
            try
            {
                CacheFactory cacheFactory = CacheFactory.CreateCacheFactory();

                Console.WriteLine("Connected to the Geode Distributed System");

                // Create a Geode Cache with the "clientPdxRemoteQuery.xml" Cache XML file.
                Cache cache = cacheFactory.Set("cache-xml-file", "XMLs/clientPdxSerializer.xml").Create();

                Console.WriteLine("Created the Geode Cache");

                // Get the example Region from the Cache which is declared in the Cache XML file.
                IRegion <string, Person> region = cache.GetRegion <string, Person>("Person");

                Console.WriteLine("Obtained the Region from the Cache");

                //to map .net type tp pdx type or java type
                Serializable.SetPdxTypeMapper(new PdxTypeMapper());

                // Register inbuilt reflection based autoserializer to serialize the domain types(Person class) as pdx format
                Serializable.RegisterPdxSerializer(new AutoSerializerEx());
                Console.WriteLine("Registered Person Query Objects");

                // Populate the Region with some PortfolioPdx objects.
                Person p1 = new Person("John", 1 /*ID*/, 23 /*age*/);
                Person p2 = new Person("Jack", 2 /*ID*/, 20 /*age*/);
                Person p3 = new Person("Tony", 3 /*ID*/, 35 /*age*/);

                region["Key1"] = p1;
                region["Key2"] = p2;
                region["Key3"] = p3;

                Console.WriteLine("Populated some Person Objects");

                //find the pool
                Pool pool = PoolManager.Find("examplePool");

                // Get the QueryService from the pool
                QueryService <string, Person> qrySvc = pool.GetQueryService <string, Person>();

                Console.WriteLine("Got the QueryService from the Pool");

                // Execute a Query which returns a ResultSet.
                Query <Person>          qry     = qrySvc.NewQuery("SELECT DISTINCT * FROM /Person");
                ISelectResults <Person> results = qry.Execute();

                Console.WriteLine("ResultSet Query returned {0} rows", results.Size);

                // Execute a Query which returns a StructSet.
                QueryService <string, Struct> qrySvc1 = pool.GetQueryService <string, Struct>();
                Query <Struct>          qry1          = qrySvc1.NewQuery("SELECT name, age FROM /Person 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(1), si[1].ToString());
                }


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

                Console.WriteLine("Closed the Geode Cache");
            }
            // An exception should not occur
            catch (GeodeException gfex)
            {
                Console.WriteLine("PdxSerializer Geode Exception: {0}", gfex.Message);
            }
        }