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(); }
private static void Worker(int sessionId) { DurableSession session = DurableSession.AttachSession(new SessionAttachInfo(headnode, sessionId)); int numRequests = 32; NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport); string guid = Guid.NewGuid().ToString(); // 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>(guid, 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(); client.Close(); Console.WriteLine("done"); } using (BrokerClient <IService1> client = new BrokerClient <IService1>(guid, session, binding)) { 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); } }
/// <summary> /// Start a new session using for testing multiple sessions and maxunit parameters /// </summary> public Session StartNewSession(SessionStartInfo sessionStartInfo, int max) { Session session = Session.CreateSession(sessionStartInfo); var epr = new EndpointAddress(string.Format(NetTcpEndpointPattern, Server, session.Id)); Info("EPR: {0}", epr); Info("Begin to send requests"); 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; 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); } 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; } return(session); }
private static void ClientSendRequest(BrokerClient <IService1> client, string clientId, int msg_count, byte[] task_data) { Log("Client {0}: Begin to send requests.", clientId); try { for (int j = 0; j < msg_count; j++) { client.SendRequest <ComputeWithInputDataRequest>(new ComputeWithInputDataRequest(millisec_for_each_req, task_data, commonData_dataClientId, output_data_size, DateTime.Now)); if (flush_per_req != req_count && (j + 1) % flush_per_req == 0) { client.Flush(10 * 60 * 1000); } } Log("Client {0}: Begin to call EndOfMessage.", clientId); if (batchCount == 1) { data.ReqEom = DateTime.Now; } client.EndRequests(10 * 60 * 1000); if (batchCount == 1) { data.ReqEomDone = DateTime.Now; } Log("Client {0}: EndOfMessage done.", clientId); } catch (WebException e) { if (e.Response is HttpWebResponse) { HttpWebResponse response = e.Response as HttpWebResponse; using (StreamReader reader = new StreamReader(response.GetResponseStream())) { Log("Unexpected WebException when client {0} sending requests: {1}", clientId, response.StatusCode, reader.ReadToEnd()); } // Do not continue anymore Environment.Exit(int.MinValue); } else { throw e; } } catch (Exception e) { Log("Unexpected exception when client {0} sending requests: {1}", clientId, e.ToString()); // Do not continue anymore Environment.Exit(int.MinValue); } }
static void Main(string[] args) { //Change headnode here const string headnode = "head.contoso.com"; const string serviceName = "CommonData.PrimeFactorization"; SessionStartInfo info = new SessionStartInfo(headnode, serviceName); Random random = new Random(); try { //create an interactive session using (Session session = Session.CreateSession(info)) { Console.WriteLine("Session {0} has been created", session.Id); using (BrokerClient <IPrimeFactorization> client = new BrokerClient <IPrimeFactorization>(session)) { //send request int num = random.Next(1, Int32.MaxValue); FactorizeRequest request = new FactorizeRequest(num); client.SendRequest <FactorizeRequest>(request, num); client.EndRequests(); //get response 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)); } } session.Close(); Console.WriteLine("done"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } } catch (System.Exception ex) { Console.WriteLine(ex.Message); } }
static void Main(string[] args) { //change headnode name and service name SessionStartInfo info = new SessionStartInfo("head.contoso.com", "PrimeFactorizationService"); try { //Create a durable session DurableSession session = DurableSession.CreateSession(info); Console.WriteLine("Session {0} has been created", session.Id); //Send batch request Random random = new Random(); const int numRequests = 100; using (BrokerClient <IPrimeFactorization> client = new BrokerClient <IPrimeFactorization>(session)) { Console.WriteLine("Sending {0} requests...", numRequests); for (int i = 0; i < numRequests; i++) { int number = random.Next(1, Int32.MaxValue); FactorizeRequest request = new FactorizeRequest(number); //The second param is used to identify each request. //It can be retrieved from the response. client.SendRequest <FactorizeRequest>(request, number); } client.EndRequests(); Console.WriteLine("All the {0} requests have been sent", numRequests); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } } catch (System.Exception ex) { Console.WriteLine(ex.Message); } }
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(); } } }
private static void CustomizedResponseHandlerTest(SessionBase session) { NetTcpBinding binding = Utils.CreateNetTcpBinding(); byte[] task_data = new byte[input_data_size]; (new Random()).NextBytes(task_data); object mylock = default(object); for (int i = 0; i < req_count; i++) { string clientId = Guid.NewGuid().ToString(); BrokerClient <IService1> client = new BrokerClient <IService1>(clientId, session, binding); ResponseHandlerBase handler; handler = new ComputeWithInputDataResponseHandler(client, clientId, common_data_size, retryRequestAndIgnoreRetryOperationError); // Measure the set response handler time Stopwatch watch = Stopwatch.StartNew(); client.SetResponseHandler <ComputeWithInputDataResponse>( response => { lock (mylock) { response.Dispose(); client.Close(); } } ); watch.Stop(); Log("Elapsed time for SetResponseHandler is {0} milliseconds", watch.ElapsedMilliseconds); // Send requests client.SendRequest <ComputeWithInputDataRequest>(new ComputeWithInputDataRequest(millisec_for_each_req, task_data, commonData_dataClientId, output_data_size, DateTime.Now)); data.ReqEom = DateTime.Now; client.EndRequests(10 * 60 * 1000); data.ReqEomDone = DateTime.Now; // Send every 0-4 sec //Thread.Sleep((new Random()).Next(4000)); } }
static void Main(string[] args) { //change the head node name here SessionStartInfo info = new SessionStartInfo("head.contoso.com", "CalculatorService"); //create an interactive session using (Session session = Session.CreateSession(info)) { Console.WriteLine("Session {0} has been created", session.Id); //create a broker client using (BrokerClient <ICalculator> client = new BrokerClient <ICalculator>(session)) { //send request AddRequest request = new AddRequest(1, 2); client.SendRequest <AddRequest>(request); client.EndRequests(); //get response foreach (BrokerResponse <AddResponse> response in client.GetResponses <AddResponse>()) { double result = response.Result.AddResult; Console.WriteLine("Add 1 and 2, and we get {0}", result); } //This can be omitted if a BrokerClient object //is created in a "using" clause. client.Close(); } //This should be explicitly invoked session.Close(); } Console.WriteLine("Done invoking SOA service"); Console.WriteLine("Press any key to exit"); Console.ReadKey(); }
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(); } }
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; } }
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(); } }
static void Main(string[] args) { // Replace [HeadName] with the real machine name of the HeadNode in your cluster, say "[headnode]" const string headnode = "[HeadName]"; const string serviceName = "EchoService"; int numOfRequests = 10; SessionStartInfo sessionStartInfo = new SessionStartInfo(headnode, serviceName); // UseInprocessBroker indicates what kind of broker session is going to use. True means inprocess broker will be adopted // while false means a dedicated broker node will be used by the session. Console.WriteLine("Enable UseInprocessBroker..."); sessionStartInfo.UseInprocessBroker = true; // Inprocess broker is only supported with non-shared interactive session, // so please make sure the property ShareSession of SessionStartInfo is set to false. sessionStartInfo.ShareSession = false; Console.WriteLine("Creating an interactive session..."); using (Session session = Session.CreateSession(sessionStartInfo)) { Console.WriteLine("Interactive Session {0} created.", session.Id); // With inprocess broker, client can directly talk to its service hosts on computer nodes, so the EndPointReference is null. Console.WriteLine("Session's EndpointReference: {0}.", session.EndpointReference == null ? "NULL": session.EndpointReference.ToString()); // Inprocess broker only support V3 style broker client, so you should create broker client as below instead of // Service1Client tcpclient = new Service1Client(new NetTcpBinding(SecurityMode.Transport), session.NetTcpEndpointReference); using (BrokerClient <IService1> client = new BrokerClient <IService1>(session)) { Console.WriteLine("Sending {0} requests...", numOfRequests); for (int i = 0; i < numOfRequests; i++) { EchoRequest request = new EchoRequest("Hello World " + i.ToString()); client.SendRequest <EchoRequest>(request, i); } Console.WriteLine("Calling EndRequests to notify the end of sending requests... "); client.EndRequests(); Console.WriteLine("Retrieving responses..."); int count = 0; foreach (BrokerResponse <EchoResponse> response in client.GetResponses <EchoResponse>()) { string reply = response.Result.EchoResult; Console.WriteLine("Received response for request {0}: {1}", response.GetUserData <int>(), reply); count++; } if (count != numOfRequests) { Console.WriteLine("Error: Responses lost. Expected {0} responses, but actually {1} returned.", numOfRequests, count); } Console.WriteLine("Retrieving results done."); } session.Close(); } Console.WriteLine("Session closed."); Console.WriteLine("Press any key to exit."); Console.ReadKey(); }
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); } } }
static void Main(string[] args) { //Change headnode here const string headnode = "head.contoso.com"; const string serviceName = "PrimeFactorizationService"; SessionStartInfo info = new SessionStartInfo(headnode, serviceName); //Enable session pool info.ShareSession = true; info.UseSessionPool = true; try { //create an interactive session using (Session session = Session.CreateSession(info)) { Console.WriteLine("Session {0} has been created", session.Id); //in one session, each broker client should have a unique id string ClientId = Guid.NewGuid().ToString(); //use this event sync main thread and callback AutoResetEvent done = new AutoResetEvent(false); using (BrokerClient <IPrimeFactorization> client = new BrokerClient <IPrimeFactorization>(ClientId, session)) { Console.WriteLine("BrokerClient {0} has been created", ClientId); //set callback function. this handler will be invoke before service replies. client.SetResponseHandler <FactorizeResponse>((response) => { int number = response.GetUserData <int>(); int[] factors = response.Result.FactorizeResult; Console.WriteLine("{0} = {1}", number, string.Join <int>(" * ", factors)); //release the lock done.Set(); }); Random random = new Random(); int num = random.Next(1, Int32.MaxValue); //send request FactorizeRequest request = new FactorizeRequest(num); client.SendRequest <FactorizeRequest>(request, num); client.EndRequests(); //wait until callback returns done.WaitOne(); } Console.WriteLine("Factorization done."); Console.WriteLine("Press any key to exit"); Console.ReadKey(); } } catch (System.Exception ex) { Console.WriteLine(ex.Message); } }
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; }
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(); }
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(); }
static void Main(string[] args) { CmdParser parser = new CmdParser(args); Config config = new Config(parser); if (config.HelpInfo) { config.PrintHelp(); return; } if (config.Verbose) { config.PrintUsedParams(parser); } if (config.PrintUnusedParams(parser)) { config.PrintHelp(); return; } // TODO: SessionStartInfoFactory SessionStartInfo info = null; if (config.IsNoSession) { // Start session without session manager if (config.InprocessBroker) { info = new SessionStartInfo(config.ServiceName, config.RegPath, null, config.TargetList?.ToArray()); info.UseInprocessBroker = true; info.IsNoSession = true; } else { info = new SessionStartInfo(config.HeadNode, config.ServiceName, config.RegPath, null, config.TargetList?.ToArray()); info.UseInprocessBroker = false; info.IsNoSession = true; } } else { info = new SessionStartInfo(config.HeadNode, config.ServiceName); info.IsNoSession = false; info.UseInprocessBroker = config.InprocessBroker; } if (!string.IsNullOrEmpty(config.Username)) { info.Username = config.Username; } if (!string.IsNullOrEmpty(config.Password)) { info.Password = config.Password; } if (!string.IsNullOrEmpty(config.JobName)) { info.ServiceJobName = config.JobName; } if (!string.IsNullOrEmpty(config.AzureStorageConnectionString)) { info.AzureStorageConnectionString = config.AzureStorageConnectionString; info.BrokerLauncherStorageConnectionString = config.AzureStorageConnectionString; } switch (config.ResourceType.ToLowerInvariant()) { case "core": info.SessionResourceUnitType = SessionUnitType.Core; break; case "node": info.SessionResourceUnitType = SessionUnitType.Node; break; case "socket": info.SessionResourceUnitType = SessionUnitType.Socket; break; case "gpu": info.SessionResourceUnitType = SessionUnitType.Gpu; break; default: break; } if (config.MaxResource > 0) { info.MaximumUnits = config.MaxResource; } if (config.MinResource > 0) { info.MinimumUnits = config.MinResource; } switch (config.TransportScheme.ToLowerInvariant()) { case "nettcp": info.TransportScheme = TransportScheme.NetTcp; break; case "http": info.TransportScheme = TransportScheme.Http; break; case "nethttp": info.TransportScheme = TransportScheme.NetHttp; break; case "custom": info.TransportScheme = TransportScheme.Custom; break; case "azstorage": info.TransportScheme = TransportScheme.AzureStorage; break; default: break; } info.JobTemplate = config.JobTemplate; info.SessionPriority = config.Priority; info.NodeGroupList = new List <string>(config.NodeGroups.Split(new char[] { ',' })); info.RequestedNodesList = new List <string>(config.Nodes.Split(new char[] { ',' })); info.Secure = !config.Insecure && !config.IsNoSession; info.UseAzureQueue = config.AzureQueue; info.ShareSession = config.ShareSession; info.UseSessionPool = config.SessionPool; info.ParentJobIds = StringToIntList(config.ParentIds); info.ServiceHostIdleTimeout = config.ServiceIdleSec == -1 ? config.ServiceIdleSec : config.ServiceIdleSec * 1000; info.ServiceHangTimeout = config.ServiceHangSec == -1 ? config.ServiceHangSec : config.ServiceHangSec * 1000; info.UseWindowsClientCredential = config.UseWCC; info.UseAad = config.UseAad; if (config.Runtime > 0) { info.Runtime = config.Runtime; } if (!string.IsNullOrEmpty(config.Environment)) { foreach (string keyValue in config.Environment.Split(new char[] { ',' })) { string[] p = keyValue.Split(new char[] { '=' }); if (p.Length == 2) { info.Environments.Add(p[0], p[1]); } } } Stopwatch watch = new Stopwatch(); int timeoutMilliSec = config.MsgTimeoutSec * 1000; Dictionary <Guid, Dictionary <Guid, TaskRecord> > brokerClientTaskTimeRecords = new Dictionary <Guid, Dictionary <Guid, TaskRecord> >(config.BrokerClient); Dictionary <Guid, DateTime> brokerSendRequestStartTime = new Dictionary <Guid, DateTime>(config.BrokerClient); Dictionary <Guid, DateTime> brokerSendRequestEndTime = new Dictionary <Guid, DateTime>(config.BrokerClient); Dictionary <Guid, DateTime> brokerGetResponseStartTime = new Dictionary <Guid, DateTime>(config.BrokerClient); Dictionary <Guid, DateTime> brokerGetResponseEndTime = new Dictionary <Guid, DateTime>(config.BrokerClient); Random rTimeMS = new Random(); Random rSizeKB = new Random(); int maxTimeMS = 0; int minTimeMS = 0; int maxSizeKB = 0; int minSizeKB = 0; if (!string.IsNullOrEmpty(config.TimeMSRandom)) { string[] values = config.TimeMSRandom.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries); if (values.Length == 2) { int.TryParse(values[0], out minTimeMS); int.TryParse(values[1], out maxTimeMS); } } if (!string.IsNullOrEmpty(config.SizeKBRandom)) { string[] values = config.SizeKBRandom.Split(new char[] { '_' }, StringSplitOptions.RemoveEmptyEntries); if (values.Length == 2) { int.TryParse(values[0], out minSizeKB); int.TryParse(values[1], out maxSizeKB); } } for (int c = 0; c < config.BrokerClient; c++) { Dictionary <Guid, TaskRecord> taskTimeReconds = new Dictionary <Guid, TaskRecord>(config.NumberOfRequest); for (int i = 0; i < config.NumberOfRequest; i++) { Guid g = Guid.NewGuid(); TaskRecord t = new TaskRecord() { RequestTime = DateTime.MinValue, ResponseTime = DateTime.MinValue }; if (maxTimeMS > 0) { t.CallDurationMS = rTimeMS.Next(minTimeMS, maxTimeMS); } else { t.CallDurationMS = config.CallDurationMS; } if (maxSizeKB > 0) { t.MessageSizeByte = rSizeKB.Next(minSizeKB, maxSizeKB) * 1024; } else { t.MessageSizeByte = config.MessageSizeByte; } taskTimeReconds.Add(g, t); } Guid clientGuid = Guid.NewGuid(); brokerClientTaskTimeRecords.Add(clientGuid, taskTimeReconds); brokerSendRequestStartTime.Add(clientGuid, DateTime.MinValue); brokerSendRequestEndTime.Add(clientGuid, DateTime.MinValue); brokerGetResponseStartTime.Add(clientGuid, DateTime.MinValue); brokerGetResponseEndTime.Add(clientGuid, DateTime.MinValue); } // Create an interactive or durable session Logger.Info("Creating a session for CcpEchoSvc service..."); SessionBase session = null; try { watch.Start(); if (config.Durable) { session = DurableSession.CreateSession(info); } else { session = Session.CreateSession(info); } watch.Stop(); Logger.Info("{0, -35} : {1}", "Session ID", session.Id); Logger.Info("{0, -35} : {1:F3} sec", "Session creation time", watch.Elapsed.TotalSeconds); //session warm up time if (config.WarmupTimeSec > 0) { Logger.Info("Session warming up in {0} seconds...", config.WarmupTimeSec); Thread.Sleep(config.WarmupTimeSec * 1000); } int clientNumber = config.BrokerClient; int clientCounter = 0; AutoResetEvent allDone = new AutoResetEvent(false); foreach (Guid g in brokerClientTaskTimeRecords.Keys) { ThreadPool.QueueUserWorkItem((o) => { Guid brokerClientGuid = (Guid)o; AutoResetEvent done = new AutoResetEvent(false); int count = 0; int clientC = Interlocked.Increment(ref clientCounter); Stopwatch watchT = new Stopwatch(); try { // Create a BrokerClient proxy using (BrokerClient <IEchoSvc> client = new BrokerClient <IEchoSvc>(brokerClientGuid.ToString(), session)) { if (config.AsyncResponseHandler) { //set getresponse handler Logger.Info("Setting response handler ({0}/{1}) to receive responses async.", clientC, config.BrokerClient); client.SetResponseHandler <GenerateLoadResponse>((item) => { try { Guid gg = item.RequestMessageId; StatisticInfo si = item.Result.GenerateLoadResult; if (config.Verbose) { Logger.Info("Response async received ({0}/{1}) {2} : {3}. StartTime-EndTime : {4:HH:mm:ss.fff}-{5:HH:mm:ss.fff}", clientC, config.BrokerClient, item.GetUserData <int>(), gg, si.StartTime, si.EndTime); } brokerClientTaskTimeRecords[brokerClientGuid][gg].ResponseTime = DateTime.Now; } catch (FaultException ex) { Logger.Warning("FaultException while getting responses in callback. \n{0}", ex.ToString()); } catch (RetryOperationException ex) { Logger.Warning("RetryOperationException while getting responses in callback. \n{0}", ex.ToString()); } catch (SessionException ex) { Logger.Warning("SessionException while getting responses in callback. \n{0}", ex.ToString()); } catch (Exception ex) { Logger.Warning("Exception while getting responses in callback. \n{0}", ex.ToString()); } if (Interlocked.Increment(ref count) == config.NumberOfRequest) { done.Set(); } }); } Logger.Info("Sending {0} requests for broker client ({1}/{2})...", config.NumberOfRequest, clientC, config.BrokerClient); brokerSendRequestStartTime[brokerClientGuid] = DateTime.Now; watchT.Restart(); int i = 0; foreach (Guid requestGuid in brokerClientTaskTimeRecords[brokerClientGuid].Keys) { i++; GenerateLoadRequest request = new GenerateLoadRequest(brokerClientTaskTimeRecords[brokerClientGuid][requestGuid].CallDurationMS, new byte[brokerClientTaskTimeRecords[brokerClientGuid][requestGuid].MessageSizeByte], null); client.SendRequest <GenerateLoadRequest>(request, i, timeoutMilliSec, new System.Xml.UniqueId(requestGuid)); if (config.Verbose) { Logger.Info("Sent request {0} for ({1}/{2}) : {3} : timeMS - {4} sizeByte - {5}", i, clientC, config.BrokerClient, requestGuid, brokerClientTaskTimeRecords[brokerClientGuid][requestGuid].CallDurationMS, brokerClientTaskTimeRecords[brokerClientGuid][requestGuid].MessageSizeByte); } brokerClientTaskTimeRecords[brokerClientGuid][requestGuid].RequestTime = DateTime.Now; if (config.Flush > 0 && i % config.Flush == 0) { client.Flush(timeoutMilliSec); } } // Flush the message client.EndRequests(timeoutMilliSec); watchT.Stop(); brokerSendRequestEndTime[brokerClientGuid] = DateTime.Now; double requestElapsedSeconds = watchT.Elapsed.TotalSeconds; double requestThroughput = config.NumberOfRequest / requestElapsedSeconds; Logger.Info("{0, -35} : {1:F3} sec", string.Format("Requests sent time ({0}/{1})", clientC, config.BrokerClient), requestElapsedSeconds); Logger.Info("{0, -35} : {1:F2} /sec", string.Format("Requests throughput ({0}/{1})", clientC, config.BrokerClient), requestThroughput); if (!config.AsyncResponseHandler) { Logger.Info("Retrieving responses for broker client ({0}/{1})...", clientC, config.BrokerClient); try { brokerGetResponseStartTime[brokerClientGuid] = DateTime.Now; watchT.Restart(); int responseNumber = 0; foreach (BrokerResponse <GenerateLoadResponse> response in client.GetResponses <GenerateLoadResponse>(timeoutMilliSec)) { try { Guid gg = response.RequestMessageId; StatisticInfo si = response.Result.GenerateLoadResult; if (config.Verbose) { Logger.Info("Response received ({0}/{1}) {2} : {3}. StartTime-EndTime : {4:HH:mm:ss.fff}-{5:HH:mm:ss.fff}", clientC, config.BrokerClient, response.GetUserData <int>(), gg, si.StartTime, si.EndTime); } else { Logger.Progress(string.Empty, responseNumber, config.NumberOfRequest); } brokerClientTaskTimeRecords[brokerClientGuid][gg].ResponseTime = DateTime.Now; } catch (FaultException e) { // Application exceptions Logger.Warning("FaultException when getting responses. \n{0}", e.ToString()); } catch (RetryOperationException e) { // RetryOperationExceptions may or may not be recoverable Logger.Warning("RetryOperationException when getting responses. \n{0}", e.ToString()); } catch (SessionException e) { // Exception Logger.Warning("SessionException when getting responses. \n{0}", e.ToString()); } catch (Exception e) { // Exception Logger.Warning("Exception when getting responses. \n{0}", e.ToString()); } finally { responseNumber++; } } watchT.Stop(); brokerGetResponseEndTime[brokerClientGuid] = DateTime.Now; double elapsedTimeSec = watchT.Elapsed.TotalSeconds; Logger.Info("{0, -35} : {1:F3} sec", string.Format("GetResponses time ({0}/{1})", clientC, config.BrokerClient), elapsedTimeSec); Logger.Info("{0, -35} : {1:F2} /sec", string.Format("GetResponses throughput ({0}/{1})", clientC, config.BrokerClient), responseNumber / elapsedTimeSec); } catch (Exception ex) { Logger.Error("Error occured getting responses.\n{0}", ex.ToString()); } } else { //wait for receiving responses async. done.WaitOne(); } } } catch (Exception e) { //swallow the exception in the thread. Logger.Error("Error occured in broker client thread.\n{0}", e.ToString()); } if (Interlocked.Decrement(ref clientNumber) == 0) { allDone.Set(); } }, g); } // for t Logger.Info("Wait for all broker clients."); allDone.WaitOne(); } catch (Exception e) { Logger.Error("Error occured.\n{0}", e.ToString()); } finally { if (session != null) { //explict close the session to free the resource session.Close(!config.ShareSession); session.Dispose(); } } //calc the request/response throughput for all broker client double allRequestsElapsedSeconds = (brokerSendRequestEndTime.Values.Max() - brokerSendRequestStartTime.Values.Min()).TotalSeconds; double allRequestThroughput = config.NumberOfRequest * config.BrokerClient / allRequestsElapsedSeconds; Logger.Info("{0, -35} : {1:F3} sec", "All requests sending time", allRequestsElapsedSeconds); Logger.Info("{0, -35} : {1:F2} /sec", "All requests throughput", allRequestThroughput); double allResponsesElapsedSeconds = (brokerGetResponseEndTime.Values.Max() - brokerGetResponseStartTime.Values.Min()).TotalSeconds; double allResponseThroughput = config.NumberOfRequest * config.BrokerClient / allResponsesElapsedSeconds; Logger.Info("{0, -35} : {1:F3} sec", "All resposnes receiving time", allResponsesElapsedSeconds); Logger.Info("{0, -35} : {1:F2} /sec", "All responses throughput", allResponseThroughput); //calc the min/max/average request e2e time double[] times = new double[config.NumberOfRequest * config.BrokerClient]; DateTime[] dates = new DateTime[config.NumberOfRequest * config.BrokerClient]; DateTime[] dates_req = new DateTime[config.NumberOfRequest * config.BrokerClient]; int k = 0; foreach (Guid g in brokerClientTaskTimeRecords.Keys) { foreach (TaskRecord r in brokerClientTaskTimeRecords[g].Values) { times[k] = (r.ResponseTime - r.RequestTime).TotalSeconds; dates[k] = r.ResponseTime; dates_req[k] = r.RequestTime; k++; } } Logger.Info("{0, -35} : {1:F3} sec", "Response time Min", times.Min()); Logger.Info("{0, -35} : {1:F3} sec", "Response time Max", times.Max()); Logger.Info("{0, -35} : {1:F3} sec", "Response time Ave", times.Average()); DateTime first = dates.Min(); DateTime last = dates.Max(); DateTime first_req = dates_req.Min(); double elapsedSec = (last - first).TotalSeconds; double elapsedSec_req = (last - first_req).TotalSeconds; Logger.Info("{0, -35} : {1:HH:mm:ss.fff}", "Response first", first); Logger.Info("{0, -35} : {1:HH:mm:ss.fff}", "Response last", last); Logger.Info("{0, -35} : {1:F3} sec", "Responses elapsed", elapsedSec); Logger.Info("{0, -35} : {1:F2} /sec", "Responses throughput", config.NumberOfRequest * config.BrokerClient / elapsedSec); Logger.Info("{0, -35} : {1:F3} sec", "Request E2E elapsed", elapsedSec_req); Logger.Info("{0, -35} : {1:F2} /sec", "Request E2E throughput", config.NumberOfRequest * config.BrokerClient / elapsedSec_req); Logger.Info("Echo Done."); }
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(); }
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(); }
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()); } } }
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(); }
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(); } }
static void Main(string[] args) { // either fill in this value or use the command-line parameter string headnode = ""; string serviceName = "StaticWorkbookService"; string jobTemplate = "AzureTemplate"; string relativePath = "workbooks"; string spreadsheetName = "StaticWorkbook.xlsx"; // SOA variables Session session = null; BrokerClient <IStaticWorkbookService> client = null; bool sessionCreatedSuccessfully = false; // parse command-line arguments for (int i = 0; i < args.Length; i++) { if (args[i].Equals("-headnode") && i < args.Length - 1) { headnode = args[++i]; } ; if (args[i].Equals("-serviceName") && i < args.Length - 1) { serviceName = args[++i]; } ; if (args[i].Equals("-jobTemplate") && i < args.Length - 1) { jobTemplate = args[++i]; } ; if (args[i].Equals("-relativePath") && i < args.Length - 1) { relativePath = args[++i]; } ; if (args[i].Equals("-spreadsheetName") && i < args.Length - 1) { spreadsheetName = args[++i]; } ; } if (null == headnode || headnode.Equals("")) { Console.WriteLine(""); Console.WriteLine("Error: call this application with the argument -headnode [name]."); Console.WriteLine(""); Console.WriteLine("Arguments:"); Console.WriteLine(""); Console.WriteLine("-headnode [name] the name of your cluster scheduler"); Console.WriteLine("-serviceName [name] optional, defaults to 'StaticWorkbookService'"); Console.WriteLine("-jobTemplate [name] optional, defaults to 'AzureTemplate'"); Console.WriteLine("-relativePath [name] optional, defaults to 'Workbooks'"); Console.WriteLine("-spreadsheetName [name] optional, defaults to 'StaticWorkbook.xlsx'"); Console.WriteLine(""); return; } try { // Create the SOA session and client SessionStartInfo info = new SessionStartInfo(headnode, serviceName); info.SessionResourceUnitType = SessionUnitType.Core; info.MinimumUnits = 1; info.MaximumUnits = 128; info.Secure = false; info.JobTemplate = jobTemplate; Console.WriteLine("Creating session and client"); session = Session.CreateSession(info); client = new BrokerClient <IStaticWorkbookService>(session); // The Azure VM nodes use an environment variable to // describe the root installation path for packages // uploaded with hpcpack. We used a relative path to // upload the spreadsheets, so we add that path to // the environment variable to locate the spreadsheet. string spreadsheetPath = string.Format(@"%CCP_PACKAGE_ROOT%\{0}\{1}", relativePath, spreadsheetName); // call the workbook with different sets of parameters. // we're just pasting values into the spreadsheet, and requesting // some other cells as the results after the calculation. // have a look at the spreadsheet to see what cells we // are updating and what cells we are retrieving after // the calculation. // these values are constant, we are varying strike and time double spotPrice = 100; double volatility = 0.25; double riskFreeRate = 0.035; double dividendYield = 0.02; for (double strike = 75; strike <= 125; strike += 5) { for (double timeInMonths = 1; timeInMonths <= 24; timeInMonths++) { double timeInYears = timeInMonths / 12.0; // the values are passed to the service using the // Excel range identifiers. we can pass as many as // necessary. just make sure they're the same length, // and that they match up (e.g. C5 -> spotPrice). string[] ranges = { "C5", "C6", "C7", "C8", "C9", "C10" }; object[] values = { spotPrice, strike, timeInYears, volatility, riskFreeRate, dividendYield }; // the output values are the cells we want to retrieve // when the calculation is complete string[] outputRanges = { "C15", "C16" }; // to map our results back to the input parameters, we // can use the index value CalculateParametersRequest req = new CalculateParametersRequest(); req.spreadsheetPath = spreadsheetPath; req.inputRanges = ranges; req.inputValues = values; req.outputRanges = outputRanges; // we're passing the strike price and time values as "user data" // attached to the request. that will let us tie the results // back to the input data when the calculation completes. client.SendRequest <CalculateParametersRequest>(req, new double[] { strike, timeInMonths }); } } client.EndRequests(); sessionCreatedSuccessfully = true; } catch (Exception e) { Console.WriteLine("Failed to start session and send requests.\n" + "Verify that head node is correctly specified and all\n" + "sample documentation steps have been followed.\n" + "Error: {0}", e.ToString()); } if (sessionCreatedSuccessfully) { Console.WriteLine("Waiting for response(s)..."); // note that results will be returned in random order, based on which node // calculates and returns a value first. because the input parameters // are returned as well, if we wanted we could sort the results before // printing. for now, we will just output them to the terminal. try { BrokerResponseEnumerator <CalculateParametersResponse> responses = client.GetResponses <CalculateParametersResponse>(); foreach (BrokerResponse <CalculateParametersResponse> response in responses) { double[] userData = response.GetUserData <double[]>(); object[] results = response.Result.CalculateParametersResult; Console.WriteLine("Strike {0:0.00},\tExpiry {1:00} months: Call {2:00.00}, Put {3:00.00}", userData[0], (int)userData[1], Double.Parse(results[0].ToString()), Double.Parse(results[1].ToString())); } } catch (Exception e) { Console.WriteLine("Failed to get responses. Error: {0}", e.ToString()); } } // done - clean up Console.WriteLine("\r\nCleaning up..."); try { if (client != null) { client.Close(); } } catch { Console.WriteLine("Failed to close client cleanly."); } finally { if (client != null) { client.Dispose(); } } try { if (session != null) { session.Close(); } } catch { Console.WriteLine("Failed to close session cleanly. Check for running jobs."); } finally { if (session != null) { session.Dispose(); } } }
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 }
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(); } }
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(); }