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)
    {
        CClientSocket.QueueConfigure.MessageQueuePassword = "******";
        SetWorkDirectory();
        ReplicationSetting rs = new ReplicationSetting();

        using (CReplication <HelloWorld> hw = new CReplication <HelloWorld>(rs))
        {
            Dictionary <string, CConnectionContext> ConnQueue = new Dictionary <string, CConnectionContext>();
            CConnectionContext cc = new CConnectionContext("127.0.0.1", 20901, "replication", "p4localhost");
#if PocketPC
#else
            ConnQueue["Tolocal"] = cc;
#endif
            cc = new CConnectionContext("192.168.1.109", 20901, "remote_rep", "PassOne");
            ConnQueue["ToLinux"] = cc;
            bool ok = hw.Start(ConnQueue, "hw_root_queue_name");
            hw.StartJob();
            ok = hw.Send(hwConst.idSayHelloHelloWorld, "David", "Young");
            ok = hw.Send(hwConst.idEchoHelloWorld, CMyStruct.MakeOne());
            hw.EndJob();
            Console.WriteLine("Press key ENTER to shut down the application ......");
            Console.ReadLine();
        }
    }
Example #3
0
 private void CheckConnQueueName(Dictionary <string, CConnectionContext> mapQueueConn)
 {
     m_mapQueueConn.Clear();
     if (mapQueueConn == null || mapQueueConn.Count == 0)
     {
         throw new ArgumentException("One middle server required at least");
     }
     foreach (string key in mapQueueConn.Keys)
     {
         CConnectionContext cc = mapQueueConn[key];
         if (cc == null)
         {
             throw new InvalidOperationException("An invalid host found");
         }
         string v = key;
         if (v == null)
         {
             throw new InvalidOperationException("A non-empty string for persistent queue name required for each of hosts");
         }
         v = v.Trim();
         v = v.Trim(DIR_SEP);
         if (v.Length == 0)
         {
             throw new InvalidOperationException("A non-empty string for persistent queue name required for each of hosts");
         }
         if (DoesQueueExist(v))
         {
             throw new InvalidOperationException("Queue name duplicated -- " + v);
         }
         m_mapQueueConn[v] = cc;
     }
 }
Example #4
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 #5
0
 internal bool IsSame(CConnectionContext cc)
 {
     if (cc == null)
     {
         return(false);
     }
     return(cc.Host == Host && cc.Port == Port);
 }
Example #6
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 #7
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 #8
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 #9
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 #10
0
        private static bool StartPool(MyCase mc)
        {
            uint threads, sessions_per_host; bool ok = false;

            System.Collections.Generic.List <CConnectionContext> Hosts; CSocketPool <CSql> pool = null;
            switch (mc)
            {
            case MyCase.mcMasterWithClientQueue:
                Master            = new SPA.CMyMaster(Config.Master.DefaultDB, false, Config.Master.RecvTimeout);
                Master.QueueName  = "qmaster"; pool = Master; threads = Config.Master.Threads;
                sessions_per_host = Config.Master.Sessions_Per_Host; Hosts = Config.Master.Hosts;
                break;

            case MyCase.mcSlaveWithClientQueue:
                Slave             = new SPA.CMyMaster.CSlavePool(Config.Slave.DefaultDB, Config.Slave.RecvTimeout);
                Slave.QueueName   = "qslave"; pool = Slave; threads = Config.Slave.Threads;
                sessions_per_host = Config.Slave.Sessions_Per_Host; Hosts = Config.Slave.Hosts;
                break;

            case MyCase.mcMasterWithoutClientQueue:
                MasterNotQueued   = new SPA.CMyMaster.CSlavePool(Config.Master.DefaultDB, Config.Master.RecvTimeout);
                pool              = MasterNotQueued; threads = Config.Master.Threads;
                sessions_per_host = Config.Master.Sessions_Per_Host; Hosts = Config.Master.Hosts;
                break;

            default:
                throw new System.NotImplementedException("Not implemented");
            }
            pool.DoSslServerAuthentication += (sender, cs) => {
                int errCode; string res = cs.UCert.Verify(out errCode);
                return(errCode == 0);  //true -- user id and password will be sent to server
            };
            uint sockets_per_thread = sessions_per_host * (uint)Hosts.Count;

            if (sockets_per_thread > 0 && threads > 0)
            {
                CConnectionContext[,] ppCC = new CConnectionContext[threads, sockets_per_thread];
                for (uint i = 0; i < threads; ++i)
                {
                    for (uint j = 0; j < (uint)Hosts.Count; ++j)
                    {
                        for (uint n = 0; n < sessions_per_host; ++n)
                        {
                            ppCC[i, j *sessions_per_host + n] = Hosts[(int)j];
                        }
                    }
                }
                ok = pool.StartSocketPool(ppCC);
                //not automatcally merge requests saved in local/client message queue files in case there is one host only
                if (Hosts.Count < 2)
                {
                    pool.QueueAutoMerge = false;
                }
            }
            return(ok);
        }
Example #11
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 #12
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 #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 btnConnect_Click(object sender, EventArgs e)
 {
     if (m_SocketPool.ConnectedSockets > 0)
         return;
     m_SocketPool.ShutdownPool();
     CConnectionContext cc = new CConnectionContext(txtHost.Text, uint.Parse(txtPort.Text), "SocketPro", "PassOne");
     if (m_SocketPool.StartSocketPool(cc, 1, 1))
     {
         btnEcho.Enabled = true;
         btnSQL.Enabled = true;
     }
 }
Example #15
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 #16
0
        /// <summary>
        /// Start a socket pool for replication
        /// </summary>
        /// <param name="mapQueueConn">A dictionary for message queue name and connecting context. a unique name must be specified for each of connecting contexts</param>
        /// <param name="rootQueueName">A string for root replication queue name. It is ignored if it is not replicable</param>
        /// <param name="ta">COM thread apartment; and it defaults to taNone. It is ignored on non-window platforms</param>
        /// <returns>True if there is at least one connection established; and false if there is no connection</returns>
        public virtual bool Start(Dictionary <string, CConnectionContext> mapQueueConn, string rootQueueName, tagThreadApartment ta)
        {
            CheckConnQueueName(mapQueueConn);
            uint n      = 0;
            bool secure = false;
            int  all    = m_mapQueueConn.Count;

            if (all > 1)
            {
                ++all;
            }
            if (rootQueueName == null)
            {
                rootQueueName = "";
            }
            rootQueueName = rootQueueName.Trim();
            rootQueueName = rootQueueName.Trim(DIR_SEP);
            if (rootQueueName.Length == 0)
            {
                string appName = System.AppDomain.CurrentDomain.FriendlyName;
                int    dot     = appName.LastIndexOf('.');
                if (dot == -1)
                {
                    rootQueueName = appName;
                }
                else
                {
                    rootQueueName = appName.Substring(0, dot);
                }
            }
            string[] vDbFullName = new string[all];
            CConnectionContext[,] mcc = new CConnectionContext[1, all];
            foreach (string key in m_mapQueueConn.Keys)
            {
                mcc[0, n] = m_mapQueueConn[key];
                if (!secure && mcc[0, n].EncrytionMethod == tagEncryptionMethod.TLSv1)
                {
                    secure = true;
                }
                vDbFullName[n] = m_rs.QueueDir + key;
                ++n;
            }
            if (all > 1)
            {
                CConnectionContext last = new CConnectionContext("127.0.0.1", ushort.MaxValue, "UReplication", "");
                last.EncrytionMethod = secure ? tagEncryptionMethod.TLSv1 : tagEncryptionMethod.NoEncryption;
                mcc[0, n]            = last;
                vDbFullName[n]       = m_rs.QueueDir + rootQueueName;
            }
            EndProcess(vDbFullName, secure, mcc, ta);
            return(m_pool.ConnectedSockets > 0);
        }
Example #17
0
        private bool IsRepeated(CConnectionContext cc)
        {
            int count = 0;

            foreach (var c in m_Hosts.Values)
            {
                if (c != cc)
                {
                    count += cc.IsSame(c) ? 1 : 0;
                }
            }
            return(count > 0);
        }
Example #18
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 #19
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 #20
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 #21
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (m_SocketPool.ConnectedSockets > 0)
            {
                return;
            }
            m_SocketPool.ShutdownPool();
            CConnectionContext cc = new CConnectionContext(txtHost.Text, uint.Parse(txtPort.Text), "SocketPro", "PassOne");

            if (m_SocketPool.StartSocketPool(cc, 1))
            {
                btnEcho.Enabled = true;
                btnSQL.Enabled  = true;
            }
        }
Example #22
0
 /// <summary>
 ///  Start a pool of sockets with one connection context
 /// </summary>
 /// <param name="cc">A connection context structure</param>
 /// <param name="socketsPerThread">The number of socket connections per thread</param>
 /// <param name="threads">The number of threads in a pool which defaults to 1</param>
 /// <param name="avg">A boolean value for building internal socket pool, which defaults to true.</param>
 /// <param name="ta">A value for COM thread apartment if there is COM object involved. It is ignored on non-window platforms, and default to tagThreadApartment.taNone</param>
 /// <returns>False if there is no connection established; and true as long as there is one connection started</returns>
 public bool StartSocketPool(CConnectionContext cc, uint socketsPerThread, uint threads, bool avg, tagThreadApartment ta)
 {
     if (threads == 0)
     {
         threads = 1;
     }
     CConnectionContext[,] mcc = new CConnectionContext[threads, socketsPerThread];
     for (uint m = 0; m < socketsPerThread; ++m)
     {
         for (uint n = 0; n < threads; ++n)
         {
             mcc[n, m] = cc;
         }
     }
     return(StartSocketPool(mcc, avg, ta));
 }
Example #23
0
    public static void StartMySQLPools()
    {
        CConfig config = CConfig.GetConfig();

        CYourServer.Master = new CMaster(config.m_master_default_db, true);

        //These case-sensitivities depends on your DB running platform and sensitivity settings.
        //All of them are false or case-insensitive by default
        Master.Cache.FieldNameCaseSensitive = false;
        Master.Cache.TableNameCaseSensitive = false;
        Master.Cache.DBNameCaseSensitive    = false;

        //start master pool for cache and update accessing
        bool ok = CYourServer.Master.StartSocketPool(config.m_ccMaster, config.m_nMasterSessions, 1); //one thread enough

        if (config.m_master_queue_name != null && config.m_master_queue_name.Length > 0)
        {
            CYourServer.Master.QueueName = config.m_master_queue_name;
        }

        //compute threads and sockets_per_thread
        uint threads            = config.m_slave_threads;
        uint sockets_per_thread = (uint)config.m_vccSlave.Count * config.m_sessions_per_host;

        CYourServer.Slave = new CMaster.CSlavePool(config.m_slave_default_db);
        if (config.m_slave_queue_name != null && config.m_slave_queue_name.Length > 0)
        {
            CYourServer.Slave.QueueName = config.m_slave_queue_name;
        }

        CConnectionContext[,] ppCC = new CConnectionContext[threads, sockets_per_thread];
        for (uint i = 0; i < threads; ++i)
        {
            for (uint j = 0; j < (uint)config.m_vccSlave.Count; ++j)
            {
                for (uint n = 0; n < config.m_sessions_per_host; ++n)
                {
                    ppCC[i, j *config.m_sessions_per_host + n] = config.m_vccSlave[(int)j];
                }
            }
        }
        //start slave pool for query accessing
        ok = CYourServer.Slave.StartSocketPool(ppCC);

        //wait until all data of cached tables are brought from backend database server to this middle server application cache
        ok = CYourServer.Master.AsyncHandlers[0].WaitAll();
    }
Example #24
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 #25
0
        private static bool StartPool(bool master)
        {
            uint threads, sessions_per_host; bool ok = false;
            List <CConnectionContext> Hosts; CSocketPool <CSql> pool;

            if (master)
            {
                Master            = new SPA.CMyMaster(Config.Master.DefaultDB, false, Config.Master.RecvTimeout);
                Master.QueueName  = "qmaster"; pool = Master; threads = Config.Master.Threads;
                sessions_per_host = Config.Master.Sessions_Per_Host; Hosts = Config.Master.Hosts;
            }
            else
            {
                Slave             = new SPA.CMySlave(Config.Slave.DefaultDB, Config.Slave.RecvTimeout);
                Slave.QueueName   = "qslave"; pool = Slave; threads = Config.Slave.Threads;
                sessions_per_host = Config.Slave.Sessions_Per_Host; Hosts = Config.Slave.Hosts;
            }
            pool.DoSslServerAuthentication += (sender, cs) => {
                int errCode; string res = cs.UCert.Verify(out errCode);
                return(errCode == 0);  //true -- user id and password will be sent to server
            };
            uint sockets_per_thread = sessions_per_host * (uint)Hosts.Count;

            if (sockets_per_thread > 0 && threads > 0)
            {
                CConnectionContext[,] ppCC = new CConnectionContext[threads, sockets_per_thread];
                for (uint i = 0; i < threads; ++i)
                {
                    for (uint j = 0; j < (uint)Hosts.Count; ++j)
                    {
                        for (uint n = 0; n < sessions_per_host; ++n)
                        {
                            ppCC[i, j *sessions_per_host + n] = Hosts[(int)j];
                        }
                    }
                }
                ok = pool.StartSocketPool(ppCC);
                //no automatcally merging requests saved in local/client message queue files in case master or one host
                if (Hosts.Count < 2 || master)
                {
                    pool.QueueAutoMerge = false;
                }
            }
            return(ok);
        }
Example #26
0
            /// <summary>
            ///  Start a pool of sockets with one connection context
            /// </summary>
            /// <param name="cc">A connection context structure</param>
            /// <param name="socketsPerThread">The number of socket connections per thread</param>
            /// <param name="threads">The number of threads in a pool which defaults to the number of CPU cores</param>
            /// <param name="avg">A boolean value for building internal socket pool, which defaults to true.</param>
            /// <param name="ta">A value for COM thread apartment if there is COM object involved. It is ignored on non-window platforms, and default to tagThreadApartment.taNone</param>
            /// <returns>False if there is no connection established; and true as long as there is one connection started</returns>
            public bool StartSocketPool(CConnectionContext cc, uint socketsPerThread, uint threads, bool avg, tagThreadApartment ta)
            {
                if (threads == 0)
#if WINCE
                { threads = 1; }
#else
                { threads = (uint)Environment.ProcessorCount; }
#endif
                CConnectionContext[,] mcc = new CConnectionContext[threads, socketsPerThread];
                for (uint m = 0; m < socketsPerThread; ++m)
                {
                    for (uint n = 0; n < threads; ++n)
                    {
                        mcc[n, m] = cc;
                    }
                }
                return(StartSocketPool(mcc, avg, ta));
            }
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>())
        {
            //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 #28
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 #29
0
    static sqlpush()
    {
        CClientSocket.QueueConfigure.MessageQueuePassword = "******";
        CClientSocket.QueueConfigure.WorkDirectory = "c:\\cyetest\\sqllog";
        ReplicationSetting rs = new ReplicationSetting();
        Dictionary<string, CConnectionContext> QNameConn = new Dictionary<string, CConnectionContext>();

        CConnectionContext cc = new CConnectionContext("127.0.0.1", 20901, "SocketPro", "PassOne");

        string []parts = Utilities.GetObjectParts(Utilities.GetDbFullName());

        string qName = parts[2] + "_ToLocal";
        QNameConn[qName] = cc;

        cc = new CConnectionContext("10.3.10.53", 20901, "SocketPro", "PassOne");
        qName = parts[2] + "_ToLinux";
        QNameConn[qName] = cc;

        m_hm = new CSqlReplication<MyAdo>(rs, QNameConn);
    }
Example #30
0
        protected override void OnSocketPoolEvent(tagSocketPoolEvent spe, CSql handler)
        {
            switch (spe)
            {
            case tagSocketPoolEvent.speConnected: {
                CConnectionContext cc = handler.AttachedClientSocket.ConnectionContext;
                if (cc.Zip && cc.AnyData != null && cc.AnyData.ToString() == "fast")
                {
                    //turn on fast compression for both client and server sides
                    handler.AttachedClientSocket.ZipLevel = SocketProAdapter.tagZipLevel.zlBestSpeed;
                    handler.AttachedClientSocket.SetZipLevelAtSvr(SocketProAdapter.tagZipLevel.zlBestSpeed);
                }
            }
            break;

            default:
                break;
            }
            base.OnSocketPoolEvent(spe, handler);
        }
Example #31
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 #32
0
    static sqlpush()
    {
        CClientSocket.QueueConfigure.MessageQueuePassword = "******";
        CClientSocket.QueueConfigure.WorkDirectory        = "c:\\cyetest\\sqllog";
        ReplicationSetting rs = new ReplicationSetting();
        Dictionary <string, CConnectionContext> QNameConn = new Dictionary <string, CConnectionContext>();

        CConnectionContext cc = new CConnectionContext("127.0.0.1", 20901, "SocketPro", "PassOne");

        string [] parts = Utilities.GetObjectParts(Utilities.GetDbFullName());

        string qName = parts[2] + "_ToLocal";

        QNameConn[qName] = cc;

        cc               = new CConnectionContext("10.3.10.53", 20901, "SocketPro", "PassOne");
        qName            = parts[2] + "_ToLinux";
        QNameConn[qName] = cc;

        m_hm = new CSqlReplication <MyAdo>(rs, QNameConn);
    }
Example #33
0
            void CopyCC(CConnectionContext[,] cc)
            {
                int threads          = cc.GetLength(0);
                int socketsPerThread = cc.GetLength(1);

                if (socketsPerThread * threads == 0)
                {
                    throw new InvalidOperationException("Must set connection context argument properly");
                }

                lock (m_cs)
                {
                    m_mcc = new CConnectionContext[threads, socketsPerThread];
                    for (uint m = 0; m < socketsPerThread; ++m)
                    {
                        for (uint n = 0; n < threads; ++n)
                        {
                            if (cc[n, m] == null)
                            {
                                throw new ArgumentException("Must set connection context argument properly");
                            }
                            else
                            {
                                CConnectionContext c   = new CConnectionContext();
                                CConnectionContext src = cc[n, m];
                                c.Host            = src.Host;
                                c.Password        = src.GetPassword();
                                c.Port            = src.Port;
                                c.EncrytionMethod = src.EncrytionMethod;
                                c.UserId          = src.UserId;
                                c.V6        = src.V6;
                                c.Zip       = src.Zip;
                                c.AnyData   = src.AnyData;
                                m_mcc[n, m] = c;
                            }
                        }
                    }
                }
            }
Example #34
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 #35
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 #36
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 #37
0
 static void Main(string[] args)
 {
     CClientSocket.QueueConfigure.MessageQueuePassword = "******";
     SetWorkDirectory();
     ReplicationSetting rs = new ReplicationSetting();
     using (CReplication<HelloWorld> hw = new CReplication<HelloWorld>(rs))
     {
         Dictionary<string, CConnectionContext> ConnQueue = new Dictionary<string, CConnectionContext>();
         CConnectionContext cc = new CConnectionContext("127.0.0.1", 20901, "replication", "p4localhost");
     #if PocketPC
     #else
         ConnQueue["Tolocal"] = cc;
     #endif
         cc = new CConnectionContext("192.168.1.109", 20901, "remote_rep", "PassOne");
         ConnQueue["ToLinux"] = cc;
         bool ok = hw.Start(ConnQueue, "hw_root_queue_name");
         hw.StartJob();
         ok = hw.Send(hwConst.idSayHelloHelloWorld, "David", "Young");
         ok = hw.Send(hwConst.idEchoHelloWorld, CMyStruct.MakeOne());
         hw.EndJob();
         Console.WriteLine("Press key ENTER to shut down the application ......");
         Console.ReadLine();
     }
 }
Example #38
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 #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();
        }
    }
Example #42
0
 private void async_Load(object sender, EventArgs e)
 {
     CConnectionContext cc = new CConnectionContext("127.0.0.1", 20901, "MyUserId", "MyPassword");
     btnTest.Enabled = m_spHw.StartSocketPool(cc, 1, 1);
 }
Example #43
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 #44
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 #45
0
 /// <summary>
 ///  Start a pool of sockets with one connection context
 /// </summary>
 /// <param name="cc">A connection context structure</param>
 /// <param name="socketsPerThread">The number of socket connections per thread</param>
 /// <param name="threads">The number of threads in a pool which defaults to the number of CPU cores</param>
 /// <param name="avg">A boolean value for building internal socket pool, which defaults to true.</param>
 /// <returns>False if there is no connection established; and true as long as there is one connection started</returns>
 public bool StartSocketPool(CConnectionContext cc, uint socketsPerThread, uint threads, bool avg)
 {
     return(StartSocketPool(cc, socketsPerThread, threads, avg, tagThreadApartment.taNone));
 }