static void Main(string[] args) { BrokerClient client = null; try { client = new BrokerClient(); Console.WriteLine("Username : "******"0" + i; v.value = "a" + i; client.StorePair(k, v, myid); Console.WriteLine(i); } Console.WriteLine("done store"); for (int i = 0; i < 10; i++) { IKey k = new Key(); k.key = "0" + i; IValue v = (IValue)client.ReadPair(k); Console.WriteLine(v.value); } Console.WriteLine("done read"); object[] aux = (object[])client.GetAllPairs(myid); for (int i = 0; i < aux.Length; ++i) { KeyValuePair <object, object>[] a = (KeyValuePair <object, object>[])aux[i]; foreach (KeyValuePair <object, object> pair in a) { Console.WriteLine("Key - {0} , Value - {1}", ((IKey)pair.Key).key, ((IValue)pair.Value).value); } } client.Close(); } catch (TimeoutException) { Console.WriteLine("Service operation time out"); client.Abort(); } catch (FaultException exception) { Console.WriteLine(exception.Message); client.Abort(); } catch (CommunicationException) { Console.WriteLine("communication problem"); client.Abort(); } }
static void Main(string[] args) { BrokerClient client = null; try { client = new BrokerClient(); Console.WriteLine("Username : "******"0" + i; v.value = "a" + i; client.StorePair(k, v, myid); Console.WriteLine(i); } Console.WriteLine("done store"); for (int i = 0; i < 10; i++) { IKey k = new Key(); k.key = "0" + i; IValue v = (IValue)client.ReadPair(k); Console.WriteLine(v.value); } Console.WriteLine("done read"); object[] aux = (object[])client.GetAllPairs(myid); for (int i = 0; i < aux.Length; ++i) { KeyValuePair<object, object>[] a = (KeyValuePair<object, object>[])aux[i]; foreach (KeyValuePair<object, object> pair in a) { Console.WriteLine("Key - {0} , Value - {1}", ((IKey)pair.Key).key, ((IValue)pair.Value).value); } } client.Close(); } catch (TimeoutException) { Console.WriteLine("Service operation time out"); client.Abort(); } catch (FaultException exception) { Console.WriteLine(exception.Message); client.Abort(); } catch (CommunicationException) { Console.WriteLine("communication problem"); client.Abort(); } }
public string VerificaCredenziali(string username, string password, string role) { string addr = null; BrokerClient client = new BrokerClient(); addr = client.GestisciLogin(username, password, role); client.Close(); return(addr); }
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); } }
private static void InternalGetResponseTestSingleThread(SessionBase session) { NetTcpBinding binding = Utils.CreateNetTcpBinding(); int faultCalls = 0; byte[] task_data = new byte[input_data_size]; (new Random()).NextBytes(task_data); data.SendStart = DateTime.Now; for (int i = 0; i < batchCount; i++) { int msg_count = req_count / batchCount; if (i == batchCount - 1) { msg_count += req_count % batchCount; } string clientId = Environment.MachineName + "-" + i.ToString() + "-" + Process.GetCurrentProcess().Id.ToString(); using (var client = new BrokerClient <IService1>(clientId, session, binding)) { ClientSendRequest(client, clientId, msg_count, task_data); } } //Log("The max interval of SendRequest opertaion is {0} milliseconds.", sendInterval); data.SendEnd = DateTime.Now; for (int i = 0; i < batchCount; i++) { string clientId = Environment.MachineName + "-" + i.ToString() + "-" + Process.GetCurrentProcess().Id.ToString(); using (var client = new BrokerClient <IService1>(clientId, session)) { List <ResultData> results = ClientGetResponse(client, clientId); data.ResultCollection.AddRange(results); try { client.Close(durable, 10 * 60 * 1000); } catch (Exception e) { Log("Purge client {0} failed: {1}", clientId, e.ToString()); } } } data.RetrieveEnd = DateTime.Now; data.FaultCount = faultCalls; }
public string RegistraUtente(string username, string password, string mail, string role) { string addr = null; BrokerClient client = new BrokerClient(); try { addr = client.GestisciIscrizione(username, password, mail, role); } catch (Exception e) { } client.Close(); return(addr); }
public override void AddConsequences() { Consequence consequence = new Consequence("Poll", "Consumer"); consequence.Runnable = () => { BrokerClient brokerClient = new BrokerClient(new HostInfo(TestContext.GetValue("agent1-host"), Int32.Parse(TestContext.GetValue("agent1-port")))); NetNotification notification = brokerClient.Poll(DestinationName, 10000); if (notification != null) { consequence.Sucess = true; brokerClient.Acknowledge(notification.Subscription, notification.Message.MessageId); } brokerClient.Close(); consequence.Done = true; }; this.AddConsequence(consequence); }
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(); }
static void Main(string[] args) { BrokerClient client = new BrokerClient(); client.GestisciIscrizione("ale", "alessandro", "*****@*****.**", "utente"); Console.ReadLine(); client.Close(); // //try // //{ // BasicHttpBinding myBinding = new BasicHttpBinding(); // myBinding.MaxReceivedMessageSize = 2147483647; // myBinding.MaxBufferSize = 2147483647; // EndpointAddress myEndpoint = new EndpointAddress("http://*****:*****@"C:\Users\mmart\Desktop\Download\PC-Wallpaper-Hello-Spring.jpg"; * int numBytesToRead = (int)fileInfo.Length; * byte[] bytes = new byte[numBytesToRead + 1]; * int bytesRead = 0; * * while (numBytesToRead > 0) * { * // Read may return anything from 0 to numBytesToRead. * int n = fileInfo.FileByteStream.Read(bytes, bytesRead, bytes.Length); * * // Break when the end of the file is reached. * if (n == 0) * break; * * bytesRead += n; * numBytesToRead -= n; * } * numBytesToRead = bytes.Length; * * // Write the byte array to the other FileStream. * using (FileStream fsNew = new FileStream(pathNew, * FileMode.Create, FileAccess.Write)) * { * fsNew.Write(bytes, 0, numBytesToRead); * }*/ // // genere gen = genere.Fantasy; // // Libro libro = new Libro // // { // // Titolo = "Hobbit", // // Autore = "Tolkien", // // Anno = 1970, // // Gen = gen // // }; // // Recensione recOld = new Recensione(); // // recOld.Libro = libro; // // recOld.Punteggio = 4; // // recOld.Username = "******"; // // recOld.Commento = "bello"; // // recOld.Id = 2; // // SegnalazioneLibro segnalazione = new SegnalazioneLibro(); // // segnalazione.Libro = libro; // // segnalazione.Username = "******"; // // //Lista[] rec = client.CercaLista("estate"); // // //foreach (Lista l in rec) // // //{ // // // Console.WriteLine(l.Username + " " + l.Gen.ToString()); // // // foreach (Libro lib in l.ListaLibri) // // // Console.WriteLine(lib.Titolo + " " + lib.Autore); // // //} // // //Libro[] listaLibri = client.CercaGenere("Romanzo"); // // //foreach (Libro lib in listaLibri) // // // Console.WriteLine(lib.Titolo + " " + lib.Autore); // // //string username = client.CercaUtente("andre"); // // //if (username == null) // // // Console.WriteLine("Utente non esistente"); // // //else // // // Console.WriteLine(username); // // Libro libro3 = new Libro(){ // // Titolo = "Orgoglio e Pregiudizio", // // Autore = "Jane Austen", // // Anno = 1813, // // Gen = genere.Romanzo // // }; // // Libro libro2 = new Libro(){ // // Titolo = "Blart", // // Autore = "Barker", // // Anno = 2002, // // Gen = genere.Fantasy // // }; // // Recensione rec3 = new Recensione(){ // // Punteggio = 5, // // Libro = libro3, // // Commento = "Amo questo libro, da leggere assolutamente!", // // Username = "******" // // }; // // rec3.Username = "******"; // // rec3.Id = 4; // // Lista lista2 = new Lista(){ // // Nome = "estate al mare", // // Gen = genere.Avventura, // // IsVisibile = false, // // Username = "******", // // ListaLibri = new Libro[3] // // }; // // lista2.ListaLibri[0] = libro; // // lista2.ListaLibri[1] = libro3; // // lista2.ListaLibri[2] = libro2; // // //client.InserisciLibroCover("Harry Potter e la pietra filosofale", "J. K. Rowling", 1998, "Fantasy", "Harry-potter-e-la-pietra-filosofale-copertina-originale.jpg", "marti"); // ////UPLOAD FILE // //System.IO.FileInfo fileInfo = new System.IO.FileInfo("C:\\Users\\mmart\\Desktop\\Harry-potter-e-la-pietra-filosofale-copertina-originale.jpg"); // //RemoteFileInfo uploadRequestInfo = new RemoteFileInfo(); // //using (System.IO.FileStream stream = // // new System.IO.FileStream("C:\\Users\\mmart\\Desktop\\Harry-potter-e-la-pietra-filosofale-copertina-originale.jpg", // // System.IO.FileMode.Open, System.IO.FileAccess.Read)) // //{ // // uploadRequestInfo.FileName = "Harry-potter-e-la-pietra-filosofale-copertina-originale.jpg"; // // uploadRequestInfo.Length = fileInfo.Length; // // uploadRequestInfo.FileByteStream = stream; // // client.UploadFile(uploadRequestInfo); // // //clientUpload.UploadFile(stream); // //} // // //Lista[] listeCreate = client.GetListeSalvate("marti"); // // //foreach (Lista l in listeCreate) { // // // Console.WriteLine(l.Nome + " " + l.Gen.ToString()); // // // foreach (Libro lib in l.ListaLibri) // // // Console.WriteLine(lib.Titolo + " " + lib.Autore); // // //} // // Recensione[] recensioniScritte = client.GetRecensioniSalvate("marti"); // // foreach (Recensione l in recensioniScritte) // // { // // Console.WriteLine(l.Libro.Titolo+ " " + l.Libro.Autore +" " + l.Punteggio + " " + l.Commento +" " +l.Username); // // } // Libro[] libri = client.GetClassificaGenere("Fantasy"); // foreach (Libro l in libri) // Console.WriteLine(l.Titolo + " " + l.Autore); // Console.WriteLine("Fine!"); // ((IClientChannel)client).Close(); // Console.ReadLine(); ////} //// catch (Exception ex) //// { //// Console.WriteLine(ex.InnerException); //// } Console.ReadLine(); Console.ReadLine(); }
static void Main(string[] args) { BrokerClient client = new BrokerClient(); string host = null; try { Console.WriteLine("Richiesta inviata"); host = client.GestisciLogin("gestoreMarco", "gestoreMarco", "gestoreSicurezza"); Console.WriteLine(host); } catch (FaultException <AccessFault> e) { Console.WriteLine(e.Detail.Message); } Console.ReadLine(); client.Close(); EntryOperazione e1 = new EntryOperazione { DataOra = DateTime.Now, Username = "******", Luogo = "Bologna", TipoOperazione = "salvataggio lista personale" }; EntryOperazione e2 = new EntryOperazione { DataOra = DateTime.Now, Username = "******", Luogo = "Bologna", TipoOperazione = "creazione lista personale" }; EntryOperazione[] entries = new EntryOperazione[2]; entries[0] = e1; entries[1] = e2; try { if (host != null) { DateTime dateTimeStart = new DateTime(2018, 6, 17); DateTime dateTimeStop = new DateTime(2018, 6, 18); BasicHttpBinding myBinding = new BasicHttpBinding(); EndpointAddress myEndpoint = new EndpointAddress(host); ChannelFactory <IGestoreSicurezza> myChannelFactory = new ChannelFactory <IGestoreSicurezza>(myBinding, myEndpoint); // Create a channel. IGestoreSicurezza clientGestoreSicurezza = myChannelFactory.CreateChannel(); //clientGestoreSicurezza.PrintLogOperazioni(entries); //Console.WriteLine("scrittura log avvenuta con successo!"); List <string> operazioni = clientGestoreSicurezza.GetEntryOperazioni(dateTimeStart).OfType <string>().ToList(); foreach (string op in operazioni) { Console.WriteLine(op); } ((IClientChannel)clientGestoreSicurezza).Close(); Console.ReadLine(); } } catch (FaultException <BookFault> e) { Console.WriteLine(e.Detail.Message); } }
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 static void InternalResponseHandlerTestMultiThreads(SessionBase session) { NetTcpBinding binding = Utils.CreateNetTcpBinding(); byte[] task_data = new byte[input_data_size]; (new Random()).NextBytes(task_data); AutoResetEvent allClientSendEvt = new AutoResetEvent(false); AutoResetEvent allClientDoneEvt = new AutoResetEvent(false); int clientSendCounting = batchCount; int clientDoneCounting = batchCount; data.SendStart = DateTime.Now; for (int i = 0; i < batchCount; i++) { int msg_count = req_count / batchCount; if (i == batchCount - 1) { msg_count += req_count % batchCount; } string clientId = Environment.MachineName + "-" + i.ToString() + "-" + Process.GetCurrentProcess().Id.ToString(); Thread t = new Thread(new ThreadStart(() => { AutoResetEvent batchDone = new AutoResetEvent(false); using (var client = new BrokerClient <IService1>(clientId, session, binding)) { ResponseHandlerBase handler; handler = new ComputeWithInputDataResponseHandler(client, clientId, common_data_size, retryRequestAndIgnoreRetryOperationError); client.SetResponseHandler <ComputeWithInputDataResponse>(((ComputeWithInputDataResponseHandler)handler).ResponseHandler <ComputeWithInputDataResponse>); ClientSendRequest(client, clientId, msg_count, task_data); if (Interlocked.Decrement(ref clientSendCounting) <= 0) { allClientSendEvt.Set(); } handler.WaitOne(); Log("Client {0}: All requests returned.", clientId); lock (lockobject) { data.ResultCollection.AddRange(handler.results); data.FaultCount = handler.faultCalls; } try { client.Close(durable, 10 * 60 * 1000); } catch (Exception e) { Log("Purge client {0} failed: {1}", clientId, e.ToString()); } if (Interlocked.Decrement(ref clientDoneCounting) <= 0) { allClientDoneEvt.Set(); } } })); t.Start(); } allClientSendEvt.WaitOne(); data.SendEnd = DateTime.Now; allClientDoneEvt.WaitOne(); data.RetrieveEnd = DateTime.Now; }
private static void InternalGetResponseTestMultiThreads(SessionBase session) { NetTcpBinding binding = Utils.CreateNetTcpBinding(); int faultCalls = 0; byte[] task_data = new byte[input_data_size]; (new Random()).NextBytes(task_data); AutoResetEvent allClientSendEvt = new AutoResetEvent(false); AutoResetEvent allClientDoneEvt = new AutoResetEvent(false); int clientSendCounting = batchCount; int clientDoneCounting = batchCount; data.SendStart = DateTime.Now; for (int i = 0; i < batchCount; i++) { int msg_count = req_count / batchCount; if (i == batchCount - 1) { msg_count += req_count % batchCount; } string clientId = Environment.MachineName + "-" + i.ToString() + "-" + Process.GetCurrentProcess().Id.ToString(); //Console.WriteLine("--Client Id = {0}", clientId); var client = new BrokerClient <IService1>(clientId, session, binding); Thread t = new Thread(new ThreadStart(() => { ClientSendRequest(client, clientId, msg_count, task_data); if (Interlocked.Decrement(ref clientSendCounting) <= 0) { allClientSendEvt.Set(); } })); Thread t2 = new Thread(new ThreadStart(() => { List <ResultData> results = ClientGetResponse(client, clientId); lock (lockobject) { data.ResultCollection.AddRange(results); } try { client.Close(durable, 10 * 60 * 1000); } catch (Exception e) { Log("Purge client {0} failed: {1}", clientId, e.ToString()); } finally { client.Close(); client.Dispose(); if (Interlocked.Decrement(ref clientDoneCounting) <= 0) { allClientDoneEvt.Set(); } } })); t.Start(); t2.Start(); } allClientSendEvt.WaitOne(); data.SendEnd = DateTime.Now; allClientDoneEvt.WaitOne(); data.RetrieveEnd = DateTime.Now; data.FaultCount = faultCalls; }
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) { //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(); }