public static void TransportWithMessageCredential_NotSupported_NetHttps() { string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; // BasicHttpsSecurityMode.TransportWithMessageCredential is accessible but not supported. // Verify the correct exception and message is thrown. // When/if Message Security is supported this test will fail and will serve as a reminder to add test coverage. Assert.Throws<PlatformNotSupportedException>(() => { try { // *** SETUP *** \\ NetHttpsBinding netHttpsBinding = new NetHttpsBinding(BasicHttpsSecurityMode.TransportWithMessageCredential); factory = new ChannelFactory<IWcfService>(netHttpsBinding, new EndpointAddress(Endpoints.HttpBaseAddress_NetHttps)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }); }
public static void DefaultSettings_Echo_RoundTrips_String() { ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; string testString = "Hello"; Binding binding = null; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.True(result == testString, String.Format("Error: expected response from service: '{0}' Actual was: '{1}'", testString, result)); // *** CLEANUP *** \\ factory.Close(); ((ICommunicationObject)serviceProxy).Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
public static void DefaultSettings_Echo_RoundTrips_String() { string variationDetails = "Client:: BasicHttpBinding/DefaultValues\nServer:: BasicHttpBinding/DefaultValues"; string testString = "Hello"; StringBuilder errorBuilder = new StringBuilder(); bool success = false; BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None); try { ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); IWcfService serviceProxy = factory.CreateChannel(); string result = serviceProxy.Echo(testString); success = string.Equals(result, testString); if (!success) { errorBuilder.AppendLine(String.Format(" Error: expected response from service: '{0}' Actual was: '{1}'", testString, result)); } } catch (Exception ex) { errorBuilder.AppendLine(String.Format(" Error: Unexpected exception was caught while doing the basic echo test for variation...\n'{0}'\nException: {1}", variationDetails, ex.ToString())); } Assert.True(errorBuilder.Length == 0, "Test case FAILED with errors: " + errorBuilder.ToString()); }
public void Ipc_byteArray() { var uri = "ipc:///" + MethodBase.GetCurrentMethod().Name; using (var server = new ServiceHost(new Service(), new Uri(uri))) { var binding = new LocalBinding { MaxConnections = 5 }; server.AddServiceEndpoint(typeof(IService), binding, uri); server.Open(); Thread.Sleep(100); using (var channelFactory = new ChannelFactory<IService>(binding)) { var client = channelFactory.CreateChannel(new EndpointAddress(uri)); client.Execute(new byte[0]); byte[] bytes = new byte[512]; new Random().NextBytes(bytes); var timer = new Stopwatch(); timer.Start(); for (int i = 0; i < 5000; i++) client.Execute(bytes); timer.Stop(); Trace.WriteLine(timer.ElapsedMilliseconds.ToString() + " ms", MethodBase.GetCurrentMethod().Name); } } }
public static void BasicAuthenticationInvalidPwd_throw_MessageSecurityException() { StringBuilder errorBuilder = new StringBuilder(); // Will need to use localized string once it is available // On Native retail, the message is stripped to 'HttpAuthorizationForbidden, Basic' // On Debug or .Net Core, the entire message is "The HTTP request was forbidden with client authentication scheme 'Basic'." // Thus we will only check message contains "forbidden" string message = "forbidden"; MessageSecurityException exception = Assert.Throws<MessageSecurityException>(() => { BasicHttpBinding basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; ChannelFactory<IWcfCustomUserNameService> factory = new ChannelFactory<IWcfCustomUserNameService>(basicHttpBinding, new EndpointAddress(Endpoints.Https_BasicAuth_Address)); factory.Credentials.UserName.UserName = "******"; factory.Credentials.UserName.Password = "******"; IWcfCustomUserNameService serviceProxy = factory.CreateChannel(); string testString = "I am a test"; string result = serviceProxy.Echo(testString); }); Assert.True(exception.Message.ToLower().Contains(message), string.Format("Expected exception message to contain: '{0}', actual message is: '{1}'", message, exception.Message)); }
public static void CustomBinding_Message_Interceptor() { ChannelFactory<IWcfChannelExtensibilityContract> factory = null; IWcfChannelExtensibilityContract serviceProxy = null; try { // *** SETUP *** \\ CustomBinding binding = new CustomBinding( new InterceptingBindingElement(new MessageModifier()), new HttpTransportBindingElement()); factory = new ChannelFactory<IWcfChannelExtensibilityContract>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_ChannelExtensibility)); serviceProxy = factory.CreateChannel(); // *** EXECUTE & VALIDATE *** \\ int[] windSpeeds = new int[] { 100, 90, 80, 70, 60, 50, 40, 30, 20, 10 }; for (int i = 0; i < 10; i++) { serviceProxy.ReportWindSpeed(windSpeeds[i]); } // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
public static void UnexpectedException_Throws_FaultException() { string faultMsg = "This is a test fault msg"; BasicHttpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; EndpointAddress endpointAddress = null; FaultException<ExceptionDetail> exception = Assert.Throws<FaultException<ExceptionDetail>>(() => { // *** SETUP *** \\ binding = new BasicHttpBinding(); endpointAddress = new EndpointAddress(Endpoints.HttpBaseAddress_Basic); factory = new ChannelFactory<IWcfService>(binding, endpointAddress); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ try { serviceProxy.ThrowInvalidOperationException(faultMsg); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }); // *** ADDITIONAL VALIDATION *** \\ Assert.True(String.Equals(exception.Detail.Message, faultMsg), String.Format("Expected Fault Message: {0}, actual: {1}", faultMsg, exception.Detail.Message)); }
public static void NonExistentAction_Throws_ActionNotSupportedException() { string exceptionMsg = "The message with Action 'http://tempuri.org/IWcfService/NotExistOnServer' cannot be processed at the receiver, due to a ContractFilter mismatch at the EndpointDispatcher. This may be because of either a contract mismatch (mismatched Actions between sender and receiver) or a binding/security mismatch between the sender and the receiver. Check that sender and receiver have the same contract and the same binding (including security requirements, e.g. Message, Transport, None)."; try { BasicHttpBinding binding = new BasicHttpBinding(); using (ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic))) { IWcfService serviceProxy = factory.CreateChannel(); serviceProxy.NotExistOnServer(); } } catch (Exception e) { if (e.GetType() != typeof(System.ServiceModel.ActionNotSupportedException)) { Assert.True(false, string.Format("Expected exception: {0}, actual: {1}", "ActionNotSupportedException", e.GetType())); } if (e.Message != exceptionMsg) { Assert.True(false, string.Format("Expected Fault Message: {0}, actual: {1}", exceptionMsg, e.Message)); } return; } Assert.True(false, "Expected ActionNotSupportedException exception, but no exception thrown."); }
public static void SendTimeout_For_Long_Running_Operation_Throws_TimeoutException() { TimeSpan serviceOperationTimeout = TimeSpan.FromMilliseconds(10000); BasicHttpBinding binding = new BasicHttpBinding(); binding.SendTimeout = TimeSpan.FromMilliseconds(5000); ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); Stopwatch watch = new Stopwatch(); try { var exception = Assert.Throws<TimeoutException>(() => { IWcfService proxy = factory.CreateChannel(); watch.Start(); proxy.EchoWithTimeout("Hello", serviceOperationTimeout); }); } finally { watch.Stop(); } // want to assert that this completed in > 5 s as an upper bound since the SendTimeout is 5 sec // (usual case is around 5001-5005 ms) Assert.InRange<long>(watch.ElapsedMilliseconds, 4985, 6000); }
public static void SameBinding_SecurityModeNone_EchoString() { string variationDetails = "Client:: NetTcpBinding/SecurityMode = None\nServer:: NetTcpBinding/SecurityMode = None"; string testString = "Hello"; StringBuilder errorBuilder = new StringBuilder(); bool success = false; try { NetTcpBinding binding = new NetTcpBinding(SecurityMode.None); ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_Address)); IWcfService serviceProxy = factory.CreateChannel(); string result = serviceProxy.Echo(testString); success = string.Equals(result, testString); if (!success) { errorBuilder.AppendLine(String.Format(" Error: expected response from service: '{0}' Actual was: '{1}'", testString, result)); } } catch (Exception ex) { errorBuilder.AppendLine(String.Format(" Error: Unexpected exception was caught while doing the basic echo test for variation...\n'{0}'\nException: {1}", variationDetails, ex.ToString())); for (Exception innerException = ex.InnerException; innerException != null; innerException = innerException.InnerException) { errorBuilder.AppendLine(String.Format("Inner exception: {0}", innerException.ToString())); } } Assert.True(errorBuilder.Length == 0, "Test case FAILED with errors: " + errorBuilder.ToString()); }
public static void NetTcp_TransportSecurity_StreamedResponse_RoundTrips_String() { string testString = "Hello"; NetTcpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ binding = new NetTcpBinding(SecurityMode.Transport); binding.TransferMode = TransferMode.StreamedResponse; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Transport_Security_Streamed_Address)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ var returnStream = serviceProxy.GetStreamFromString(testString); var result = StreamToString(returnStream); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
public static void NotExistentHost_Throws_EndpointNotFoundException() { string nonExistentHost = "http://nonexisthost/WcfService/WindowsCommunicationFoundation"; ChannelFactory<IWcfService> factory = null; EndpointAddress endpointAddress = null; BasicHttpBinding binding = null; IWcfService serviceProxy = null; // *** VALIDATE *** \\ EndpointNotFoundException exception = Assert.Throws<EndpointNotFoundException>(() => { // *** SETUP *** \\ binding = new BasicHttpBinding(); binding.SendTimeout = TimeSpan.FromMilliseconds(20000); endpointAddress = new EndpointAddress(nonExistentHost); factory = new ChannelFactory<IWcfService>(binding, endpointAddress); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ try { serviceProxy.Echo("Hello"); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }); // *** ADDITIONAL VALIDATION FOR NET NATIVE *** \\ // On .Net Native retail, exception message is stripped to include only parameter Assert.True(exception.Message.Contains(nonExistentHost), string.Format("Expected exception message to contain: '{0}'\nThe exception message was: {1}", nonExistentHost, exception.Message)); }
public void CallServiceReturningSession2TimesFor2Channels_sessionAreDifferentForDifferentChannels() { var address = @"net.pipe://127.0.0.1/1/test.test/test" + MethodBase.GetCurrentMethod().Name; var serv = new SessionService(); var host = new ServiceHost(serv, new Uri(address)); var b = new NetNamedPipeBinding(); host.AddServiceEndpoint(typeof(ISessionService), b, address); var f1 = new ChannelFactory<ISessionService>(b); var f2 = new ChannelFactory<ISessionService>(b); var client1 = f1.CreateChannel(new EndpointAddress(address)); var client2 = f2.CreateChannel(new EndpointAddress(address)); host.Open(); var session11 = client1.Call(); var session21 = client2.Call(); var session22 = client2.Call(); var session12 = client1.Call(); f1.Dispose(); f2.Dispose(); host.Dispose(); Assert.AreEqual(session11, session12); Assert.AreEqual(session21, session22); Assert.AreNotEqual(session11, session21); }
public static void SameBinding_Soap11_EchoString() { CustomBinding binding = null; EndpointAddress endpointAddress = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; string testString = "Hello"; string result = null; try { // *** SETUP *** \\ binding = new CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8), new HttpTransportBindingElement()); endpointAddress = new EndpointAddress(Endpoints.HttpSoap11_Address); factory = new ChannelFactory<IWcfService>(binding, endpointAddress); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.True(String.Equals(result, testString), String.Format(" Error: expected response from service: '{0}' Actual was: '{1}'", testString, result)); // *** CLEANUP *** \\ factory.Close(); ((ICommunicationObject)serviceProxy).Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
public static void SecurityModeTransport_Echo_RoundTrips_String() { string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport); factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_DefaultBinding_Address)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
public static void DefaultSettings_Tcp_Binary_Echo_RoundTrips_String() { string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ CustomBinding binding = new CustomBinding( new SslStreamSecurityBindingElement(), new BinaryMessageEncodingBindingElement(), new TcpTransportBindingElement()); var endpointIdentity = new DnsEndpointIdentity(Endpoints.Tcp_CustomBinding_SslStreamSecurity_HostName); factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(new Uri(Endpoints.Tcp_CustomBinding_SslStreamSecurity_Address), endpointIdentity)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
public static void BasicHttp_DefaultSettings_Echo_RoundTrips_String_StreamedRequest() { string testString = "Hello"; BasicHttpBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; Stream stream = null; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.TransferMode = TransferMode.StreamedRequest; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); serviceProxy = factory.CreateChannel(); stream = StringToStream(testString); // *** EXECUTE *** \\ var result = serviceProxy.GetStringFromStream(stream); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
public static void DefaultSettings_Https_Text_Echo_RoundTrips_String() { string testString = "Hello"; CustomBinding binding = null; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ binding = new CustomBinding(new TextMessageEncodingBindingElement(), new HttpsTransportBindingElement()); factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpsSoap12_Address)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.NotNull(result); Assert.Equal(testString, result); // *** CLEANUP *** \\ factory.Close(); ((ICommunicationObject)serviceProxy).Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
public static void DefaultSettings_Echo_RoundTrips_String() { string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ NetHttpBinding binding = new NetHttpBinding(); factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_NetHttp)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.NotNull(result); Assert.Equal(testString, result); // *** CLEANUP *** \\ factory.Close(); ((ICommunicationObject)serviceProxy).Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
public static void DigestAuthentication_Echo_RoundTrips_String_No_Domain() { ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; string testString = "Hello"; BasicHttpBinding binding; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Digest; factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Http_DigestAuth_NoDomain_Address)); factory.Credentials.HttpDigest.ClientCredential = BridgeClientAuthenticationManager.NetworkCredential; serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.True(result == testString, string.Format("Error: expected response from service: '{0}' Actual was: '{1}'", testString, result)); // *** CLEANUP *** \\ factory.Close(); ((ICommunicationObject)serviceProxy).Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
public static void CustomTextMessageEncoder_Http_RequestReply_Buffered() { ChannelFactory<IWcfService> channelFactory = null; IWcfService client = null; string testString = "Hello"; try { // *** SETUP *** \\ CustomBinding binding = new CustomBinding(new CustomTextMessageBindingElement(Encoding.UTF8.WebName), new HttpTransportBindingElement { MaxReceivedMessageSize = ScenarioTestHelpers.SixtyFourMB, MaxBufferSize = ScenarioTestHelpers.SixtyFourMB }); channelFactory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.CustomTextEncoderBuffered_Address)); client = channelFactory.CreateChannel(); // *** EXECUTE *** \\ string result = client.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(result, testString); // *** CLEANUP *** \\ ((ICommunicationObject)client).Close(); channelFactory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)client, channelFactory); } }
public static void SameBinding_Binary_EchoComplexString() { string variationDetails = "Client:: CustomBinding/BinaryEncoder/Http\nServer:: CustomBinding/BinaryEncoder/Http"; StringBuilder errorBuilder = new StringBuilder(); bool success = false; try { CustomBinding binding = new CustomBinding(new BinaryMessageEncodingBindingElement(), new HttpTransportBindingElement()); ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBinary_Address)); IWcfService serviceProxy = factory.CreateChannel(); ComplexCompositeType compositeObject = ScenarioTestHelpers.GetInitializedComplexCompositeType(); ComplexCompositeType result = serviceProxy.EchoComplex(compositeObject); success = compositeObject.Equals(result); if (!success) { errorBuilder.AppendLine(String.Format(" Error: expected response from service: '{0}' Actual was: '{1}'", compositeObject, result)); } } catch (Exception ex) { errorBuilder.AppendLine(String.Format(" Error: Unexpected exception was caught while doing the basic echo test for variation...\n'{0}'\nException: {1}", variationDetails, ex.ToString())); for (Exception innerException = ex.InnerException; innerException != null; innerException = innerException.InnerException) { errorBuilder.AppendLine(String.Format("Inner exception: {0}", innerException.ToString())); } } Assert.True(errorBuilder.Length == 0, errorBuilder.ToString()); }
public static void TextMessageEncoder_WrongContentTypeResponse_Throws_ProtocolException() { ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; string testContentType = "text/blah"; Binding binding = null; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ Assert.Throws<ProtocolException>(() => { serviceProxy.ReturnContentType(testContentType); }); // *** VALIDATE *** \\ // *** CLEANUP *** \\ factory.Close(); ((ICommunicationObject)serviceProxy).Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
// Verify product throws MessageSecurityException when the Dns identity from the server does not match the expectation public static void ServiceIdentityNotMatch_Throw_MessageSecurityException() { string testString = "Hello"; NetTcpBinding binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.Transport; binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None; EndpointAddress endpointAddress = new EndpointAddress(new Uri(Endpoints.Tcp_VerifyDNS_Address), new DnsEndpointIdentity("wrongone")); ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, endpointAddress); IWcfService serviceProxy = factory.CreateChannel(); try { var exception = Assert.Throws<MessageSecurityException>(() => { var result = serviceProxy.Echo(testString); Assert.Equal(testString, result); }); Assert.True(exception.Message.Contains(Endpoints.Tcp_VerifyDNS_HostName), string.Format("Expected exception message contains: '{0}', actual: '{1}')", Endpoints.Tcp_VerifyDNS_HostName, exception.Message)); } finally { ScenarioTestHelpers.CloseCommunicationObjects(factory); } }
public static bool RunBasicEchoTest(Binding binding, string address, string variation, StringBuilder errorBuilder, Action<ChannelFactory> factorySettings = null) { Logger.LogInformation("Starting basic echo test.\nTest variation:...\n{0}\nUsing address: '{1}'", variation, address); bool success = false; try { ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(address)); if (factorySettings != null) { factorySettings(factory); } IWcfService serviceProxy = factory.CreateChannel(); string result = serviceProxy.Echo(testString); success = string.Equals(result, testString); if (!success) { errorBuilder.AppendLine(String.Format(" Error: expected response from service: '{0}' Actual was: '{1}'", testString, result)); } } catch (Exception ex) { Logger.LogInformation(" {0}", ex.Message); errorBuilder.AppendLine(String.Format(" Error: Unexpected exception was caught while doing the basic echo test for variation...\n'{0}'\nException: {1}", variation, ex.ToString())); } Logger.LogInformation(" Result: {0} ", success ? "PASS" : "FAIL"); return success; }
public static void SameBinding_Binary_EchoComplexString() { CustomBinding binding = null; ChannelFactory<IWcfService> factory = null; EndpointAddress endpointAddress = null; IWcfService serviceProxy = null; ComplexCompositeType compositeObject = null; ComplexCompositeType result = null; try { // *** SETUP *** \\ binding = new CustomBinding(new BinaryMessageEncodingBindingElement(), new HttpTransportBindingElement()); endpointAddress = new EndpointAddress(Endpoints.HttpBinary_Address); factory = new ChannelFactory<IWcfService>(binding, endpointAddress); serviceProxy = factory.CreateChannel(); compositeObject = ScenarioTestHelpers.GetInitializedComplexCompositeType(); // *** EXECUTE *** \\ result = serviceProxy.EchoComplex(compositeObject); // *** VALIDATE *** \\ Assert.True(compositeObject.Equals(result), String.Format(" Error: expected response from service: '{0}' Actual was: '{1}'", compositeObject, result)); // *** CLEANUP *** \\ factory.Close(); ((ICommunicationObject)serviceProxy).Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
public static void DefaultCtor_NetHttps_Echo_RoundTrips_String() { string testString = "Hello"; ChannelFactory<IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ NetHttpsBinding netHttpsBinding = new NetHttpsBinding(); factory = new ChannelFactory<IWcfService>(netHttpsBinding, new EndpointAddress(Endpoints.HttpBaseAddress_NetHttps)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.True(String.Equals(testString, result), String.Format("Expected result was {0}. Actual was {1}", testString, result)); // *** CLEANUP *** \\ factory.Close(); ((ICommunicationObject)serviceProxy).Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
public static void BasicAuthentication_RoundTrips_Echo() { StringBuilder errorBuilder = new StringBuilder(); try { BasicHttpBinding basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic; ChannelFactory<IWcfCustomUserNameService> factory = new ChannelFactory<IWcfCustomUserNameService>(basicHttpBinding, new EndpointAddress(Endpoints.Https_BasicAuth_Address)); factory.Credentials.UserName.UserName = "******"; factory.Credentials.UserName.Password = "******"; IWcfCustomUserNameService serviceProxy = factory.CreateChannel(); string testString = "I am a test"; string result = serviceProxy.Echo(testString); bool success = string.Equals(result, testString); if (!success) { errorBuilder.AppendLine(string.Format("Basic echo test.\nTest variation:...\n{0}\nUsing address: '{1}'", "BasicAuthentication_RoundTrips_Echo", Endpoints.Https_BasicAuth_Address)); errorBuilder.AppendLine(String.Format(" Error: expected response from service: '{0}' Actual was: '{1}'", testString, result)); } } catch (Exception ex) { errorBuilder.AppendLine(string.Format("Basic echo test.\nTest variation:...\n{0}\nUsing address: '{1}'", "BasicAuthentication_RoundTrips_Echo", Endpoints.Https_BasicAuth_Address)); errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString())); } Assert.True(errorBuilder.Length == 0, String.Format("Test Case: BasicAuthentication FAILED with the following errors: {0}", errorBuilder)); }
public void ServerAncClientExceptionsEndpointBehavior() { var hook = new ExceptionsEndpointBehaviour(); var address = @"net.pipe://127.0.0.1/test" + this.GetType().Name + "_" + MethodBase.GetCurrentMethod().Name; var serv = new ExceptionService(); using (var host = new ServiceHost(serv, new Uri[] { new Uri(address), })) { var b = new NetNamedPipeBinding(); var serverEndpoint = host.AddServiceEndpoint(typeof(IExceptionService), b, address); serverEndpoint.Behaviors.Add(hook); host.Open(); var f = new ChannelFactory<IExceptionService>(b); f.Endpoint.Behaviors.Add(hook); var c = f.CreateChannel(new EndpointAddress(address)); try { c.DoException("message"); } catch (InvalidOperationException ex) { StringAssert.AreEqualIgnoringCase("message", ex.Message); } host.Abort(); } }
public static void SameBinding_Soap11_EchoString() { string variationDetails = "Client:: CustomBinding/HttpTransport/TextEncoding/Soap11 = None\nServer:: CustomBinding/HttpTransport/TextEncoding/Soap11"; string testString = "Hello"; StringBuilder errorBuilder = new StringBuilder(); bool success = false; try { CustomBinding binding = new CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8), new HttpTransportBindingElement()); ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.HttpSoap11_Address)); IWcfService serviceProxy = factory.CreateChannel(); string result = serviceProxy.Echo(testString); success = string.Equals(result, testString); if (!success) { errorBuilder.AppendLine(String.Format(" Error: expected response from service: '{0}' Actual was: '{1}'", testString, result)); } } catch (Exception ex) { errorBuilder.AppendLine(String.Format(" Error: Unexpected exception was caught while doing the basic echo test for variation...\n'{0}'\nException: {1}", variationDetails, ex.ToString())); for (Exception innerException = ex.InnerException; innerException != null; innerException = innerException.InnerException) { errorBuilder.AppendLine(String.Format("Inner exception: {0}", innerException.ToString())); } } Assert.True(errorBuilder.Length == 0, "Test case FAILED with errors: " + errorBuilder.ToString()); }
public static void Abort_During_Implicit_Open_Closes_Sync_Waiters() { // This test is a regression test of an issue with CallOnceManager. // When a single proxy is used to make several service calls without // explicitly opening it, the CallOnceManager queues up all the requests // that happen while it is opening the channel (or handling previously // queued service calls. If the channel was closed or faulted during // the handling of any queued requests, it caused a pathological worst // case where every queued request waited for its complete SendTimeout // before failing. // // This test operates by making multiple concurrent synchronous service // calls, but stalls the Opening event to allow them to be queued before // any of them are allowed to proceed. It then aborts the channel when // the first service operation is allowed to proceed. This causes the // CallOnce manager to deal with all its queued operations and cause // them to complete other than by timing out. BasicHttpBinding binding = null; ChannelFactory <IWcfService> factory = null; IWcfService serviceProxy = null; int timeoutMs = 20000; long operationsQueued = 0; int operationCount = 5; Task <string>[] tasks = new Task <string> [operationCount]; Exception[] exceptions = new Exception[operationCount]; string[] results = new string[operationCount]; bool isClosed = false; DateTime endOfOpeningStall = DateTime.Now; int serverDelayMs = 100; TimeSpan serverDelayTimeSpan = TimeSpan.FromMilliseconds(serverDelayMs); string testMessage = "testMessage"; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.TransferMode = TransferMode.Streamed; // SendTimeout is the timeout used for implicit opens binding.SendTimeout = TimeSpan.FromMilliseconds(timeoutMs); factory = new ChannelFactory <IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); serviceProxy = factory.CreateChannel(); // Force the implicit open to stall until we have multiple concurrent calls pending. // This forces the CallOnceManager to have a queue of waiters it will need to notify. ((ICommunicationObject)serviceProxy).Opening += (s, e) => { // Wait until we see sync calls have been queued DateTime startOfOpeningStall = DateTime.Now; while (true) { endOfOpeningStall = DateTime.Now; // Don't wait forever -- if we stall longer than the SendTimeout, it means something // is wrong other than what we are testing, so just fail early. if ((endOfOpeningStall - startOfOpeningStall).TotalMilliseconds > timeoutMs) { Assert.True(false, "The Opening event timed out waiting for operations to queue, which was not expected for this test."); } // As soon as we have all our Tasks at least running, wait a little // longer to allow them finish queuing up their waiters, then stop stalling the Opening if (Interlocked.Read(ref operationsQueued) >= operationCount) { Task.Delay(500).Wait(); endOfOpeningStall = DateTime.Now; return; } Task.Delay(100).Wait(); } }; // Each task will make a synchronous service call, which will cause all but the // first to be queued for the implicit open. The first call to complete then closes // the channel so that it is forced to deal with queued waiters. Func <string> callFunc = () => { // We increment the # ops queued before making the actual sync call, which is // technically a short race condition in the test. But reversing the order would // timeout the implicit open and fault the channel. Interlocked.Increment(ref operationsQueued); // The call of the operation is what creates the entry in the CallOnceManager queue. // So as each Task below starts, it increments the count and adds a waiter to the // queue. We ask for a small delay on the server side just to introduce a small // stall after the sync request has been made before it can complete. Otherwise // fast machines can finish all the requests before the first one finishes the Close(). string result = serviceProxy.EchoWithTimeout("test", serverDelayTimeSpan); lock (tasks) { if (!isClosed) { try { isClosed = true; ((ICommunicationObject)serviceProxy).Abort(); } catch { } } } return(result); }; // *** EXECUTE *** \\ DateTime startTime = DateTime.Now; for (int i = 0; i < operationCount; ++i) { tasks[i] = Task.Run(callFunc); } for (int i = 0; i < operationCount; ++i) { try { results[i] = tasks[i].GetAwaiter().GetResult(); } catch (Exception ex) { exceptions[i] = ex; } } // *** VALIDATE *** \\ double elapsedMs = (DateTime.Now - endOfOpeningStall).TotalMilliseconds; // Before validating that the issue was fixed, first validate that we received the exceptions or the // results we expected. This is to verify the fix did not introduce a behavioral change other than the // elimination of the long unnecessary timeouts after the channel was closed. int nFailures = 0; for (int i = 0; i < operationCount; ++i) { if (exceptions[i] == null) { Assert.True((String.Equals("test", results[i])), String.Format("Expected operation #{0} to return '{1}' but actual was '{2}'", i, testMessage, results[i])); } else { ++nFailures; TimeoutException toe = exceptions[i] as TimeoutException; Assert.True(toe == null, String.Format("Task [{0}] should not have failed with TimeoutException", i)); } } Assert.True(nFailures > 0, String.Format("Expected at least one operation to throw an exception, but none did. Elapsed time = {0} ms.", elapsedMs)); Assert.True(nFailures < operationCount, String.Format("Expected at least one operation to succeed but none did. Elapsed time = {0} ms.", elapsedMs)); // The original issue was that sync waiters in the CallOnceManager were not notified when // the channel became unusable and therefore continued to time out for the full amount. // Additionally, because they were executed sequentially, it was also possible for each one // to time out for the full amount. Given that we closed the channel, we expect all the queued // waiters to have been immediately waked up and detected failure. int expectedElapsedMs = (operationCount * serverDelayMs) + timeoutMs / 2; Assert.True(elapsedMs < expectedElapsedMs, String.Format("The {0} operations took {1} ms to complete which exceeds the expected {2} ms", operationCount, elapsedMs, expectedElapsedMs)); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
/// <summary> /// Called by <see cref="DataPortal" /> to delete a /// business object. /// </summary> /// <param name="objectType">Type of business object to create.</param> /// <param name="criteria">Criteria object describing business object.</param> /// <param name="context"> /// <see cref="Server.DataPortalContext" /> object passed to the server. /// </param> /// <param name="isSync">True if the client-side proxy should synchronously invoke the server.</param> #pragma warning disable 1998 public async Task <DataPortalResult> Delete(Type objectType, object criteria, DataPortalContext context, bool isSync) #pragma warning restore 1998 { #if !(ANDROID || IOS) && !NETFX_CORE ChannelFactory <IWcfPortal> cf = GetChannelFactory(); var proxy = GetProxy(cf); WcfResponse response = null; #if NET40 try { var request = new DeleteRequest(objectType, criteria, context); if (isSync) { response = proxy.Delete(request); } else { var worker = new Csla.Threading.BackgroundWorker(); var tcs = new TaskCompletionSource <WcfResponse>(); worker.RunWorkerCompleted += (o, e) => { tcs.SetResult((WcfResponse)e.Result); }; worker.DoWork += (o, e) => { e.Result = proxy.Delete(request); }; worker.RunWorkerAsync(); response = await tcs.Task; } if (cf != null) { cf.Close(); } object result = response.Result; if (result is Exception) { throw (Exception)result; } return((DataPortalResult)result); } catch { cf.Abort(); throw; } #else try { var request = new DeleteRequest(objectType, criteria, context); if (isSync) { response = proxy.Delete(request); } else { response = await proxy.DeleteAsync(request); } if (cf != null) { cf.Close(); } } catch { cf.Abort(); throw; } object result = response.Result; if (result is Exception) { throw (Exception)result; } return((DataPortalResult)result); #endif #else var request = GetBaseCriteriaRequest(); request.TypeName = objectType.AssemblyQualifiedName; if (!(criteria is IMobileObject)) { criteria = new PrimitiveCriteria(criteria); } request.CriteriaData = MobileFormatter.Serialize(criteria); request = ConvertRequest(request); var proxy = GetProxy(); DataPortalResult result = null; #if !NETFX_CORE && !(IOS || ANDROID) var tcs = new TaskCompletionSource <DataPortalResult>(); proxy.DeleteCompleted += (s, e) => { try { Csla.WcfPortal.WcfResponse response = null; if (e.Error == null) { response = ConvertResponse(e.Result); } ContextDictionary globalContext = null; if (response != null) { globalContext = (ContextDictionary)MobileFormatter.Deserialize(response.GlobalContext); } if (e.Error == null && response != null && response.ErrorData == null) { result = new DataPortalResult(null, null, globalContext); } else if (response != null && response.ErrorData != null) { var ex = new DataPortalException(response.ErrorData); result = new DataPortalResult(null, ex, globalContext); } else { result = new DataPortalResult(null, e.Error, globalContext); } } catch (Exception ex) { result = new DataPortalResult(null, ex, null); } finally { tcs.SetResult(result); } }; proxy.DeleteAsync(request); var finalresult = await tcs.Task; if (finalresult.Error != null) { throw finalresult.Error; } return(finalresult); #else try { var response = await proxy.DeleteAsync(request); response = ConvertResponse(response); if (response == null) { throw new DataPortalException("null response", null); } var globalContext = (ContextDictionary)MobileFormatter.Deserialize(response.GlobalContext); if (response.ErrorData == null) { result = new DataPortalResult(null, null, globalContext); } else { var ex = new DataPortalException(response.ErrorData); result = new DataPortalResult(null, ex, globalContext); } } catch (Exception ex) { result = new DataPortalResult(null, ex, null); } if (result.Error != null) { throw result.Error; } return(result); #endif #endif }
public static IMTService getNewProxy(string port) { var epAddr = new EndpointAddress($"net.tcp://localhost:{port}/MTService"); return(ChannelFactory <IMTService> .CreateChannel(new NetTcpBinding(), epAddr)); }
public static IReadableChannel CreateGZipCompressChannel(this ChannelFactory factory, IReadableChannel channel, CompressionLevel compressionLevel) { var deflater = new WritableDeflateChannel(compressionLevel, ZLibNative.GZip_DefaultWindowBits); return(factory.MakeReadableChannel(channel, deflater.Execute)); }
public static T FindService <T>() { ChannelFactory <T> chanel = new ChannelFactory <T>(typeof(T).Name); return(chanel.CreateChannel()); }
public static void Main(string[] args) { AppDomain.CurrentDomain.UnhandledException += AppDomain_CurrentDomain_UnhandledException; try { IniConfigSource confFile = new IniConfigSource(configFile); confFile.Reload(); IConfig serviceConfig = confFile.Configs["Service"]; serviceHostName = serviceConfig.GetString("service_host_name"); servicePort = serviceConfig.GetString("service_port"); serviceWebPort = serviceConfig.GetString("service_web_port"); driverServiceHostName = serviceConfig.GetString("driver_service_host_name"); driverServicePort = serviceConfig.GetString("driver_service_port"); IConfig bitrixConfig = confFile.Configs["Bitrix"]; baseAddress = bitrixConfig.GetString("base_address"); IConfig mysqlConfig = confFile.Configs["Mysql"]; mysqlServerHostName = mysqlConfig.GetString("mysql_server_host_name"); mysqlServerPort = mysqlConfig.GetString("mysql_server_port", "3306"); mysqlUser = mysqlConfig.GetString("mysql_user"); mysqlPassword = mysqlConfig.GetString("mysql_password"); mysqlDatabase = mysqlConfig.GetString("mysql_database"); } catch (Exception ex) { logger.Fatal(ex, "Ошибка чтения конфигурационного файла."); return; } logger.Info("Запуск службы оплаты заказов по sms"); try { var conStrBuilder = new MySqlConnectionStringBuilder { Server = mysqlServerHostName, Port = UInt32.Parse(mysqlServerPort), Database = mysqlDatabase, UserID = mysqlUser, Password = mysqlPassword, SslMode = MySqlSslMode.None }; QSMain.ConnectionString = conStrBuilder.GetConnectionString(true); var dbConfig = FluentNHibernate.Cfg.Db.MySQLConfiguration.Standard .Dialect <NHibernate.Spatial.Dialect.MySQL57SpatialDialect>() .ConnectionString(QSMain.ConnectionString); OrmConfig.ConfigureOrm(dbConfig, new[] { System.Reflection.Assembly.GetAssembly(typeof(Vodovoz.HibernateMapping.OrganizationMap)), System.Reflection.Assembly.GetAssembly(typeof(QS.Banks.Domain.Bank)), System.Reflection.Assembly.GetAssembly(typeof(QS.HistoryLog.HistoryMain)), System.Reflection.Assembly.GetAssembly(typeof(QS.Project.Domain.UserBase)) }); MainSupport.LoadBaseParameters(); QS.HistoryLog.HistoryMain.Enable(); ChannelFactory <IAndroidDriverService> channelFactory = new ChannelFactory <IAndroidDriverService>( new BasicHttpBinding(), string.Format("http://{0}:{1}/AndroidDriverService", driverServiceHostName, driverServicePort) ); IDriverPaymentService driverPaymentService = new DriverPaymentService(channelFactory); var paymentSender = new BitrixPaymentWorker(baseAddress); SmsPaymentServiceInstanceProvider smsPaymentServiceInstanceProvider = new SmsPaymentServiceInstanceProvider(paymentSender, driverPaymentService); ServiceHost smsPaymentServiceHost = new SmsPaymentServiceHost(smsPaymentServiceInstanceProvider); ServiceEndpoint webEndPoint = smsPaymentServiceHost.AddServiceEndpoint( typeof(ISmsPaymentService), new WebHttpBinding(), $"http://{serviceHostName}:{serviceWebPort}/SmsPaymentWebService" ); WebHttpBehavior httpBehavior = new WebHttpBehavior(); webEndPoint.Behaviors.Add(httpBehavior); smsPaymentServiceHost.AddServiceEndpoint( typeof(ISmsPaymentService), new BasicHttpBinding(), $"http://{serviceHostName}:{servicePort}/SmsPaymentService" ); smsPaymentServiceHost.Description.Behaviors.Add(new PreFilter()); smsPaymentServiceHost.Open(); logger.Info("Server started."); (smsPaymentServiceInstanceProvider.GetInstance(null) as ISmsPaymentService)?.SynchronizePaymentStatuses(); UnixSignal[] signals = { new UnixSignal(Signum.SIGINT), new UnixSignal(Signum.SIGHUP), new UnixSignal(Signum.SIGTERM) }; UnixSignal.WaitAny(signals); } catch (Exception e) { logger.Fatal(e); } finally { if (Environment.OSVersion.Platform == PlatformID.Unix) { Thread.CurrentThread.Abort(); } Environment.Exit(0); } }
private BuildResultCode BuildSlave() { // Mount build path ((FileSystemProvider)VirtualFileSystem.ApplicationData).ChangeBasePath(builderOptions.BuildDirectory); VirtualFileSystem.CreateDirectory(VirtualFileSystem.ApplicationDatabasePath); // Open WCF channel with master builder var namedPipeBinding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None) { SendTimeout = TimeSpan.FromSeconds(300.0), MaxReceivedMessageSize = int.MaxValue }; var processBuilderRemote = ChannelFactory <IProcessBuilderRemote> .CreateChannel(namedPipeBinding, new EndpointAddress(builderOptions.SlavePipe)); try { RegisterRemoteLogger(processBuilderRemote); // Make sure to laod all assemblies containing serializers // TODO: Review how costly it is to do so, and possibily find a way to restrict what needs to be loaded (i.e. only app plugins?) foreach (var assemblyLocation in processBuilderRemote.GetAssemblyContainerLoadedAssemblies()) { AssemblyContainer.Default.LoadAssemblyFromPath(assemblyLocation, builderOptions.Logger); } // Create scheduler var scheduler = new Scheduler(); var status = ResultStatus.NotProcessed; // Schedule command string buildPath = builderOptions.BuildDirectory; Builder.OpenObjectDatabase(buildPath, VirtualFileSystem.ApplicationDatabaseIndexName); var logger = builderOptions.Logger; MicroThread microthread = scheduler.Add(async() => { // Deserialize command and parameters Command command = processBuilderRemote.GetCommandToExecute(); // Run command var inputHashes = FileVersionTracker.GetDefault(); var builderContext = new BuilderContext(inputHashes, null); var commandContext = new RemoteCommandContext(processBuilderRemote, command, builderContext, logger); MicrothreadLocalDatabases.MountDatabase(commandContext.GetOutputObjectsGroups()); command.PreCommand(commandContext); status = await command.DoCommand(commandContext); command.PostCommand(commandContext, status); // Returns result to master builder processBuilderRemote.RegisterResult(commandContext.ResultEntry); }); while (true) { scheduler.Run(); // Exit loop if no more micro threads lock (scheduler.MicroThreads) { if (!scheduler.MicroThreads.Any()) { break; } } Thread.Sleep(0); } // Rethrow any exception that happened in microthread if (microthread.Exception != null) { builderOptions.Logger.Fatal(microthread.Exception.ToString()); return(BuildResultCode.BuildError); } if (status == ResultStatus.Successful || status == ResultStatus.NotTriggeredWasSuccessful) { return(BuildResultCode.Successful); } return(BuildResultCode.BuildError); } finally { // Close WCF channel // ReSharper disable SuspiciousTypeConversion.Global ((IClientChannel)processBuilderRemote).Close(); // ReSharper restore SuspiciousTypeConversion.Global } }
private static void AppDomain_ProcessExit(object sender, EventArgs e) { ChannelFactory.Dispose(); Console.WriteLine("The process has exited."); }
public GraphiteBackend(IGraphiteConfiguration configuration) { this.factory = new ChannelFactory(configuration, null); this.graphiteChannel = this.factory.CreateChannel("gauge", "graphite"); }
public void Close() { ChannelFactory <IComm> temp = (ChannelFactory <IComm>)channel; temp.Close(); }
public CommunicationWithSIEM() { factory = new ChannelFactory <ISIEMSendToUI>(new NetTcpBinding(), new EndpointAddress("net.tcp://192.168.137.2:12001/ISIEMSendToUI")); }
static void Main() { // Create the custom binding and an endpoint address for the service. Binding multipleTokensBinding = BindingHelper.CreateMultiFactorAuthenticationBinding(); EndpointAddress serviceAddress = new EndpointAddress("http://localhost/servicemodelsamples/service.svc"); ChannelFactory <IEchoService> channelFactory = null; IEchoService client = null; Console.WriteLine("Username authentication required."); Console.WriteLine("Provide a valid machine or domain account. [domain\\user]"); Console.WriteLine(" Enter username:"******" Enter password:"******""; ConsoleKeyInfo info = Console.ReadKey(true); while (info.Key != ConsoleKey.Enter) { if (info.Key != ConsoleKey.Backspace) { if (info.KeyChar != '\0') { password += info.KeyChar; } info = Console.ReadKey(true); } else if (info.Key == ConsoleKey.Backspace) { if (password != "") { password = password.Substring(0, password.Length - 1); } info = Console.ReadKey(true); } } for (int i = 0; i < password.Length; i++) { Console.Write("*"); } Console.WriteLine(); try { // Create a proxy with the previously create binding and endpoint address channelFactory = new ChannelFactory <IEchoService>(multipleTokensBinding, serviceAddress); // configure the username credentials, the client certificate and the server certificate on the channel factory channelFactory.Credentials.UserName.UserName = username; channelFactory.Credentials.UserName.Password = password; channelFactory.Credentials.ClientCertificate.SetCertificate("CN=client.com", StoreLocation.CurrentUser, StoreName.My); channelFactory.Credentials.ServiceCertificate.SetDefaultCertificate("CN=localhost", StoreLocation.LocalMachine, StoreName.My); client = channelFactory.CreateChannel(); Console.WriteLine("Echo service returned: {0}", client.Echo()); ((IChannel)client).Close(); channelFactory.Close(); } catch (CommunicationException e) { Abort((IChannel)client, channelFactory); // if there is a fault then print it out FaultException fe = null; Exception tmp = e; while (tmp != null) { fe = tmp as FaultException; if (fe != null) { break; } tmp = tmp.InnerException; } if (fe != null) { Console.WriteLine("The server sent back a fault: {0}", fe.CreateMessageFault().Reason.GetMatchingTranslation().Text); } else { Console.WriteLine("The request failed with exception: {0}", e); } } catch (TimeoutException) { Abort((IChannel)client, channelFactory); Console.WriteLine("The request timed out"); } catch (Exception e) { Abort((IChannel)client, channelFactory); Console.WriteLine("The request failed with unexpected exception: {0}", e); } Console.WriteLine(); Console.WriteLine("Press <ENTER> to terminate client."); Console.ReadLine(); }
public ClientRuntimeChannel(ServiceEndpoint endpoint, ChannelFactory channelFactory, EndpointAddress remoteAddress, Uri via) : this(endpoint.CreateClientRuntime(null), endpoint.Contract, channelFactory.DefaultOpenTimeout, channelFactory.DefaultCloseTimeout, null, channelFactory.OpenedChannelFactory, endpoint.Binding.MessageVersion, remoteAddress, via) { channel_factory = channelFactory; }
public WcfAccess(String endPointName) { factory = new ChannelFactory <Microsoft.BizTalk.Adapter.Wcf.Runtime.ITwoWayAsyncVoid>(endPointName); client = factory.CreateChannel(); }
public HttpResponseMessage Post([FromBody] CertificateRequest request) { HttpResponseMessage result = null; if (request == null) { result = Request.CreateResponse(HttpStatusCode.InternalServerError); return(result); } var actualSecretKey = ConfigurationManager.AppSettings["ClientSecretKey"]; if (string.IsNullOrEmpty(request.ClientSecret) || !request.ClientSecret.Equals(actualSecretKey)) { result = Request.CreateResponse(HttpStatusCode.InternalServerError); return(result); } var hostName = "client-endpoint"; if (!string.IsNullOrEmpty(request.HostName)) { hostName = request.HostName; } if (request.GenerateRandom) { hostName = "client-" + Guid.NewGuid().ToString().Replace("-", ""); } byte[] data = null; var serviceNamespace = ConfigurationManager.AppSettings["ServiceNamespace"]; var serviceKey = ConfigurationManager.AppSettings["ServiceKey"]; var serviceKeyName = ConfigurationManager.AppSettings["ServiceKeyName"]; var servicePath = ConfigurationManager.AppSettings["ServicePath"]; Console.WriteLine("HOSTNAME: " + hostName); var binding = new NetTcpRelayBinding(); binding.SendTimeout = TimeSpan.FromMinutes(10); binding.ReceiveTimeout = TimeSpan.FromMinutes(10); binding.OpenTimeout = TimeSpan.FromMinutes(10); binding.CloseTimeout = TimeSpan.FromMinutes(10); var cf = new ChannelFactory <ICertificateGeneratorChannel>( binding, new EndpointAddress(ServiceBusEnvironment.CreateServiceUri("sb", serviceNamespace, servicePath))); cf.Endpoint.Behaviors.Add(new TransportClientEndpointBehavior { TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(serviceKeyName, serviceKey) }); using (var ch = cf.CreateChannel()) { data = ch.GetCertificate(hostName); } result = Request.CreateResponse(HttpStatusCode.OK); result.Content = new StreamContent(new MemoryStream(data)); result.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment"); result.Content.Headers.ContentDisposition.FileName = "client.pfx"; result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream"); return(result); }
public async Task <string> GetCookieAsync() { var channelFactory = new ChannelFactory <ICookieService>("FortuneServiceWcf", _dicoveryAddressResolver.GetEndpointAddress("FortuneServiceWcf")); return(await channelFactory.CreateChannel().GetCookieAsync()); }
public static T FindService <T>(string endPointName) { ChannelFactory <T> chanel = new ChannelFactory <T>(endPointName); return(chanel.CreateChannel()); }
public Client(string hostname = "localhost", short port = 8000) { this.channelFactory = new ChannelFactory <ICommunicationService>(new WebHttpBinding(), $"http://{hostname}:{port}"); this.channelFactory.Endpoint.Behaviors.Add(new WebHttpBehavior()); this.channel = this.channelFactory.CreateChannel(); }
public static IReadableChannel CreateGZipDecompressChannel(this ChannelFactory factory, IReadableChannel channel) { var inflater = new ReadableDeflateChannel(ZLibNative.GZip_DefaultWindowBits); return(factory.MakeReadableChannel(channel, inflater.Execute)); }
public void Dispose() { this.channelFactory = null; this.channel = null; }
private JobExecutionResult Execute(string jobData, BasicHttpCallbackJobMetaData callbackJobData) { JobExecutionResult result = new JobExecutionResult(); BasicHttpBinding binding = new BasicHttpBinding(callbackJobData.SecurityMode); binding.MaxReceivedMessageSize = callbackJobData.MessageSize; binding.ReaderQuotas.MaxStringContentLength = callbackJobData.MessageSize; binding.MaxBufferSize = callbackJobData.MessageSize; binding.ReceiveTimeout = TimeSpan.FromMilliseconds(callbackJobData.TimeoutMilliseconds); binding.SendTimeout = TimeSpan.FromMilliseconds(callbackJobData.TimeoutMilliseconds); binding.Security.Transport.ClientCredentialType = callbackJobData.TransportCredentialType; if (callbackJobData.MessageCredentialType.HasValue) { binding.Security.Message.ClientCredentialType = callbackJobData.MessageCredentialType.Value; } //This convoluted bit is used to ensure SSL (transport security) certificates are only ignored for urls where the job has it specified. if (callbackJobData.IgnoreCertificateErrors) { //The logic is not foolproof. If you have 2 requests at the same time to the same host with different IgnoreCertificateErrors settings, the first one in will win. //The fix is to not use different settings for IgnoreCertificateErrors when calling the same host. lock (IgnoreSSLCertificatesForUriList) { if (!IgnoreSSLCertificatesForUriList.ContainsKey(callbackJobData.CallbackUrl)) { IgnoreSSLCertificatesForUriList.Add(callbackJobData.CallbackUrl, 1); } else { //Store a counter for how many times this url has been called with the ignore bit set. IgnoreSSLCertificatesForUriList[callbackJobData.CallbackUrl]++; } } } EndpointAddress endpoint = new EndpointAddress(callbackJobData.CallbackUrl); Response response = null; switch (callbackJobData.ContractType) { case ContractType.Basic: ChannelFactory <IBasicJobCallback> channelFactory = new ChannelFactory <IBasicJobCallback>(binding, endpoint); if (callbackJobData.IgnoreCertificateErrors) { //Ignore X509 certs for message security channelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None; channelFactory.Credentials.ServiceCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck; } if (!string.IsNullOrEmpty(callbackJobData.Username) && !string.IsNullOrEmpty(callbackJobData.Password)) { //Event though Credentials and Credentials.Windows is used for different authentication mechanisms, it works just setting all like this channelFactory.Credentials.UserName.UserName = callbackJobData.Username; channelFactory.Credentials.UserName.Password = callbackJobData.Password; channelFactory.Credentials.Windows.ClientCredential.Domain = callbackJobData.Domain; channelFactory.Credentials.Windows.ClientCredential.UserName = callbackJobData.Username; channelFactory.Credentials.Windows.ClientCredential.Password = callbackJobData.Password; } IBasicJobCallback basicJobCallbackService = channelFactory.CreateChannel(); try { response = basicJobCallbackService.Execute(new BasicJobCallbackRequest { Data = jobData, MetaData = callbackJobData.MetaData }); } catch { throw; } finally { try { channelFactory.Close(); } catch { } } break; case ContractType.Composite: ChannelFactory <ICompositeJobCallback> compositeChannelFactory = new ChannelFactory <ICompositeJobCallback>(binding, endpoint); if (callbackJobData.IgnoreCertificateErrors) { //Ignore X509 certs for message security compositeChannelFactory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = System.ServiceModel.Security.X509CertificateValidationMode.None; compositeChannelFactory.Credentials.ServiceCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck; } if (!string.IsNullOrEmpty(callbackJobData.Username) && !string.IsNullOrEmpty(callbackJobData.Password)) { //Event though Credentials and Credentials.Windows is used for different authentication mechanisms, it works just setting all like this compositeChannelFactory.Credentials.UserName.UserName = callbackJobData.Username; compositeChannelFactory.Credentials.UserName.Password = callbackJobData.Password; compositeChannelFactory.Credentials.Windows.ClientCredential.Domain = callbackJobData.Domain; compositeChannelFactory.Credentials.Windows.ClientCredential.UserName = callbackJobData.Username; compositeChannelFactory.Credentials.Windows.ClientCredential.Password = callbackJobData.Password; } CompositeBasicHttpCallbackJobMetaData metaData = (CompositeBasicHttpCallbackJobMetaData)callbackJobData; ICompositeJobCallback compositeJobCallbackService = compositeChannelFactory.CreateChannel(); try { response = compositeJobCallbackService.Execute(new CompositeBasicJobCallbackRequest { Data = jobData, MetaData = metaData.MetaData, MethodName = metaData.MethodName }); } catch { throw; } finally { try { compositeChannelFactory.Close(); } catch { } } break; } if (response != null) { if (response.Result != null) { callbackJobData.MetaData = response.Result.MetaData; if (callbackJobData.ContractType == ContractType.Basic) { result.MetaData = callbackJobData.Serialize(); } else { result.MetaData = ((CompositeBasicHttpCallbackJobMetaData)callbackJobData).Serialize(); } } else { if (callbackJobData.ContractType == ContractType.Basic) { result.MetaData = callbackJobData.Serialize(); } else { result.MetaData = ((CompositeBasicHttpCallbackJobMetaData)callbackJobData).Serialize(); } result.ResultStatus = JobResultStatus.Fail; result.ErrorMessage = "Response.Result was null."; } if (response.Exception != null) { Exception ex = response.Exception.GetBase(); result.ResultStatus = JobResultStatus.Fail; result.ErrorMessage = Utils.GetExceptionMessage(ex); } else { result.ResultStatus = response.Result.ResultStatus; result.ErrorMessage = response.Result.ErrorMessage; } } return(result); }
public ServiceProxy() { _channelFactory = new ChannelFactory <IDQService>("DQService"); }
/// <summary> /// Returns the WCF proxy object used for /// communication with the data portal /// server. /// </summary> /// <param name="cf"> /// The ChannelFactory created by GetChannelFactory(). /// </param> protected virtual IWcfPortal GetProxy(ChannelFactory <IWcfPortal> cf) { return(cf.CreateChannel()); }
public static void Certificate_With_CanonicalName_Fqdn_Address_EchoString() { bool shouldCallSucceed = false; var domainNameEndpointUri = new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_With_CanonicalName_DomainName_Address); // Get just the hostname part of the domainName Uri var domainNameHost = domainNameEndpointUri.Host.Split('.')[0]; var fqdnEndpointUri = new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_With_CanonicalName_Fqdn_Address); var endpointAddress = new EndpointAddress(fqdnEndpointUri); // If the WCF service's reported FQDN is the same as the services's reported hostname, // it means that there the WCF service is set up on a network where FQDNs aren't used, only hostnames. // Since our pass/fail detection logic on whether or not this is an FQDN depends on whether the host name has a '.', we don't test this case if (string.Compare(domainNameHost, fqdnEndpointUri.Host, StringComparison.OrdinalIgnoreCase) != 0) { shouldCallSucceed = fqdnEndpointUri.Host.IndexOf('.') > -1; } string testString = "Hello"; ChannelFactory <IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport); binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None; factory = new ChannelFactory <IWcfService>(binding, endpointAddress); factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust; serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); var errorBuilder = new StringBuilder(); errorBuilder.AppendFormat("The call to '{0}' should have failed but succeeded. ", fqdnEndpointUri.Host); errorBuilder.AppendFormat("This means that the certificate validation passed when it should have failed. "); errorBuilder.AppendFormat("Check the certificate returned by the endpoint at '{0}' ", fqdnEndpointUri); errorBuilder.AppendFormat("to see that it is correct; if it is, there is likely an issue with the identity checking logic."); Assert.True(shouldCallSucceed, errorBuilder.ToString()); } catch (MessageSecurityException exception) { // If there's a MessageSecurityException, we assume that the cert validation failed. Unfortunately checking for the // message is really brittle and we can't account for loc and how .NET Native will display the exceptions // The exception message should look like: // // System.ServiceModel.Security.MessageSecurityException : Identity check failed for outgoing message. The expected // DNS identity of the remote endpoint was 'localhost' but the remote endpoint provided DNS claim 'example.com'.If this // is a legitimate remote endpoint, you can fix the problem by explicitly specifying DNS identity 'example.com' as // the Identity property of EndpointAddress when creating channel proxy. var errorBuilder = new StringBuilder(); errorBuilder.AppendFormat("The call to '{0}' should have been successful but failed with a MessageSecurityException. ", fqdnEndpointUri.Host); errorBuilder.AppendFormat("This usually means that the certificate validation failed when it should have passed. "); errorBuilder.AppendFormat("When connecting to host '{0}', the expectation is that the DNSClaim will be for the same hostname. ", fqdnEndpointUri.Host); errorBuilder.AppendFormat("Exception message: {0}{1}", Environment.NewLine, exception.Message); Assert.True(!shouldCallSucceed, errorBuilder.ToString()); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
private void cmdConnect_Click(object sender, EventArgs e) { if (CURRENT_IP == "127.0.0.1" || CURRENT_IP == "localhost") { mWebStreamClient = ChannelFactory <IWebStreamingService> .CreateChannel(new NetNamedPipeBinding() { MaxReceivedMessageSize = 10000000 }, new EndpointAddress("net.pipe://localhost/MPExtended/StreamingService")); mStreamClient = ChannelFactory <IStreamingService> .CreateChannel(new NetNamedPipeBinding() { MaxReceivedMessageSize = 10000000 }, new EndpointAddress("net.pipe://localhost/MPExtended/StreamingService")); mServiceClient = ChannelFactory <IMediaAccessService> .CreateChannel(new NetNamedPipeBinding() { MaxReceivedMessageSize = 10000000 }, new EndpointAddress("net.pipe://localhost/MPExtended/MediaAccessService")); mTvClient = ChannelFactory <ITVAccessService> .CreateChannel(new NetNamedPipeBinding() { MaxReceivedMessageSize = 10000000 }, new EndpointAddress("net.pipe://localhost/MPExtended/TVAccessService")); } else { #pragma warning disable 0162 mWebStreamClient = ChannelFactory <IWebStreamingService> .CreateChannel(new BasicHttpBinding(), new EndpointAddress("http://" + CURRENT_IP + ":4321/MPExtended/StreamingService")); mStreamClient = ChannelFactory <IStreamingService> .CreateChannel(new BasicHttpBinding(), new EndpointAddress("http://" + CURRENT_IP + ":4321/MPExtended/StreamingService")); mServiceClient = ChannelFactory <IMediaAccessService> .CreateChannel(new BasicHttpBinding(), new EndpointAddress("http://" + CURRENT_IP + ":4321/MPExtended/MediaAccessService")); mTvClient = ChannelFactory <ITVAccessService> .CreateChannel(new BasicHttpBinding(), new EndpointAddress("http://" + CURRENT_IP + ":4321/MPExtended/TVAccessService")); #pragma warning restore 0162 } Log("Initialized"); // providers var config = mServiceClient.GetServiceDescription(); movieProvider = config.AvailableMovieLibraries.First().Id; fileProvider = config.AvailableFileSystemLibraries.First().Id; // load movies try { cbMovies.Items.Clear(); mMovies = mServiceClient.GetMoviesDetailed(movieProvider, null, null); foreach (WebMovieDetailed movie in mMovies) { cbMovies.Items.Add(movie.Title); } Log("Loaded movies"); } catch (Exception) { Log("Failed to connect to MAS"); } // load chanels try { cbChannels.Items.Clear(); mChannels = new List <WebChannelBasic>(); foreach (WebChannelGroup group in mTvClient.GetGroups()) { WebChannelBasic[] channels = mTvClient.GetChannelsBasic(group.Id).ToArray(); foreach (WebChannelBasic ch in channels) { cbChannels.Items.Add(ch.Title); mChannels.Add(ch); } } Log("Loaded channels"); } catch (Exception) { Log("Failed to connect to TV4Home"); } // load profiles try { cbProfiles.Items.Clear(); mProfiles = mWebStreamClient.GetTranscoderProfiles(); foreach (WebTranscoderProfile profile in mProfiles) { cbProfiles.Items.Add(profile.Name); } cbProfiles.SelectedIndex = 0; } catch (Exception) { Log("Failed to load profiles"); } }
public static void Certificate_With_CanonicalName_Localhost_Address_EchoString() { var localhostEndpointUri = new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_With_CanonicalName_Localhost_Address); var endpointAddress = new EndpointAddress(localhostEndpointUri); bool shouldCallSucceed = string.Compare(localhostEndpointUri.Host, "localhost", StringComparison.OrdinalIgnoreCase) == 0; string testString = "Hello"; ChannelFactory <IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport); binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None; factory = new ChannelFactory <IWcfService>(binding, endpointAddress); factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust; serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo(testString); // *** VALIDATE *** \\ Assert.Equal(testString, result); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); var errorBuilder = new StringBuilder(); errorBuilder.AppendFormat("The call to '{0}' should have failed but succeeded. ", localhostEndpointUri.Host); errorBuilder.AppendFormat("This means that the certificate validation passed when it should have failed. "); errorBuilder.AppendFormat("Check the certificate returned by the endpoint at '{0}' ", localhostEndpointUri); errorBuilder.AppendFormat("to see that it is correct; if it is, there is likely an issue with the identity checking logic."); Assert.True(shouldCallSucceed, errorBuilder.ToString()); } catch (Exception exception) when(exception is CommunicationException || exception is MessageSecurityException) { if ((exception is MessageSecurityException) || (exception is CommunicationException) && !string.Equals(exception.InnerException.GetType().ToString(), "System.ServiceModel.Security.MessageSecurityException")) { // If there's a MessageSecurityException, we assume that the cert validation failed. Unfortunately checking for the // message is really brittle and we can't account for loc and how .NET Native will display the exceptions // The exception message should look like: // // System.ServiceModel.Security.MessageSecurityException : Identity check failed for outgoing message. The expected // DNS identity of the remote endpoint was 'localhost' but the remote endpoint provided DNS claim 'example.com'.If this // is a legitimate remote endpoint, you can fix the problem by explicitly specifying DNS identity 'example.com' as // the Identity property of EndpointAddress when creating channel proxy. var errorBuilder = new StringBuilder(); errorBuilder.AppendFormat("The call to '{0}' should have been successful but failed with a MessageSecurityException. ", localhostEndpointUri.Host); errorBuilder.AppendFormat("This usually means that the certificate validation failed when it should have passed. "); errorBuilder.AppendFormat("When connecting to host '{0}', the expectation is that the DNSClaim will be for the same hostname. ", localhostEndpointUri.Host); errorBuilder.AppendFormat("Exception message: {0}{1}", Environment.NewLine, exception.Message); Assert.True(!shouldCallSucceed, errorBuilder.ToString()); } } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
public static void ServiceRestart_Throws_CommunicationException() { // This test validates that if the Service were to shut-down, re-start or otherwise die in the // middle of an operation the client will not just hang. It should instead receive a CommunicationException. string restartServiceAddress = ""; ChannelFactory <IWcfService> setupHostFactory = null; IWcfService setupHostServiceProxy = null; ChannelFactory <IWcfRestartService> factory = null; IWcfRestartService serviceProxy = null; BasicHttpBinding binding = new BasicHttpBinding(); // *** Step 1 *** \\ // We need the Service to create and open a ServiceHost and then give us the endpoint address for it. try { setupHostFactory = new ChannelFactory <IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); setupHostServiceProxy = setupHostFactory.CreateChannel(); restartServiceAddress = setupHostServiceProxy.GetRestartServiceEndpoint(); // *** CLEANUP *** \\ ((ICommunicationObject)setupHostServiceProxy).Close(); setupHostFactory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)setupHostServiceProxy, setupHostFactory); } // *** Additional Setup *** \\ // The restartServiceAddress we got from the Service used localhost as the host name. // We need the actual host name for the client call to work. // To make it easier to parse, localhost was replaced with '[HOST]'. // Use Endpoints.HttpBaseAddress_Basic only for the purpose of extracting the Service host name. // Then update 'restartServiceAddress' with it. string hostName = new Uri(Endpoints.HttpBaseAddress_Basic).Host; restartServiceAddress = restartServiceAddress.Replace("[HOST]", hostName); // Get the last portion of the restart service url which is a Guid and convert it back to a Guid // This is needed by the RestartService operation as a Dictionary key to get the ServiceHost string uniqueIdentifier = restartServiceAddress.Substring(restartServiceAddress.LastIndexOf("/") + 1); Guid guid = new Guid(uniqueIdentifier); // *** Step 2 *** \\ // Simple echo call to make sure the newly created endpoint is working. try { factory = new ChannelFactory <IWcfRestartService>(binding, new EndpointAddress(restartServiceAddress)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.NonRestartService(guid); Assert.True(result == "Success!", string.Format("Test Case failed, expected the returned string to be: {0}, instead it was: {1}", "Success!", result)); } catch (Exception ex) { string exceptionMessage = ex.Message; string innerExceptionMessage = ex.InnerException?.Message; string testExceptionMessage = $"The ping to validate the newly created endpoint failed.\nThe endpoint pinged was: {restartServiceAddress}\nThe GUID used to extract the ServiceHost from the server side dictionary was: {guid}"; string fullExceptionMessage = $"testExceptionMessage: {testExceptionMessage}\nexceptionMessage: {exceptionMessage}\ninnerExceptionMessage: {innerExceptionMessage}"; Assert.True(false, fullExceptionMessage); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } // *** Step 3 *** \\ // The actual part of the test where the host is killed in the middle of the operation. // We expect the test should not hang and should receive a CommunicationException. CommunicationException exception = Assert.Throws <CommunicationException>(() => { factory = new ChannelFactory <IWcfRestartService>(binding, new EndpointAddress(restartServiceAddress)); serviceProxy = factory.CreateChannel(); try { // *** EXECUTE *** \\ serviceProxy.RestartService(guid); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }); }
private BuildResultCode BuildSlave() { // Mount build path ((FileSystemProvider)VirtualFileSystem.ApplicationData).ChangeBasePath(builderOptions.BuildDirectory); PrepareDatabases(); VirtualFileSystem.CreateDirectory(VirtualFileSystem.ApplicationDatabasePath); // Open WCF channel with master builder var namedPipeBinding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None) { SendTimeout = TimeSpan.FromSeconds(300.0) }; var processBuilderRemote = ChannelFactory <IProcessBuilderRemote> .CreateChannel(namedPipeBinding, new EndpointAddress(builderOptions.SlavePipe)); try { RegisterRemoteLogger(processBuilderRemote); // Create scheduler var scheduler = new Scheduler(); var status = ResultStatus.NotProcessed; // Schedule command string buildPath = builderOptions.BuildDirectory; string buildProfile = builderOptions.BuildProfile; Builder.SetupBuildPath(buildPath, VirtualFileSystem.ApplicationDatabaseIndexName); var logger = builderOptions.Logger; MicroThread microthread = scheduler.Add(async() => { // Deserialize command and parameters Command command = processBuilderRemote.GetCommandToExecute(); BuildParameterCollection parameters = processBuilderRemote.GetBuildParameters(); // Run command var inputHashes = FileVersionTracker.GetDefault(); var builderContext = new BuilderContext(buildPath, buildProfile, inputHashes, parameters, 0, null); var commandContext = new RemoteCommandContext(processBuilderRemote, command, builderContext, logger); IndexFileCommand.MountDatabase(commandContext.GetOutputObjectsGroups()); command.PreCommand(commandContext); status = await command.DoCommand(commandContext); command.PostCommand(commandContext, status); // Returns result to master builder processBuilderRemote.RegisterResult(commandContext.ResultEntry); }); while (true) { scheduler.Run(); // Exit loop if no more micro threads lock (scheduler.MicroThreads) { if (!scheduler.MicroThreads.Any()) { break; } } Thread.Sleep(0); } // Rethrow any exception that happened in microthread if (microthread.Exception != null) { builderOptions.Logger.Fatal(microthread.Exception.ToString()); return(BuildResultCode.BuildError); } if (status == ResultStatus.Successful || status == ResultStatus.NotTriggeredWasSuccessful) { return(BuildResultCode.Successful); } return(BuildResultCode.BuildError); } finally { // Close WCF channel // ReSharper disable SuspiciousTypeConversion.Global ((IClientChannel)processBuilderRemote).Close(); // ReSharper restore SuspiciousTypeConversion.Global } }
static void Main() { string creditCardNumber = "11111111"; DateTime expirationTime = new DateTime(2010, 12, 15, 0, 0, 0, 0, DateTimeKind.Utc); string issuer = Constants.TestCreditCardIssuer; ChannelFactory <IEchoService> channelFactory = null; IEchoService client = null; Console.WriteLine("Please enter your credit card information:"); Console.WriteLine("Please enter a credit card number (hit [enter] to pick 11111111 - a valid number on file): "); string input = Console.ReadLine(); if (input.Trim() != string.Empty) { creditCardNumber = input; bool readDate = false; while (!readDate) { Console.WriteLine("Please enter the expiration time (yyyy/mm/dd): "); input = Console.ReadLine().Trim(); try { expirationTime = DateTime.Parse(input, System.Globalization.DateTimeFormatInfo.InvariantInfo, System.Globalization.DateTimeStyles.AdjustToUniversal); readDate = true; } catch (Exception) { Console.WriteLine("You did not enter a valid date format. Please try again"); } } Console.WriteLine("Please enter the issuer of the credit card (hit enter to pick {0}", Constants.TestCreditCardIssuer); input = Console.ReadLine().Trim(); if (input != string.Empty) { issuer = input; } } try { Binding creditCardBinding = BindingHelper.CreateCreditCardBinding(); EndpointAddress serviceAddress = new EndpointAddress("http://localhost/servicemodelsamples/service.svc"); // Create a client with given client endpoint configuration channelFactory = new ChannelFactory <IEchoService>(creditCardBinding, serviceAddress); // configure the credit card credentials on the channel factory CreditCardClientCredentials credentials = new CreditCardClientCredentials(new CreditCardInfo(creditCardNumber, issuer, expirationTime)); // configure the service certificate on the credentials credentials.ServiceCertificate.SetDefaultCertificate("CN=localhost", StoreLocation.LocalMachine, StoreName.My); // replace ClientCredentials with CreditCardClientCredentials channelFactory.Endpoint.Behaviors.Remove(typeof(ClientCredentials)); channelFactory.Endpoint.Behaviors.Add(credentials); client = channelFactory.CreateChannel(); Console.WriteLine("Echo service returned: {0}", client.Echo()); ((IChannel)client).Close(); channelFactory.Close(); } catch (CommunicationException e) { Abort((IChannel)client, channelFactory); // if there is a fault then print it out FaultException fe = null; Exception tmp = e; while (tmp != null) { fe = tmp as FaultException; if (fe != null) { break; } tmp = tmp.InnerException; } if (fe != null) { Console.WriteLine("The server sent back a fault: {0}", fe.CreateMessageFault().Reason.GetMatchingTranslation().Text); } else { Console.WriteLine("The request failed with exception: {0}", e); } } catch (TimeoutException) { Abort((IChannel)client, channelFactory); Console.WriteLine("The request timed out"); } catch (Exception e) { Abort((IChannel)client, channelFactory); Console.WriteLine("The request failed with unexpected exception: {0}", e); } Console.WriteLine(); Console.WriteLine("Press <ENTER> to terminate client."); Console.ReadLine(); }
public void Install(ChannelFactory channelFactory, IKernel kernel, IWcfBurden burden) { BindChannelFactoryAware(channelFactory, kernel, burden); }