Esempio n. 1
0
        public Action defaultServiceAction()
        {
            Action serviceAction = () =>
            {
                if (Util.verbose)
                {
                    Console.Write("\n  starting Receiver.defaultServiceAction");
                }
                Message msg = null;
                while (true)
                {
                    msg = rcvr.getMessage();   // note use of non-service method to deQ messages
                    //
                    Console.Write("\n  Received message:");
                    Console.Write("\n  sender is {0}", msg.fromUrl);
                    if (msg.messageID > 0)
                    {
                        HiResTimer timer = latencyTimers.ElementAt(msg.messageID);
                        timer.Stop();
                        latencyValues[msg.messageID] = timer.ElapsedMicroseconds;
                        Console.Write("\n  Request ID: {0}\n", msg.messageID);
                        Console.Write("\n  content is {0}\n", msg.content);
                        Console.Write("\n  Latency is {0} microseconds\n", latencyValues.ElementAt(msg.messageID));
                    }
                    rcvCount++;
                    //serverProcessMessage(msg);
                    if (msg.content == "closeReceiver")
                    {
                        break;
                    }
                }
            };

            return(serviceAction);
        }
    static void Main()
    {
        HiResTimer timer = new HiResTimer();

        // This example shows how to use the high-resolution counter to
        // time an operation.

        // Get counter value before the operation starts.
        Int64 counterAtStart = timer.Value;

        // Perform an operation that takes a measureable amount of time.
        for (int count = 0; count < 10000; count++)
        {
            count++;
            count--;
        }

        // Get counter value when the operation ends.
        Int64 counterAtEnd = timer.Value;

        // Get time elapsed in tenths of a millisecond.
        Int64 timeElapsedInTicks = counterAtEnd - counterAtStart;
        Int64 timeElapseInTenthsOfMilliseconds =
            (timeElapsedInTicks * 10000) / timer.Frequency;

        MessageBox.Show("Time Spent in operation (tenths of ms) "
                        + timeElapseInTenthsOfMilliseconds +
                        "\nCounter Value At Start: " + counterAtStart +
                        "\nCounter Value At End : " + counterAtEnd +
                        "\nCounter Frequency : " + timer.Frequency);
    }
     public Receiver()
 {
   if (rcvBlockingQ == null)
     rcvBlockingQ = new BlockingQueue<Message>();
         block = new byte[BlockSize];
         hrt = new HRTimer.HiResTimer();
     }
Esempio n. 4
0
        private void Run()
        {
            RSLClient rslClient = new RSLClient(serviceIdentity, "KV", ps.Verbose);

            Thread.Sleep(3000);

            Random rng = new Random();

            for (int requestNum = 1; true; ++requestNum)
            {
                KVRequest request      = GetRandomRequest(rng, ps);
                byte[]    requestBytes = request.Encode();
                var       startTime    = HiResTimer.Ticks;
                byte[]    replyBytes   = rslClient.SubmitRequest(requestBytes, ps.Verbose);
                var       endTime      = HiResTimer.Ticks;
                KVReply   reply        = KVReply.Decode(replyBytes, 0);

                if (ps.PrintRequestsAndReplies)
                {
                    Console.WriteLine("Received reply of type {0}", reply.ReplyType);
                    if (reply is KVGetFoundReply gfr)
                    {
                        Console.WriteLine("Value obtained for get was {0}", gfr.Val);
                    }
                }
                Console.WriteLine("#req {0} {1} {2}",
                                  id,
                                  requestNum,
                                  HiResTimer.TicksToMilliseconds(endTime - startTime));
            }
        }
Esempio n. 5
0
        private void bnInvoke_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            try
            {
                Init();

                HiResTimer hrt = new HiResTimer();

                hrt.Start();
                object result = wsp.InvokeCall();
                hrt.Stop();

                tbElapsedTime.Text = hrt.ElapsedMicroseconds.ToString();
                tbResult.Text      = result.ToString();

                if (wsp.EnableMessageAccess)
                {
                    string tmpReqFile  = SaveRequestToTempFile(wsp.SoapRequest);
                    string tmpRespFile = SaveResponseToTempFile(wsp.SoapResponse);

                    object obj = null;
                    webBrowserRequest.Navigate("file://" + tmpReqFile, ref obj, ref obj, ref obj, ref obj);
                    webBrowserResponse.Navigate("file://" + tmpRespFile, ref obj, ref obj, ref obj, ref obj);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            this.Cursor = Cursors.Default;
        }
Esempio n. 6
0
        /// <summary>
        /// Called periodically by the main form allowing statistics to
        /// be rendered.  This will be called on the UI thread.
        /// </summary>
        public void OnTimer()
        {
            if (!running)
            {
                statusBox.Text = string.Empty;
                return;
            }

            StringBuilder sb   = new StringBuilder();
            TimeSpan      time = HiResTimer.CalcTimeSpan(startTimer);
            long          cTotal;
            long          cTimeout;

            cTotal   = Interlocked.Read(ref this.cTotal);
            cTimeout = Interlocked.Read(ref this.cTimeout);

            sb.AppendFormat("Total:    {0}\r\n", cTotal);
            sb.AppendFormat("Rate:     {0:0.00}/sec\r\n", (cTotal - cPerf) / time.TotalSeconds);
            sb.AppendFormat("Ave Rate: {0:0.00}/sec\r\n", cTotal / (SysTime.Now - startTime).TotalSeconds);
            sb.AppendFormat("Retry:    {0}\r\n", MainForm.Router.Metrics.SessionRetries.Count);
            sb.AppendFormat("Timeout:  {0}\r\n", MainForm.Router.Metrics.SessionTimeouts.Count);

            if (cParallelQueries == 1)
            {
                sb.AppendFormat("Latency:  {0}ms\r\n", TimeSpan.FromTicks(Interlocked.Read(ref totalLatency) / cTotal).TotalMilliseconds);
            }

            statusBox.Text = sb.ToString();

            cPerf      = cTotal;
            startTimer = HiResTimer.Count;
        }
Esempio n. 7
0
 private void TestButton_Click(object sender, EventArgs e)
 {
     _timer               = new HiResTimer();
     _timer.Interval      = 1;
     _timer.AutoReset     = true;
     _timer.TestFinished += _timer_TestFinished;
     _timer.BeginTest();
 }
Esempio n. 8
0
        // Create Communication channel proxy, sndBlockingQ, and
        // start sndThrd to send messages that client enqueues

        public Sender()
        {
            block                = new byte[BlockSize];
            hrt                  = new HiResTimer();
            sndBlockingQ         = new BlockingQueue <Message>();
            sndThrd              = new Thread(ThreadProc);
            sndThrd.IsBackground = true;
            sndThrd.Start();
        }
Esempio n. 9
0
        //----< Entry point into Write Client >------------------------------
        static void Main(string[] args)
        {
            WriteClient clnt    = new WriteClient();
            bool        success = clnt.ProcessCommandArgsAndFile(clnt, args);

            if (!success)
            {
                return;
            }

            HiResTimer     timer       = new HiResTimer(); timer.Start();
            List <Message> messageList = clnt.ProcessXML("MessagePrototype.xml");

            clnt.latencyTimers.Add(new HiResTimer());
            clnt.latencyValues.Add(new ulong());
            foreach (Message message in messageList)
            {
                if (clnt.sndr.sendMessage(message))
                {
                    HiResTimer temp = new HiResTimer();
                    temp.Start(); clnt.latencyTimers.Add(temp);
                    clnt.latencyValues.Add(new ulong());
                    Console.Write("\n  Request ID: {0}\n", message.messageID);
                    Console.WriteLine(message.content);
                }
                else
                {
                    Console.Write("\n  could not connect in {0} attempts", clnt.sndr.MaxConnectAttempts);
                    clnt.sndr.shutdown(); clnt.rcvr.shutDown(); return;
                }
            }
            timer.Stop(); Console.WriteLine("\n  =====================================================");
            Console.WriteLine("\n   Total time to send all the messages: {0} microseconds", timer.ElapsedMicroseconds);
            Console.WriteLine("\n  =====================================================");

            Message msg = new Message();

            msg.fromUrl = clnt.localUrl;
            msg.toUrl   = clnt.remoteUrl;
            msg.content = "done";
            clnt.sndr.sendMessage(msg);
            while (true)
            {
                if (clnt.rcvCount == messageList.Count())
                {
                    Thread.Sleep(50);
                    clnt.performanceAnalysis();
                    break;
                }
            }
            Util.waitForUser();
            clnt.rcvr.shutDown();
            clnt.sndr.shutdown();
            Console.Write("\n\n");
        }
Esempio n. 10
0
        static void Main(string[] args)
        {
            Params ps = new Params();

            foreach (var arg in args)
            {
                if (!ps.ProcessCommandLineArgument(arg))
                {
                    usage();
                    return;
                }
            }

            var serviceIdentity = ServiceIdentity.ReadFromFile(ps.ServiceFileName);

            if (serviceIdentity == null)
            {
                return;
            }
            if (serviceIdentity.ServiceType != "IronSHT")
            {
                Console.Error.WriteLine("ERROR - Service described by {0} is of type {1}, not IronSHT", ps.ServiceFileName,
                                        serviceIdentity.ServiceType);
                return;
            }

            HiResTimer.Initialize();
            if (ps.Verbose)
            {
                Console.WriteLine("Client process starting {0} threads running for {1} s...", ps.NumThreads, ps.ExperimentDuration);
            }

            Console.WriteLine("[[READY]]");

            // Setup the system
            var setupThreads = Client.StartSetupThreads(ps, serviceIdentity).ToArray();

            setupThreads[0].Join();
            Console.WriteLine("[[SETUP COMPLETE]]");

            // Start the experiment
            var threads = Client.StartExperimentThreads(ps, serviceIdentity).ToArray();

            if (ps.ExperimentDuration == 0)
            {
                threads[0].Join();
            }
            else
            {
                Thread.Sleep((int)ps.ExperimentDuration * 1000);
                Console.Out.WriteLine("[[DONE]]");
                Console.Out.Flush();
                Environment.Exit(0);
            }
        }
Esempio n. 11
0
        static void Main(string[] args)
        {
            HiResTimer hrt = new HiResTimer();

            hrt.Start();
            M();
            hrt.Stop();

            Console.WriteLine("{0}", hrt.ElapsedMicroseconds);
            Console.ReadLine();
        }
Esempio n. 12
0
        Tserver(int max)
        {
            this.maxthreads        = max;
            host                   = comm.rcvr.CreateRecvChannel(endPoint);                 // service hosted
            rcvThread              = new Thread(new ThreadStart(this.rcvThreadProc));
            rcvThread.IsBackground = true;
            rcvThread.Start();

            block = new byte[BlockSize];
            hrt   = new HiResTimer();
        }
Esempio n. 13
0
        //----< run client demo >----------------------------------------

        static void Main(string[] args)
        {
            Console.Title = "Client 1 Console";
            Console.Write("\n  Testing Client Demo");
            Console.Write("\n =====================\n");
            Client clnt = new Client();

            clnt.comm.sndr.channel = Sender.CreateServiceChannel("http://localhost:8082/StreamService");
            HiResTimer hrt = new HiResTimer();

            hrt.Start();
            clnt.comm.sndr.uploadFile("TestDriver.dll");
            clnt.comm.sndr.uploadFile("TestedCode.dll");
            hrt.Stop();
            Console.WriteLine("\n**********************************************************************");
            Console.WriteLine("\nDemonstrating requirement 12 latency");
            Console.Write(
                "\n\n  total elapsed time for uploading = {0} microsec.\n",
                hrt.ElapsedMicroseconds
                );
            Message msg = clnt.makeMessage("Brahma", clnt.endPoint, clnt.endPoint);

            msg.type = "TestRequest";
            msg      = clnt.makeMessage("Brahma", clnt.endPoint, clnt.endPoint);
            msg.body = MessageTest.makeTestRequest();
            Console.WriteLine("\n**********************************************************************");
            Console.WriteLine("\n Demonstrating requirement 2 : XML messages");
            msg.showMsg();
            string remoteEndPoint = Comm <Client> .makeEndPoint("http://localhost", 8080);

            msg    = msg.copy();
            msg.to = remoteEndPoint;
            clnt.comm.sndr.PostMessage(msg);
            string repository = Comm <Client> .makeEndPoint("http://localhost", 8082);

            msg      = clnt.makeMessage("Brahma", clnt.endPoint, repository);
            msg.type = "testlogs";
            msg.body = "brahma";
            clnt.comm.sndr.PostMessage(msg);
            Console.Write("\n  press key to exit: ");
            Console.ReadKey();
            msg.body = "quit";
            clnt.comm.sndr.PostMessage(msg);
            msg.showMsg();
            Console.Write("\n\n  Press key to terminate client");
            Console.ReadKey();
            Console.Write("\n\n");
            clnt.wait();
            ((IChannel)clnt.comm.sndr).Close();
            Console.Write("\n\n");
        }
Esempio n. 14
0
        void EmulateCyclesWithout1541()
        {
#if TIMERS
            uint       lc    = CycleCounter;
            HiResTimer timer = new HiResTimer();
            timer.Start();
            const uint cycleCount = 4000000;
#endif

            thread_running = true;
            while (!quit_thyself)
            {
                // The order of calls is important here
                if (TheVIC.EmulateCycle())
                {
                    TheSID.EmulateLine();
                }
                TheCIA1.CheckIRQs();
                TheCIA2.CheckIRQs();
                TheCIA1.EmulateCycle();
                TheCIA2.EmulateCycle();
                TheCPU.EmulateCycle();

                CycleCounter++;

#if TIMERS
                if (CycleCounter - lc == cycleCount)
                {
                    timer.Stop();
                    lc = CycleCounter;
                    double elapsedSec = timer.ElapsedMilliseconds / 1000.0f;

                    Console.WriteLine("------------------------------------");
                    Console.WriteLine("{0} ms elapsed for {1:N} cycles", timer.ElapsedMilliseconds, cycleCount);
                    Console.WriteLine("CIA1: TA Interrupts: {0} -> int/s: {1}", TheCIA1.ta_interrupts, TheCIA1.ta_interrupts / elapsedSec);
                    Console.WriteLine("CPU Instructions: {0} -> ins/s: {1}", TheCPU.ins_counter, TheCPU.ins_counter / elapsedSec);

                    // reset counters
                    TheCIA1.ta_interrupts = 0;
                    TheCIA1.tb_interrupts = 0;
                    TheCIA2.ta_interrupts = 0;
                    TheCIA2.tb_interrupts = 0;
                    TheCPU.ins_counter    = 0;

                    timer.Reset();
                    timer.Start();
                    //TheDisplay.Surface.Update();
                }
#endif
            }
        }
Esempio n. 15
0
        static void Main(string[] args)
        {
            Params ps = new Params();

            foreach (var arg in args)
            {
                if (!ps.ProcessCommandLineArgument(arg))
                {
                    usage();
                    return;
                }
            }

            if (!ps.Validate())
            {
                usage();
                return;
            }

            var serviceIdentity = ServiceIdentity.ReadFromFile(ps.ServiceFileName);

            if (serviceIdentity == null)
            {
                return;
            }

            HiResTimer.Initialize();
            if (ps.Verbose)
            {
                Console.WriteLine("Client process starting {0} threads running for {1} s...", ps.NumThreads, ps.ExperimentDuration);
            }

            Console.WriteLine("[[READY]]");

            // Start the experiment
            var threads = Client.StartThreads <Client>(ps, serviceIdentity).ToArray();

            if (ps.ExperimentDuration == 0)
            {
                threads[0].Join();
            }
            else
            {
                Thread.Sleep((int)ps.ExperimentDuration * 1000);
                Console.Out.WriteLine("[[DONE]]");
                Console.Out.Flush();
                Environment.Exit(0);
            }
        }
Esempio n. 16
0
 public DebugControl()
 {
     InitializeComponent();
     if (ControlsHelper.IsDesignMode(this))
     {
         return;
     }
     _TestTimer           = new HiResTimer(1, "TestTimer");
     _TestTimer.AutoReset = true;
     CpuTimer             = new System.Timers.Timer();
     CpuTimer.Interval    = 1000;
     CpuTimer.AutoReset   = false;
     CpuTimer.Elapsed    += CpuTimer_Elapsed;
     LoadSettings();
     CheckTimer();
 }
Esempio n. 17
0
        public void ThreadProc(InternalMessage imsg) //all file loading exceptions are handled here
        {
            FileClient    clnt        = new FileClient();;
            HiResTimer    hrt         = new HiResTimer();
            MessageClient msgSender   = new MessageClient();
            Message       msgToClient = new Message();

            Console.WriteLine("");
            Console.WriteLine("===============================================================");
            try
            {
                clnt.CreateFileChannel(imsg.connectMessage.fileConnectAddress);
                Console.WriteLine("\n Identifying Load request message...");
                if (imsg.fileMessage.loadType == "Download")
                {
                    foreach (string file in imsg.fileMessage.fileNames)
                    {
                        clnt.download(file, imsg.fileMessage.loadPath);
                    }
                    msgToClient = msgSender.SetupMessages(true, "Files successfully downloaded by Repository.", imsg.recipient);
                }
                else
                {
                    foreach (string file in imsg.fileMessage.fileNames)
                    {
                        clnt.upload(file, imsg.fileMessage.loadPath);
                    }
                    msgToClient = msgSender.SetupMessages(true, "Files successfully uploaded from Repository.", imsg.recipient);
                }
            }
            catch (Exception ex)
            {
                msgToClient = msgSender.SetupMessages(false, "\n[Error message]:" + ex.Message, imsg.recipient);
            }
            finally
            {
                Console.WriteLine("\nConnecting to message channel...");
                msgSender.CreateMessageChannel(imsg.connectMessage.MessageConnectAddress);
                Console.WriteLine("\nSending message about loading status back...");
                hrt.Start();
                msgSender.channel.PostMessage(msgToClient);
                hrt.Stop();
                Console.WriteLine("");
                Console.WriteLine("\nMessage sent back in {0} microsec.", hrt.ElapsedMicroseconds);
                Console.WriteLine("");
            }
        }
Esempio n. 18
0
        public void THMsgProc()
        {
            while (true)
            {
                HiResTimer hrt = new HiResTimer();
                Message    msg = msgReciever.TryGetTHMessage();
                Console.WriteLine("\n<--------------------------------------------------------->");
                Console.WriteLine("\nMessage recieved from test harness.");
                if (msg.recipient == "AboutLog")
                {
                    Console.WriteLine("\nDemonstrating test logs and results:");
                    TestResults tr = msgReciever.ParseResultMsg(msg);
                    Console.WriteLine(tr.log);

                    Console.WriteLine("\nDemonstrating querying results from repository:");
                    Console.WriteLine("\nSending message to repository...");
                    SetupQueryMessageToRepo(tr, "http://localhost:4048/ICommService/BasicHttp",
                                            "http://localhost:8088/ICommService/BasicHttp", "Upload");

                    msgSenderwithRepo.channel.PostMessage(msgToRepoQuery);

                    Console.WriteLine("\nWaiting for message from repository...");
                    hrt.Start();
                    Message repoReply = msgReciever.TryGetRepoMessage("Query");
                    hrt.Stop();
                    Console.WriteLine("");
                    Console.WriteLine("\nRecieved message in {0} microsec.", hrt.ElapsedMicroseconds);
                    Console.WriteLine("");
                    TestLoadStatus loadStatus = msgReciever.ParseLoadMsg(repoReply);
                    Console.WriteLine(loadStatus.loadMessage);
                    if (loadStatus.status)
                    {
                        using (FileStream fs = new FileStream(Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "..\\..\\..\\TestResults", tr.LogName + "Summary.txt"), FileMode.Open))
                            using (StreamReader sr = new StreamReader(fs))
                            {
                                Console.WriteLine(sr.ReadToEnd());
                            }
                    }
                }
                else
                {
                    Console.WriteLine("\nDemonstrating dll load status in test harness:");
                    Console.WriteLine(msgReciever.ParseLoadMsg(msg).loadMessage);
                }
            }
        }
 public void THMsgProc()
 {
     while (true)
     {
         HiResTimer hrt = new HiResTimer();
         Message    msg = msgReciever.TryGetTHMessage();
         Console.WriteLine("\n<--------------------------------------------------------->");
         Console.WriteLine("\nMessage recieved from test harness.");
         if (msg.recipient == "AboutLog")
         {
             Console.WriteLine("\nDemonstrating test logs and results:");
             TestResults tr = msgReciever.ParseResultMsg(msg);
             Console.WriteLine(tr.log);
             Console.WriteLine("\nDemonstrating querying results from repository:");
             Console.WriteLine("\nSending message to repository...");
             clientUtil.SetupQueryMessageToRepo(msgToRepoQuery, tr, "http://localhost:4244/ICommService/BasicHttp",
                                                "http://localhost:8284/ICommService/BasicHttp", "Upload");
             msgSenderwithRepo.channel.PostMessage(msgToRepoQuery);
             Console.WriteLine("\nWaiting for message from repository...");
             hrt.Start();
             Message repoReply = msgReciever.TryGetRepoMessage("Query");
             hrt.Stop();
             Console.WriteLine("");
             Console.WriteLine("\nRecieved message in {0} microsec.", hrt.ElapsedMicroseconds);
             Console.WriteLine("");
             TestLoadStatus loadStatus = msgReciever.ParseLoadMsg(repoReply);
             Console.WriteLine(loadStatus.loadMessage);
             using (FileStream fs = new FileStream(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "..\\..\\..\\TestResults", tr.LogName + "Summary.txt"), FileMode.Open))
                 using (StreamReader sr = new StreamReader(fs))
                 {
                     Dispatcher.Invoke(
                         new Action <string>(ShowStringResult),
                         System.Windows.Threading.DispatcherPriority.Background,
                         new string[] { sr.ReadToEnd() });
                 }
         }
         else
         {
             Console.WriteLine("\nDemonstrating dll load status in test harness:");
             Dispatcher.Invoke(
                 new Action <string>(ShowLoadMsg),
                 System.Windows.Threading.DispatcherPriority.Background,
                 new string[] { msgReciever.ParseLoadMsg(msg).loadMessage });
         }
     }
 }
        private void btnSendReq_Click(object sender, RoutedEventArgs e)
        {
            Thread childTH = new Thread(new ThreadStart(THMsgProc));

            childTH.Start();


            HiResTimer hrt = new HiResTimer();

            clientUtil.SetupLoadMessageToRepo(msgToRepoLoad, testCodeList, "http://localhost:4244/ICommService/BasicHttp",
                                              "http://localhost:8284/ICommService/BasicHttp", "Download");

            msgSenderwithRepo.channel.PostMessage(msgToRepoLoad);
            Thread childRepo = new Thread(RepoMsgProc);

            childRepo.Start();
        }
 public PerformanceTestUserControl()
 {
     InitializeComponent();
     if (IsDesignMode)
     {
         return;
     }
     _TestTimer           = new HiResTimer();
     _TestTimer.Interval  = 1;
     _TestTimer.AutoReset = true;
     CpuTimer             = new System.Timers.Timer();
     CpuTimer.Interval    = 1000;
     CpuTimer.AutoReset   = false;
     CpuTimer.Elapsed    += CpuTimer_Elapsed;
     LoadSettings();
     CheckTimer();
 }
Esempio n. 22
0
        static void Main(string[] args)
        {
            object locker = new object();

            lock (locker)
            {
                Client client = new Client();
                client.ClientSetup(client);
                Thread childTH = new Thread(new ThreadStart(client.THMsgProc));
                childTH.Start();
                try
                {
                    client.GetRequestFiles();
                    foreach (info_In_One_Request_Folder info in client.folderInfoList)
                    {
                        HiResTimer hrt = new HiResTimer();
                        client.SetupLoadMessageToRepo(info, "http://localhost:4048/ICommService/BasicHttp",
                                                      "http://localhost:8088/ICommService/BasicHttp", "Download");
                        client.msgSenderwithRepo.channel.PostMessage(client.msgToRepoLoad);
                        Console.WriteLine("\nWaiting for message from repository");
                        hrt.Start();
                        Message msgFromRepo = client.msgReciever.TryGetRepoMessage("Load");
                        hrt.Stop();
                        TestLoadStatus loadStatus = client.msgReciever.ParseLoadMsg(msgFromRepo);
                        Console.WriteLine("");
                        Console.WriteLine("\nRecieved message from repository in {0} microsec", hrt.ElapsedMicroseconds);
                        Console.WriteLine("");
                        Console.WriteLine(loadStatus.loadMessage);
                        if (loadStatus.status)
                        {
                            Console.WriteLine("\nSending message to TH");
                            client.SetupMessageToTH(info, "http://localhost:4048/ICommService/BasicHttp", "http://localhost:8088/ICommService/BasicHttp");
                            client.msgSenderwithTH.channel.PostMessage(client.msgToTH);
                        }
                    }
                    childTH.Join();
                    Console.ReadKey();
                }
                catch (Exception ex)
                {
                    Console.Write("\n\n  {0}", ex.Message);
                }
                Console.Write("\n\n");
            }
        }
Esempio n. 23
0
        //----< create local directory and load from Repository >--------

        RequestInfo processRequestAndLoadFiles(Message testRequest)
        {
            HiResTimer  hrt       = new HiResTimer();
            string      localDir_ = "";
            RequestInfo rqi       = new RequestInfo();

            rqi.requestInfo = extractTests(testRequest);
            List <string> files = extractCode(rqi.requestInfo);

            localDir_ = makeKey(testRequest.author);
            Console.WriteLine(" \n Key :", localDir_);
            Console.WriteLine("\n**********************************************************************");
            Console.WriteLine("\nDemonstrating requirement 8 ,unique key");
            // name of temporary dir to hold test files
            rqi.tempDirName = localDir_;
            lock (sync_)                {
                filePath_ = System.IO.Path.GetFullPath(localDir_);      // LoadAndTest will use this path
                TLS[Thread.CurrentThread.ManagedThreadId] = filePath_;
            }                Console.Write("\n  creating local test directory \"" + localDir_ + "\"");
            System.IO.Directory.CreateDirectory(localDir_);           //for file streaming to download files
            this.comm.sndr.channel = Sender.CreateServiceChannel("http://localhost:8082/StreamService");
            Console.Write("\n  loading code from Repository");
            foreach (string file in files)
            {
                hrt.Start();
                try                {
                    string name = System.IO.Path.GetFileName(file);
                    this.comm.sndr.changepath(System.IO.Path.GetFullPath(localDir_));
                    this.comm.sndr.download(file);
                }
                catch (Exception message)                       {
                    Console.Write("Exception of file", message);
                    Console.Write("\n    TID" + Thread.CurrentThread.ManagedThreadId + ": could not retrieve file \"" + file + "\"");
                }            hrt.Stop();
                Console.Write(
                    "\n\n  Total elapsed time for downloading = {0}",
                    hrt.ElapsedMicroseconds);
                Console.Write("\n    TID" + Thread.CurrentThread.ManagedThreadId + ": retrieved file \"" + file + "\"");
            }
            Console.WriteLine();
            return(rqi);
        }
Esempio n. 24
0
        public void runOneSimulation()
        {
            //generate home
            this.Homes = Util.HomeGenerator.GenerateHome(this.Config);

            HiResTimer timer = new HiResTimer();

            //run different algorithms
            foreach (String assignerType in Enum.GetNames(typeof(AssignerType)))
            {
                List <Home> homes = CloneHomes(this.Homes);
                //Console.WriteLine("--------------------{0}------------------", assignerType);
                Simulator = new Simulator(Config, homes, assignerType);
                timer.ReStart();
                Simulator.Simulate(0, Config.TotalTimeSlot - 1);
                double elapseTime = timer.TimeElapseInTenthsOfMilliseconds;
                //write simulation results into file
                SimulationResultProcess.ProcessHomeResult(homes, Config.SimulationOutputPath + assignerType, elapseTime);
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Called periodically by the main form allowing statistics to
        /// be rendered.  This will be called on the UI thread.
        /// </summary>
        public void OnTimer()
        {
            if (!running)
            {
                statusBox.Text = string.Empty;
                return;
            }

            StringBuilder sb   = new StringBuilder();
            TimeSpan      time = HiResTimer.CalcTimeSpan(startTimer);
            long          cTotal;

            cTotal = Interlocked.Read(ref this.cTotal);

            sb.AppendFormat("Messages: {0}\r\n", cTotal);
            sb.AppendFormat("Status:   {0}\r\n", status ? "OK" : "FAILURE");

            statusBox.Text = sb.ToString();

            startTimer = HiResTimer.Count;
        }
Esempio n. 26
0
        /// <summary>
        /// Called periodically by the main form allowing statistics to
        /// be rendered.  This will be called on the UI thread.
        /// </summary>
        public void OnTimer()
        {
            if (!running)
            {
                statusBox.Text = string.Empty;
                return;
            }

            StringBuilder sb   = new StringBuilder();
            TimeSpan      time = HiResTimer.CalcTimeSpan(startTimer);
            long          cTotal;

            cTotal = Interlocked.Read(ref this.cTotal);

            sb.AppendFormat("Total:    {0}\r\n", cTotal);
            sb.AppendFormat("Rate:     {0:0.00}/sec\r\n", (cTotal - cPerf) / time.TotalSeconds);
            sb.AppendFormat("Ave Rate: {0:0.00}/sec\r\n", cTotal / (SysTime.Now - startTime).TotalSeconds);
            statusBox.Text = sb.ToString();

            cPerf      = cTotal;
            startTimer = HiResTimer.Count;
        }
        public void When_Sleep_IsCalled_For_NusThen_Sleep_IsProperLong()
        {
            HiResTimer timer = new HiResTimer();

            // This example shows how to use the high-resolution counter to
            // time an operation.

            // Get counter value before the operation starts.
            Int64 counterAtStart = timer.Value;

            // Perform an operation that takes a measureable amount of time.
            for (int count = 0; count < 10000; count++)
            {
                count++;
                count--;
            }

            // Get counter value when the operation ends.
            Int64 counterAtEnd = timer.Value;

            // Get time elapsed in tenths of a millisecond.
            Int64 timeElapsedInTicks = counterAtEnd - counterAtStart;
            Int64 timeElapseInTenthsOfMilliseconds = (timeElapsedInTicks * 10000) / timer.Frequency;
        }
Esempio n. 28
0
        private void Run()
        {
            RSLClient rslClient = new RSLClient(serviceIdentity, "Counter", ps.Verbose);

            Thread.Sleep(3000);

            for (int requestNum = 1; true; ++requestNum)
            {
                var    request      = new IncrementRequest();
                byte[] requestBytes = request.Encode();
                var    startTime    = HiResTimer.Ticks;
                byte[] replyBytes   = rslClient.SubmitRequest(requestBytes, ps.Verbose);
                var    endTime      = HiResTimer.Ticks;
                var    reply        = IncrementReply.Decode(replyBytes);
                if (ps.PrintReplies)
                {
                    Console.WriteLine("Received increment reply with counter {0}", reply.counterValue);
                }
                Console.WriteLine("#req {0} {1} {2}",
                                  id,
                                  requestNum,
                                  HiResTimer.TicksToMilliseconds(endTime - startTime));
            }
        }
Esempio n. 29
0
        //---------------------------------------------------------------------
        // Background thread

        /// <summary>
        /// The background thread.
        /// </summary>
        private void BkThread()
        {
            MsgEP ep = "abstract://LillTek/Test/Message/Query";

            IAsyncResult[] ar = new IAsyncResult[cParallelQueries];
            ResponseMsg    ack;
            long           startCount;

            while (true)
            {
                startCount = HiResTimer.Count;

                for (int i = 0; i < cParallelQueries; i++)
                {
                    ar[i] = MainForm.Router.BeginQuery(ep, new QueryMsg(cbPayload), null, null);
                }

                for (int i = 0; i < cParallelQueries; i++)
                {
                    try
                    {
                        ack = (ResponseMsg)MainForm.Router.EndQuery(ar[i]);
                        Interlocked.Increment(ref cTotal);
                    }
                    catch (TimeoutException)
                    {
                        Interlocked.Increment(ref cTimeout);
                    }
                    catch
                    {
                    }
                }

                Interlocked.Add(ref totalLatency, HiResTimer.CalcTimeSpan(startCount).Ticks);
            }
        }
    //
    //----< parse file into identifiers and store in Hashtable >-------

    public void ParseFile(string fileName)    {
      HiResTimer total = new HiResTimer();
      HiResTimer open = new HiResTimer();
      HiResTimer parse = new HiResTimer();
      try      {
        total.Start();
        open.Start();
        StreamReader fs = new StreamReader(fileName);
        open.Stop();
        openTime = open.ElapsedMicroseconds;
                 parse.Start();
        int size = 0;
        string line;
        while((line = fs.ReadLine()) != null)        {
          string[] tokens = line.Split();
          foreach(string token in tokens)          {
            if(token == "\n" | token.Length == 0)              continue;
            if(Verbose)
              Console.Write("\n    {0}",token);
            string tok, compositeToken = token;
            while(compositeToken != "")            {
              tok = extractIdent(ref compositeToken);
              if(tok == "")                continue;
              if(Verbose)
                Console.Write("\n      {0}",tok);
              if(table.Contains(tok))
                table[tok] = 1 + (int)table[tok];
              else              {
                table[tok] = 1;
                size += tok.Length;              }            }          }        }
        parse.Stop();
        parseTime = parse.ElapsedMicroseconds;
        total.Stop();
        totalTime = total.ElapsedMicroseconds;
        Console.Write("\n   Open time: {0} microsec",openTime); 
        Console.Write("\n  Parse time: {0} microsec",parseTime); 
        Console.Write("\n  total time: {0} microsec",totalTime); 
        Console.Write("\n   Hash size: {0} bytes",size);      }
      catch      {
        Console.Write("\n  Could not open file \"{0}\"\n\n",fileName);      }    }
Esempio n. 31
0
 repository()
 {
     block = new byte[BlockSize];
     hrt   = new HiResTimer();
     host  = comm.rcvr.CreateRecvChannel(endPoint);
 }
Esempio n. 32
0
 /// <summary>
 /// Proces wheh the response has been received
 /// </summary>
 /// <param name="srvr"></param>
 /// <param name="sndr"></param>
 /// <param name="msg"></param>
 /// <param name="msgid"></param>
 private static void ProcessResponse(Server srvr, Sender sndr, ref Message msg, ref string msgid)
 {
     HiResTimer hres = new HiResTimer(); //High Resolution Timer
     hres.Start();
     XDocument doc = XDocument.Load(new StringReader(msg.content));
     string op = doc.Descendants("Operation").Select(i => i).Single().Value;
     if (op == "Read")
         srvr.ProcessReadMessage(ref msg, ref msgid);
     else
         srvr.ProcessMessage(ref msg, ref msgid);
     hres.Stop();
     Console.WriteLine("Server execution time for processing message(MsgID:{0}) is {1} microseconds \n", msgid, hres.ElapsedMicroseconds);
     Util.swapUrls(ref msg);  // swap urls for outgoing message
     if (srvr.tot.ContainsKey(msg.toUrl))
     {
         ulong x = ulong.Parse(srvr.tot[msg.toUrl].ToString());
         x += hres.ElapsedMicroseconds;
         srvr.tot[msg.toUrl] = x.ToString();
     }
     else
         srvr.tot[msg.toUrl] = hres.ElapsedMicroseconds;
     sndr.sendMessage(msg);
 }
Esempio n. 33
0
 /// <summary>
 /// Performance testing by inserting queries
 /// </summary>
 /// <param name="hres"></param>
 /// <param name="msg"></param>
 /// <param name="clnt"></param>
 /// <param name="sndr"></param>
 /// <returns></returns>
 private static Message PerformanceTest(HiResTimer hres, Message msg, ReadClient clnt, Sender sndr)
 {
     XmlTextReader textReader = new XmlTextReader("Input.xml");
     HiResTimer timerH = new HiResTimer();
     if (File.Exists("Input.xml"))
     {
         XDocument docTemp;
         string msgid;
         //GetKeyCriteria
         GetByKeyCriteria(hres, msg, clnt, sndr, timerH, out docTemp, out msgid);
         //GetByMetadataCriteria
         docTemp = GetByMetadataCriteria(msg, clnt, sndr, ref msgid);
         //GetByTimeStampCriteria
         docTemp = GetByTimeStampCriteria(msg, clnt, sndr, ref msgid);
         docTemp = GetByKey(msg, clnt, sndr, ref msgid);                //GetByKey
         docTemp = GetChildren(msg, clnt, sndr, ref msgid);                //GetChildren
     }
     timerH.Stop();
     clnt.ReadClientTime = timerH.ElapsedMicroseconds;
     msg = new Message();
     msg.fromUrl = clnt.localUrl;
     msg.toUrl = clnt.remoteUrl;
     msg.content = "done";
     sndr.sendMessage(msg);
     return msg;
 }
Esempio n. 34
0
 /// <summary>
 ///  GetByKeyCriteria criteria for the query type 
 /// </summary>
 /// <param name="hres"></param>
 /// <param name="msg"></param>
 /// <param name="clnt"></param>
 /// <param name="sndr"></param>
 /// <param name="timerH"></param>
 /// <param name="docTemp"></param>
 /// <param name="msgid"></param>
 private static void GetByKeyCriteria(HiResTimer hres, Message msg, ReadClient clnt, Sender sndr, HiResTimer timerH, out XDocument docTemp, out string msgid)
 {
     docTemp = XDocument.Load("Input.xml");
     clnt.RemoveOtherReads(ref docTemp, "GetKeyCriteria");
     clnt.RemoveOtherWrites(ref docTemp, "GetKeyCriteria");
     XElement k = docTemp.Descendants("OperationMessage").Where(d => d.Element("QueryType").Value == "GetKeyCriteria").Select(j => j).Single();
     clnt.numMsgs = int.Parse(k.Elements("Count").Single().Value);
     clnt.total += clnt.numMsgs;
     hres.Start();
     timerH.Start();//High resolution timer started       
     msgid = "";
     for (int i = 0; i < clnt.numMsgs; i++)
     {
         docTemp = XDocument.Load("Input.xml");
         clnt.RemoveOtherReads(ref docTemp, "GetKeyCriteria");
         clnt.RemoveOtherWrites(ref docTemp, "GetKeyCriteria");
         msgid = clnt.msgRand++.ToString();
         XElement y = null;
         y = docTemp.Descendants("OperationMessage").Where(d => d.Element("QueryType").Value == "GetKeyCriteria").Select(j => j).Single();
         y.Elements("MessageID").Single().Value = msgid;
         y.Elements("InsertTime").Single().Value = DateTime.Now.Ticks.ToString();
         msg.content = docTemp.ToString();
         msg.fromUrl = clnt.localUrl;
         msg.toUrl = clnt.remoteUrl;
         if (sndr.sendMessage(msg))
         {
             Console.Write("Sent message(Message ID {0}) to GetCriteria from key\n", msgid);
             Thread.Sleep(50);
         }
     }
 }
Esempio n. 35
0
 static void Main(string[] args)
 {
        HiResTimer hres = new HiResTimer(); //High Resolution Timer
     Console.Write("\nStarting CommService Read client");
     Console.Write("\n =============================\n");
     Console.Title = "Read Client";
     Message msg = new Message();
     ReadClient clnt = new ReadClient();
     clnt.processCommandLine(args);
     string localPort = Util.urlPort(clnt.localUrl);
     string localAddr = Util.urlAddress(clnt.localUrl);
     Receiver rcvr = new Receiver(localPort, localAddr);
     Action serviceAction = DefineServiceAction(hres, clnt, rcvr);
     if (rcvr.StartService())
         rcvr.doService(serviceAction);
     Sender sndr = new Sender(clnt.localUrl);  // Sender needs localUrl for start message         
     msg.fromUrl = clnt.localUrl;
     msg.toUrl = clnt.remoteUrl;
     Console.Write("Sender's url is {0}", msg.fromUrl);
     Console.Write("Attempting to connect to {0}\n", msg.toUrl);
     if (!sndr.Connect(msg.toUrl))
     {
         Console.Write("Could not connect in {0} attempts\n", sndr.MaxConnectAttempts);
         sndr.shutdown();
         rcvr.shutDown();
         return;
     }
     msg = PerformanceTest(hres, msg, clnt, sndr);
     // Wait for user to press a key to quit.
     Util.waitForUser();
     // shut down this client's Receiver and Sender by sending close messages
     rcvr.shutDown();
     sndr.shutdown();
     Console.Write("\n\n");
 }
Esempio n. 36
0
 /// <summary>
 ///  Performance testing by inserting items
 /// </summary>
 /// <param name="hres"></param>
 /// <param name="msg"></param>
 /// <param name="clnt"></param>
 /// <param name="rcvr"></param>
 /// <param name="sndr"></param>
 private static void PerformanceTesting(HiResTimer hres, Message msg, WriterClient clnt, Receiver rcvr, Sender sndr)
 {
     try
     {
         XmlTextReader textReader = new XmlTextReader("Input.xml");
         string xmlStr = "";
         HiResTimer t = new HiResTimer();
         t.Start();
         if (File.Exists("Input.xml"))
         {
             XDocument docTemp;
             string key, msgid;
             xmlStr = InsertPerformance(hres, msg, clnt, sndr, xmlStr, out docTemp, out key, out msgid);
             string keyUp;
             XElement l;
             UpdatePerformance(msg, clnt, sndr, ref xmlStr, out docTemp, key, ref msgid, out keyUp, out l);
             //Delete entries
             docTemp = DeletePerformance(msg, clnt, sndr, ref xmlStr, key, ref msgid, ref keyUp, l);
         }
         t.Stop();
         clnt.WriteClientTime = t.ElapsedMicroseconds;
         msg = new Message();
         msg.fromUrl = clnt.localUrl;
         msg.toUrl = clnt.remoteUrl;
         msg.content = "done";
         sndr.sendMessage(msg);
         // Wait for user to press a key to quit.
         Util.waitForUser();
         // shut down this client's Receiver and Sender by sending close messages
         rcvr.shutDown();
         sndr.shutdown();
         Console.Write("\n\n");
     }
     catch (CustomException ex)
     {
         throw new CustomException("Error in main of peformance testing", ex);
     }
 }
Esempio n. 37
0
        /// <summary>
        /// Insert performance results writer client
        /// </summary>
        /// <param name="hres"></param>
        /// <param name="msg"></param>
        /// <param name="clnt"></param>
        /// <param name="sndr"></param>
        /// <param name="xmlStr"></param>
        /// <param name="docTemp"></param>
        /// <param name="key"></param>
        /// <param name="msgid"></param>
        /// <returns></returns>
        private static string InsertPerformance(HiResTimer hres, Message msg, WriterClient clnt, Sender sndr, string xmlStr, out XDocument docTemp, out string key, out string msgid)
        {
            docTemp = XDocument.Load("Input.xml");
            XElement k = docTemp.Descendants("OperationMessage").Where(d => d.Element("Operation").Value == "Insert").Select(i => i).Single();
            if (k.Elements("Count").Single().Value != "")
                clnt.numMsgs = int.Parse(k.Elements("Count").Single().Value);
            clnt.total += clnt.numMsgs;
            hres.Start();     //High resolution timer started     
            key = "";
            msgid = "";
            for (int i = 0; i < clnt.numMsgs; i++)
            {
                docTemp = XDocument.Load("Input.xml");
                xmlStr = clnt.InsertGenerator(docTemp, ref msgid, ref key, "int");    //Generate data using the xml structure
                msg.content = xmlStr;
                msg.fromUrl = clnt.localUrl;
                msg.toUrl = clnt.remoteUrl;
                if (sndr.sendMessage(msg))
                {
                    Console.Write("Sent message(Message ID {0}) to insert into DB successfully\n", msgid);
                    Thread.Sleep(50);
                }
            }

            return xmlStr;
        }
Esempio n. 38
0
 /// <summary>
 ///  Define service action that needs to be handled for receiver requests at the client
 /// </summary>
 /// <param name="hres"></param>
 /// <param name="clnt"></param>
 /// <param name="rcvr"></param>
 /// <returns></returns>
 private static Action DefineServiceAction(HiResTimer hres, WriterClient clnt, Receiver rcvr)
 {
     try
     {
         Action serviceAction = ServiceActionMake(hres, clnt, rcvr);
         return serviceAction;
     }
     catch (CustomException ex)
     {
         throw new CustomException("Error in define service action of writer client", ex);
     }
 }
Esempio n. 39
0
 private static Action ServiceActionMake(HiResTimer hres, WriterClient clnt, Receiver rcvr)
 {
     Action serviceAction = () =>
     {
         Message msg1 = null;
         while (true)
         {
             msg1 = rcvr.getMessage();   // note use of non-service method to deQ messages                           
             if (msg1.content == "done")
             {
                 hres.Stop(); ulong lookUpTime = hres.ElapsedMicroseconds;
                 Message msg2 = new Message();
                 msg2.fromUrl = clnt.localUrl;
                 msg2.toUrl = clnt.wpfClientURL;
                 msg2.content = "LookupTime;" + lookUpTime + ";" + "CntMsg;" + (ulong)clnt.total + ";";
                 Sender wpfSender = new Sender(clnt.localUrl);
                 wpfSender.sendMessage(msg2);
                 Console.WriteLine("\n----------------------Overall Performance Statistics for Write Client-----------------------------\n");
                 Console.WriteLine("Number of messages processed is {0}", clnt.total);
                 Console.WriteLine("\nTotal Execution time for the messages to be processed at Client Side is {0} microsecs", clnt.WriteClientTime);
                 Console.WriteLine("\nAverage Execution time for the messages to be processed at Client Side is {0} microsecs", clnt.WriteClientTime / (ulong)clnt.total);
                 Console.WriteLine("\nTotal Execution time for the messages from Client-Server-Client {0} microsecs", lookUpTime);
                 Console.WriteLine("\nAverage Execution time for the messages from Client-Server-Client is {0} microsecs", lookUpTime / (ulong)clnt.total);
                 Console.WriteLine("\n----------------------Overall Performance Statistics for Write Client-----------------------------\n");
                 break;
             }
             else if (msg1.content == "connection start message")
                 Console.WriteLine("Connection start message receieved at client side");
             else
             {
                 XDocument docTemp = XDocument.Load(new StringReader(msg1.content));
                 string mid = docTemp.Descendants("OperationMessage").Elements("MessageID").Single().Value;
                 string op = docTemp.Descendants("OperationMessage").Elements("Operation").Single().Value;
                 string resp = docTemp.Descendants("OperationMessage").Elements("Response").Single().Value;
                 Console.Write("\nMessage - MessageID:{0} received at the client", mid);
                 Console.Write("\nSender:{0}", msg1.fromUrl); Console.Write("\nOperation :{0}", op);
                 Console.Write("\nResponse :{0}", resp);
                 string oldDt = docTemp.Descendants("InsertTime").Select(i => i).Single().Value.ToString();
                 long microseconds = (DateTime.Now.Ticks - long.Parse(oldDt)) / 10;
                 Console.Write("\nExecution time for message(MessageID:{1}) is {0} microseconds\n", microseconds, mid);
             }
         }
         Util.waitForUser();
     };
     return serviceAction;
 }
Esempio n. 40
0
    static void Main(string[] args)
    {
try
        {
            HiResTimer hres = new HiResTimer(); //High Resolution Timer
            Console.Write("\nStarting CommService write client");
            Console.Write("\n =============================\n");
            Console.Title = "Write Client";
            Message msg = new Message();
            WriterClient clnt = new WriterClient();
            clnt.processCommandLine(args);
            string localPort = Util.urlPort(clnt.localUrl);
            string localAddr = Util.urlAddress(clnt.localUrl);
            Receiver rcvr = new Receiver(localPort, localAddr);
            Action serviceAction = DefineServiceAction(hres, clnt, rcvr);
            if (rcvr.StartService())
                rcvr.doService(serviceAction);
            Sender sndr = new Sender(clnt.localUrl);  // Sender needs localUrl for start message         
            msg.fromUrl = clnt.localUrl;
            msg.toUrl = clnt.remoteUrl;
            Console.Write("Sender's url is {0}", msg.fromUrl);
            Console.Write("Attempting to connect to {0}\n", msg.toUrl);
            if (!sndr.Connect(msg.toUrl))
            {
                Console.Write("Could not connect in {0} attempts\n", sndr.MaxConnectAttempts);
                sndr.shutdown();
                rcvr.shutDown();
                return;
            }
            PerformanceTesting(hres, msg, clnt, rcvr, sndr);
        }
        catch (CustomException ex)
        {
            throw new CustomException("Error in main of writer client", ex);
        }
    }
    static void Main(string[] args)
    {
      Console.Write("{0}{1}",
        "\n  Time Parsing Operations ",
        "\n =========================\n"
      );

      OpTimer ot = new OpTimer();
      ot.Verbose = false;
      string fileName = "../../Test.cs";
      ot.ParseFile(fileName);

      HiResTimer hrt = new HiResTimer();
      hrt.Start();
      int N = 1000;
      for(int i=0; i<N; ++i)
        ot.HashLookUp("class");
      hrt.Stop();
      ulong lookUpTime = hrt.ElapsedMicroseconds;
      Console.Write("\n   {0} lookups took {1} microseconds",N,lookUpTime);
      Console.Write("\n\n");
      ot.showTable();
      Console.Write("\n\n");
    }
Esempio n. 42
0
		private void bnInvoke_Click(object sender, EventArgs e)
		{
			this.Cursor = Cursors.WaitCursor;
			
			try
			{
				Init();

				HiResTimer hrt = new HiResTimer();

				hrt.Start();
				object result = wsp.InvokeCall();
				hrt.Stop();

				tbElapsedTime.Text = hrt.ElapsedMicroseconds.ToString();
				tbResult.Text = result.ToString();

				if(wsp.EnableMessageAccess)
				{
					string tmpReqFile = SaveRequestToTempFile(wsp.SoapRequest);
					string tmpRespFile = SaveResponseToTempFile(wsp.SoapResponse);

					object obj = null;
					webBrowserRequest.Navigate ("file://" + tmpReqFile, ref obj, ref obj, ref obj, ref obj);
					webBrowserResponse.Navigate ("file://" + tmpRespFile, ref obj, ref obj, ref obj, ref obj);
				}
			}
			catch(Exception ex)
			{
				MessageBox.Show(ex.Message);
			}

			this.Cursor = Cursors.Default;
		}
 //Main function parses and sends the messages to server//
 static void Main(string[] args)        {
     Util.verbose = false;
     Server srvr = new Server();
     srvr.ProcessCommandLine(args);
     Console.Title = "Server";
     Console.Write(String.Format("\n  Starting CommService server listening on port {0}", srvr.port));
     Console.Write("\n ====================================================\n");
     Sender sndr = new Sender(Util.makeUrl(srvr.address, srvr.port));
     Receiver rcvr = new Receiver(srvr.port, srvr.address);
     Action serviceAction = () =>               {
         Message msg = null;
         DBEngine<int, DBElement<int, string>> dbserver = new DBEngine<int, DBElement<int, string>>(); //new DBEngine
         QueryEngine QE = new QueryEngine();
         HiResTimer timer = new HiResTimer(); //new object for timer
         while (true)                 {
             msg = rcvr.getMessage();   // note use of non-service method to deQ messages
             Console.Write("\n  Received message:");
             Console.Write("\n  sender is {0}", msg.fromUrl);
             Console.Write("\n  content is {0}\n", msg.content);
             if (msg.content == "connection start message")
                 continue; // don't send back start message
             if (msg.content == "done")
             { Console.Write("\n  client has finished\n");continue; }
             if (msg.content == "closeServer")
             {  Console.Write("received closeServer"); break; }
             timer.Start();                  //start timer
             XElement insertelem = XElement.Parse(msg.content);
             XElement res = new XElement("result", "not found");
             processor rdbserver = new processor();
             Console.WriteLine("\n----------write client operations----------");
             Console.WriteLine("\n");
             //----------select the required method to perform operations------------//
             if (insertelem.Element("Type").Value.Equals("Insert"))
                 res = rdbserver.insert(insertelem, dbserver);
                else if (insertelem.Element("Type").Value.Equals("Delete"))
                 res = rdbserver.Delete(insertelem, dbserver);
              else if (insertelem.Element("Type").Value.Equals("EditName"))
                 res = rdbserver.EditName(insertelem, dbserver);
              else if (insertelem.Element("Type").Value.Equals("getvalue"))
                 res = rdbserver.getvalue(insertelem, dbserver, QE);
              else if (insertelem.Element("Type").Value.Equals("EditDescr"))
                 res = rdbserver.editdescr(insertelem, dbserver);
              else if (insertelem.Element("Type").Value.Equals("getchildren"))
                 res = rdbserver.getchildren(insertelem, dbserver, QE);
             else if (insertelem.Element("Type").Value.Equals("Persist"))
                 res = rdbserver.persistdb(insertelem, dbserver);
             else   Console.Write("   operation failed   ");
              Console.WriteLine("\n-------------server response----------");
             XElement response = new XElement("resonse");
             response.Add(res);
             timer.Stop();              //stop timer
             Console.WriteLine("the time taken for operation is {0}", timer.ElapsedMicroseconds + " MicroSeconds ");
             srvr.send_wpf_msg(timer.ElapsedMicroseconds, sndr);
             Util.swapUrls(ref msg);
             msg.content = response.ToString();
             sndr.sendMessage(msg);             //sending message    
               }   };
     if (rcvr.StartService())
     rcvr.doService(serviceAction); // This serviceAction is asynchronous so the call doesn't block.
     Util.waitForUser();        }    }