static void Main(string[] args) { CalculatorClient wcfClient = new CalculatorClient("NetNamedPipeBinding_ICalculator"); try { // Call the Add service operation. double value1 = 100.00D; double value2 = 15.99D; double result = wcfClient.Add(value1, value2); Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result); } catch (TimeoutException timeProblem) { Console.WriteLine("The service operation timed out. " + timeProblem.Message); Console.ReadLine(); wcfClient.Abort(); } catch (CommunicationException commProblem) { Console.WriteLine("There was a communication problem. " + commProblem.Message + commProblem.StackTrace); Console.ReadLine(); wcfClient.Abort(); } Console.WriteLine(); Console.WriteLine("Press <ENTER> to terminate client."); Console.ReadLine(); }
private void ClientRun() { //<snippet19> // Create the binding. WSHttpBinding myBinding = new WSHttpBinding(); myBinding.Security.Mode = SecurityMode.Message; myBinding.Security.Message.ClientCredentialType = MessageCredentialType.Windows; // Disable credential negotiation and the establishment of // a security context. myBinding.Security.Message.NegotiateServiceCredential = false; myBinding.Security.Message.EstablishSecurityContext = false; // Create the endpoint address and set the SPN identity. // The SPN must match the identity of the service's SPN. // If using SvcUtil to generate a configuration file, the SPN // will be published as the <servicePrincipalName> element under the // <identity> element. EndpointAddress ea = new EndpointAddress( new Uri("http://machineName/Calculator"), EndpointIdentity.CreateSpnIdentity("service_spn_name")); // Create the client. CalculatorClient cc = new CalculatorClient(myBinding, ea); // Begin using the client. try { cc.Open(); Console.WriteLine(cc.Add(200, 1111)); Console.ReadLine(); // Close the client. cc.Close(); } //</snippet19> catch (TimeoutException tex) { Console.WriteLine(tex.Message); cc.Abort(); } catch (CommunicationException cex) { Console.WriteLine(cex.Message); cc.Abort(); } finally { Console.WriteLine("Closed the client"); Console.ReadLine(); } }
static void Main() { // Create a client with Certificate endpoint configuration CalculatorClient client = new CalculatorClient("Certificate"); try { client.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, "alice"); // Call the Add service operation. double value1 = 100.00D; double value2 = 15.99D; double result = client.Add(value1, value2); Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result); // Call the Subtract service operation. value1 = 145.00D; value2 = 76.54D; result = client.Subtract(value1, value2); Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result); // Call the Multiply service operation. value1 = 9.00D; value2 = 81.25D; result = client.Multiply(value1, value2); Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result); // Call the Divide service operation. value1 = 22.00D; value2 = 7.00D; result = client.Divide(value1, value2); Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result); client.Close(); } catch (TimeoutException e) { Console.WriteLine("Call timed out : {0}", e.Message); client.Abort(); } catch (CommunicationException e) { Console.WriteLine("Call failed : {0}", e.Message); client.Abort(); } catch (Exception e) { Console.WriteLine("Call failed : {0}", e.Message); client.Abort(); } Console.WriteLine(); Console.WriteLine("Press <ENTER> to terminate client."); Console.ReadLine(); }
public static void ClientRun() { //<snippet2> // Create the binding. WSHttpBinding myBinding = new WSHttpBinding(); myBinding.Security.Mode = SecurityMode.Transport; myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; // Create the endpoint address. Note that the machine name // must match the subject or DNS field of the X.509 certificate // used to authenticate the service. EndpointAddress ea = new EndpointAddress("https://machineName/Calculator"); // Create the client. The code for the calculator // client is not shown here. See the sample applications // for examples of the calculator code. CalculatorClient cc = new CalculatorClient(myBinding, ea); // The client must provide a user name and password. The code // to return the user name and password is not shown here. Use // a database to store the user name and passwords, or use the // ASP.NET Membership provider database. cc.ClientCredentials.UserName.UserName = ReturnUsername(); cc.ClientCredentials.UserName.Password = ReturnPassword(); try { // Begin using the client. cc.Open(); Console.WriteLine(cc.Add(100, 11)); Console.ReadLine(); // Close the client. cc.Close(); } //</snippet2> catch (TimeoutException tex) { Console.WriteLine(tex.Message); cc.Abort(); } catch (CommunicationException cex) { Console.WriteLine(cex.Message); cc.Abort(); } finally { Console.WriteLine("Closed the client"); Console.ReadLine(); } }
private void ClientRun() { //<snippet14> // Create the binding. WSHttpBinding myBinding = new WSHttpBinding(); myBinding.Security.Mode = SecurityMode.Transport; myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate; // Create the endpoint address. Note that the machine name // must match the subject or DNS field of the X.509 certificate // used to authenticate the service. EndpointAddress ea = new EndpointAddress("https://localhost:8006/Calculator"); // Create the client. The code for the calculator // client is not shown here. See the sample applications // for examples of the calculator code. CalculatorClient cc = new CalculatorClient(myBinding, ea); // The client must specify a certificate trusted by the server. cc.ClientCredentials.ClientCertificate.SetCertificate( StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, "contoso.com"); // Begin using the client. Console.WriteLine(cc.Add(100, 1111)); try { cc.Open(); // Close the client. cc.Close(); } //</snippet14> catch (TimeoutException tex) { Console.WriteLine(tex.Message); cc.Abort(); } catch (CommunicationException cex) { Console.WriteLine(cex.Message); cc.Abort(); } finally { Console.WriteLine("Closed the client"); Console.ReadLine(); } }
static void Main() { // Create a client with given client endpoint configuration CalculatorClient client = new CalculatorClient(); try { // Call the Add service operation. int value1 = 15; int value2 = 3; int result = client.Add(value1, value2); Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result); // Call the Subtract service operation. value1 = 145; value2 = 76; result = client.Subtract(value1, value2); Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result); // Call the Multiply service operation. value1 = 9; value2 = 81; result = client.Multiply(value1, value2); Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result); // Call the Divide service operation - trigger a divide by zero error. value1 = 22; value2 = 0; result = client.Divide(value1, value2); Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result); //Closing the client gracefully closes the connection and cleans up resources client.Close(); } catch (FaultException<MathFault> e) { Console.WriteLine("FaultException<MathFault>: Math fault while doing " + e.Detail.Operation + ". Problem: " + e.Detail.ProblemType); client.Abort(); } catch (FaultException e) { Console.WriteLine("Unknown FaultException: " + e.GetType().Name + " - " + e.Message); client.Abort(); } catch (Exception e) { Console.WriteLine("EXCEPTION: " + e.GetType().Name + " - " + e.Message); client.Abort(); } Console.WriteLine(); Console.WriteLine("Press <ENTER> to terminate client."); Console.ReadLine(); }
static void Main() { // Create a client with given client endpoint configuration CalculatorClient client = new CalculatorClient(); try { // Call the Add service operation. int value1 = 15; int value2 = 3; int result = client.Add(value1, value2); Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result); // Call the Subtract service operation. value1 = 145; value2 = 76; result = client.Subtract(value1, value2); Console.WriteLine("Subtract({0},{1}) = {2}", value1, value2, result); // Call the Multiply service operation. value1 = 9; value2 = 81; result = client.Multiply(value1, value2); Console.WriteLine("Multiply({0},{1}) = {2}", value1, value2, result); // Call the Divide service operation - trigger a divide by zero error. value1 = 22; value2 = 0; result = client.Divide(value1, value2); Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result); //Closing the client gracefully closes the connection and cleans up resources client.Close(); } catch (FaultException <MathFault> e) { Console.WriteLine("FaultException<MathFault>: Math fault while doing " + e.Detail.Operation + ". Problem: " + e.Detail.ProblemType); client.Abort(); } catch (FaultException e) { Console.WriteLine("Unknown FaultException: " + e.GetType().Name + " - " + e.Message); client.Abort(); } catch (Exception e) { Console.WriteLine("EXCEPTION: " + e.GetType().Name + " - " + e.Message); client.Abort(); } Console.WriteLine(); Console.WriteLine("Press <ENTER> to terminate client."); Console.ReadLine(); }
private void ClientRun() { //<snippet17> // Create the binding. WSHttpBinding myBinding = new WSHttpBinding(); myBinding.Security.Mode = SecurityMode.Message; myBinding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate; // Create the endpoint address. EndpointAddress ea = new EndpointAddress("http://machineName/Calculator"); // Create the client. CalculatorClient cc = new CalculatorClient(myBinding, ea); // Specify a certificate to use for authenticating the client. cc.ClientCredentials.ClientCertificate.SetCertificate( StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, "Cohowinery.com"); // Begin using the client. try { cc.Open(); Console.WriteLine(cc.Add(200, 1111)); Console.ReadLine(); // Close the client. cc.Close(); } //</snippet17> catch (TimeoutException tex) { Console.WriteLine(tex.Message); cc.Abort(); } catch (CommunicationException cex) { Console.WriteLine(cex.Message); cc.Abort(); } finally { Console.WriteLine("Closed the client"); Console.ReadLine(); } }
private void ClientRun() { //<snippet16> // Create the binding. WSHttpBinding myBinding = new WSHttpBinding(); myBinding.Security.Mode = SecurityMode.Message; myBinding.Security.Message.ClientCredentialType = MessageCredentialType.UserName; // Create the endpoint address. EndpointAddress ea = new EndpointAddress("http://machineName/Calculator"); // Create the client. CalculatorClient cc = new CalculatorClient(myBinding, ea); // Set the user name and password. The code to // return the user name and password is not shown here. Use // an interface to query the user for the information. cc.ClientCredentials.UserName.UserName = ReturnUsername(); cc.ClientCredentials.UserName.Password = ReturnPassword(); // Begin using the client. try { cc.Open(); Console.WriteLine(cc.Add(200, 1111)); Console.ReadLine(); // Close the client. cc.Close(); } //</snippet16> catch (TimeoutException tex) { Console.WriteLine(tex.Message); cc.Abort(); } catch (CommunicationException cex) { Console.WriteLine(cex.Message); cc.Abort(); } finally { Console.WriteLine("Closed the client"); Console.ReadLine(); } }
public static void RunClient() { //<snippet6> // Create the binding. WSHttpBinding myBinding = new WSHttpBinding(); myBinding.Security.Mode = SecurityMode.Transport; myBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None; // Create the endpoint address. Note that the machine name // must match the subject or DNS field of the X.509 certificate // used to authenticate the service. EndpointAddress ea = new EndpointAddress("https://machineName/Calculator"); // Create the client. The code for the calculator // client is not shown here. See the sample applications // for examples of the calculator code. CalculatorClient cc = new CalculatorClient(myBinding, ea); // Begin using the client. try { cc.Open(); Console.WriteLine(cc.Add(100, 1111)); // Close the client. cc.Close(); } //</snippet6> catch (TimeoutException tex) { Console.WriteLine(tex.Message); cc.Abort(); } catch (CommunicationException cex) { Console.WriteLine(cex.Message); cc.Abort(); } finally { Console.WriteLine("Closed the client"); Console.ReadLine(); } }
public static void RunClient() { //<snippet4> // Create the binding. NetTcpBinding myBinding = new NetTcpBinding(); myBinding.Security.Mode = SecurityMode.Transport; myBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows; // Create the endpoint address. EndpointAddress myEndpointAddress = new EndpointAddress("net.tcp://localhost:8008/Calculator"); // Create the client. The code for the calculator client // is not shown here. See the sample applications // for examples of the calculator code. CalculatorClient cc = new CalculatorClient(myBinding, myEndpointAddress); try { cc.Open(); // Begin using the client. Console.WriteLine(cc.Add(100, 11)); Console.ReadLine(); // Close the client. cc.Close(); } //</snippet4> catch (TimeoutException tex) { Console.WriteLine(tex.Message); cc.Abort(); } catch (CommunicationException cex) { Console.WriteLine(cex.Message); cc.Abort(); } finally { Console.WriteLine("Closed the client"); Console.ReadLine(); } }
static void DemonstrateCommunicationException() { // Create a client CalculatorClient client = new CalculatorClient(); try { // Call the Add service operation. double value1 = 100.00D; double value2 = 15.99D; double result = client.Add(value1, value2); Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result); // Simulate a network problem by aborting the connection. Console.WriteLine("Simulated network problem occurs..."); client.Abort(); // Call the Divide service operation. Now that the channel has been // abruptly terminated, the next call will fail. value1 = 22.00D; value2 = 7.00D; result = client.Divide(value1, value2); Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result); // SHOULD NOT GET HERE -- Divide should throw // If we had gotten here, we would want to close the client gracefully so // that the channel closes gracefully and cleans up resources. client.Close(); Console.WriteLine("Service successfully returned all results."); } catch (TimeoutException exception) { Console.WriteLine("Got {0}", exception.GetType()); client.Abort(); } catch (CommunicationException exception) { // Control comes here when client.Divide throws. The actual Exception // type is CommunicationObjectAbortedException, which is a subclass of // CommunicationException. Console.WriteLine("Got {0}", exception.GetType()); client.Abort(); } }
private void ClientRun() { //<snippet18> // Create the binding. WSHttpBinding myBinding = new WSHttpBinding(); myBinding.Security.Mode = SecurityMode.Message; myBinding.Security.Message.ClientCredentialType = MessageCredentialType.Windows; // Create the endpoint address. EndpointAddress ea = new EndpointAddress("net.tcp://machineName:8008/Calculator"); // Create the client. CalculatorClient cc = new CalculatorClient(myBinding, ea); // Begin using the client. try { cc.Open(); Console.WriteLine(cc.Add(200, 1111)); Console.ReadLine(); // Close the client. cc.Close(); } //</snippet18> catch (TimeoutException tex) { Console.WriteLine(tex.Message); cc.Abort(); } catch (CommunicationException cex) { Console.WriteLine(cex.Message); cc.Abort(); } finally { Console.WriteLine("Closed the client"); Console.ReadLine(); } }
// This method shows the correct way to clean up a client, including catching the // approprate Exceptions. static void DemonstrateCleanupWithExceptions() { // Create a client CalculatorClient client = new CalculatorClient(); try { // Demonstrate a successful client call. Console.WriteLine("Calling client.Add(0.0, 0.0);"); double addValue = client.Add(0.0, 0.0); Console.WriteLine(" client.Add(0.0, 0.0); returned {0}", addValue); // Demonstrate a failed client call. Console.WriteLine("Calling client.Divide(0.0, 0.0);"); double divideValue = client.Divide(0.0, 0.0); Console.WriteLine(" client.Divide(0.0, 0.0); returned {0}", divideValue); // Do a clean shutdown if everything works. In this sample we do not end up // here, but correct code should Close the client if everything was successful. Console.WriteLine("Closing the client"); client.Close(); } catch (CommunicationException e) { // Because the server suffered an internal server error, it rudely terminated // our connection, so we get a CommunicationException. Console.WriteLine("Got {0} from Divide.", e.GetType()); client.Abort(); } catch (TimeoutException e) { // In this sample we do not end up here, but correct code should catch // TimeoutException when calling a client. Console.WriteLine("Got {0} from Divide.", e.GetType()); client.Abort(); } catch (Exception e) { // In this sample we do not end up here. It is best practice to clean up the // client if some unexpected Exception occurs. Console.WriteLine("Got unexpected {0} from Divide, rethrowing.", e.GetType()); client.Abort(); throw; } }
static void Main(string[] args) { // помощник вывода в консоль ConsoleWriter writer = new ConsoleWriter(); // создадим клиент сервиса CalculatorClient client = new CalculatorClient("BasicHttpBinding_ICalculator"); try { // проверка соединения writer.Write("Проверка соединения с сервисом... "); if (!string.Equals(client.TestConnection(), "OK", StringComparison.InvariantCultureIgnoreCase)) { throw new Exception("Проверка соединения не удалась"); } writer.WriteLineSuccess(); writer.WriteLine(); // лямбда-функция проверки метода var CheckArithmeticOperation = new Action <Func <double, double, double>, string, double, double, double> ( (operation, operationName, arg1, arg2, expectedResult) => { writer.Write("Проверка операции '"); writer.Write(ConsoleColor.White, operation.Method.Name); writer.Write("', {0} {1} {2} = ", arg1.ToString(CultureInfo.InvariantCulture), operationName, arg2.ToString(CultureInfo.InvariantCulture)); double result = operation(arg1, arg2); if (result == expectedResult) { // проверка пройдена writer.Write("{0} ", result.ToString(CultureInfo.InvariantCulture)); writer.WriteLineSuccess(); } else { // ошибка throw new Exception(string.Format("Ошибка проверки метода '{0}': {1} {2} {3} != {4}", operation.Method.Name, arg1.ToString(CultureInfo.InvariantCulture), operationName, arg2.ToString(CultureInfo.InvariantCulture), expectedResult.ToString(CultureInfo.InvariantCulture))); } } ); // проверка метода Addition CheckArithmeticOperation(client.Addition, "+", 2.5, 5, 2.5 + 5); // проверка метода Subtraction CheckArithmeticOperation(client.Subtraction, "-", 2.5, 5, 2.5 - 5); // проверка метода Multiplication CheckArithmeticOperation(client.Multiplication, "*", 2.5, 5, 2.5 * 5); // проверка метода Division CheckArithmeticOperation(client.Division, "/", 2.5, 5, 2.5 / 5); // в конце работы закрываем клиент client.Close(); } catch (Exception ex) { // в случае ошибки необходимо принудительно закрыть клиент методом Abort() client.Abort(); // выводим информацию об ошибке writer.WriteLine(); writer.WriteLineError("Ошибка: {0}", ex.Message); } Console.WriteLine(); Console.WriteLine("Нажмите любую клавишу для продолжения..."); Console.ReadKey(); }
private void ClientRun() { //<snippet20> // Create the binding. WSHttpBinding myBinding = new WSHttpBinding(); myBinding.Security.Mode = SecurityMode.Message; myBinding.Security.Message.ClientCredentialType = MessageCredentialType.Certificate; // Disable credential negotiation and the establishment of // a security context. myBinding.Security.Message.NegotiateServiceCredential = false; myBinding.Security.Message.EstablishSecurityContext = false; // Create the endpoint address. EndpointAddress ea = new EndpointAddress("http://machineName/Calculator"); // Create the client. CalculatorClient cc = new CalculatorClient(myBinding, ea); // Specify a certificate to use for authenticating the client. cc.ClientCredentials.ClientCertificate.SetCertificate( StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, "Cohowinery.com"); // Specify a default certificate for the service. cc.ClientCredentials.ServiceCertificate.SetDefaultCertificate( StoreLocation.CurrentUser, StoreName.TrustedPeople, X509FindType.FindBySubjectName, "Contoso.com"); // Begin using the client. try { cc.Open(); Console.WriteLine(cc.Add(200, 1111)); Console.ReadLine(); // Close the client. cc.Close(); } //</snippet20> catch (TimeoutException tex) { Console.WriteLine(tex.Message); cc.Abort(); } catch (CommunicationException cex) { Console.WriteLine(cex.Message); cc.Abort(); } finally { Console.WriteLine("Closed the client"); Console.ReadLine(); } }
static void DemonstrateTimeoutException() { // Create a client CalculatorClient client = new CalculatorClient(); try { // Call the Add service operation. double value1 = 100.00D; double value2 = 15.99D; double result = client.Add(value1, value2); Console.WriteLine("Add({0},{1}) = {2}", value1, value2, result); // Set a ridiculously small timeout. This will cause the next call to // fail with a TimeoutException because it cannot process in time. Console.WriteLine("Set timeout too short for method to complete..."); client.InnerChannel.OperationTimeout = TimeSpan.FromMilliseconds(0.001); // Call the Divide service operation. value1 = 22.00D; value2 = 7.00D; result = client.Divide(value1, value2); Console.WriteLine("Divide({0},{1}) = {2}", value1, value2, result); // SHOULD NOT GET HERE -- Divide should throw // If we had gotten here, we would want to close the client gracefully so // that the channel closes gracefully and cleans up resources. client.Close(); Console.WriteLine("Service successfully returned all results."); } catch (TimeoutException exception) { // Control comes here when client.Divide throws a TimeoutException. Console.WriteLine("Got {0}", exception.GetType()); client.Abort(); } catch (CommunicationException exception) { Console.WriteLine("Got {0}", exception.GetType()); client.Abort(); } }