Exemplo n.º 1
0
        static void Main(string[] args)
        {
            if (args.Length >= 1)
            {
                name = args[0];
            }

            if (args.Length >= 2)
            {
                headnode = args[1];
            }

            if (args.Length >= 3)
            {
                messageCount = int.Parse(args[2]);
            }

            Console.WriteLine("Creating session...");

            using (Session session = Session.CreateSession(new SessionStartInfo(headnode, "HelloWorld")))
            {
                using (BrokerClient<IHelloWorld> brokerClient = new BrokerClient<IHelloWorld>(session))
                {
                    brokerClient.SetResponseHandler<SayHelloResponse>(ResponseHandler);

                    Console.WriteLine("Sending requests...");

                    for (int i = 0; i < messageCount; i++)
                    {
                        brokerClient.SendRequest(new SayHelloRequest(name));
                    }

                    Console.WriteLine("Committing requests...");

                    brokerClient.EndRequests();

                    Console.WriteLine("Waiting for responses...");
                    Console.ReadLine();
                }
            }
        }
Exemplo n.º 2
0
        public static void SendRequests(Session session, List<BrokerClient<ISoamSvc>> clientList)
        {
            ThreadStart runnalbe = new ThreadStart(() =>
            {

                // 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
                String clientId = Guid.NewGuid().ToString();
                BrokerClient<ISoamSvc> client = new BrokerClient<ISoamSvc>(clientId, session);
                clientList.Add(client);

                for (int i = 0; i < numBatchRequests; i++)
                {
                    // SoamInvokeRequest are created as you add Service Reference
                    // SoamInvokeService to the project
                    MyInput input = new MyInput();
                    SoamInvokeRequest request = new SoamInvokeRequest();
                    request.SetSoamInputObject(input);
                    client.SendRequest<SoamInvokeRequest>(request, i);
                    //Console.WriteLine("\tSent request {0}: {1}", i, input);
                }

                // 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();
            });

            Thread[] threads = new Thread[numBatchs];
            for (int i = 0; i < numBatchs; i++)
            {
                threads[i] = new Thread(runnalbe);
                threads[i].Start();
            }

            for (int i = 0; i < numBatchs; i++)
            {
                try
                {
                    threads[i].Join();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.ToString());
                }
            }
        }
Exemplo n.º 3
0
        public void BvtCase3()
        {
            Info("Start BVT");
            List <string>    results = new List <string>();
            SessionStartInfo sessionStartInfo;

            sessionStartInfo = BuildSessionStartInfo(Server, EchoSvcName, null, null, null, null, SessionUnitType.Node, null, null, null);

            sessionStartInfo.Secure = false;
            sessionStartInfo.BrokerSettings.SessionIdleTimeout = 60 * 10 * 1000;
            Info("Begin to create session");
            string            serviceJobId;
            int               clients           = 2;
            AutoResetEvent    evt               = new AutoResetEvent(false);
            Session           session           = Session.CreateSession(sessionStartInfo);
            SessionAttachInfo sessionAttachInfo = new SessionAttachInfo(sessionStartInfo.Headnode, session.Id);

            session = Session.AttachSession(sessionAttachInfo);

            serviceJobId = session.Id;
            var epr = new EndpointAddress(string.Format(NetTcpEndpointPattern, Server, serviceJobId));

            Info("EPR: {0}", epr);
            Task[] tasks = new Task[2];
            for (int i = 0; i < 2; 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 clients) <= 0)
                        {
                            evt.Set();
                        }
                    }
                });
            }
            evt.WaitOne();
            Task.WaitAll(tasks);
            session.Close(true);
            session.Dispose();

            // VerifyJobStatus(serviceJobId);
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            //change the headnode name here
            const string headnode = "localhost";
            const string serviceName = "JavaEchoSvc1";
            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<IEchoSvc> client = new BrokerClient<IEchoSvc>(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();
        }
Exemplo n.º 5
0
        static void Main(string[] args)
        {
            const string headnode    = "[headnode]";
            const string serviceName = "EchoService";
            const int    numRequests = 12;
            int          count       = 0;

            SessionStartInfo info = new SessionStartInfo(headnode, serviceName);
            AutoResetEvent   done = new AutoResetEvent(false);

            Console.Write("Creating a session for EchoService...");
            using (Session session = Session.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))
                {
                    //set getresponse handler
                    client.SetResponseHandler <EchoResponse>((item) =>
                    {
                        try
                        {
                            Console.WriteLine("\tReceived response for request {0}: {1}",
                                              item.GetUserData <int>(), item.Result.EchoResult);
                        }
                        catch (SessionException ex)
                        {
                            Console.WriteLine("SessionException while getting responses in callback: {0}", ex.Message);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("Exception while getting responses in callback: {0}", ex.Message);
                        }

                        if (Interlocked.Increment(ref count) == numRequests)
                        {
                            done.Set();
                        }
                    });

                    // start to send requests
                    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...");

                    // Main thread block here waiting for the retrieval process
                    // to complete.  As the thread that receives the "numRequests"-th
                    // responses does a Set() on the event, "done.WaitOne()" will pop
                    done.WaitOne();
                    Console.WriteLine("Done retrieving {0} responses", numRequests);
                }

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

            Console.WriteLine("Press any key to exit.");
            Console.Read();
        }
Exemplo n.º 6
0
        static void Main(string[] args)
        {
            string hostname = "[headnode]";

            // DataClient Id used to identify the data, this should be unique across the cluster
            string raw_data_id        = "raw_data_id";
            string dictionary_data_id = "dictionary_data_id";

            Console.WriteLine("Start. " + DateTime.Now.ToLongTimeString());

            // Create a DataClient to store a Dictionary data
            using (DataClient client = DataClient.Create(hostname, dictionary_data_id))
            {
                Console.WriteLine("Data {0} Created. {1} ", dictionary_data_id, DateTime.Now.ToLongTimeString());
                // Here we have a DataClient whose life cycle is not managed by SOA
                Dictionary <string, string> objects = new Dictionary <string, string>();
                objects.Add("key1", "value1");
                objects.Add("key2", "value2");
                // WriteAll() can only be called once on a data client.
                client.WriteAll <Dictionary <string, string> >(objects);
            }

            SessionStartInfo sessionStartInfo = new SessionStartInfo(hostname, "CommonDataService");

            // Pass DataClient Id in SOA session's environment variable so that it could be read from service code
            sessionStartInfo.Environments.Add("DICTIONARY_DATA_ID", dictionary_data_id);

            using (Session session = Session.CreateSession(sessionStartInfo))
            {
                Console.WriteLine("Session {0} Created. {1} ", session.Id, DateTime.Now.ToLongTimeString());

                // Create a DataClient to store the raw data read from the file
                using (DataClient client = DataClient.Create(hostname, raw_data_id))
                {
                    Console.WriteLine("Data {0} Created {1}. ", client.Id, DateTime.Now.ToLongTimeString());
                    // Add a data life cycle management so that it'll be deleted when session is done
                    // Otherwise, the data will have to be cleaned up by client
                    client.SetDataLifeCycle(new DataLifeCycle(session.Id));
                    // WriteRawBytesAll() doesn't serialize the object and will write the byte stream directly.
                    // Use this when you want to transport a file or have non-.Net code that cannot handle .net serialization.
                    client.WriteRawBytesAll(File.ReadAllBytes("DataFile.txt"));
                }

                // Send/Receive SOA requests
                using (BrokerClient <ICommonDataService> client = new BrokerClient <ICommonDataService>(session))
                {
                    Console.WriteLine("Send Requests. " + DateTime.Now.ToLongTimeString());
                    client.SendRequest <GetDataRequest>(new GetDataRequest(raw_data_id));
                    client.EndRequests();
                    Console.WriteLine("Get Response. " + DateTime.Now.ToLongTimeString());
                    foreach (BrokerResponse <GetDataResponse> resp in client.GetResponses <GetDataResponse>())
                    {
                        string result = resp.Result.GetDataResult;
                        Console.WriteLine(result);
                    }
                }
                Console.WriteLine("Start closing session. " + DateTime.Now.ToLongTimeString());
            }
            Console.WriteLine("Session Closed. " + DateTime.Now.ToLongTimeString());

            Console.WriteLine("Start cleaning up the Data {0}. {1} ", dictionary_data_id, DateTime.Now.ToLongTimeString());
            // We should delete the DataClient "dictionary_data_id" here since it's not managed by SOA
            DataClient.Delete(hostname, dictionary_data_id);

            Console.WriteLine("Press any key to exit.");
            Console.ReadKey();
        }
Exemplo n.º 7
0
        public void doSubmit(Dictionary <string, string> runParameters)
        {
            m_start = System.Environment.TickCount;

            //
            // Configure session with cluster:
            //
            string[] parameterKeys = { "HeadNode", "Service", "JobTemplate", "Tasks", "TaskTime" };
            foreach (string parameterKey in parameterKeys)
            {
                if (!runParameters.ContainsKey(parameterKey))
                {
                    outputError(parameterKey);
                }
            }

            string           headNode = runParameters["HeadNode"];
            SessionStartInfo info     = new SessionStartInfo(headNode, runParameters["Service"]);

            info.SessionResourceUnitType = SessionUnitType.Core;
            if (runParameters.ContainsKey("MinCores"))
            {
                info.MinimumUnits = Convert.ToInt32(runParameters["MinCores"]);
            }
            if (runParameters.ContainsKey("MaxCores"))
            {
                info.MaximumUnits = Convert.ToInt32(runParameters["MaxCores"]);
            }
            if (runParameters.ContainsKey("Priority"))
            {
                info.SessionPriority = Convert.ToInt32(runParameters["Priority"]);
            }

            info.Secure = false;                               // generally off in the classroom:
            info.BrokerSettings.SessionIdleTimeout = 15000;    // 15 secs:
            info.JobTemplate = runParameters["JobTemplate"];


            int tasks    = Convert.ToInt32(runParameters["Tasks"]);
            int taskTime = Convert.ToInt32(runParameters["TaskTime"]);

            double taskFailureChance = 0.0;

            if (runParameters.ContainsKey("TaskFailureChance"))
            {
                taskFailureChance = Convert.ToDouble(runParameters["TaskFailureChance"]);
            }
            int taskTimeDeviation = 0;

            if (runParameters.ContainsKey("TaskTimeDeviation"))
            {
                taskTimeDeviation = Convert.ToInt32(runParameters["TaskTimeDeviation"]);
            }
            int taskThrottling = 0;

            if (runParameters.ContainsKey("TaskThrottling"))
            {
                taskThrottling = Convert.ToInt32(runParameters["TaskThrottling"]);
            }

            //
            // User is prompted for run-as credentials, then session
            // is opened for business:
            //
            Session.SetInterfaceMode(false /*GUI*/, (IntPtr)0);
            Console.WriteLine("Creating session: {0}ms", System.Environment.TickCount - m_start);
            using (var session = Session.CreateSession(info))
            {
                Console.WriteLine("Session Created: {0}ms", System.Environment.TickCount - m_start);

                var mode    = (info.Secure) ? SecurityMode.Transport : SecurityMode.None;
                var binding = new NetTcpBinding(mode);
                using (var proxy = new BrokerClient <ClusterTesterService.IClusterTesterService>(session, binding))
                {
                    m_signal = new Semaphore(0, 1);
                    proxy.SetResponseHandler <ClusterTesterService.RunTaskResponse>(doSubmit_ServiceCallback, m_signal);

                    Console.WriteLine("Connected to session {0}: {1}ms", session.Id, System.Environment.TickCount - m_start);

                    //
                    // Make the N service calls:
                    //
                    Console.WriteLine("Sending requests: {0}", System.Environment.TickCount - m_start);
                    Random random = new Random();
                    int    thisTaskTime;
                    for (int i = 0; i < tasks; i++)
                    {
                        if (taskTimeDeviation != 0)
                        {
                            thisTaskTime = Math.Max(0, gaussian(random, taskTime, taskTimeDeviation));
                        }
                        else
                        {
                            thisTaskTime = taskTime;
                        }

                        if (taskThrottling > 0)
                        {
                            Thread.Sleep(taskThrottling);
                        }

                        proxy.SendRequest(new ClusterTesterService.RunTaskRequest(i, thisTaskTime, taskFailureChance));
                    }
                    proxy.EndRequests();
                    Console.WriteLine("End requests: {0}ms", System.Environment.TickCount - m_start);

                    //
                    // wait on callbacks
                    //
                    m_signal.WaitOne();
                    session.Close();
                }
            }

            Console.WriteLine("Exit program: {0}ms", System.Environment.TickCount - m_start);
            m_stop = System.Environment.TickCount;
        }
Exemplo n.º 8
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();
            }
        }
Exemplo n.º 9
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();
        }