Ejemplo n.º 1
0
        static void Main(string[] args)
        {
            SessionStartInfo info = new SessionStartInfo(headnode, serviceName);

            Console.Write("Creating a session for EchoService...");

            // Create a durable session
            // Request and response messages in a durable session are persisted so that
            // in event of failure, no requests nor responses will be lost.  Another authorized
            // client can attached to a session with the same session Id and retrieve responses
            using (DurableSession session = DurableSession.CreateSession(info))
            {
                Console.WriteLine("done session id = {0}", session.Id);

                Thread[] threads = new Thread[TotalThread];

                for (int i = 0; i < TotalThread; i++)
                {
                    threads[i] = new Thread(new ThreadStart(() => { Worker(session.Id); }));
                    threads[i].Start();
                }

                for (int i = 0; i < TotalThread; i++)
                {
                    threads[i].Join();
                }

                session.Close();
            }

            Console.WriteLine("Press any key to exit.");
            Console.Read();
        }
Ejemplo n.º 2
0
        private void retrieveResp()
        {
            #region Init
            result[] results = new result[10];
            for (int i = 0; i < 10; i++)
            {
                results[i] = new result();
            }
            #endregion

            SessionAttachInfo attachInfo = new SessionAttachInfo(Config.headNode, Convert.ToInt32(this.Range["D20", missing].Value2));

            using (DurableSession session = DurableSession.AttachSession(attachInfo))
            {
                using (BrokerClient <IService1> client = new BrokerClient <IService1>(session))
                {
                    foreach (BrokerResponse <PriceAsianOptionsResponse> response in client.GetResponses <PriceAsianOptionsResponse>())
                    {
                        cellContext idx   = response.GetUserData <cellContext>();
                        double      price = response.Result.PriceAsianOptionsResult;
                        Interlocked.Increment(ref results[idx.iteration].count);

                        this.Range[idx.range, missing].Value2 = price;

                        results[idx.iteration].min = Math.Min(results[idx.iteration].min, price);
                        results[idx.iteration].max = Math.Max(results[idx.iteration].max, price);

                        results[idx.iteration].sumPrice       += price;
                        results[idx.iteration].sumSquarePrice += price * price;

                        results[idx.iteration].stdDev = Math.Sqrt(results[idx.iteration].sumSquarePrice - results[idx.iteration].sumPrice * results[idx.iteration].sumPrice / results[idx.iteration].count) / ((results[idx.iteration].count == 1) ? 1 : results[idx.iteration].count - 1);
                        results[idx.iteration].stdErr = results[idx.iteration].stdDev / Math.Sqrt(results[idx.iteration].count);

                        if (results[idx.iteration].count == 100)
                        {
                            int i = idx.iteration;
                            this.Range[string.Format("{0}14", cols[i]), missing].Value2 = results[i].sumPrice / results[i].count;
                            this.Range[string.Format("{0}15", cols[i]), missing].Value2 = results[i].min;
                            this.Range[string.Format("{0}16", cols[i]), missing].Value2 = results[i].max;
                            this.Range[string.Format("{0}17", cols[i]), missing].Value2 = results[i].stdDev;
                            this.Range[string.Format("{0}18", cols[i]), missing].Value2 = results[i].stdErr;
                        }
                    }
                }
                session.Close();
            }

            #region Summarize
            for (int i = 0; i < 10; i++)
            {
                this.Range[string.Format("{0}14", cols[i]), missing].Value2 = results[i].sumPrice / results[i].count;
                this.Range[string.Format("{0}15", cols[i]), missing].Value2 = results[i].min;
                this.Range[string.Format("{0}16", cols[i]), missing].Value2 = results[i].max;
                this.Range[string.Format("{0}17", cols[i]), missing].Value2 = results[i].stdDev;
                this.Range[string.Format("{0}18", cols[i]), missing].Value2 = results[i].stdErr;
            }
            #endregion
        }
Ejemplo n.º 3
0
        static void Main(string[] args)
        {
            //change the headnode name here
            const string     headnode    = "[headnode]";
            const string     serviceName = "EchoService";
            const int        numRequests = 12;
            SessionStartInfo info        = new SessionStartInfo(headnode, serviceName);

            //session in the session pool should be a shared session
            info.ShareSession   = true;
            info.UseSessionPool = true;
            Console.Write("Creating a session using session pool for EchoService...");

            using (DurableSession session = DurableSession.CreateSession(info))
            {
                Console.WriteLine("done session id = {0}", session.Id);
                NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);

                //to make sure the client id is unique among the sessions
                string clientId = Guid.NewGuid().ToString();

                using (BrokerClient <IService1> client = new BrokerClient <IService1>(clientId, session, binding))
                {
                    Console.Write("Sending {0} requests...", numRequests);
                    for (int i = 0; i < numRequests; i++)
                    {
                        EchoRequest request = new EchoRequest("hello world!");
                        client.SendRequest <EchoRequest>(request, i);
                    }

                    client.EndRequests();
                    Console.WriteLine("done");

                    Console.WriteLine("Retrieving responses...");
                    foreach (var response in client.GetResponses <EchoResponse>())
                    {
                        try
                        {
                            string reply = response.Result.EchoResult;
                            Console.WriteLine("\tReceived response for request {0}: {1}", response.GetUserData <int>(), reply);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error occured while processing {0}-th request: {1}", response.GetUserData <int>(), ex.Message);
                        }
                    }

                    Console.WriteLine("Done retrieving {0} responses", numRequests);
                }

                //should not purge the session if the session is expected to stay in the session pool
                //the shared session is kept in the session pool
                session.Close(false);
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
Ejemplo n.º 4
0
        static void Main(string[] args)
        {
            try
            {
                //Input sessionId here
                int sessionId;
                Console.Write("Input the session id : ");
                sessionId = Int32.Parse(Console.ReadLine());

                //Change the headnode name here
                SessionAttachInfo info = new SessionAttachInfo("head.contoso.com", sessionId);

                //Attach to session
                DurableSession session = DurableSession.AttachSession(info);
                Console.WriteLine("Attached to session {0}", sessionId);

                int numberResponse = 0;

                //Get responses
                using (BrokerClient <IPrimeFactorization> client = new BrokerClient <IPrimeFactorization>(session))
                {
                    foreach (BrokerResponse <FactorizeResponse> response in client.GetResponses <FactorizeResponse>())
                    {
                        int   number  = response.GetUserData <int>();
                        int[] factors = response.Result.FactorizeResult;

                        Console.WriteLine("{0} = {1}", number, string.Join <int>(" * ", factors));

                        numberResponse++;
                    }
                }

                session.Close(true);
                Console.WriteLine("{0} responses have been received", numberResponse);

                Console.WriteLine("Press any key to exit");
                Console.ReadKey();
            }
            catch (System.Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Ejemplo n.º 5
0
        static void Main(string[] args)
        {
            //change the headnode name here
            const string headnode    = "[headnode]";
            const string serviceName = "Microsoft.Hpc.Excel.XllContainer64";

            //Query service versions of Microsoft.Hpc.Excel.XllContainer64
            Version[] versions = SessionBase.GetServiceVersions(headnode, serviceName);

            foreach (Version version in versions)
            {
                Console.WriteLine("Microsoft.Hpc.Excel.XllContainer64 version {0} is found in the service registration.", version.ToString());
            }

            //Get the latest version for the versions are already sorted,
            Version latest = versions[0];

            //Here is should be version 1.1 for v3 sp2
            Console.WriteLine("The latest version is {0}", latest);


            //Create a session for Microsoft.Hpc.Excel.XllContainer64 with the latest version
            SessionStartInfo info = new SessionStartInfo(headnode, serviceName, latest);

            Console.Write("Creating a session for Microsoft.Hpc.Excel.XllContainer64 version {0} ...", latest);

            // Create a durable session
            using (DurableSession session = DurableSession.CreateSession(info))
            {
                Console.WriteLine("done session id = {0}", session.Id);
                //explict close the session to free the resource
                session.Close();
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
Ejemplo n.º 6
0
        static void Main(string[] args)
        {
            //change the headnode name here
            const string headnode    = "[headnode]";
            const string serviceName = "EchoService";
            const int    numRequests = 8;

            SessionStartInfo info = new SessionStartInfo(headnode, serviceName);

            //the sample code needs at least 2 cores in the cluster
            info.SessionResourceUnitType = SessionUnitType.Core;
            info.MaximumUnits            = 2;
            info.MinimumUnits            = 2;

            Console.Write("Creating a session for EchoService...");
            using (DurableSession session = DurableSession.CreateSession(info))
            {
                Console.WriteLine("done session id = {0}", session.Id);
                NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);

                using (BrokerClient <IService1> client = new BrokerClient <IService1>(session, binding))
                {
                    Console.Write("Sending {0} requests...", numRequests);

                    for (int i = 0; i < numRequests; i++)
                    {
                        EchoOnExitRequest request = new EchoOnExitRequest(new TimeSpan(0, 0, 5));
                        client.SendRequest <EchoOnExitRequest>(request, i);
                    }

                    client.EndRequests();
                    Console.WriteLine("done");

                    // cancel half of the service tasks when processing the requests
                    ThreadPool.QueueUserWorkItem(delegate
                    {
                        //wait 5 seconds to try cancel service tasks.
                        Thread.Sleep(3 * 1000);
                        try
                        {
                            Scheduler scheduler = new Scheduler();
                            try
                            {
                                scheduler.Connect(headnode);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine("Error connecting store.{0}", e.ToString());
                                return;
                            }

                            int jobId         = session.GetProperty <int>("HPC_ServiceJobId");
                            ISchedulerJob job = scheduler.OpenJob(jobId);
                            job.Refresh();
                            ISchedulerCollection taskList = job.GetTaskList(null, null, true);
                            int onFlag = 0;
                            foreach (ISchedulerTask task in taskList)
                            {
                                // cancel half of the service tasks
                                if (onFlag++ % 2 == 0)
                                {
                                    try
                                    {
                                        if (task.State == TaskState.Running)
                                        {
                                            Console.WriteLine("Try to cancel task {0}", task.TaskId);
                                            job.CancelTask(task.TaskId);
                                            job.Commit();
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine("Got exception when trying to cancel task {0}:{1}", task.TaskId, ex.Message);
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Exception when trying to cancel the service tasks. {0}", ex.Message);
                        }
                    });


                    Console.WriteLine("Retrieving responses...");

                    try
                    {
                        int count = 0;

                        foreach (var response in client.GetResponses <EchoOnExitResponse>())
                        {
                            try
                            {
                                string reply = response.Result.EchoOnExitResult;
                                Console.WriteLine("\tReceived response for request {0}: {1}", response.GetUserData <int>(), reply);
                                count++;
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Error occured while processing {0}-th request: {1}", response.GetUserData <int>(), ex.Message);
                            }
                        }

                        Console.WriteLine("Done retrieving responses.{0}/{1} responses retrieved ", count, numRequests);
                    }
                    catch (SessionException ex)
                    {
                        Console.WriteLine("SessionException while getting responses: {0}", ex.Message);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception while getting responses: {0}", ex.Message);
                    }
                }

                // Close connections and delete messages stored in the system
                session.Close();

                Console.WriteLine("Press any key to exit.");
                Console.ReadKey();
            }
        }
Ejemplo n.º 7
0
        static void Main(string[] args)
        {
            //change the headnode name here
            const string     headnode    = "[headnode]";
            const string     serviceName = "EchoService";
            const int        numRequests = 12;
            SessionStartInfo info        = new SessionStartInfo(headnode, serviceName);

            Console.Write("Creating a session for EchoService...");

            // Create a durable session
            // Request and response messages in a durable session are persisted so that
            // in event of failure, no requests nor responses will be lost.  Another authorized
            // client can attached to a session with the same session Id and retrieve responses
            using (DurableSession session = DurableSession.CreateSession(info))
            {
                Console.WriteLine("done session id = {0}", session.Id);
                NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);

                // Create a BrokerClient proxy
                // This proxy is able to map One-Way, Duplex message exchange patterns
                // with the Request / Reply Services.  As such, the client program can send the
                // requests, exit and re-attach to the session to retrieve responses (see the
                // FireNRecollect project for details
                using (BrokerClient <IService1> client = new BrokerClient <IService1>(session, binding))
                {
                    Console.Write("Sending {0} requests...", numRequests);
                    for (int i = 0; i < numRequests; i++)
                    {
                        // EchoRequest are created as you add Service Reference
                        // EchoService to the project
                        EchoRequest request = new EchoRequest("hello world!");
                        client.SendRequest <EchoRequest>(request, i);
                    }

                    // Flush the message.  After this call, the runtime system
                    // starts processing the request messages.  If this call is not called,
                    // the system will not process the requests.  The client.GetResponses() will return
                    // with an empty collection
                    client.EndRequests();
                    Console.WriteLine("done");

                    Console.WriteLine("Retrieving responses...");

                    // GetResponses from the runtime system
                    // EchoResponse class is created as you add Service Reference "EchoService"
                    // to the project
                    foreach (var response in client.GetResponses <EchoResponse>())
                    {
                        try
                        {
                            string reply = response.Result.EchoResult;
                            Console.WriteLine("\tReceived response for request {0}: {1}", response.GetUserData <int>(), reply);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Error occured while processing {0}-th request: {1}", response.GetUserData <int>(), ex.Message);
                        }
                    }

                    Console.WriteLine("Done retrieving {0} responses", numRequests);
                }

                //explict close the session to free the resource
                session.Close();
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
Ejemplo n.º 8
0
        public void BvtDurableCase3()
        {
            Info("Start BVT");
            SessionStartInfo sessionStartInfo;

            sessionStartInfo              = BuildSessionStartInfo(Server, EchoSvcName, null, null, null, null, SessionUnitType.Node, null, null, null);
            sessionStartInfo.Secure       = false;
            sessionStartInfo.ShareSession = true;

            Info("Begin to create session");
            string         serviceJobId;
            int            clientNum     = 2;
            AutoResetEvent anotherClient = new AutoResetEvent(false);

            using (DurableSession session = DurableSession.CreateSession(sessionStartInfo))
            {
                serviceJobId = session.Id;
                var epr = new EndpointAddress(string.Format(NetTcpEndpointPattern, Server, serviceJobId));
                Info("EPR: {0}", epr);
                Task[] tasks = new Task[clientNum];
                for (int i = 0; i < clientNum; i++)
                {
                    var idx = i;
                    tasks[i] = Task.Run(
                        () =>
                    {
                        string guid = Guid.NewGuid().ToString();
                        try
                        {
                            Info("Client {0}: Begin to send requests.", guid);
                            using (BrokerClient <IEchoSvc> client = new BrokerClient <IEchoSvc>(guid, session))
                            {
                                for (int j = 0; j < NumberOfCalls; j++)
                                {
                                    client.SendRequest <EchoRequest>(new EchoRequest(j.ToString()), j + ":" + guid);
                                }

                                Info("Client {0}: Begin to call EndOfMessage.", guid);
                                client.EndRequests();
                                Info("Client {0}: Begin to get responses.", guid);
                                int count = 0;
                                if (idx == 0)
                                {
                                    foreach (BrokerResponse <EchoResponse> response in client.GetResponses <EchoResponse>())
                                    {
                                        count++;
                                        Info(response.Result.EchoResult);
                                        string[] rtn = response.Result.EchoResult.Split(new[] { ':' });
                                        Assert(
                                            rtn[rtn.Length - 1] == response.GetUserData <string>().Split(new[] { ':' })[0] && response.GetUserData <string>().Split(new[] { ':' })[1] == guid,
                                            "Result is corrupt: expected:computername:{0}, actual:{1}",
                                            response.GetUserData <string>().Split(new[] { ':' })[0],
                                            response.Result.EchoResult);
                                    }
                                }
                                else
                                {
                                    foreach (var response in client.GetResponses())
                                    {
                                        count++;
                                        EchoResponse result = (EchoResponse)response.Result;
                                        Info(result.EchoResult);
                                        string[] rtn = result.EchoResult.Split(new[] { ':' });
                                        Assert(
                                            rtn[rtn.Length - 1] == response.GetUserData <string>().Split(new[] { ':' })[0] && response.GetUserData <string>().Split(new[] { ':' })[1] == guid,
                                            "Result is corrupt: expected:computername:{0}, actual:{1}",
                                            response.GetUserData <string>(),
                                            result.EchoResult);
                                    }
                                }

                                if (count == NumberOfCalls)
                                {
                                    Info("Client {0}: Total {1} calls returned.", guid, count);
                                }
                                else
                                {
                                    Error("Client {0}: Total {1} calls returned, but losing {2} results.", guid, count, NumberOfCalls - count);
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            Error("Unexpected exception of Client {0}", e.ToString());
                            throw;
                        }
                        finally
                        {
                            if (Interlocked.Decrement(ref clientNum) <= 0)
                            {
                                anotherClient.Set();
                            }
                        }
                    });
                }

                anotherClient.WaitOne();
                Task.WaitAll(tasks);
                session.Close(true);
                session.Dispose();
            }
        }
Ejemplo n.º 9
0
        public void BvtDurableCase1()
        {
            Info("Start BVT");
            SessionStartInfo sessionStartInfo;

            sessionStartInfo        = BuildSessionStartInfo(Server, EchoSvcName, null, null, null, null, SessionUnitType.Node, null, null, null);
            sessionStartInfo.Secure = false;
            string serviceJobId;

            Info("Begin to create Durable Session.");
            string guid = Guid.NewGuid().ToString();

            using (DurableSession session = DurableSession.CreateSession(sessionStartInfo))
            {
                serviceJobId = session.Id;
                var epr = new EndpointAddress(string.Format(NetTcpEndpointPattern, Server, serviceJobId));
                Info("EPR: {0}", epr);
                try
                {
                    Info("Client {0}: Begin to send requests.", guid);
                    using (BrokerClient <IEchoSvc> client = new BrokerClient <IEchoSvc>(guid, session))
                    {
                        for (int i = 0; i < NumberOfCalls; i++)
                        {
                            client.SendRequest <EchoRequest>(new EchoRequest(i.ToString()), i + ":" + guid);
                        }

                        Info("Client {0}: Begin to call EndOfMessage.", guid);
                        client.EndRequests();
                    }
                }
                catch (Exception e)
                {
                    Error("Unexpected exception of Client {0}", e.ToString());
                    throw;
                }
            }

            // sleep 10 seconds
            Info("Client disconnects and sleep 10 seconds");
            Thread.Sleep(10000);

            SessionAttachInfo sessionAttachInfo = new SessionAttachInfo(Server, serviceJobId);
            int count = 0;

            Info("Begin to attach Durable Session.");
            try
            {
                using (DurableSession session = DurableSession.AttachSession(sessionAttachInfo))
                {
                    Info("Begin to retrieve results.");
                    using (BrokerClient <IEchoSvc> client = new BrokerClient <IEchoSvc>(guid, session))
                    {
                        foreach (BrokerResponse <EchoResponse> response in client.GetResponses <EchoResponse>())
                        {
                            Info(response.Result.EchoResult);
                            string[] rtn = response.Result.EchoResult.Split(new[] { ':' });
                            Assert(
                                rtn[rtn.Length - 1] == response.GetUserData <string>().Split(new[] { ':' })[0] && response.GetUserData <string>().Split(new[] { ':' })[1] == guid,
                                "Result is corrupt: expected:computername:{0}, actual:{1}",
                                response.GetUserData <string>().Split(new[] { ':' })[0],
                                response.Result.EchoResult);
                            count++;
                        }
                    }

                    session.Close();
                }

                if (NumberOfCalls == count)
                {
                    Info("Total {0} calls returned.", count);
                }
                else
                {
                    Error("Total {0} calls returned, but losing {1} results.\n", count, NumberOfCalls - count);
                }
            }
            catch (Exception e)
            {
                Error("Unexpected exception during attaching and getting response {0}", e.ToString());
                throw;
            }
        }
Ejemplo n.º 10
0
        static void Main(string[] args)
        {
            const string headnode    = "[headnode]";
            const string serviceName = "EchoService";

            if (args.Length == 1)
            {
                // attach to the session
                int sessionId          = Int32.Parse(args[0]);
                SessionAttachInfo info = new SessionAttachInfo(headnode, sessionId);

                Console.Write("Attaching to session {0}...", sessionId);
                // Create attach to a session
                using (DurableSession session = DurableSession.AttachSession(info))
                {
                    Console.WriteLine("done.");

                    // Create a client proxy
                    using (BrokerClient <IService1> client = new BrokerClient <IService1>(session))
                    {
                        Console.WriteLine("Retrieving results...");
                        // Get all the results
                        foreach (BrokerResponse <EchoResponse> response in client.GetResponses <EchoResponse>())
                        {
                            string reply = response.Result.EchoResult;
                            Console.WriteLine("\tReceived response for request {0}: {1}", response.GetUserData <int>(), reply);
                        }
                        Console.WriteLine("Done retrieving results.");
                    }

                    // Close the session to reclaim the system storage
                    // used to store the results.  After the session is closed
                    // you cannot attatch to the same session again
                    session.Close();
                }
            }
            else
            {
                // Create a durable session, fire the requests and exit
                SessionStartInfo info = new SessionStartInfo(headnode, serviceName);
                Console.Write("Creating a session...");
                using (DurableSession session = DurableSession.CreateSession(info))
                {
                    Console.WriteLine("done session id = {0}.", session.Id);
                    NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);

                    using (BrokerClient <IService1> client = new BrokerClient <IService1>(session, binding))
                    {
                        Console.Write("Sending requests...");
                        for (int i = 0; i < 12; i++)
                        {
                            EchoRequest request = new EchoRequest("hello world!");
                            client.SendRequest <EchoRequest>(request, i);
                        }
                        client.EndRequests();
                        Console.WriteLine("done");
                    }

                    Console.WriteLine("Type \"FileNRecollect.exe {0}\" to collect the results", session.Id);
                }
            }
        }
Ejemplo n.º 11
0
        private void submitReq()
        {
            #region Initialization
            double initial       = (double)rngInitial.Value2;
            double exercise      = (double)rngInitial.Value2;
            double up            = (double)rngUp.Value2;
            double down          = (double)rngDown.Value2;
            double interest      = (double)rngInterest.Value2;
            int    periods       = Convert.ToInt32(rngPeriods.Value2);
            int    runs          = Convert.ToInt32(rngRuns.Value2);
            double interestStart = (double)rngInterestStart.Value2;
            double interestEnd   = (double)rngInterestEnd.Value2;
            double interestStep  = (double)rngStep.Value2;
            #endregion

            #region fire request

            SessionStartInfo info = new SessionStartInfo(Config.headNode, "AsianOptionsService");
            info.Secure = false;
            info.BrokerSettings.SessionIdleTimeout = 12 * 60 * 60; // 12 hours

            DurableSession.SetInterfaceMode(false, IntPtr.Zero);   //set interface mode to non console

            using (DurableSession session = DurableSession.CreateSession(info))
            {
                this.Range["C20", missing].Value2 = "Session Created. SessionId";
                this.Range["D20", missing].Value2 = session.Id;
                Thread.Sleep(1000);
                this.Range["C21", missing].Value2 = " Sending Req...";

                NetTcpBinding binding;
                binding = new NetTcpBinding(SecurityMode.None);

                using (BrokerClient <IService1> client = new BrokerClient <IService1>(session, binding))
                {
                    int count    = 0;
                    int reqCount = 0;

                    for (double interestIdx = interestStart; interestIdx < interestEnd; interestIdx += interestStep, count++)
                    {
                        this.Range["C21", missing].Value2 = string.Format("Sending Req Batch {0}", count);

                        bool batch_succeed    = false;
                        int  batch_retrycount = 0;

                        while (!batch_succeed && batch_retrycount < 3)
                        {
                            for (int j = 0; j < cols.Length; j++)
                            {
                                string col = cols[j];

                                for (int i = 2; i <= 11; i++)
                                {
                                    PriceAsianOptionsRequest priceRequest = new PriceAsianOptionsRequest(initial, exercise, up, down, interestIdx, periods, runs);
                                    cellContext ctx = new cellContext();
                                    ctx.range     = string.Format("{0}{1}", col, i);
                                    ctx.iteration = count;

                                    bool i_succeed    = false;
                                    int  i_retrycount = 0;
                                    while (!i_succeed && i_retrycount < 3)
                                    {
                                        try
                                        {
                                            client.SendRequest <PriceAsianOptionsRequest>(priceRequest, ctx);
                                            i_succeed = true;
                                            this.Range["D21", missing].Value2 = string.Format("{0} Req sent.", ++reqCount);
                                        }
                                        catch (Exception)
                                        {
                                            // Populate the cell with an error message
                                            this.Range[ctx.range, missing].Value2 = "#SendErr#";
                                            i_retrycount++;
                                        }
                                    }

                                    if (!i_succeed)
                                    {
                                        this.Range["C22", missing].Value2 = "Session failed.";
                                        this.Range["D20", missing].Clear();
                                        session.Close();
                                        return;
                                    }
                                }
                            }

                            try
                            {
                                client.Flush();
                                this.Range["C22", missing].Value2 = string.Format("Req Batch {0} Flushed.", count);
                                batch_succeed = true;
                            }
                            catch (Exception)
                            {
                                // Populate the cell with an error message
                                this.Range["C22", missing].Value2 = "ClientFlush failed.";
                                batch_retrycount++;
                            }

                            if (!batch_succeed)
                            {
                                this.Range["C22", missing].Value2 = "Session failed.";
                                this.Range["D20", missing].Clear();
                                session.Close();
                                return;
                            }
                        }
                    }

                    client.EndRequests();
                    this.Range["C21", missing].Value2 = "Closing.";
                }
            }

            this.Range["C21", missing].Value2 = "Request sent.";
            this.Range["C22", missing].Value2 = "Request flushed.";

            #endregion
        }
Ejemplo n.º 12
0
        static void Main(string[] args)
        {
            //change the headnode name here
            const string     headnode    = "[headnode]";
            const string     serviceName = "EchoService";
            const int        numRequests = 12;
            SessionStartInfo startInfo   = new SessionStartInfo(headnode, serviceName);

            startInfo.BrokerSettings.SessionIdleTimeout = 15 * 60 * 1000;
            startInfo.BrokerSettings.ClientIdleTimeout  = 15 * 60 * 1000;

            Console.Write("Creating a session for EchoService...");

            // Create a durable session
            int       sessionId       = 0;
            const int retryCountMax   = 20;
            const int retryIntervalMs = 5000;

            DurableSession session = DurableSession.CreateSession(startInfo);

            sessionId = session.Id;
            Console.WriteLine("Done session id = {0}", sessionId);


            //send requests with reliable broker client
            bool successFlag = false;
            int  retryCount  = 0;

            using (BrokerClient <IService1> client = new BrokerClient <IService1>(session))
            {
                Console.Write("Sending {0} requests...", numRequests);
                while (!successFlag && retryCount++ < retryCountMax)
                {
                    try
                    {
                        for (int i = 0; i < numRequests; i++)
                        {
                            client.SendRequest <EchoRequest>(new EchoRequest(i.ToString()), i);
                        }

                        client.EndRequests();
                        successFlag = true;
                        Console.WriteLine("done");
                    }
                    catch (Exception e)
                    {
                        //general exceptions
                        Console.WriteLine("Exception {0}", e.ToString());
                        Thread.Sleep(retryIntervalMs);
                    }
                }
            }


            //attach the session
            SessionAttachInfo attachInfo = new SessionAttachInfo(headnode, sessionId);

            successFlag = false;
            retryCount  = 0;
            Console.WriteLine("Retrieving responses...");
            using (BrokerClient <IService1> client = new BrokerClient <IService1>(session))
            {
                int responseCount = 0;
                retryCount = 0;
                while (responseCount < numRequests && retryCount++ < retryCountMax)
                {
                    try
                    {
                        foreach (var response in client.GetResponses <EchoResponse>())
                        {
                            Console.WriteLine("\tReceived response for request {0}: {1}", response.GetUserData <int>(), response.Result.EchoResult);
                            responseCount++;
                        }
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine(e.ToString());
                        Thread.Sleep(retryIntervalMs);
                    }
                }
            }

            Console.WriteLine("Close the session...");
            session.Close(true);

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
Ejemplo n.º 13
0
        static void Main(string[] args)
        {
            //change the headnode name  here
            const string headnode    = "[headnode]";
            const string serviceName = "EchoService";
            const int    numRequests = 100;

            SessionStartInfo info = new SessionStartInfo(headnode, serviceName);

            //the cluster need to have a minimum 2 cores to run this sample code
            info.SessionResourceUnitType = SessionUnitType.Core;
            info.MaximumUnits            = 2;
            info.MinimumUnits            = 2;

            Console.Write("Creating a session for EchoService...");

            using (DurableSession session = DurableSession.CreateSession(info))
            {
                Console.WriteLine("done session id = {0}", session.Id);
                NetTcpBinding binding   = new NetTcpBinding(SecurityMode.Transport);
                int           sessionId = session.Id;
                using (BrokerClient <IService1> client = new BrokerClient <IService1>(session, binding))
                {
                    Console.Write("Sending {0} requests...", numRequests);

                    for (int i = 0; i < numRequests; i++)
                    {
                        EchoOnExitRequest request = new EchoOnExitRequest(new TimeSpan(0, 0, 1));
                        client.SendRequest <EchoOnExitRequest>(request, i);
                    }

                    client.EndRequests();
                    Console.WriteLine("done");

                    //separate a work thread to purge the client when the requests are processing
                    ThreadPool.QueueUserWorkItem(delegate
                    {
                        //wait 30 seconds to try cancel service tasks.
                        Console.Write("Will cancel the requests in 30 seconds.");
                        Thread.Sleep(30 * 1000);
                        try
                        {
                            client.Close(true);
                            Console.WriteLine("The broker client is purged.");
                        }
                        catch (Exception ee)
                        {
                            Console.WriteLine("Exception in callback when purging the client. {0}", ee.ToString());
                        }
                    });

                    // retieving the responses
                    Console.WriteLine("Retrieving responses...");

                    try
                    {
                        int count = 0;

                        foreach (var response in client.GetResponses <EchoOnExitResponse>())
                        {
                            try
                            {
                                string reply = response.Result.EchoOnExitResult;
                                Console.WriteLine("\tReceived response for request {0}: {1}", response.GetUserData <int>(), reply);
                                count++;
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Error occured while processing {0}-th request: {1}", response.GetUserData <int>(), ex.Message);
                            }
                        }

                        Console.WriteLine("Done retrieving responses.{0}/{1} responses retrieved ", count, numRequests);
                    }
                    catch (SessionException ex)
                    {
                        Console.WriteLine("SessionException while getting responses: {0}", ex.Message);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine("Exception while getting responses: {0}", ex.Message);
                    }
                }

                // Close the session.
                session.Close();

                Console.WriteLine("Press any key to exit.");
                Console.ReadKey();
            }
        }
Ejemplo n.º 14
0
        private static void V3ClientSample(SessionStartInfo startInfo)
        {
            using (DurableSession session = DurableSession.CreateSession(startInfo))
            {
                using (BrokerClient <IGenericServiceV3> client = new BrokerClient <IGenericServiceV3>(session))
                {
                    GenericServiceRequest request1 = new GenericServiceRequest();
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (BinaryWriter writer = new BinaryWriter(ms))
                        {
                            writer.Write((int)0);
                            writer.Write((int)123);
                        }

                        request1.Data = Convert.ToBase64String(ms.ToArray());
                    }

                    // Use user data to differentiate operations
                    // 0 stands for GetData()
                    // 1 stands for GetDataUsingDataContract()
                    client.SendRequest <GenericServiceRequest>(request1, 0);

                    GenericServiceRequest request2 = new GenericServiceRequest();
                    using (MemoryStream ms = new MemoryStream())
                    {
                        using (BinaryWriter writer = new BinaryWriter(ms))
                        {
                            writer.Write((int)1);
                            writer.Write(true);
                            writer.Write("DataData");
                        }

                        request2.Data = Convert.ToBase64String(ms.ToArray());
                    }

                    client.SendRequest <GenericServiceRequest>(request2, 1);
                    client.EndRequests();

                    foreach (BrokerResponse <GenericServiceResponse> response in client.GetResponses <GenericServiceResponse>())
                    {
                        int operationIndex = response.GetUserData <int>();
                        switch (operationIndex)
                        {
                        case 0:
                            // GetData
                            Console.WriteLine("GetDataResult: {0}", response.Result.Data);
                            break;

                        case 1:
                            // GetDataUsingDataContract
                            CompositeType result;
                            using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(response.Result.Data)))
                                using (BinaryReader reader = new BinaryReader(ms))
                                {
                                    result             = new CompositeType();
                                    result.BoolValue   = reader.ReadBoolean();
                                    result.StringValue = reader.ReadString();
                                }

                            Console.WriteLine("GetDataUsingDataContractResult: BoolValue={0}\tStringValue={1}", result.BoolValue, result.StringValue);
                            break;
                        }
                    }
                }

                session.Close();
            }
        }
Ejemplo n.º 15
0
        static void Main(string[] args)
        {
            //change the headnode name here
            const string     headnode    = "[headnode]";
            const string     serviceName = "EchoService";
            const int        numRequests = 12;
            SessionStartInfo startInfo   = new SessionStartInfo(headnode, serviceName);

            startInfo.BrokerSettings.SessionIdleTimeout = 15 * 60 * 1000;
            startInfo.BrokerSettings.ClientIdleTimeout  = 15 * 60 * 1000;

            Console.Write("Creating a session for EchoService...");

            // Create a durable session
            int            sessionId       = 0;
            DurableSession session         = null;
            bool           successFlag     = false;
            int            retryCount      = 0;
            const int      retryCountMax   = 20;
            const int      retryIntervalMs = 5000;

            while (!successFlag && retryCount++ < retryCountMax)
            {
                try
                {
                    session     = DurableSession.CreateSession(startInfo);
                    successFlag = true;
                }
                catch (EndpointNotFoundException e)
                {
                    Console.WriteLine("EndpointNotFoundException {0}", e.ToString());
                }
                catch (CommunicationException e)
                {
                    Console.WriteLine("CommunicationException {0}", e.ToString());
                }
                catch (TimeoutException e)
                {
                    Console.WriteLine("TimeoutException {0}", e.ToString());
                }
                catch (SessionException e)
                {
                    Console.WriteLine("SessionException {0}, error code 0x{1:x}", e.ToString(), e.ErrorCode);
                    // if session fatal errors happen, no retry
                    if (SOAFaultCode.Category(e.ErrorCode).Equals(SOAFaultCodeCategory.SessionFatalError))
                    {
                        Console.WriteLine("SessionExceptionCategory : SessionFatalError {0}", e.ToString());
                        Console.WriteLine("No retry.");
                        retryCount = retryCountMax;
                        continue;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("General exception {0}", e.ToString());
                }

                if (!successFlag)
                {
                    Console.WriteLine("=== Sleep {0} ms to retry. Retry count left {1}. ===", retryIntervalMs, retryCountMax - retryCount);
                    Thread.Sleep(retryIntervalMs);
                }
            }

            if (!successFlag)
            {
                Console.WriteLine("Create durable session failed.");
                return;
            }

            sessionId = session.Id;
            Console.WriteLine("Done session id = {0}", sessionId);


            //send requests
            successFlag = false;
            retryCount  = 0;
            const int sendTimeoutMs = 5000;

            const int clientPurgeTimeoutMs = 60000;

            while (!successFlag && retryCount++ < retryCountMax)
            {
                using (BrokerClient <IService1> client = new BrokerClient <IService1>(session))
                {
                    Console.Write("Sending {0} requests...", numRequests);

                    try
                    {
                        for (int i = 0; i < numRequests; i++)
                        {
                            //client.SendRequest<EchoFaultRequest>(new EchoFaultRequest("dividebyzeroexception"), i, sendTimeoutMs);
                            client.SendRequest <EchoDelayRequest>(new EchoDelayRequest(5000), i, sendTimeoutMs);
                        }

                        client.EndRequests();
                        successFlag = true;
                        Console.WriteLine("done");
                    }

                    catch (TimeoutException e)
                    {
                        // Timeout exceptions
                        Console.WriteLine("TimeoutException {0}", e.ToString());
                    }
                    catch (CommunicationException e)
                    {
                        //CommunicationException
                        Console.WriteLine("CommunicationException {0}", e.ToString());
                    }
                    catch (SessionException e)
                    {
                        Console.WriteLine("SessionException {0}, error code 0x{1:x}", e.ToString(), e.ErrorCode);

                        if (SOAFaultCode.Broker_BrokerUnavailable == e.ErrorCode)
                        {
                            Console.WriteLine("SessionException : BrokerUnavailable {0}", e.ToString());
                        }
                        // Session Exceptions are unrecoverable unless they are application errors
                        if (SOAFaultCode.Category(e.ErrorCode).Equals(SOAFaultCodeCategory.ApplicationError))
                        {
                            Console.WriteLine("SessionExceptionCategory : ApplicationError {0}", e.ToString());
                        }

                        // if session fatal errors happen, no retry
                        if (SOAFaultCode.Category(e.ErrorCode).Equals(SOAFaultCodeCategory.SessionFatalError))
                        {
                            Console.WriteLine("SessionExceptionCategory : SessionFatalError {0}", e.ToString());
                            Console.WriteLine("No retry.");
                            retryCount = retryCountMax;
                            continue;
                        }
                    }
                    catch (Exception e)
                    {
                        //general exceptions
                        Console.WriteLine("Exception {0}", e.ToString());
                    }

                    //purge client if not succeeded, needed?
                    if (!successFlag)
                    {
                        try
                        {
                            client.Close(true, clientPurgeTimeoutMs);
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Failed to purge the client after send request failure {0}", e.ToString());
                        }
                    }
                }

                if (!successFlag)
                {
                    Console.WriteLine("=== Sleep {0} ms to retry. Retry count left {1}. ===", retryIntervalMs, retryCountMax - retryCount);
                    Thread.Sleep(retryIntervalMs);
                }
            }

            if (!successFlag)
            {
                Console.WriteLine("Send requests failed.");
                return;
            }

            //dispose the session here
            session.Dispose();

            //attach the session
            SessionAttachInfo attachInfo = new SessionAttachInfo(headnode, sessionId);


            successFlag = false;
            retryCount  = 0;
            const int attachTimeoutMs = 15000;

            while (!successFlag && retryCount++ < retryCountMax)
            {
                try
                {
                    session     = DurableSession.AttachSession(attachInfo);
                    successFlag = true;
                }
                catch (EndpointNotFoundException e)
                {
                    Console.WriteLine("{0}", e.ToString());
                }
                catch (CommunicationException e)
                {
                    Console.WriteLine("{0}", e.ToString());
                }
                catch (SessionException e)
                {
                    Console.WriteLine("SessionException {0}, error code 0x{1:x}", e.ToString(), e.ErrorCode);
                    // if session fatal errors happen, no retry
                    if (SOAFaultCode.Category(e.ErrorCode).Equals(SOAFaultCodeCategory.SessionFatalError))
                    {
                        Console.WriteLine("SessionExceptionCategory : SessionFatalError {0}", e.ToString());
                        Console.WriteLine("No retry.");
                        retryCount = retryCountMax;
                        continue;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("General exception {0}", e.ToString());
                }

                if (!successFlag)
                {
                    Console.WriteLine("=== Sleep {0} ms to retry. Retry count left {1}. ===", retryIntervalMs, retryCountMax - retryCount);
                    Thread.Sleep(retryIntervalMs);
                }
            }

            if (!successFlag)
            {
                Console.WriteLine("Attach durable session failed.");
                return;
            }



            successFlag = false;
            retryCount  = 0;
            const int getTimeoutMs         = 30000;
            const int clientCloseTimeoutMs = 15000;

            Console.WriteLine("Retrieving responses...");
            while (!successFlag && retryCount++ < retryCountMax)
            {
                using (BrokerClient <IService1> client = new BrokerClient <IService1>(session))
                {
                    // GetResponses from the runtime system
                    // EchoResponse class is created as you add Service Reference "EchoService" to the project
                    try
                    {
                        //foreach (var response in client.GetResponses<EchoFaultResponse>(getTimeoutMs))
                        foreach (var response in client.GetResponses <EchoDelayResponse>(getTimeoutMs))
                        {
                            try
                            {
                                //string reply = response.Result.EchoFaultResult ;
                                int reply = response.Result.EchoDelayResult;
                                Console.WriteLine("\tReceived response for delay request {0}: {1}", response.GetUserData <int>(), reply);
                            }
                            catch (FaultException <DivideByZeroException> e)
                            {
                                // Application exceptions
                                Console.WriteLine("FaultException<DivideByZeroException> {0}", e.ToString());
                            }
                            catch (FaultException e)
                            {
                                // Application exceptions
                                Console.WriteLine("FaultException {0}", e.ToString());
                            }
                            catch (RetryOperationException e)
                            {
                                // RetryOperationExceptions may or may not be recoverable
                                Console.WriteLine("RetryOperationException {0}", e.ToString());
                            }
                        }

                        successFlag = true;
                        Console.WriteLine("Done retrieving {0} responses", numRequests);
                    }

                    catch (TimeoutException e)
                    {
                        // Timeout exceptions
                        Console.WriteLine("TimeoutException {0}", e.ToString());
                    }
                    catch (CommunicationException e)
                    {
                        //CommunicationException
                        Console.WriteLine("CommunicationException {0}", e.ToString());
                    }
                    catch (SessionException e)
                    {
                        Console.WriteLine("SessionException {0}, error code 0x{1:x}", e.ToString(), e.ErrorCode);

                        if (SOAFaultCode.Broker_BrokerUnavailable == e.ErrorCode)
                        {
                            Console.WriteLine("SessionException : BrokerUnavailable {0}", e.ToString());
                        }
                        // Session Exceptions are unrecoverable unless they are application errors
                        if (SOAFaultCode.Category(e.ErrorCode).Equals(SOAFaultCodeCategory.ApplicationError))
                        {
                            Console.WriteLine("SessionExceptionCategory : ApplicationError {0}", e.ToString());
                        }
                        // if session fatal errors happen, no retry
                        if (SOAFaultCode.Category(e.ErrorCode).Equals(SOAFaultCodeCategory.SessionFatalError))
                        {
                            Console.WriteLine("SessionExceptionCategory : SessionFatalError {0}", e.ToString());
                            Console.WriteLine("No retry.");
                            retryCount = retryCountMax;
                            continue;
                        }
                    }
                    catch (Exception e)
                    {
                        //general exceptions
                        Console.WriteLine("Exception {0}", e.ToString());
                    }

                    try
                    {
                        client.Close(false, clientCloseTimeoutMs);
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("Exception", e.ToString());
                    }
                }

                if (!successFlag)
                {
                    Console.WriteLine("=== Sleep {0} ms to retry. Retry count left {1}. ===", retryIntervalMs, retryCountMax - retryCount);
                    Thread.Sleep(retryIntervalMs);
                }
            }

            //explict close the session to free the resource
            successFlag = false;
            retryCount  = 0;

            Console.WriteLine("Close the session...");
            while (!successFlag && retryCount++ < retryCountMax)
            {
                try
                {
                    session.Close(true);
                    successFlag = true;
                }
                catch (SessionException e)
                {
                    Console.WriteLine("SessionException {0}, error code 0x{1:x}", e.ToString(), e.ErrorCode);
                    // if session fatal errors happen, no retry
                    if (SOAFaultCode.Category(e.ErrorCode).Equals(SOAFaultCodeCategory.SessionFatalError))
                    {
                        Console.WriteLine("SessionExceptionCategory : SessionFatalError {0}", e.ToString());
                        Console.WriteLine("No retry.");
                        retryCount = retryCountMax;
                        continue;
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine("{0}", e.ToString());
                }

                if (!successFlag)
                {
                    Console.WriteLine("=== Sleep {0} ms to retry. Retry count left {1}. ===", retryIntervalMs, retryCountMax - retryCount);
                    Thread.Sleep(retryIntervalMs);
                }
            }

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }