Example #1
0
    static void Main(string[] args)
    {
        CConnectionContext cc = new CConnectionContext("localhost", 20901, "hwClientUserId", "password4hwClient");
        using (CSocketPool<HelloWorld> spHw = new CSocketPool<HelloWorld>(true)) //true -- automatic reconnecting
        {
            bool ok = spHw.StartSocketPool(cc, 1, 1);
            HelloWorld hw = spHw.Seek(); //or HelloWorld hw = spHw.Lock();

            //optionally start a persistent queue at client side to ensure auto failure recovery and once-only delivery
            ok = hw.AttachedClientSocket.ClientQueue.StartQueue("helloworld", 24 * 3600, false); //time-to-live 1 day and true for encryption

            //process requests one by one synchronously
            Console.WriteLine(hw.SayHello("Jone", "Dole"));
            hw.Sleep(5000);
            CMyStruct msOriginal = CMyStruct.MakeOne();
            CMyStruct ms = hw.Echo(msOriginal);

            //asynchronously process multiple requests with inline batching for best network efficiency
            ok = hw.SendRequest(hwConst.idSayHelloHelloWorld, "Jack", "Smith", (ar) =>
            {
                string ret;
                ar.Load(out ret);
                Console.WriteLine(ret);
            });
            CAsyncServiceHandler.DAsyncResultHandler arh = null;
            ok = hw.SendRequest(hwConst.idSleepHelloWorld, (int)5000, arh);
            ok = hw.SendRequest(hwConst.idEchoHelloWorld, msOriginal, (ar) =>
            {
                ar.Load(out ms);
            });
            ok = hw.WaitAll();
            Console.WriteLine("Press ENTER key to shutdown the demo application ......");
            Console.ReadLine();
        }
    }
Example #2
0
    static void Main(string[] args)
    {
        Console.WriteLine("Remote host: ");
        string             host = Console.ReadLine();
        CConnectionContext cc   = new CConnectionContext(host, 20901, "async_queue_client", "pwd_for_async_queue");

        using (CSocketPool <CAsyncQueue> spAq = new CSocketPool <CAsyncQueue>())
        {
            if (!spAq.StartSocketPool(cc, 1, 1))
            {
                Console.WriteLine("Failed in connecting to remote async queue server");
                Console.WriteLine("Press any key to close the application ......");
                Console.Read();
                return;
            }
            CAsyncQueue aq = spAq.Seek();

            //Optionally, you can enqueue messages with transaction style by calling the methods StartQueueTrans and EndQueueTrans in pair
            aq.StartQueueTrans(TEST_QUEUE_KEY, (errCode) =>
            {
                //error code could be one of CAsyncQueue.QUEUE_OK, CAsyncQueue.QUEUE_TRANS_ALREADY_STARTED, ......
            });
            TestEnqueue(aq);

            //test message batching
            using (CScopeUQueue sb = new CScopeUQueue())
            {
                CUQueue q = sb.UQueue;
                CAsyncQueue.BatchMessage(idMessage3, "Hello", "World", q);
                CAsyncQueue.BatchMessage(idMessage4, true, 234.456, "MyTestWhatever", q);
                aq.EnqueueBatch(TEST_QUEUE_KEY, q, (res) =>
                {
                    System.Diagnostics.Debug.Assert(res == 2);
                });
            }
            aq.EndQueueTrans(false);
            TestDequeue(aq);
            aq.WaitAll();

            //get a queue key two parameters, message count and queue file size by default option oMemoryCached
            aq.FlushQueue(TEST_QUEUE_KEY, (messageCount, fileSize) =>
            {
                Console.WriteLine("Total message count={0}, queue file size={1}", messageCount, fileSize);
            });

            aq.GetKeys((keys) =>
            {
                keys = null;
            });

            aq.CloseQueue(TEST_QUEUE_KEY, (errCode) =>
            {
                //error code could be one of CAsyncQueue.QUEUE_OK, CAsyncQueue.QUEUE_TRANS_ALREADY_STARTED, ......
            });

            Console.WriteLine("Press any key to close the application ......");
            Console.Read();
        }
    }
Example #3
0
 private void Cleanup()
 {
     if (m_pool != null)
     {
         m_pool.Dispose();
         m_pool = null;
     }
 }
Example #4
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            CConnectionContext cc = new CConnectionContext(txtHost.Text, 20902, txtUser.Text, txtPassword.Text);

            m_spMysql = new CSocketPool <CMysql>(false);

            //set event for MySQL/Mariadb database shutdown
            m_spMysql.SocketPoolEvent += new CSocketPool <CMysql> .DOnSocketPoolEvent(m_spMysql_SocketPoolEvent);

            if (!m_spMysql.StartSocketPool(cc, 1, 1))
            {
                txtMessage.Text = "No connection to " + txtHost.Text;
                return;
            }
            CMysql mysql = m_spMysql.AsyncHandlers[0];

            //set event for tracking all database table update events, delete, update and insert
            m_spMysql.Sockets[0].Push.OnPublish += new DOnPublish(Push_OnPublish);

            //create a DB session with default to sample database sakil
            bool ok = mysql.Open("sakila", null, DB_CONSTS.ENABLE_TABLE_UPDATE_MESSAGES);

            m_ds = new DataSet("real-time cache");
            DataTable dt     = null;
            string    errMsg = "";

            //query all cached tables into client side for intial cache data
            ok = mysql.Execute("", (h, ret, err_msg, affected, fail_ok, id) =>
            {
                //this callback is fired from worker thread from socket pool thread
                ok     = (ret == 0);
                errMsg = err_msg;
            }, (h, data) =>
            {
                //this callback is fired from worker thread from socket pool thread
                CMysql.AppendRowDataIntoDataTable(data, dt);
            }, (h) =>
            {
                //this callback is fired from worker thread from socket pool thread
                dt           = CMysql.MakeDataTable(h.ColumnInfo);
                string name  = h.ColumnInfo[0].DBPath + "." + h.ColumnInfo[0].TablePath;
                dt.TableName = name;
                m_ds.Tables.Add(dt);
            });
            ok = mysql.WaitAll();
            txtMessage.Text = errMsg;
            lstTables.Items.Clear();
            foreach (DataTable table in m_ds.Tables)
            {
                lstTables.Items.Add(table.TableName);
            }
            if (m_ds.Tables.Count > 0)
            {
                lstTables.SelectedIndex = 0;
            }
            btnDisconnect.Enabled = ok;
            btnConnect.Enabled    = !ok;
        }
Example #5
0
    static void Main(string[] args)
    {
        Console.WriteLine("Remote SocketPro file streaming server:");
        CConnectionContext cc = new CConnectionContext(Console.ReadLine(), 20901, "MyUserId", "MyPassword");

        using (CSocketPool <CStreamingFile> spRf = new CSocketPool <CStreamingFile>())
        {
            bool ok = spRf.StartSocketPool(cc, 1, 1);
            if (!ok)
            {
                Console.WriteLine("Can not connect to remote server and press ENTER key to shutdown the application ......");
                Console.ReadLine(); return;
            }
            CStreamingFile rf = spRf.Seek();
            Console.WriteLine("Input a remote file path:");
            //test both downloading and uploading files in file stream (it is different from byte stream)
            string RemoteFile = Console.ReadLine();
            string LocalFile  = "spfile1.test";
            //downloading test
            ok = rf.Download(LocalFile, RemoteFile, (file, res, errMsg) =>
            {
                if (res != 0)
                {
                    Console.WriteLine("Error code: {0}, error message: {1}", res, errMsg);
                }
                else
                {
                    Console.WriteLine("Downloading {0} completed", file.RemoteFile);
                }
            }, (file, downloaded) =>
            {
                //downloading progress
                Console.WriteLine("Downloading rate: {0}%", downloaded * 100 / file.FileSize);
            });
            ok = rf.WaitAll();

            //uploading test
            RemoteFile += ".copy";
            ok          = rf.Upload(LocalFile, RemoteFile, (file, res, errMsg) =>
            {
                if (res != 0)
                {
                    Console.WriteLine("Error code: {0}, error message: {1}", res, errMsg);
                }
                else
                {
                    Console.WriteLine("Uploading {0} completed", file.RemoteFile);
                }
            }, (file, uploaded) =>
            {
                //uploading progress
                Console.WriteLine("Uploading rate: {0}%", uploaded * 100 / file.FileSize);
            });
            ok = rf.WaitAll();
            Console.WriteLine("Press key ENTER to shutdown the demo application ......");
            Console.ReadLine();
        }
    }
Example #6
0
    static void Main(string[] args)
    {
        //set a two-dimensional array of socket connection contexts
        #if PocketPC
        CConnectionContext[,] ccs = new CConnectionContext[1, 1];
        #else
        CConnectionContext[,] ccs = new CConnectionContext[System.Environment.ProcessorCount, 1];
        #endif
        int threads = ccs.GetLength(0);
        int sockets_per_thread = ccs.GetLength(1);
        for (int n = 0; n < threads; ++n)
        {
            for (int j = 0; j < sockets_per_thread; ++j)
            {
                string ipAddress;
                if (j == 0)
                    ipAddress = "192.168.1.111";
                else
                    ipAddress = "localhost";
                ccs[n, j] = new CConnectionContext(ipAddress, 20901, "adoclient", "password4AdoClient");
            }
        }

        using (CSocketPool<RAdo> spAdo = new CSocketPool<RAdo>(true)) //true -- automatic reconnecting
        {
            //start a pool of sockets
            if (!spAdo.StartSocketPool(ccs))
            {
                Console.WriteLine("No socket connection");
                return;
            }

            RAdo ado = spAdo.Seek();

            //process two requests one by one with synchronous communication style
            DataSet ds = ado.GetDataSet("select * from dimProduct", "select * from dimAccount");
            Console.WriteLine("Dataset returned with {0} tables", ds.Tables.Count);
            DataTable dt = ado.GetDataTable("select * from dimCustomer");
            Console.WriteLine("Datatable returned with columns = {0}, rows = {1}", dt.Columns.Count, dt.Rows.Count);

            //send two requests in parallel with asynchronous communication style
            RAdo ado1 = spAdo.Seek();
            bool ok = ado1.SendRequest(radoConst.idGetDataTableRAdo, "select * from dimCustomer", (ar) =>
            {
                Console.WriteLine("Datatable returned with columns = {0}, rows = {1}", ado1.CurrentDataTable.Columns.Count, ado1.CurrentDataTable.Rows.Count);
            });

            RAdo ado2 = spAdo.Seek();
            ok = ado2.SendRequest(radoConst.idGetDataSetRAdo, "select * from dimProduct", "select * from dimAccount", (ar) =>
            {
                Console.WriteLine("Dataset returned with {0} tables", ado2.CurrentDataSet.Tables.Count);
            });
            //ok = ado1.WaitAll() && ado2.WaitAll();
            Console.WriteLine("Press key ENTER to shutdown the demo application ......");
            Console.ReadLine();
        }
    }
Example #7
0
    static void Main(string[] args)
    {
        Console.WriteLine("Remote SocketPro file streaming server:");
        CConnectionContext cc = new CConnectionContext(Console.ReadLine(), 20901, "MyUserId", "MyPassword");

        using (CSocketPool <CStreamingFile> spRf = new CSocketPool <CStreamingFile>())
        {
            if (!spRf.StartSocketPool(cc, 1))
            {
                Console.WriteLine("Can not connect to remote server and press ENTER key to shutdown the application ......");
                Console.ReadLine(); return;
            }
            CStreamingFile rf = spRf.Seek();
            Console.WriteLine("Input a remote file path:");
            //test both downloading and uploading files in file stream (it is different from byte stream)
            string RemoteFile = Console.ReadLine();
            string LocalFile  = "spfile1.test";
            try
            {
                //downloading test
                var td = rf.download(LocalFile, RemoteFile, (file, downloaded) =>
                {
                    Console.WriteLine("Downloading rate: {0}%", downloaded * 100 / file.FileSize);
                });

                //uploading test
                RemoteFile += ".copy";
                var tu = rf.upload(LocalFile, RemoteFile, (file, uploaded) =>
                {
                    Console.WriteLine("Uploading rate: {0}%", uploaded * 100 / file.FileSize);
                });
                Console.WriteLine(td.Result);
                Console.WriteLine();
                Console.WriteLine(tu.Result);
            }
            catch (AggregateException ex)
            {
                foreach (Exception e in ex.InnerExceptions)
                {
                    //An exception from server (CServerError), Socket closed after sending a request (CSocketError) or request canceled (CSocketError),
                    Console.WriteLine(e);
                }
            }
            catch (CSocketError ex)
            {
                //Socket is already closed before sending a request
                Console.WriteLine(ex);
            }
            catch (Exception ex)
            {
                //bad operations such as invalid arguments, bad operations and de-serialization errors, and so on
                Console.WriteLine(ex);
            }
            Console.WriteLine("Press key ENTER to shutdown the demo application ......");
            Console.ReadLine();
        }
    }
Example #8
0
 static void Main(string[] args)
 {
     CConnectionContext cc = new CConnectionContext("127.0.0.1", 20901, "lb_worker", "pwdForlb_worker");
     using (CSocketPool<PiWorker> spPi = new CSocketPool<PiWorker>(true)) //true -- automatic reconnecting
     {
         spPi.StartSocketPool(cc, 1);
         Console.WriteLine("Press key ENTER to shutdown the demo application ......");
         Console.ReadLine();
     }
 }
Example #9
0
 private void Connection_Closed(string s)
 {
     if (m_spMysql != null)
     {
         m_spMysql.Dispose();
         m_spMysql = null;
     }
     btnDisconnect.Enabled = false;
     btnConnect.Enabled    = true;
     txtMessage.Text       = s;
 }
Example #10
0
    static void Main(string[] args)
    {
        CConnectionContext cc = new CConnectionContext("127.0.0.1", 20901, "lb_worker", "pwdForlb_worker");

        using (CSocketPool <PiWorker> spPi = new CSocketPool <PiWorker>(true)) //true -- automatic reconnecting
        {
            spPi.StartSocketPool(cc, 1);
            Console.WriteLine("Press key ENTER to shutdown the demo application ......");
            Console.ReadLine();
        }
    }
Example #11
0
        void EndProcess(string[] vDbFullName, bool secure, CConnectionContext[,] mcc, tagThreadApartment ta)
        {
            m_pool = new CSocketPool <THandler>(!m_rs.NoAutoConn, m_rs.RecvTimeout, m_rs.ConnTimeout);
            if (secure)
            {
                m_pool.DoSslServerAuthentication += (sender, cs) =>
                {
                    if (cs.ConnectionContext.Port == ushort.MaxValue)
                    {
                        return(true);
                    }
                    return(DoSslServerAuthentication(cs));
                };
            }

            m_pool.SocketPoolEvent += (sender, spe, handler) =>
            {
                switch (spe)
                {
                case tagSocketPoolEvent.speSocketClosed:
                    handler.CleanCallbacks();
                    break;

                case tagSocketPoolEvent.speConnecting:
                    if (handler.AttachedClientSocket.ConnectionContext.Port == ushort.MaxValue)
                    {
                        handler.AttachedClientSocket.ConnectingTimeout = 500;
                    }
                    break;

                default:
                    break;
                }
            };

            bool ok = m_pool.StartSocketPool(mcc, true, ta);
            int  n  = 0;

            foreach (CClientSocket s in m_pool.Sockets)
            {
                string key = vDbFullName[n];
                ok = s.ClientQueue.StartQueue(key, m_rs.TTL, secure);
                ++n;
            }
            if (Replicable)
            {
                SourceQueue.EnsureAppending(TargetQueues);
            }
            THandler[] targetHandlers = TargetHandlers;
            foreach (THandler h in targetHandlers)
            {
                ok = h.AttachedClientSocket.DoEcho();
            }
        }
Example #12
0
    static void Main(string[] args)
    {
        CConnectionContext cc = new CConnectionContext("localhost", 20901, "MyUserId", "MyPassword");
        using (CSocketPool<RemotingFile> spRf = new CSocketPool<RemotingFile>())
        {
            do
            {
                bool ok = spRf.StartSocketPool(cc, 1, 1);
                if (!ok)
                {
                    Console.WriteLine("Can not connect to remote server");
                    break;
                }

                RemotingFile rf = spRf.Seek();

                //downloading test
                CStreamHelper.DProgress progress = (sender, pos) =>
                {
                    Console.WriteLine("Downloading progress = " + (pos * 100) / sender.DownloadingStreamSize);
                };
                rf.StreamHelper.Progress += progress;
                Console.WriteLine("Input a remote file to download ......");
                string RemoteFile = Console.ReadLine();
                string LocalFile = "spfile.test";
                Stream s = new FileStream(LocalFile, FileMode.Append);
                string res = rf.StreamHelper.Download(s, RemoteFile);
                if (res.Length == 0 && rf.WaitAll())
                    Console.WriteLine("Successful to download file " + RemoteFile);
                else
                    Console.WriteLine("Failed to download file " + RemoteFile);
                s.Close();
                rf.StreamHelper.Progress -= progress; //remove the callback

                //uploading test
                RemoteFile = "spfile.testr";
                s = new FileStream(LocalFile, FileMode.Open);
                ulong FileSize = (ulong)s.Length;
                rf.StreamHelper.Progress += (sender, pos) =>
                {
                    Console.WriteLine("Uploading progress = " + (pos * 100) / FileSize);
                };
                res = rf.StreamHelper.Upload(s, RemoteFile);
                if (res == "" && rf.WaitAll())
                    Console.WriteLine("Successful to upload file " + LocalFile);
                else
                    Console.WriteLine("Failed to upload file " + LocalFile);
                s.Close();
            } while (false);
            Console.WriteLine("Press key ENTER to shutdown the demo application ......");
            Console.ReadLine();
        }
    }
Example #13
0
    static void Main(string[] args)
    {
        Console.WriteLine("This is worker client. Remote router host: ");
        CConnectionContext cc = new CConnectionContext(Console.ReadLine(), 20901, "lb_worker", "pwdForlb_worker");

        using (CSocketPool <PiWorker> spPi = new CSocketPool <PiWorker>())
        {
            spPi.StartSocketPool(cc, 1, (uint)Environment.ProcessorCount);
            Console.WriteLine("Press key ENTER to shutdown the demo application ......");
            Console.ReadLine();
        }
    }
Example #14
0
        private void m_spMysql_SocketPoolEvent(CSocketPool <CMysql> sender, tagSocketPoolEvent spe, CMysql AsyncServiceHandler)
        {
            switch (spe)
            {
            case tagSocketPoolEvent.speSocketClosed:
                //this event is fired from worker thread from socket pool thread
                BeginInvoke(m_closed, "Database server or network shut down");
                break;

            default:
                break;
            }
        }
Example #15
0
        private async void btnConnect_Click(object sender, EventArgs e)
        {
            CConnectionContext cc = new CConnectionContext(txtHost.Text, 20901, txtUser.Text, txtPassword.Text);

            m_spSqlite = new CSocketPool <CSqlite>(false);

            //set event for MySQL/Mariadb database shutdown
            m_spSqlite.SocketPoolEvent += new CSocketPool <CSqlite> .DOnSocketPoolEvent(m_spSqlite_SocketPoolEvent);

            if (!m_spSqlite.StartSocketPool(cc, 1))
            {
                txtMessage.Text = "No connection to " + txtHost.Text;
                return;
            }
            CSqlite sqlite = m_spSqlite.AsyncHandlers[0];

            //set event for tracking all database table update events, delete, update and insert
            m_spSqlite.Sockets[0].Push.OnPublish += new DOnPublish(Push_OnPublish);

            //create a DB session with default to sample database sakil
            sqlite.Open("sakila.db", null, DB_CONSTS.ENABLE_TABLE_UPDATE_MESSAGES);

            m_ds = new DataSet("real-time cache");
            DataTable dt = null;
            //query all cached tables into client side for intial cache data
            var res = await sqlite.execute("", (h, data) =>
            {
                //this callback is fired from worker thread from socket pool thread
                CSqlite.AppendRowDataIntoDataTable(data, dt);
            }, (h) =>
            {
                //this callback is fired from worker thread from socket pool thread
                dt           = CSqlite.MakeDataTable(h.ColumnInfo);
                string name  = h.ColumnInfo[0].DBPath + "." + h.ColumnInfo[0].TablePath;
                dt.TableName = name;
                m_ds.Tables.Add(dt);
            });

            txtMessage.Text = res.em;
            lstTables.Items.Clear();
            foreach (DataTable table in m_ds.Tables)
            {
                lstTables.Items.Add(table.TableName);
            }
            if (m_ds.Tables.Count > 0)
            {
                lstTables.SelectedIndex = 0;
            }
            btnDisconnect.Enabled = (res.ec == 0);
            btnConnect.Enabled    = (res.ec != 0);
        }
Example #16
0
    static void Main(string[] args)
    {
        Console.WriteLine("Remote host: ");
        string             host = Console.ReadLine();
        CConnectionContext cc   = new CConnectionContext(host, 20901, "usqlite_client", "pwd_for_usqlite");

        using (CSocketPool <CSqlite> spSqlite = new CSocketPool <CSqlite>())
        {
            if (!spSqlite.StartSocketPool(cc, 1, 1))
            {
                Console.WriteLine("Failed in connecting to remote async sqlite server");
                Console.WriteLine("Press any key to close the application ......");
                Console.Read();
                return;
            }
            CSqlite sqlite = spSqlite.Seek();
            bool    ok     = sqlite.Open("", (handler, res, errMsg) =>
            {
                Console.WriteLine("res = {0}, errMsg: {1}", res, errMsg);
            });
            TestCreateTables(sqlite);
            List <KeyValuePair <CDBColumnInfoArray, CDBVariantArray> > lstRowset = new List <KeyValuePair <CDBColumnInfoArray, CDBVariantArray> >();
            ok = sqlite.BeginTrans();
            TestPreparedStatements(sqlite, lstRowset);
            InsertBLOBByPreparedStatement(sqlite, lstRowset);
            ok = sqlite.EndTrans();
            sqlite.WaitAll();

            int index = 0;
            Console.WriteLine();
            Console.WriteLine("+++++ Start rowsets +++");
            foreach (KeyValuePair <CDBColumnInfoArray, CDBVariantArray> it in lstRowset)
            {
                Console.Write("Statement index = {0}", index);
                if (it.Key.Count > 0)
                {
                    Console.WriteLine(", rowset with columns = {0}, records = {1}.", it.Key.Count, it.Value.Count / it.Key.Count);
                }
                else
                {
                    Console.WriteLine(", no rowset received.");
                }
                ++index;
            }
            Console.WriteLine("+++++ End rowsets +++");
            Console.WriteLine();
            Console.WriteLine("Press any key to close the application ......");
            Console.Read();
        }
    }
Example #17
0
    static void Main(string[] args)
    {
        bool ok;

        CClientSocket.QueueConfigure.MessageQueuePassword = "******";
        if (System.Environment.OSVersion.Platform == PlatformID.Unix)
        {
            CClientSocket.QueueConfigure.WorkDirectory = "/home/yye/sp_test/";
        }
        else
        {
            CClientSocket.QueueConfigure.WorkDirectory = "c:\\sp_test";
        }
        Console.WriteLine("This is a client. Remote router host: ");
        CConnectionContext cc = new CConnectionContext(Console.ReadLine(), 20901, "lb_client", "pwd_lb_client");

        using (CSocketPool <Pi> spPi = new CSocketPool <Pi>(true)) //true -- automatic reconnecting
        {
            ok = spPi.StartSocketPool(cc, 1, 1);
            CClientSocket cs = spPi.Sockets[0];

            //use persistent queue to ensure auto failure recovery and at-least-once or once-only delivery
            ok = cs.ClientQueue.StartQueue("pi_queue", 24 * 3600, (cs.EncryptionMethod == tagEncryptionMethod.TLSv1));
            cs.ClientQueue.RoutingQueueIndex = true;

            Pi pi = spPi.AsyncHandlers[0];
            pi.WaitAll(); //make sure all existing queued requests are processed before executing next requests

            double dPi       = 0.0;
            int    nDivision = 1000;
            int    nNum      = 10000000;
            double dStep     = 1.0 / nNum / nDivision;
            int    nReturns  = 0;
            for (int n = 0; n < nDivision; ++n)
            {
                double dStart = (double)n / nDivision;
                ok = pi.SendRequest(piConst.idComputePi, dStart, dStep, nNum, (ar) => {
                    double res;
                    ar.Load(out res);
                    dPi += res;
                    ++nReturns;
                });
            }
            ok = pi.WaitAll();
            Console.WriteLine("Your pi = {0}, returns = {1}", dPi, nReturns);
            Console.WriteLine("Press ENTER key to shutdown the demo application ......");
            Console.ReadLine();
        }
    }
Example #18
0
    static void Demo_Multiple_SendRequest_MultiThreaded_Wrong(object sp)
    {
        uint cycle = m_cycle; CSocketPool <CSqlite> spSqlite = (CSocketPool <CSqlite>)sp;

        while (cycle > 0)
        {
            //Seek an async handler on the min number of requests queued in memory and its associated socket connection
            CSqlite sqlite = spSqlite.Seek();
            //lock(sqlite) //uncomment this call to remove potential batch request overlap
            StreamSQLsWithManualTransaction(sqlite);
            --cycle;
        }
        foreach (CSqlite s in spSqlite.AsyncHandlers)
        {
            s.WaitAll();
        }
    }
Example #19
0
    static void Main(string[] args)
    {
        Console.WriteLine("Remote host: ");
        string host = Console.ReadLine();
        CConnectionContext cc = new CConnectionContext(host, 20901, "async_queue_client", "pwd_for_async_queue");
        using (CSocketPool<CAsyncQueue> spAq = new CSocketPool<CAsyncQueue>())
        {
            if (!spAq.StartSocketPool(cc, 1, 1))
            {
                Console.WriteLine("Failed in connecting to remote async queue server");
                Console.WriteLine("Press any key to close the application ......");
                Console.Read();
                return;
            }
            CAsyncQueue aq = spAq.Seek();

            //Optionally, you can enqueue messages with transaction style by calling the methods StartQueueTrans and EndQueueTrans in pair
            aq.StartQueueTrans(TEST_QUEUE_KEY, (errCode) =>
            {
                //error code could be one of CAsyncQueue.QUEUE_OK, CAsyncQueue.QUEUE_TRANS_ALREADY_STARTED, ......
            });
            TestEnqueue(aq);
            aq.EndQueueTrans(false);
            TestDequeue(aq);
            aq.WaitAll();

            //get a queue key two parameters, message count and queue file size by default option oMemoryCached
            aq.FlushQueue(TEST_QUEUE_KEY, (messageCount, fileSize) =>
            {
                Console.WriteLine("Total message count={0}, queue file size={1}", messageCount, fileSize);
            });

            aq.GetKeys((keys) =>
            {
                keys = null;
            });

            aq.CloseQueue(TEST_QUEUE_KEY, (errCode) =>
            {
                //error code could be one of CAsyncQueue.QUEUE_OK, CAsyncQueue.QUEUE_TRANS_ALREADY_STARTED, ......
            });

            Console.WriteLine("Press any key to close the application ......");
            Console.Read();
        }
    }
Example #20
0
    static void Demo_Multiple_SendRequest_MultiThreaded_Correct_Lock_Unlock(object sp)
    {
        uint cycle = m_cycle; CSocketPool <CSqlite> spSqlite = (CSocketPool <CSqlite>)sp;

        while (cycle > 0)
        {
            //Take an async handler infinitely from socket pool for sending multiple requests from current thread
            CSqlite sqlite = spSqlite.Lock();
            StreamSQLsWithManualTransaction(sqlite);
            //Put back a previously locked async handler to pool for reuse
            spSqlite.Unlock(sqlite);
            --cycle;
        }
        foreach (CSqlite s in spSqlite.AsyncHandlers)
        {
            s.WaitAll();
        }
    }
Example #21
0
    static void Main(string[] args)
    {
        Console.WriteLine("Remote host: ");
        string             host = Console.ReadLine();
        CConnectionContext cc   = new CConnectionContext(host, 20901, "async_queue_client", "pwd_for_async_queue");

        using (CSocketPool <CAsyncQueue> spAq = new CSocketPool <CAsyncQueue>())
        {
            //spAq.QueueName = "qname";
            if (!spAq.StartSocketPool(cc, 1))
            {
                Console.WriteLine("Failed in connecting to remote async queue server");
                Console.WriteLine("Press key ENTER to close the application ......");
                Console.ReadLine();
                return;
            }
            CAsyncQueue aq = spAq.Seek();
            try
            {
                TestEnqueue(aq);
                Console.WriteLine(TestDequeue(aq).Result);
            }
            catch (AggregateException ex)
            {
                foreach (Exception e in ex.InnerExceptions)
                {
                    //An exception from server (CServerError), Socket closed after sending a request (CSocketError) or request canceled (CSocketError),
                    Console.WriteLine(e);
                }
            }
            catch (CSocketError ex)
            {
                //Socket is already closed before sending a request
                Console.WriteLine(ex);
            }
            catch (Exception ex)
            {
                //bad operations such as invalid arguments, bad operations and de-serialization errors, and so on
                Console.WriteLine(ex);
            }
            Console.WriteLine("Press key ENTER to close the application ......");
            Console.ReadLine();
        }
    }
Example #22
0
    static void Main(string[] args)
    {
        Console.WriteLine("Remote host: ");
        string host = Console.ReadLine();
        CConnectionContext cc = new CConnectionContext(host, 20901, "async_queue_client", "pwd_for_async_queue");
        using (CSocketPool<CAsyncQueue> spAq = new CSocketPool<CAsyncQueue>())
        {
            if (!spAq.StartSocketPool(cc, 1, 1))
            {
                Console.WriteLine("Failed in connecting to remote async queue server");
                Console.WriteLine("Press any key to close the application ......");
                Console.Read();
                return;
            }

            CAsyncQueue sq = spAq.Seek();

            //a string having 200 chars
            string s = "SocketPro is a world-leading package of secured communication software components written with request batching, asynchrony and parallel computation in mind. It offers superior performance and scalabi";
            EnqueueToServer(sq, s, 1000000);
            DequeueFromServer(sq);

            string s1024 = "";
            for (int n = 0; n < 6; ++n)
            {
                s1024 += s;
            }
            s1024 = s1024.Substring(0, 1024);
            EnqueueToServer(sq, s1024, 1000000);
            DequeueFromServer(sq);

            string s10240 = "";
            for (int n = 0; n < 10; ++n)
            {
                s10240 += s1024;
            }
            EnqueueToServer(sq, s10240, 100000);
            DequeueFromServer(sq);

            Console.WriteLine("Press key ENTER to complete dequeuing messages from server ......");
            Console.ReadLine();
        }
    }
Example #23
0
    static void Main(string[] args)
    {
        bool ok;
        CClientSocket.QueueConfigure.MessageQueuePassword = "******";
        if (System.Environment.OSVersion.Platform == PlatformID.Unix)
            CClientSocket.QueueConfigure.WorkDirectory = "/home/yye/sp_test/";
        else
            CClientSocket.QueueConfigure.WorkDirectory = "c:\\sp_test";
        CConnectionContext cc = new CConnectionContext("localhost", 20901, "lb_client", "pwd_lb_client");
        using (CSocketPool<Pi> spPi = new CSocketPool<Pi>(true)) //true -- automatic reconnecting
        {
            ok = spPi.StartSocketPool(cc, 1, 1);
            CClientSocket cs = spPi.Sockets[0];

            //use persistent queue to ensure auto failure recovery and at-least-once or once-only delivery
            ok = cs.ClientQueue.StartQueue("pi_queue", 24 * 3600, (cs.EncryptionMethod == tagEncryptionMethod.TLSv1));
            cs.ClientQueue.RoutingQueueIndex = true;

            Pi pi = spPi.AsyncHandlers[0];
            pi.WaitAll(); //make sure all existing queued requests are processed before executing next requests

            double dPi = 0.0;
            int nDivision = 1000;
            int nNum = 10000000;
            double dStep = 1.0 / nNum / nDivision;
            int nReturns = 0;
            for (int n = 0; n < nDivision; ++n) {
                double dStart = (double) n / nDivision;
                ok = pi.SendRequest(piConst.idComputePi, dStart, dStep, nNum, (ar) => {
                    double res;
                    ar.Load(out res);
                    dPi += res;
                    ++nReturns;
                });
            }
            ok = pi.WaitAll();
            Console.WriteLine("Your pi = {0}, returns = {1}", dPi, nReturns);
            Console.WriteLine("Press ENTER key to shutdown the demo application ......");
            Console.ReadLine();
        }
    }
Example #24
0
    static void Main(string[] args)
    {
        Console.WriteLine("This is a client. Remote router host: ");
        CConnectionContext cc = new CConnectionContext(Console.ReadLine(), 20901, "lb_client", "pwd_lb_client");

        using (CSocketPool <Pi> spPi = new CSocketPool <Pi>())
        {
            spPi.QueueName = "lbqueue";
            if (!spPi.StartSocketPool(cc, 1))
            {
                Console.WriteLine("No connection to " + cc.Host);
                Console.WriteLine("Press ENTER key to kill the demo ......");
                Console.ReadLine();
                return;
            }
            Pi pi = spPi.SeekByQueue();

            int    nDivision = 1000, nNum = 10000000;
            double dPi = 0, dStep = 1.0 / nNum / nDivision;
            List <Task <CScopeUQueue> > vtR = new List <Task <CScopeUQueue> >();
            for (int n = 0; n < nDivision; ++n)
            {
                double dStart = (double)n / nDivision;
                vtR.Add(pi.sendRequest(piConst.idComputePi, dStart, dStep, nNum));
            }

            foreach (var t in vtR)
            {
                CScopeUQueue sb = t.Result;
                dPi += sb.Load <double>();
                Console.WriteLine("dStart: " + sb.Load <double>());
            }

            Console.WriteLine("pi: {0}, returns: {1}", dPi, vtR.Count);
            Console.WriteLine("Press ENTER key to kill the demo ......");
            Console.ReadLine();
        }
    }
Example #25
0
    static void Main(string[] args)
    {
        Console.WriteLine("Remote host: ");
        string host = Console.ReadLine();
        CConnectionContext cc = new CConnectionContext(host, 20901, "async_queue_client", "pwd_for_async_queue");
        using (CSocketPool<CAsyncQueue> spAq = new CSocketPool<CAsyncQueue>())
        {
            if (!spAq.StartSocketPool(cc, 1, 1))
            {
                Console.WriteLine("Failed in connecting to remote async queue server");
                Console.WriteLine("Press any key to close the application ......");
                Console.Read();
                return;
            }
            CAsyncQueue aq = spAq.Seek();

            TestEnqueue(aq);
            TestDequeue(aq);

            Console.WriteLine("Press any key to close the application ......");
            Console.Read();
        }
    }
Example #26
0
    static void Main(string[] args)
    {
        CConnectionContext cc = new CConnectionContext("localhost", 20901, "hwClientUserId", "password4hwClient");

        using (CSocketPool <HelloWorld> spHw = new CSocketPool <HelloWorld>(true)) //true -- automatic reconnecting
        {
            bool       ok = spHw.StartSocketPool(cc, 1, 1);
            HelloWorld hw = spHw.Seek(); //or HelloWorld hw = spHw.Lock();

            //optionally start a persistent queue at client side to ensure auto failure recovery and once-only delivery
            ok = hw.AttachedClientSocket.ClientQueue.StartQueue("helloworld", 24 * 3600, false); //time-to-live 1 day and true for encryption

            //process requests one by one synchronously
            Console.WriteLine(hw.SayHello("Jone", "Dole"));
            hw.Sleep(5000);
            CMyStruct msOriginal = CMyStruct.MakeOne();
            CMyStruct ms         = hw.Echo(msOriginal);

            //asynchronously process multiple requests with inline batching for best network efficiency
            ok = hw.SendRequest(hwConst.idSayHelloHelloWorld, "Jack", "Smith", (ar) =>
            {
                string ret;
                ar.Load(out ret);
                Console.WriteLine(ret);
            });
            CAsyncServiceHandler.DAsyncResultHandler arh = null;
            ok = hw.SendRequest(hwConst.idSleepHelloWorld, (int)5000, arh);
            ok = hw.SendRequest(hwConst.idEchoHelloWorld, msOriginal, (ar) =>
            {
                ar.Load(out ms);
            });
            ok = hw.WaitAll();
            Console.WriteLine("Press ENTER key to shutdown the demo application ......");
            Console.ReadLine();
        }
    }
Example #27
0
    static void Main(string[] args)
    {
        Console.WriteLine("Remote host: ");
        string             host = Console.ReadLine();
        CConnectionContext cc   = new CConnectionContext(host, 20901, "async_queue_client", "pwd_for_async_queue");

        using (CSocketPool <CAsyncQueue> spAq = new CSocketPool <CAsyncQueue>())
        {
            if (!spAq.StartSocketPool(cc, 1, 1))
            {
                Console.WriteLine("Failed in connecting to remote async queue server");
                Console.WriteLine("Press key ENTER to close the application ......");
                Console.ReadLine();
                return;
            }
            CAsyncQueue aq = spAq.Seek();

            TestEnqueue(aq);
            TestDequeue(aq);

            Console.WriteLine("Press key ENTER to close the application ......");
            Console.ReadLine();
        }
    }
Example #28
0
    static Task <bool> DoFuture(CSocketPool <CSqlite> sp)
    {
        TaskCompletionSource <bool> tcs = new TaskCompletionSource <bool>();
        CSqlite sqlite = sp.Lock();

        if (sqlite == null)
        {
            lock (m_csConsole) Console.WriteLine("All sockets are disconnected from server"); tcs.SetResult(false); return(tcs.Task);
        }
        bool ok = false;

        do
        {
            if (!sqlite.BeginTrans(tagTransactionIsolation.tiReadCommited, (h, res, errMsg) =>
            {
                if (res != 0)
                {
                    lock (m_csConsole) Console.WriteLine("BeginTrans: Error code={0}, message={1}", res, errMsg);
                }
            }))
            {
                break;
            }
            if (!sqlite.Execute("delete from EMPLOYEE;delete from COMPANY", (h, res, errMsg, affected, fail_ok, id) =>
            {
                if (res != 0)
                {
                    lock (m_csConsole) Console.WriteLine("Execute_Delete: affected={0}, fails={1}, res={2}, errMsg={3}",
                                                         affected, (uint)(fail_ok >> 32), res, errMsg);
                }
            }))
            {
                break;
            }
            if (!sqlite.Prepare("INSERT INTO COMPANY(ID,NAME)VALUES(?,?)"))
            {
                break;
            }
            CDBVariantArray vData = new CDBVariantArray();
            vData.Add(1); vData.Add("Google Inc.");
            vData.Add(2); vData.Add("Microsoft Inc.");
            //send two sets of parameterised data in one shot for processing
            if (!sqlite.Execute(vData, (h, res, errMsg, affected, fail_ok, id) =>
            {
                if (res != 0)
                {
                    lock (m_csConsole) Console.WriteLine("INSERT COMPANY: affected={0}, fails={1}, res={2}, errMsg={3}",
                                                         affected, (uint)(fail_ok >> 32), res, errMsg);
                }
            }))
            {
                break;
            }
            if (!sqlite.Prepare("INSERT INTO EMPLOYEE(EMPLOYEEID,CompanyId,name,JoinDate)VALUES(?,?,?,?)"))
            {
                break;
            }
            vData.Clear();
            vData.Add(1); vData.Add(1); /*google company id*/ vData.Add("Ted Cruz"); vData.Add(DateTime.Now);
            vData.Add(2); vData.Add(1); /*google company id*/ vData.Add("Donald Trump"); vData.Add(DateTime.Now);
            vData.Add(3); vData.Add(2); /*Microsoft company id*/ vData.Add("Hillary Clinton"); vData.Add(DateTime.Now);
            //send three sets of parameterised data in one shot for processing
            if (!sqlite.Execute(vData, (h, res, errMsg, affected, fail_ok, id) =>
            {
                if (res != 0)
                {
                    lock (m_csConsole) Console.WriteLine("INSET EMPLOYEE: affected={0}, fails={1}, res={2}, errMsg={3}",
                                                         affected, (uint)(fail_ok >> 32), res, errMsg);
                }
            }))
            {
                break;
            }
            if (!sqlite.EndTrans(tagRollbackPlan.rpDefault, (h, res, errMsg) =>
            {
                if (res != 0)
                {
                    lock (m_csConsole) Console.WriteLine("EndTrans: Error code={0}, message={1}", res, errMsg);
                }
                tcs.SetResult(true);
            }, (h, canceled) =>
            {
                lock (m_csConsole) Console.WriteLine("EndTrans: " + (canceled ? "Request canceled" : "Socket closed"));
                tcs.SetResult(false);
            }))
            {
                break;
            }
            ok = true;
            sp.Unlock(sqlite); //put handler back into pool for reuse
        } while (false);
        if (!ok)
        {
            //Socket is closed at server side and the above locked handler is automatically unlocked
            lock (m_csConsole) Console.WriteLine("DoFuture: Connection disconnected error code ={0}, message ={1}",
                                                 sqlite.AttachedClientSocket.ErrorCode, sqlite.AttachedClientSocket.ErrorMsg);
            tcs.SetResult(false);
        }
        return(tcs.Task);
    }
Example #29
0
    static void Main(string[] args)
    {
        Console.WriteLine("Remote host: "); string host = Console.ReadLine();
        CConnectionContext cc = new CConnectionContext(host, 20901, "usqlite_client", "pwd_for_usqlite");

        using (CSocketPool <CSqlite> spSqlite = new CSocketPool <CSqlite>())
        {
            //start socket pool having 1 worker thread which hosts 2 non-blocking sockets
            if (!spSqlite.StartSocketPool(cc, 2, 1))
            {
                Console.WriteLine("No connection to sqlite server and press any key to close the demo ......");
                Console.Read(); return;
            }
            CSqlite sqlite = spSqlite.AsyncHandlers[0];
            //Use the above bad implementation to replace original SocketProAdapter.ClientSide.CAsyncDBHandler.Open method
            //at file socketpro/src/SproAdapter/asyncdbhandler.cs for cross SendRequest dead lock demonstration
            Console.WriteLine("Doing Demo_Cross_Request_Dead_Lock ......");
            Demo_Cross_Request_Dead_Lock(sqlite);

            //create two tables, COMPANY and EMPLOYEE
            TestCreateTables(sqlite);
            bool ok = sqlite.WaitAll();
            Console.WriteLine("{0} created, opened and shared by multiple sessions", sample_database); Console.WriteLine();

            //make sure all other handlers/sockets to open the same database mysample.db
            CSqlite[] vSqlite = spSqlite.AsyncHandlers;
            for (int n = 1; n < vSqlite.Length; ++n)
            {
                vSqlite[n].Open(sample_database, (handler, res, errMsg) =>
                {
                    if (res != 0)
                    {
                        Console.WriteLine("Open: res = {0}, errMsg: {1}", res, errMsg);
                    }
                }); ok = vSqlite[n].WaitAll();
            }

            //execute manual transactions concurrently with transaction overlapping on the same session
            var tasks = new[] {
                Task.Factory.StartNew(Demo_Multiple_SendRequest_MultiThreaded_Wrong, spSqlite),
                Task.Factory.StartNew(Demo_Multiple_SendRequest_MultiThreaded_Wrong, spSqlite),
                Task.Factory.StartNew(Demo_Multiple_SendRequest_MultiThreaded_Wrong, spSqlite)
            }; Demo_Multiple_SendRequest_MultiThreaded_Wrong(spSqlite); Task.WaitAll(tasks);
            Console.WriteLine("Demo_Multiple_SendRequest_MultiThreaded_Wrong completed"); Console.WriteLine();

            //execute manual transactions concurrently without transaction overlapping on the same session by lock/unlock
            tasks = new[] {
                Task.Factory.StartNew(Demo_Multiple_SendRequest_MultiThreaded_Correct_Lock_Unlock, spSqlite),
                Task.Factory.StartNew(Demo_Multiple_SendRequest_MultiThreaded_Correct_Lock_Unlock, spSqlite),
                Task.Factory.StartNew(Demo_Multiple_SendRequest_MultiThreaded_Correct_Lock_Unlock, spSqlite)
            }; Demo_Multiple_SendRequest_MultiThreaded_Correct_Lock_Unlock(spSqlite); Task.WaitAll();
            Console.WriteLine("Demo_Multiple_SendRequest_MultiThreaded_Correct_Lock_Unlock completed"); Console.WriteLine();

            Console.WriteLine("Demonstration of DoFuture .....");
            if (!DoFuture(spSqlite).Wait(5000))
            {
                Console.WriteLine("The requests within the function DoFuture are not completed in 5 seconds");
            }
            else
            {
                Console.WriteLine("All requests within the function DoFuture are completed");
            }
            Console.WriteLine();
            Console.WriteLine("Press any key to close the application ......"); Console.Read();
        }
    }
Example #30
0
    static void Main(string[] args)
    {
        Console.WriteLine("SocketPro performance test against a remote MySQL backend DB");
        Console.WriteLine("Remote host: ");
        string host = Console.ReadLine();

        Console.WriteLine("Database name: ");
        string dbName = Console.ReadLine();

        Console.WriteLine("Table name: ");
        string tableName = Console.ReadLine();

        Console.WriteLine("sql filter: ");
        string             filter = Console.ReadLine();
        CConnectionContext cc     = new CConnectionContext(host, 20902, "root", "Smash123");

        Console.WriteLine("Asynchronous execution (0) or synchronous execution (1) ?");
        bool sync = (Console.ReadKey().KeyChar != '0');

        using (CSocketPool <CMysql> spMysql = new CSocketPool <CMysql>())
        {
            if (!spMysql.StartSocketPool(cc, 1, 1))
            {
                Console.WriteLine("Failed in connecting to remote helloworld server");
                Console.WriteLine("Press any key to close the application ......");
                Console.Read();
                return;
            }
            Console.WriteLine("");
            Console.WriteLine("Computing ......");
            CMysql mysql = spMysql.Seek();
            CAsyncDBHandler.DResult dr = (handler, res, errMsg) =>
            {
                if (res != 0)
                {
                    Console.WriteLine("res = {0}, errMsg: {1}", res, errMsg);
                }
            };
            uint obtained = 0;
            bool ok       = mysql.Open(dbName, dr);
#if USE_DATATABLE
            List <KeyValuePair <CDBColumnInfoArray, DataTable> > ra = new List <KeyValuePair <CDBColumnInfoArray, DataTable> >();
#else
            List <KeyValuePair <CDBColumnInfoArray, CDBVariantArray> > ra = new List <KeyValuePair <CDBColumnInfoArray, CDBVariantArray> >();
#endif
            CAsyncDBHandler.DExecuteResult er = (handler, res, errMsg, affected, fail_ok, id) =>
            {
                if (res != 0)
                {
                    Console.WriteLine("fails = {0}, oks = {1}, res = {2}, errMsg: {3}", (uint)(fail_ok >> 32), (uint)fail_ok, res, errMsg);
                }
                ra.Clear();
                ++obtained;
            };
            CAsyncDBHandler.DRows r = (handler, rowData) =>
            {
                //rowset data come here
                int last = ra.Count - 1;
#if USE_DATATABLE
                KeyValuePair <CDBColumnInfoArray, DataTable> item = ra[last];
                CAsyncDBHandler.AppendRowDataIntoDataTable(rowData, item.Value);
#else
                KeyValuePair <CDBColumnInfoArray, CDBVariantArray> item = ra[last];
                item.Value.AddRange(rowData);
#endif
            };
            CAsyncDBHandler.DRowsetHeader rh = (handler) =>
            {
                //rowset header comes here
#if USE_DATATABLE
                DataTable dt = CAsyncDBHandler.MakeDataTable(handler.ColumnInfo);
                KeyValuePair <CDBColumnInfoArray, DataTable> item = new KeyValuePair <CDBColumnInfoArray, DataTable>(handler.ColumnInfo, dt);
#else
                KeyValuePair <CDBColumnInfoArray, CDBVariantArray> item = new KeyValuePair <CDBColumnInfoArray, CDBVariantArray>(handler.ColumnInfo, new CDBVariantArray());
#endif
                ra.Add(item);
            };
            obtained = 0;
            string sql = "select * from " + tableName;
            if (filter.Length > 0)
            {
                sql += " where " + filter;
            }
            int      count = 10000;
            DateTime start = DateTime.Now;
            for (int n = 0; n < count; ++n)
            {
                ok = mysql.Execute(sql, er, r, rh);
                if (sync && ok)
                {
                    ok = mysql.WaitAll();
                }
                if (!ok)
                {
                    break;
                }
            }
            if (!sync && ok)
            {
                ok = mysql.WaitAll();
            }
            double diff = (DateTime.Now - start).TotalMilliseconds;
            Console.WriteLine("Time required = {0} milliseconds for {1} query requests", diff, obtained);

            //you need to compile and run the sample project test_sharp before running the below code
            ok = mysql.Execute("USE mysqldb;delete from company where id > 3");
            string sql_insert_parameter = "INSERT INTO company(ID,NAME,ADDRESS,Income)VALUES(?,?,?,?)";
            ok = mysql.Prepare(sql_insert_parameter, dr);
            ok = mysql.WaitAll();
            int index = 0;
            count = 50000;
            Console.WriteLine();
            Console.WriteLine("Going to insert {0} records into the table mysqldb.company", count);
            start = DateTime.Now;
            CDBVariantArray vData = new CDBVariantArray();
            ok = mysql.BeginTrans();
            for (int n = 0; n < count; ++n)
            {
                vData.Add(n + 4);
                int data = (n % 3);
                switch (data)
                {
                case 0:
                    vData.Add("Google Inc.");
                    vData.Add("1600 Amphitheatre Parkway, Mountain View, CA 94043, USA");
                    vData.Add(66000000000.12);
                    break;

                case 1:
                    vData.Add("Microsoft Inc.");
                    vData.Add("700 Bellevue Way NE- 22nd Floor, Bellevue, WA 98804, USA");
                    vData.Add(93600000001.24);
                    break;

                default:
                    vData.Add("Apple Inc.");
                    vData.Add("1 Infinite Loop, Cupertino, CA 95014, USA");
                    vData.Add(234000000002.17);
                    break;
                }
                ++index;
                //send 2000 sets of parameter data onto server for processing in batch
                if (2000 == index)
                {
                    ok = mysql.Execute(vData, er);
                    ok = mysql.EndTrans();
                    vData.Clear();
                    Console.WriteLine("Commit {0} records into the table mysqldb.company", index);
                    ok    = mysql.BeginTrans();
                    index = 0;
                }
            }
            if (vData.Count > 0)
            {
                ok = mysql.Execute(vData, er);
                Console.WriteLine("Commit {0} records into the table mysqldb.company", index);
            }
            ok   = mysql.EndTrans();
            ok   = mysql.WaitAll();
            diff = (DateTime.Now - start).TotalMilliseconds;
            Console.WriteLine("Time required = {0} milliseconds for {1} insert requests", diff, count);
            Console.WriteLine();
            Console.WriteLine("Press any key to close the application ......");
            Console.ReadLine();
        }
    }
Example #31
0
    static void Main(string[] args)
    {
        CConnectionContext cc = new CConnectionContext("localhost", 20901, "MyUserId", "MyPassword");

        using (CSocketPool <RemotingFile> spRf = new CSocketPool <RemotingFile>())
        {
            do
            {
                bool ok = spRf.StartSocketPool(cc, 1, 1);
                if (!ok)
                {
                    Console.WriteLine("Can not connect to remote server");
                    break;
                }

                RemotingFile rf = spRf.Seek();

                //downloading test
                CStreamHelper.DProgress progress = (sender, pos) =>
                {
                    Console.WriteLine("Downloading progress = " + (pos * 100) / sender.DownloadingStreamSize);
                };
                rf.StreamHelper.Progress += progress;
                Console.WriteLine("Input a remote file to download ......");
                string RemoteFile = Console.ReadLine();
                string LocalFile  = "spfile.test";
                Stream s          = new FileStream(LocalFile, FileMode.Append);
                string res        = rf.StreamHelper.Download(s, RemoteFile);
                if (res.Length == 0 && rf.WaitAll())
                {
                    Console.WriteLine("Successful to download file " + RemoteFile);
                }
                else
                {
                    Console.WriteLine("Failed to download file " + RemoteFile);
                }
                s.Close();
                rf.StreamHelper.Progress -= progress; //remove the callback

                //uploading test
                RemoteFile = "spfile.testr";
                s          = new FileStream(LocalFile, FileMode.Open);
                ulong FileSize = (ulong)s.Length;
                rf.StreamHelper.Progress += (sender, pos) =>
                {
                    Console.WriteLine("Uploading progress = " + (pos * 100) / FileSize);
                };
                res = rf.StreamHelper.Upload(s, RemoteFile);
                if (res == "" && rf.WaitAll())
                {
                    Console.WriteLine("Successful to upload file " + LocalFile);
                }
                else
                {
                    Console.WriteLine("Failed to upload file " + LocalFile);
                }
                s.Close();
            } while (false);
            Console.WriteLine("Press key ENTER to shutdown the demo application ......");
            Console.ReadLine();
        }
    }
Example #32
0
    static void Main(string[] args)
    {
        CConnectionContext cc = new CConnectionContext("localhost", 20901, "hwClientUserId", "password4hwClient");

        using (CSocketPool <HelloWorld> spHw = new CSocketPool <HelloWorld>())
        {
            //optionally start a persistent queue at client side to
            //ensure auto failure recovery and once-only delivery
            //spHw.QueueName = "helloworld";
            CMyStruct ms, msOrig = CMyStruct.MakeOne();
            if (spHw.StartSocketPool(cc, 1))
            {
                HelloWorld hw = spHw.Seek();
                try
                {
                    //process requests one by one synchronously
                    Task t0 = hw.sendRequest(hwConst.idSayHelloHelloWorld, "John", "Dole");
                    Console.WriteLine(t0.Result.Load <string>());
                    Task t1 = hw.sendRequest(hwConst.idSleepHelloWorld, (int)4000);
                    Console.WriteLine("Returned buffer size should be " + t1.Result.UQueue.Size + " because server returns nothing");
                    Task t2 = hw.sendRequest(hwConst.idEchoHelloWorld, msOrig);
                    ms = t2.Result.Load <CMyStruct>();

                    //All requests are streamed with in-line batch for the best network efficiency
                    t0 = hw.sendRequest(hwConst.idSayHelloHelloWorld, "John", "Dole");
                    t1 = hw.sendRequest(hwConst.idSleepHelloWorld, (int)4000);
                    t2 = hw.sendRequest(hwConst.idEchoHelloWorld, msOrig);
                    Task t3 = hw.sendRequest(hwConst.idSayHelloHelloWorld, "Jack", "Smith");
                    Task t4 = hw.sendRequest(hwConst.idSayHelloHelloWorld, "Donald", "Trump");
                    Task t5 = hw.sendRequest(hwConst.idSleepHelloWorld, (int)15000);
                    Task t6 = hw.sendRequest(hwConst.idSayHelloHelloWorld, "Hillary", "Clinton");
                    Task t7 = hw.sendRequest(hwConst.idEchoHelloWorld, msOrig);
                    //hw.Socket.Cancel();
                    Console.WriteLine(t0.Result.Load <string>());
                    Console.WriteLine("Returned buffer size should be " + t1.Result.UQueue.Size + " because server returns nothing");
                    ms = t2.Result.Load <CMyStruct>();
                    Console.WriteLine(t3.Result.Load <string>());
                    Console.WriteLine(t4.Result.Load <string>());
                    Console.WriteLine("Returned buffer size should be " + t5.Result.UQueue.Size + " because server returns nothing");
                    Console.WriteLine(t6.Result.Load <string>());
                    ms = t7.Result.Load <CMyStruct>();
                }
                catch (AggregateException ex)
                {
                    foreach (Exception e in ex.InnerExceptions)
                    {
                        //An exception from server (CServerError), Socket closed
                        //after sending a request (CSocketError) or canceled (CSocketError),
                        Console.WriteLine(e);
                    }
                }
                catch (CSocketError ex)
                {
                    //Socket is already closed before sending a request
                    Console.WriteLine(ex);
                }
                catch (Exception ex)
                {
                    //bad operations such as invalid arguments,
                    //bad operations and de-serialization errors, and so on
                    Console.WriteLine(ex);
                }
            }
            else
            {
                Console.WriteLine("No connection to server with error message: " + spHw.Sockets[0].ErrorMsg);
            }
            Console.WriteLine("Press ENTER key to kill the demo ......");
            Console.ReadLine();
        }
    }
Example #33
0
    static void Main(string[] args)
    {
        Console.WriteLine("Input your user id ......");
        CConnectionContext cc = new CConnectionContext("localhost", 20901, Console.ReadLine(), "MyPassword", tagEncryptionMethod.TLSv1);

        //CA file is located at the directory ..\SocketProRoot\bin
        CClientSocket.SSL.SetVerifyLocation("ca.cert.pem");

        //for windows platforms, you can also use windows system store instead
        //CClientSocket.SSL.SetVerifyLocation("my"); //or "root", "my@currentuser", "root@localmachine"

        using (CSocketPool <HelloWorld> spHw = new CSocketPool <HelloWorld>()) //true -- automatic reconnecting
        {
            spHw.DoSslServerAuthentication += (sender, cs) =>
            {
                int    errCode;
                IUcert cert = cs.UCert;
                Console.WriteLine(cert.SessionInfo);
                string res = cert.Verify(out errCode);
                //do ssl server certificate authentication here
                return(errCode == 0);  //true -- user id and password will be sent to server
            };

            //error handling ignored for code clarity
            bool       ok = spHw.StartSocketPool(cc, 1, 1);
            HelloWorld hw = spHw.Seek(); //or HelloWorld hw = spHw.Lock();

            CClientSocket ClientSocket = hw.AttachedClientSocket;
            ClientSocket.Push.OnSubscribe += (cs, messageSender, groups) =>
            {
                Console.WriteLine("Subscribe for " + ToString(groups));
                Console.WriteLine(ToString(messageSender));
                Console.WriteLine();
            };

            ClientSocket.Push.OnUnsubscribe += (cs, messageSender, groups) =>
            {
                Console.WriteLine("Unsubscribe from " + ToString(groups));
                Console.WriteLine(ToString(messageSender));
                Console.WriteLine();
            };

            ClientSocket.Push.OnPublish += (cs, messageSender, groups, msg) =>
            {
                Console.WriteLine("Publish to " + ToString(groups));
                Console.WriteLine(ToString(messageSender));
                Console.WriteLine("message = " + msg);
                Console.WriteLine();
            };

            ClientSocket.Push.OnSendUserMessage += (cs, messageSender, msg) =>
            {
                Console.WriteLine("SendUserMessage");
                Console.WriteLine(ToString(messageSender));
                Console.WriteLine("message = " + msg);
                Console.WriteLine();
            };

            //asynchronously process multiple requests with inline batching for best network efficiency
            ok = hw.SendRequest(hwConst.idSayHelloHelloWorld, "Jack", "Smith", (ar) =>
            {
                string ret;
                ar.Load(out ret);
                Console.WriteLine(ret);
            });

            uint[] chat_ids = { 1, 2 };
            ok = ClientSocket.Push.Publish("We are going to call the method Sleep", chat_ids);
            CAsyncServiceHandler.DAsyncResultHandler arh = null;
            ok = hw.SendRequest(hwConst.idSleepHelloWorld, (int)5000, arh);

            Console.WriteLine("Input a receiver for receiving my message ......");
            Console.WriteLine();
            ok = ClientSocket.Push.SendUserMessage("A message from " + cc.UserId, Console.ReadLine());
            ok = hw.WaitAll();

            Console.WriteLine("Press key ENTER to shutdown the demo application ......");
            Console.ReadLine();
        }
    }
Example #34
0
    static void Main(string[] args)
    {
        const int sessions_per_host = 2; const int cycles = 10000; string[] vHost = { "localhost", "192.168.2.172" };

        using (CSocketPool <CSqlite> sp = new CSocketPool <CSqlite>()) {
            sp.QueueName = "ar_sharp";                                                               //set a local message queue to backup requests for auto fault recovery
            CConnectionContext[,] ppCc = new CConnectionContext[1, vHost.Length *sessions_per_host]; //one thread enough
            for (int n = 0; n < vHost.Length; ++n)
            {
                for (int j = 0; j < sessions_per_host; ++j)
                {
                    ppCc[0, n *sessions_per_host + j] = new CConnectionContext(vHost[n], 20901, "AClientUserId", "Mypassword");
                }
            }
            bool ok = sp.StartSocketPool(ppCc);
            if (!ok)
            {
                Console.WriteLine("There is no connection and press any key to close the application ......");
                Console.Read(); return;
            }
            string sql = "SELECT max(amount), min(amount), avg(amount) FROM payment";
            Console.WriteLine("Input a filter for payment_id"); string filter = Console.ReadLine();
            if (filter.Length > 0)
            {
                sql += (" WHERE " + filter);
            }
            var v = sp.AsyncHandlers;
            foreach (var h in v)
            {
                ok = h.Open("sakila.db", (hsqlite, res, errMsg) => {
                    if (res != 0)
                    {
                        Console.WriteLine("Error code: {0}, error message: {1}", res, errMsg);
                    }
                });
            }
            int returned = 0; double dmax = 0.0, dmin = 0.0, davg = 0.0;
            SocketProAdapter.UDB.CDBVariantArray row = new SocketProAdapter.UDB.CDBVariantArray();
            CAsyncDBHandler.DExecuteResult       er  = (h, res, errMsg, affected, fail_ok, lastId) => {
                if (res != 0)
                {
                    Console.WriteLine("Error code: {0}, error message: {1}", res, errMsg);
                }
                else
                {
                    dmax += double.Parse(row[0].ToString());
                    dmin += double.Parse(row[1].ToString());
                    davg += double.Parse(row[2].ToString());
                }
                ++returned;
            };
            CAsyncDBHandler.DRows r = (h, vData) => {
                row.Clear(); row.AddRange(vData);
            };
            CSqlite sqlite = sp.SeekByQueue(); //get one handler for querying one record
            ok = sqlite.Execute(sql, er, r); ok = sqlite.WaitAll();
            Console.WriteLine("Result: max = {0}, min = {1}, avg = {2}", dmax, dmin, davg);
            returned = 0; dmax = 0.0; dmin = 0.0; davg = 0.0;
            Console.WriteLine("Going to get {0} queries for max, min and avg", cycles);
            for (int n = 0; n < cycles; ++n)
            {
                sqlite = sp.SeekByQueue(); ok = sqlite.Execute(sql, er, r);
            }
            foreach (var h in v)
            {
                ok = h.WaitAll();
            }
            Console.WriteLine("Returned = {0}, max = {1}, min = {2}, avg = {3}", returned, dmax, dmin, davg);
            Console.WriteLine("Press any key to close the application ......"); Console.Read();
        }
    }
Example #35
0
    static void Main(string[] args)
    {
        Console.WriteLine("Remote host: ");
        string             host = Console.ReadLine();
        CConnectionContext cc   = new CConnectionContext(host, 20901, "root", "Smash123");

        using (CSocketPool <CAsyncQueue> spAq = new CSocketPool <CAsyncQueue>()) {
            if (!spAq.StartSocketPool(cc, 1, 1))
            {
                Console.WriteLine("Failed in connecting to remote async queue server, and press any key to close the application ......");
                Console.Read();
                return;
            }

            CAsyncQueue sq = spAq.Seek();

            string s4 = "Sock";
            EnqueueToServer(sq, s4, 200000000);
            DequeueFromServer(sq);

            //Manually batching messages improves throughput for high volume of tiny messages
            EnqueueToServerBatch(sq, s4, 200000000, 8 * 1024);
            DequeueFromServer(sq);

            string s32 = "SocketPro is a world-leading pac";
            EnqueueToServer(sq, s32, 200000000);
            DequeueFromServer(sq);

            //Manually batching messages improves throughput for high volume of small messages
            EnqueueToServerBatch(sq, s32, 200000000, 8 * 1024);
            DequeueFromServer(sq);

            //a string having 200 chars
            string s = "SocketPro is a world-leading package of secured communication software components written with request batching, asynchrony and parallel computation in mind. It offers superior performance and scalabi";
            EnqueueToServer(sq, s, 50000000);
            DequeueFromServer(sq);

            //Batching messages improves throughput for high volume of middle size massages
            EnqueueToServerBatch(sq, s, 50000000, 8 * 1024);
            DequeueFromServer(sq);

            string s1024 = "";
            for (int n = 0; n < 6; ++n)
            {
                s1024 += s;
            }
            s1024 = s1024.Substring(0, 1024);
            EnqueueToServer(sq, s1024, 10000000);
            DequeueFromServer(sq);

            string s10240 = "";
            for (int n = 0; n < 10; ++n)
            {
                s10240 += s1024;
            }
            EnqueueToServer(sq, s10240, 1000000);
            DequeueFromServer(sq);

            Console.WriteLine("Press key ENTER to complete the application ......");
            Console.ReadLine();
        }
    }
Example #36
0
 static void Main(string[] args)
 {
     Console.WriteLine("Remote host: ");
     string host = Console.ReadLine();
     Console.WriteLine("Embedded (0) or remote (1) mysql/mariadb database?");
     bool remote = (Console.ReadKey().KeyChar != '0');
     Console.WriteLine("");
     Console.WriteLine("Table name: ");
     string tableName = Console.ReadLine();
     Console.WriteLine("sql filter: ");
     string filter = Console.ReadLine();
     CConnectionContext cc = new CConnectionContext(host, 20901, "umysql_client", "pwd_for_mysql");
     Console.WriteLine("Asynchronous execution (0) or synchronous execution (1) ?");
     bool sync = (Console.ReadKey().KeyChar != '0');
     using (CSocketPool<CMysql> spMysql = new CSocketPool<CMysql>())
     {
         if (!spMysql.StartSocketPool(cc, 1, 1))
         {
             Console.WriteLine("Failed in connecting to remote helloworld server");
             Console.WriteLine("Press any key to close the application ......");
             Console.Read();
             return;
         }
         Console.WriteLine("");
         Console.WriteLine("Computing ......");
         CMysql mysql = spMysql.Seek();
         CMysql.DResult dr = (handler, res, errMsg) =>
         {
             if (res != 0)
                 Console.WriteLine("res = {0}, errMsg: {1}", res, errMsg);
         };
         uint obtained = 0;
         bool ok = mysql.Open("", dr, remote ? CMysql.USE_REMOTE_MYSQL : 0);
         List<KeyValuePair<CDBColumnInfoArray, CDBVariantArray>> ra = new List<KeyValuePair<CDBColumnInfoArray, CDBVariantArray>>();
         CMysql.DExecuteResult er = (handler, res, errMsg, affected, fail_ok, id) =>
         {
             if (res != 0)
                 Console.WriteLine("fails = {0}, oks = {1}, res = {2}, errMsg: {3}", (uint)(fail_ok >> 32), (uint)fail_ok, res, errMsg);
             ra.Clear();
             ++obtained;
         };
         CMysql.DRows r = (handler, rowData) =>
         {
             //rowset data come here
             int last = ra.Count - 1;
             KeyValuePair<CDBColumnInfoArray, CDBVariantArray> item = ra[last];
             item.Value.AddRange(rowData);
         };
         CMysql.DRowsetHeader rh = (handler) =>
         {
             //rowset header comes here
             KeyValuePair<CDBColumnInfoArray, CDBVariantArray> item = new KeyValuePair<CDBColumnInfoArray, CDBVariantArray>(handler.ColumnInfo, new CDBVariantArray());
             ra.Add(item);
         };
         mysql.Execute("use sakila", er);
         ok = mysql.WaitAll();
         obtained = 0;
         string sql = "select * from " + tableName;
         if (filter.Length > 0) {
             sql += " where " + filter;
         }
         uint count = 10000;
         DateTime start = DateTime.Now;
         for (uint n = 0; n < count; ++n)
         {
             ok = mysql.Execute(sql, er, r, rh);
             if (sync && ok)
                 ok = mysql.WaitAll();
             if (!ok)
                 break;
         }
         if (!sync && ok)
             ok = mysql.WaitAll();
         double diff = (DateTime.Now - start).TotalMilliseconds;
         Console.WriteLine("Time required = {0} millseconds for {1} requests", diff, obtained);
         Console.WriteLine("Press any key to close the application ......");
         Console.ReadLine();
     }
 }
Example #37
0
    static void Main(string[] args)
    {
        //set a two-dimensional array of socket connection contexts
#if PocketPC
        CConnectionContext[,] ccs = new CConnectionContext[1, 1];
#else
        CConnectionContext[,] ccs = new CConnectionContext[System.Environment.ProcessorCount, 1];
#endif
        int threads            = ccs.GetLength(0);
        int sockets_per_thread = ccs.GetLength(1);
        for (int n = 0; n < threads; ++n)
        {
            for (int j = 0; j < sockets_per_thread; ++j)
            {
                string ipAddress;
                if (j == 0)
                {
                    ipAddress = "192.168.1.111";
                }
                else
                {
                    ipAddress = "localhost";
                }
                ccs[n, j] = new CConnectionContext(ipAddress, 20901, "adoclient", "password4AdoClient");
            }
        }

        using (CSocketPool <RAdo> spAdo = new CSocketPool <RAdo>(true)) //true -- automatic reconnecting
        {
            //start a pool of sockets
            if (!spAdo.StartSocketPool(ccs))
            {
                Console.WriteLine("No socket connection");
                return;
            }

            RAdo ado = spAdo.Seek();

            //process two requests one by one with synchronous communication style
            DataSet ds = ado.GetDataSet("select * from dimProduct", "select * from dimAccount");
            Console.WriteLine("Dataset returned with {0} tables", ds.Tables.Count);
            DataTable dt = ado.GetDataTable("select * from dimCustomer");
            Console.WriteLine("Datatable returned with columns = {0}, rows = {1}", dt.Columns.Count, dt.Rows.Count);

            //send two requests in parallel with asynchronous communication style
            RAdo ado1 = spAdo.Seek();
            bool ok   = ado1.SendRequest(radoConst.idGetDataTableRAdo, "select * from dimCustomer", (ar) =>
            {
                Console.WriteLine("Datatable returned with columns = {0}, rows = {1}", ado1.CurrentDataTable.Columns.Count, ado1.CurrentDataTable.Rows.Count);
            });

            RAdo ado2 = spAdo.Seek();
            ok = ado2.SendRequest(radoConst.idGetDataSetRAdo, "select * from dimProduct", "select * from dimAccount", (ar) =>
            {
                Console.WriteLine("Dataset returned with {0} tables", ado2.CurrentDataSet.Tables.Count);
            });
            //ok = ado1.WaitAll() && ado2.WaitAll();
            Console.WriteLine("Press key ENTER to shutdown the demo application ......");
            Console.ReadLine();
        }
    }
Example #38
0
    static void Main(string[] args)
    {
        Console.WriteLine("Remote host: ");
        string             host = Console.ReadLine();
        CConnectionContext cc   = new CConnectionContext(host, 20901, "sa", "Smash123");

#if DEBUG
        using (CSocketPool <CSqlServer> spSql = new CSocketPool <CSqlServer>(true, 3600 * 1000))
#else
        using (CSocketPool <CSqlServer> spSql = new CSocketPool <CSqlServer>())
#endif
        {
            if (!spSql.StartSocketPool(cc, 1))
            {
                Console.WriteLine("Failed in connecting to remote async sql server. Press any key to close the application ......");
                Console.Read();
                return;
            }
            CSqlServer sql = spSql.Seek();

            //track all DML (DELETE, INSERT and UPDATE) events
            sql.Socket.Push.OnPublish += (sender, messageSender, group, msg) => {
                if (group[0] == DB_CONSTS.STREAMING_SQL_CHAT_GROUP_ID)
                {
                    object[]       vMsg     = (object[])msg;
                    tagUpdateEvent ue       = (tagUpdateEvent)(int)(vMsg[0]);
                    string         server   = (string)vMsg[1];
                    string         user     = (string)vMsg[2];
                    string         database = (string)vMsg[3];
                    Console.WriteLine("DML event={0}, server={1}, database={2}, user={3}, table={4}", ue, server, database, user, vMsg[4].ToString());
                }
            };
            List <KeyValuePair <CDBColumnInfoArray, CDBVariantArray> > ra = new List <KeyValuePair <CDBColumnInfoArray, CDBVariantArray> >();

            //enable monitoring DML events through triggers by flag DB_CONSTS.ENABLE_TABLE_UPDATE_MESSAGES
            bool ok = sql.Open("", dr, DB_CONSTS.ENABLE_TABLE_UPDATE_MESSAGES);
            sql.WaitAll();

            CAsyncDBHandler.DRowsetHeader rh = (h) => {
                CDBColumnInfoArray v = h.ColumnInfo;
                if (v.Count > 0)
                {
                    Console.WriteLine("dbPath={0}, tablePath={1}", v[0].DBPath, v[0].TablePath);
                    ra.Add(new KeyValuePair <CDBColumnInfoArray, CDBVariantArray>(v, new CDBVariantArray()));
                }
            };
            CAsyncDBHandler.DRows rows = (h, vData) => {
                int endIndex = ra.Count - 1;
                ra[endIndex].Value.AddRange(vData);
            };

            //bring all table data which have USqlStream trigger (usqlserver.USqlStream.PublishDMLEvent) with an empty sql input string when opening with the flag DB_CONSTS.ENABLE_TABLE_UPDATE_MESSAGES
            ok = sql.Execute("", er, rows, rh);

            TestCreateTablesAndStoredProcedures(sql);
            ok = sql.Execute("select * from SpatialTable", er, rows, rh);
            ok = sql.Execute("delete from employee;delete from company;delete from test_rare1;delete from SpatialTable;INSERT INTO SpatialTable(mygeometry, mygeography)VALUES(geometry::STGeomFromText('LINESTRING(100 100,20 180,180 180)',0),geography::Point(47.6475,-122.1393,4326))", er);
            ok = sql.Execute("INSERT INTO test_rare1(mybool,mymoney,myxml,myvariant,mydateimeoffset)values(1,23.45,'<sometest />', N'美国总统川普下个星期四','2017-05-02 00:00:00.0000000 -04:00');INSERT INTO test_rare1(mybool,mymoney,myvariant)values(0,1223.45,'This is a test for ASCII string inside sql_variant');INSERT INTO test_rare1(myvariant)values(283.45)", er);
            TestPreparedStatements(sql);
            TestPreparedStatements_2(sql);
            InsertBLOBByPreparedStatement(sql);
            CDBVariantArray vPData = new CDBVariantArray();
            //first set
            vPData.Add(0); //retval
            vPData.Add(1);
            vPData.Add(21.2);
            vPData.Add(null);
            //2nd set
            vPData.Add(0); //retval
            vPData.Add(2);
            vPData.Add(11.42);
            vPData.Add(null);
            TestStoredProcedure(sql, ra, vPData);
            sql.WaitAll();

            vPData.Clear();
            //first set
            vPData.Add(-1);                   //return int
            vPData.Add(1);                    //@testid
            vPData.Add(DateTime.Now);
            vPData.Add("<test_sqlserver />"); //@myxml
            Guid guid = Guid.NewGuid();
            vPData.Add(guid);                 //@tuuid
            vPData.Add(true);                 //@myvar

            //2nd set
            vPData.Add(-2);                         //return int
            vPData.Add(4);                          //@testid
            vPData.Add(DateTime.Now);
            vPData.Add("<test_sqlserver_again />"); //@myxml
            Guid guid2 = Guid.NewGuid();
            vPData.Add(guid2);                      //@tuuid
            vPData.Add(false);                      //@myvar
            TestStoredProcedure_2(sql, ra, vPData);
            sql.WaitAll();
            TestBatch(sql, ra);

            CDBVariantArray vParam = new CDBVariantArray();
            //first set
            vParam.Add(1);    //ID

            vParam.Add(0);    //retval
            //last three data will be updated with outputs
            vParam.Add(1);    //input @p_company_id, output retval
            vParam.Add(21.2); //input @p_sum_salary, output @p_sum_salary
            vParam.Add(null); //output @p_last_dt

            vParam.Add(2);    //EMPLOYEEID

            //2nd set
            vParam.Add(2);     //ID

            vParam.Add(0);     //retval
            //last three data will be updated with outputs
            vParam.Add(2);     //input @p_company_id, output retval
            vParam.Add(11.42); //input @p_sum_salary, output @p_sum_salary
            vParam.Add(null);  //output @p_last_dt

            vParam.Add(3);     //EMPLOYEEID
            TestBatch2(sql, ra, vParam);
            sql.WaitAll();
            int index = 0;
            Console.WriteLine("+++++ Start rowsets +++");
            foreach (KeyValuePair <CDBColumnInfoArray, CDBVariantArray> it in ra)
            {
                Console.Write("Statement index = {0}", index);
                if (it.Key.Count > 0)
                {
                    Console.WriteLine(", rowset with columns = {0}, records = {1}.", it.Key.Count, it.Value.Count / it.Key.Count);
                }
                else
                {
                    Console.WriteLine(", no rowset received.");
                }
                ++index;
            }
            Console.WriteLine("+++++ End rowsets +++");
            Console.WriteLine();
            Console.WriteLine("Press any key to close the application ......");
            Console.Read();
            Console.WriteLine("Press any key to close the application ......");
            Console.Read();
        }
    }
Example #39
0
    static void Main(string[] args)
    {
        Console.WriteLine("Remote host: ");
        string             host = Console.ReadLine();
        CConnectionContext cc   = new CConnectionContext(host, 20903, "sa", "Smash123"); //20901 for plugindev

        using (CSocketPool <COdbc> spOdbc = new CSocketPool <COdbc>(true, 600000))
        {
            if (!spOdbc.StartSocketPool(cc, 1))
            {
                Console.WriteLine("Failed in connecting to remote async odbc server");
                Console.WriteLine("Press any key to close the application ......");
                Console.Read();
                return;
            }
            COdbc odbc = spOdbc.Seek();
            bool  ok   = odbc.Open("", dr); //use default database
            List <KeyValuePair <CDBColumnInfoArray, CDBVariantArray> > ra = new List <KeyValuePair <CDBColumnInfoArray, CDBVariantArray> >();

            COdbc.DRows r = (handler, rowData) =>
            {
                //rowset data come here
                int last = ra.Count - 1;
                KeyValuePair <CDBColumnInfoArray, CDBVariantArray> item = ra[last];
                item.Value.AddRange(rowData);
            };

            COdbc.DRowsetHeader rh = (handler) =>
            {
                //rowset header comes here
                KeyValuePair <CDBColumnInfoArray, CDBVariantArray> item = new KeyValuePair <CDBColumnInfoArray, CDBVariantArray>(handler.ColumnInfo, new CDBVariantArray());
                ra.Add(item);
            };
            TestCreateTables(odbc);
            ok = odbc.Execute("delete from employee;delete from company;delete from test_rare1;delete from SpatialTable;INSERT INTO SpatialTable(mygeometry, mygeography)VALUES(geometry::STGeomFromText('LINESTRING(100 100,20 180,180 180)',0),geography::Point(47.6475,-122.1393,4326))", er);
            ok = odbc.Execute("INSERT INTO test_rare1(mybool,mymoney,myxml,myvariant,mydateimeoffset)values(1,23.45,'<sometest />', N'美国总统川普下个星期四','2017-05-02 00:00:00.0000000 -04:00');INSERT INTO test_rare1(mybool,mymoney,myvariant)values(0,1223.45,'This is a test for ASCII string inside sql_variant');INSERT INTO test_rare1(myvariant)values(283.45)", er);
            TestPreparedStatements(odbc);
            TestPreparedStatements_2(odbc);
            InsertBLOBByPreparedStatement(odbc);
            ok = odbc.Execute("SELECT * from company;select * from employee;select CONVERT(datetime,SYSDATETIME());select * from test_rare1;select * from SpatialTable", er, r, rh);
            ok = odbc.Tables("sqltestdb", "%", "%", "TABLE", er, r, rh);
            CDBVariantArray vPData = TestStoredProcedure(odbc, ra);
            ok = odbc.WaitAll();
            Console.WriteLine();
            Console.WriteLine("There are {0} output data returned", odbc.Outputs * 2);
            CDBVariantArray vPData2 = TestStoredProcedure_2(odbc, ra);
            ok = odbc.WaitAll();
            Console.WriteLine();
            Console.WriteLine("There are {0} output data returned", odbc.Outputs * 2);
            CDBVariantArray vPData3 = TestBatch(odbc, ra);
            ok = odbc.WaitAll();
            Console.WriteLine();
            Console.WriteLine("There are {0} output data returned", odbc.Outputs * 2);

            ok = odbc.Tables("AdventureWorks", "%", "%", "TABLE", er, r, rh);
            ok = odbc.WaitAll();
            ok = odbc.Execute("use AdventureWorks", er);
            KeyValuePair <CDBColumnInfoArray, CDBVariantArray> tables = ra[ra.Count - 1];
            int columns    = tables.Key.Count;
            int num_tables = tables.Value.Count / columns;
            for (int n = 0; n < num_tables; ++n)
            {
                string sql = "select * from " + tables.Value[columns * n + 1].ToString() + "." + tables.Value[columns * n + 2].ToString();
                ok = odbc.Execute(sql, er, r, rh);
            }
            ok = odbc.WaitAll();

            ok         = odbc.Tables("AdventureWorksDW", "%", "%", "TABLE", er, r, rh);
            ok         = odbc.WaitAll();
            ok         = odbc.Execute("use AdventureWorksDW", er);
            tables     = ra[ra.Count - 1];
            columns    = tables.Key.Count;
            num_tables = tables.Value.Count / columns;
            for (int n = 0; n < num_tables; ++n)
            {
                string sql = "select * from " + tables.Value[columns * n + 1].ToString() + "." + tables.Value[columns * n + 2].ToString();
                ok = odbc.Execute(sql, er, r, rh);
            }
            ok = odbc.WaitAll();

            int index = 0;
            Console.WriteLine();
            Console.WriteLine("+++++ Start rowsets +++");
            foreach (KeyValuePair <CDBColumnInfoArray, CDBVariantArray> it in ra)
            {
                Console.Write("Statement index = {0}", index);
                if (it.Key.Count > 0)
                {
                    Console.WriteLine(", rowset with columns = {0}, records = {1}.", it.Key.Count, it.Value.Count / it.Key.Count);
                }
                else
                {
                    Console.WriteLine(", no rowset received.");
                }
                ++index;
            }
            Console.WriteLine("+++++ End rowsets +++");
            Console.WriteLine();
            Console.WriteLine("Press any key to close the application ......");
            Console.Read();
        }
    }
Example #40
0
    static void Main(string[] args)
    {
        Console.WriteLine("Remote host: ");
        string host = Console.ReadLine();
        CConnectionContext cc = new CConnectionContext(host, 20901, "usqlite_client", "pwd_for_usqlite");
        using (CSocketPool<CSqlite> spSqlite = new CSocketPool<CSqlite>())
        {
            if (!spSqlite.StartSocketPool(cc, 1, 1))
            {
                Console.WriteLine("Failed in connecting to remote async sqlite server");
                Console.WriteLine("Press any key to close the application ......");
                Console.Read();
                return;
            }
            CSqlite sqlite = spSqlite.Seek();
            bool ok = sqlite.Open("", (handler, res, errMsg) =>
            {
                Console.WriteLine("res = {0}, errMsg: {1}", res, errMsg);
            });
            TestCreateTables(sqlite);
            List<KeyValuePair<CDBColumnInfoArray, CDBVariantArray>> lstRowset = new List<KeyValuePair<CDBColumnInfoArray, CDBVariantArray>>();
            ok = sqlite.BeginTrans();
            TestPreparedStatements(sqlite, lstRowset);
            InsertBLOBByPreparedStatement(sqlite, lstRowset);
            ok = sqlite.EndTrans();
            sqlite.WaitAll();

            int index = 0;
            Console.WriteLine();
            Console.WriteLine("+++++ Start rowsets +++");
            foreach (KeyValuePair<CDBColumnInfoArray, CDBVariantArray> it in lstRowset)
            {
                Console.Write("Statement index = {0}", index);
                if (it.Key.Count > 0)
                    Console.WriteLine(", rowset with columns = {0}, records = {1}.", it.Key.Count, it.Value.Count / it.Key.Count);
                else
                    Console.WriteLine(", no rowset received.");
                ++index;
            }
            Console.WriteLine("+++++ End rowsets +++");
            Console.WriteLine();
            Console.WriteLine("Press any key to close the application ......");
            Console.Read();
        }
    }
Example #41
0
    static void Main(string[] args)
    {
        Console.WriteLine("Input your user id ......");
        CConnectionContext cc = new CConnectionContext("localhost", 20901, Console.ReadLine(), "MyPassword", tagEncryptionMethod.TLSv1);

        //CA file is located at the directory ..\SocketProRoot\bin
        CClientSocket.SSL.SetVerifyLocation("ca.cert.pem");

        //for windows platforms, you can also use windows system store instead
        //CClientSocket.SSL.SetVerifyLocation("my"); //or "root", "my@currentuser", "root@localmachine"

        using (CSocketPool<HelloWorld> spHw = new CSocketPool<HelloWorld>()) //true -- automatic reconnecting
        {
            spHw.DoSslServerAuthentication += (sender, cs) =>
            {
                int errCode;
                IUcert cert = cs.UCert;
                Console.WriteLine(cert.SessionInfo);
                string res = cert.Verify(out errCode);
                //do ssl server certificate authentication here
                return (errCode == 0); //true -- user id and password will be sent to server
            };

            //error handling ignored for code clarity
            bool ok = spHw.StartSocketPool(cc, 1, 1);
            HelloWorld hw = spHw.Seek(); //or HelloWorld hw = spHw.Lock();

            CClientSocket ClientSocket = hw.AttachedClientSocket;
            ClientSocket.Push.OnSubscribe += (cs, messageSender, groups) =>
            {
                Console.WriteLine("Subscribe for " + ToString(groups));
                Console.WriteLine(ToString(messageSender));
                Console.WriteLine();
            };

            ClientSocket.Push.OnUnsubscribe += (cs, messageSender, groups) =>
            {
                Console.WriteLine("Unsubscribe from " + ToString(groups));
                Console.WriteLine(ToString(messageSender));
                Console.WriteLine();
            };

            ClientSocket.Push.OnPublish += (cs, messageSender, groups, msg) =>
            {
                Console.WriteLine("Publish to " + ToString(groups));
                Console.WriteLine(ToString(messageSender));
                Console.WriteLine("message = " + msg);
                Console.WriteLine();
            };

            ClientSocket.Push.OnSendUserMessage += (cs, messageSender, msg) =>
            {
                Console.WriteLine("SendUserMessage");
                Console.WriteLine(ToString(messageSender));
                Console.WriteLine("message = " + msg);
                Console.WriteLine();
            };

            //asynchronously process multiple requests with inline batching for best network efficiency
            ok = hw.SendRequest(hwConst.idSayHelloHelloWorld, "Jack", "Smith", (ar) =>
            {
                string ret;
                ar.Load(out ret);
                Console.WriteLine(ret);
            });

            uint[] chat_ids = { 1, 2 };
            ok = ClientSocket.Push.Publish("We are going to call the method Sleep", chat_ids);
            CAsyncServiceHandler.DAsyncResultHandler arh = null;
            ok = hw.SendRequest(hwConst.idSleepHelloWorld, (int)5000, arh);

            Console.WriteLine("Input a receiver for receiving my message ......");
            Console.WriteLine();
            ok = ClientSocket.Push.SendUserMessage("A message from " + cc.UserId, Console.ReadLine());
            ok = hw.WaitAll();

            Console.WriteLine("Press key ENTER to shutdown the demo application ......");
            Console.ReadLine();
        }
    }