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 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() { 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 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 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 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); } }
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 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 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 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 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 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 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 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 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); } }
// 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 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 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 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 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 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 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 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 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 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 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 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(); } }
/// <summary> /// Creates an instance of the wrapper around a proxy created by <see cref="ChannelFactory{TContract}"/>. /// </summary> /// <param name="channelFactory">A channel factory that can create a proxy for <typeparamref name="TContract"/>.</param> /// <param name="logger">An instance of <see cref="ILogger" />.</param> protected ChannelFactoryProxyWrapper(ChannelFactory <TContract> channelFactory, ILogger logger) { _logger = logger ?? throw new ArgumentNullException(nameof(logger)); _proxy = channelFactory?.CreateChannel() ?? throw new ArgumentNullException(nameof(channelFactory)); }
protected void Connect(Action <T> subscribe) { _channel = _factory?.CreateChannel(); subscribe(_channel); }
public static IMissionService MakeClient() { return(factory.CreateChannel()); }
static void Main(string[] args) { // <Snippet2> ServiceHost host = new ServiceHost(typeof(Service), new Uri("http://localhost:8000")); // </Snippet2> // <Snippet3> host.AddServiceEndpoint(typeof(IService), new BasicHttpBinding(), "Soap"); // </Snippet3> // <Snippet4> ServiceEndpoint endpoint = host.AddServiceEndpoint(typeof(IService), new WebHttpBinding(), "Web"); endpoint.Behaviors.Add(new WebHttpBehavior()); // </Snippet4> try { // <Snippet5> host.Open(); // </Snippet5> // <Snippet6> using (WebChannelFactory <IService> wcf = new WebChannelFactory <IService>(new Uri("http://localhost:8000/Web"))) // </Snippet6> { // <Snippet8> IService channel = wcf.CreateChannel(); string s; Console.WriteLine("Calling EchoWithGet by HTTP GET: "); s = channel.EchoWithGet("Hello, world"); Console.WriteLine(" Output: {0}", s); Console.WriteLine(""); Console.WriteLine("This can also be accomplished by navigating to"); Console.WriteLine("http://localhost:8000/Web/EchoWithGet?s=Hello, world!"); Console.WriteLine("in a web browser while this sample is running."); Console.WriteLine(""); Console.WriteLine("Calling EchoWithPost by HTTP POST: "); s = channel.EchoWithPost("Hello, world"); Console.WriteLine(" Output: {0}", s); // </Snippet8> Console.WriteLine(""); } // <Snippet10> using (ChannelFactory <IService> scf = new ChannelFactory <IService>(new BasicHttpBinding(), "http://localhost:8000/Soap")) // </Snippet10> { // <Snippet11> IService channel = scf.CreateChannel(); string s; Console.WriteLine("Calling EchoWithGet on SOAP endpoint: "); s = channel.EchoWithGet("Hello, world"); Console.WriteLine(" Output: {0}", s); Console.WriteLine(""); Console.WriteLine("Calling EchoWithPost on SOAP endpoint: "); s = channel.EchoWithPost("Hello, world"); Console.WriteLine(" Output: {0}", s); // </Snippet11> Console.WriteLine(""); } Console.WriteLine("Press [Enter] to terminate"); Console.ReadLine(); // <Snippet9> host.Close(); // </Snippet9> } catch (CommunicationException cex) { Console.WriteLine("An exception occurred: {0}", cex.Message); host.Abort(); } }
private void Connect() { ChannelFactory <IBrotherConnection> factory = new ChannelFactory <IBrotherConnection>(new NetTcpBinding(), new EndpointAddress($"net.tcp://127.255.0.2:8888/InputRequest")); proxy = factory.CreateChannel(); }
private void BtnChange_Click(object sender, RoutedEventArgs e) { //parsirati unos svaki ChannelFactory <ISolarPanelGUI> SolarPanelChannel = new ChannelFactory <ISolarPanelGUI>("ISolarPanelGUI"); ISolarPanelGUI proxySP = SolarPanelChannel.CreateChannel(); ChannelFactory <IEVChargerGUI> EVChargerChannel = new ChannelFactory <IEVChargerGUI>("IEVChargerGUI"); IEVChargerGUI proxyEV = EVChargerChannel.CreateChannel(); ChannelFactory <IConsumerGUI> ConsumerChannel = new ChannelFactory <IConsumerGUI>("IConsumerGUI"); IConsumerGUI proxyConsumer = ConsumerChannel.CreateChannel(); ChannelFactory <IUtilityGUI> UtilityChannel = new ChannelFactory <IUtilityGUI>("IUtilityGUI"); IUtilityGUI proxyUtility = UtilityChannel.CreateChannel(); double sunIntensity = 0; var consumerRezim = Common.Enums.ConsumerRezim.OFF; int consumerID = 0; var ev = Common.Enums.BatteryRezim.PRAZNJENJE; double util = 0; if (txtSun.Text != null && txtSun.Text != "") { if (double.TryParse(txtSun.Text, out sunIntensity) && sunIntensity >= 0 && sunIntensity <= 1) { proxySP.ChangeSunIntensity(sunIntensity); txtSun.Text = ""; } else { throw new ArgumentOutOfRangeException("Intenzitet Sunca mora biti broj u intervalu 0-1!"); } } if (txtConsumerId.Text != null && txtConsumerId.Text != "") { if (Int32.TryParse(txtConsumerId.Text, out consumerID)) { if (cmbBoxConsumer.Text != null && cmbBoxConsumer.Text != "") { switch (cmbBoxConsumer.Text) { case "ON": consumerRezim = Enums.ConsumerRezim.ON; break; default: consumerRezim = Enums.ConsumerRezim.OFF; break; } Trace.TraceInformation("GUI sending: Consumer id-" + consumerID + ", state-" + consumerRezim.ToString()); proxyConsumer.ChangeConsumerState(consumerID, consumerRezim); txtConsumerId.Text = ""; } } else { throw new ArgumentOutOfRangeException("Id potrosaca mora biti nenegativan broj!"); } } if (cmbBoxBatteryRegime.Text != null && cmbBoxBatteryRegime.Text != "") { switch (cmbBoxBatteryRegime.Text) { case "PUNJENJE": ev = Enums.BatteryRezim.PUNJENJE; break; default: ev = Enums.BatteryRezim.PRAZNJENJE; break; } Trace.TraceInformation("GUI to EV: " + Convert.ToBoolean(cmbBoxBatteryOnPlug.Text) + " " + ev.ToString()); proxyEV.SendRegime(Convert.ToBoolean(cmbBoxBatteryOnPlug.Text), ev); } if (txtUtilityPrice.Text != null && txtUtilityPrice.Text != "") { if (double.TryParse(txtUtilityPrice.Text, out util) && util >= 0) { util = double.Parse(txtUtilityPrice.Text); proxyUtility.SendPrice(util); txtUtilityPrice.Text = ""; } else { throw new ArgumentOutOfRangeException("Cena elektrodistribucije mora biti pozitivan broj!"); } } }
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.GetAllMoviesDetailed(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.DisplayName); 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 IContentService GetContentService() { return(contentServiceFactory.CreateChannel()); }
static async Task Main() { Console.Title = "Samples.Wcf.Endpoint"; var endpointConfiguration = new EndpointConfiguration("Samples.Wcf.Endpoint"); endpointConfiguration.UseTransport <LearningTransport>(); endpointConfiguration.EnableInstallers(); #region enable-wcf endpointConfiguration.MakeInstanceUniquelyAddressable("1"); var wcf = endpointConfiguration.Wcf(); wcf.Binding( provider: type => { return(new BindingConfiguration( binding: new NetNamedPipeBinding(), address: new Uri("net.pipe://localhost/MyService"))); }); wcf.CancelAfter( provider: type => { return(type.IsAssignableFrom(typeof(MyService)) ? TimeSpan.FromSeconds(5) : TimeSpan.FromSeconds(60)); }); #endregion var endpointInstance = await Endpoint.Start(endpointConfiguration) .ConfigureAwait(false); Console.WriteLine("Press <enter> to send a message"); Console.WriteLine("Press <escape> to send a message which will time out"); Console.WriteLine("Press any key to exit"); #region wcf-proxy var pipeFactory = new ChannelFactory <IWcfService <MyRequestMessage, MyResponseMessage> >( binding: new NetNamedPipeBinding(), remoteAddress: new EndpointAddress("net.pipe://localhost/MyService")); var pipeProxy = pipeFactory.CreateChannel(); #endregion Console.WriteLine("Proxy initialized."); while (true) { var key = Console.ReadKey(); Console.WriteLine(); if (!(key.Key == ConsoleKey.Enter || key.Key == ConsoleKey.Escape)) { break; } try { if (key.Key == ConsoleKey.Enter) { Console.WriteLine("Sending request that will succeed over proxy."); } if (key.Key == ConsoleKey.Escape) { Console.WriteLine("Sending request that will fail over proxy."); } #region wcf-proxy-call var request = new MyRequestMessage { Info = key.Key == ConsoleKey.Enter ? "Hello from handler" : "Cancel" }; var response = await pipeProxy.Process(request) .ConfigureAwait(false); #endregion Console.WriteLine($"Response '{response.Info}'"); } catch (FaultException faultException) { Console.Error.WriteLine($"Request failed due to: '{faultException.Message}'"); } } await endpointInstance.Stop() .ConfigureAwait(false); }
private bool Conectar() { bool sw = false; try { string strConexion = string.Format("net.tcp://{0}:{1}/RequestManager", this.Host, this.Port); log.Debug("Conectar. Conectando al WCF ({0})...", strConexion); EndpointAddress endPoint = new EndpointAddress(strConexion); NetTcpBinding _elbinding = new NetTcpBinding(); _elbinding.Security.Mode = SecurityMode.None; _elbinding.CloseTimeout = new TimeSpan(0, 10, 0); _elbinding.SendTimeout = new TimeSpan(0, 10, 0); _elbinding.ReceiveTimeout = new TimeSpan(0, 10, 0); //_elbinding.OpenTimeout = new TimeSpan(0, 10, 0); _elbinding.OpenTimeout = new TimeSpan(0, 10, 0); _elbinding.MaxConnections = 20000; _elbinding.MaxBufferPoolSize = int.MaxValue; _elbinding.MaxBufferSize = int.MaxValue; _elbinding.MaxReceivedMessageSize = int.MaxValue; _elbinding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.None; _elbinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None; ChannelFactory <IRequestMotorWCF> factory = new ChannelFactory <IRequestMotorWCF>(_elbinding, endPoint); factory.Closed += Factory_Closed; factory.Faulted += Factory_Faulted; factory.Opened += Factory_Opened; _client = factory.CreateChannel(); sw = true; if (factory.State == CommunicationState.Opened) { this.Conectado = sw; } } catch (Exception er) { log.Error("Conectar()", er); } //this.Conectado = sw; if (sw) { log.Debug("Conectado"); } else { log.Debug("No se pudo conectar"); } return(sw); }
public static T FindService <T>(string endPointName) { ChannelFactory <T> chanel = new ChannelFactory <T>(endPointName); return(chanel.CreateChannel()); }
public IdMappingClientImpl(string location, string pfxFilename, string password) { /* * BasicHttpBinding basicBinding = new BasicHttpBinding(BasicHttpSecurityMode.TransportWithMessageCredential); * BasicHttpSecurity security = basicBinding.Security; * security.Mode = BasicHttpSecurityMode.TransportWithMessageCredential; * * BasicHttpMessageSecurity messageSecurity = security.Message; * messageSecurity.ClientCredentialType = BasicHttpMessageCredentialType.Certificate; * messageSecurity.AlgorithmSuite = SecurityAlgorithmSuite.Default; * * HttpTransportSecurity transportSecurity = security.Transport; * transportSecurity.ClientCredentialType = HttpClientCredentialType.None; * transportSecurity.ProxyCredentialType = HttpProxyCredentialType.None; * transportSecurity.Realm = ""; * * BindingElementCollection bec = basicBinding.CreateBindingElements(); * TransportSecurityBindingElement tsp = bec.Find<TransportSecurityBindingElement>(); * HttpsTransportBindingElement httpsBinding = bec.Find<HttpsTransportBindingElement>(); * TextMessageEncodingBindingElement encoding = bec.Find<TextMessageEncodingBindingElement>(); * SecurityBindingElement securityBinding = bec.Find<SecurityBindingElement>(); * CustomBinding binding = new CustomBinding(tsp, encoding, httpsBinding); */ CustomBinding binding = new CustomBinding(); HttpsTransportBindingElement httpsTransport = new HttpsTransportBindingElement(); TextMessageEncodingBindingElement encoding = new TextMessageEncodingBindingElement(); encoding.MessageVersion = MessageVersion.Soap11; //SecurityBindingElement securityBinding = // SecurityBindingElement.CreateCertificateOverTransportBindingElement(MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10); //SecurityBindingElement securityBinding = SecurityBindingElement.CreateSslNegotiationBindingElement(false); /* * AsymmetricSecurityBindingElement securityBinding = * (AsymmetricSecurityBindingElement)SecurityBindingElement. * CreateMutualCertificateBindingElement( * MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10, true); * securityBinding.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Default; * securityBinding.SetKeyDerivation(false); * securityBinding.SecurityHeaderLayout = SecurityHeaderLayout.Lax; */ SslStreamSecurityBindingElement sslStreamSecurity = new SslStreamSecurityBindingElement(); //binding.Elements.Add(securityBinding); TransportSecurityBindingElement securityBinding = new TransportSecurityBindingElement(); securityBinding.MessageSecurityVersion = MessageSecurityVersion.WSSecurity10WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10; securityBinding.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Default; securityBinding.SetKeyDerivation(false); X509SecurityTokenParameters certToken = new X509SecurityTokenParameters(); certToken.InclusionMode = SecurityTokenInclusionMode.AlwaysToRecipient; certToken.ReferenceStyle = SecurityTokenReferenceStyle.Internal; certToken.RequireDerivedKeys = false; certToken.X509ReferenceStyle = X509KeyIdentifierClauseType.Any; securityBinding.EndpointSupportingTokenParameters.SignedEndorsing.Add(certToken); securityBinding.LocalClientSettings.DetectReplays = false; binding.Elements.Add(securityBinding); binding.Elements.Add(encoding); binding.Elements.Add(sslStreamSecurity); binding.Elements.Add(httpsTransport); /* * WSHttpBinding binding = new WSHttpBinding(SecurityMode.TransportWithMessageCredential); * WSHttpSecurity security = binding.Security; * * HttpTransportSecurity transportSecurity = security.Transport; * transportSecurity.ClientCredentialType = HttpClientCredentialType.None; * transportSecurity.ProxyCredentialType = HttpProxyCredentialType.None; * transportSecurity.Realm = ""; * * NonDualMessageSecurityOverHttp messageSecurity = security.Message; * messageSecurity.ClientCredentialType = MessageCredentialType.Certificate; * messageSecurity.NegotiateServiceCredential = false; * messageSecurity.AlgorithmSuite = SecurityAlgorithmSuite.Default; */ ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(SafeOnlineCertificateValidationCallback); string address = "https://" + location + "/safe-online-ws/idmapping"; EndpointAddress remoteAddress = new EndpointAddress(address); Binding safeOnlineBinding = new SafeOnlineBinding(); //this.client = new NameIdentifierMappingPortClient(safeOnlineBinding, remoteAddress); //X509Certificate2 certificate = new X509Certificate2("C:\\work\\test.pfx", "secret"); /* * this.client.ClientCredentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, * StoreName.My, * X509FindType.FindBySubjectName, * "Test"); * this.client.Endpoint.Contract.ProtectionLevel = ProtectionLevel.Sign; */ //this.client.Endpoint.Contract.Behaviors.Add(new SignBodyBehavior()); //this.client.Endpoint.Behaviors.Add(new SafeOnlineMessageInspectorBehavior()); /* * X509Store store = new X509Store(StoreName.My, StoreLocation.CurrentUser); * store.Open(OpenFlags.ReadOnly); * X509Certificate2 cert = store.Certificates.Find(X509FindType.FindBySubjectName, "Test", false)[0]; * this.client.ClientCredentials.ClientCertificate.Certificate = cert; */ //Console.WriteLine("cert: " + this.client.ClientCredentials.ClientCertificate.Certificate); ChannelFactory <NameIdentifierMappingPort> channelFactory = new ChannelFactory <NameIdentifierMappingPort>(safeOnlineBinding, remoteAddress); channelFactory.Credentials.ClientCertificate.SetCertificate(StoreLocation.CurrentUser, StoreName.My, X509FindType.FindBySubjectName, "Test"); //channelFactory.Credentials.ClientCertificate.Certificate = //channelFactory.Endpoint.Behaviors.Add(new SafeOnlineMessageInspectorBehavior()); //channelFactory.Endpoint.Contract.Behaviors.Add(new SignBodyBehavior()); /* * Next does not work at all. * foreach (OperationDescription operation in channelFactory.Endpoint.Contract.Operations) { * operation.ProtectionLevel = ProtectionLevel.Sign * Console.WriteLine("operation: " + operation.Name); * } */ channelFactory.Endpoint.Contract.ProtectionLevel = ProtectionLevel.Sign; this.client = channelFactory.CreateChannel(); }
// Asking for PeerTrust alone should throw SecurityNegotiationException // if the certificate is not in the TrustedPeople store. For this test // we use a valid chain-trusted certificate that we know is not in the // TrustedPeople store. public static void Https_SecModeTrans_CertValMode_PeerTrust_Fails_Not_In_TrustedPeople() { #if FULLXUNIT_NOTSUPPORTED bool root_Certificate_Installed = Root_Certificate_Installed(); bool client_Certificate_Installed = Client_Certificate_Installed(); bool peer_Certificate_Installed = Peer_Certificate_Installed(); bool ssl_Available = SSL_Available(); if (!root_Certificate_Installed || !client_Certificate_Installed || !peer_Certificate_Installed || !ssl_Available) { Console.WriteLine("---- Test SKIPPED --------------"); Console.WriteLine("Attempting to run the test in ToF, a ConditionalFact evaluated as FALSE."); Console.WriteLine("Root_Certificate_Installed evaluated as {0}", root_Certificate_Installed); Console.WriteLine("Client_Certificate_Installed evaluated as {0}", client_Certificate_Installed); Console.WriteLine("Peer_Certificate_Installed evaluated as {0}", peer_Certificate_Installed); Console.WriteLine("SSL_Available evaluated as {0}", ssl_Available); return; } #endif EndpointAddress endpointAddress = null; string testString = "Hello"; ChannelFactory <IWcfService> factory = null; IWcfService serviceProxy = null; CommunicationException communicationException = null; try { // *** SETUP *** \\ BasicHttpsBinding binding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None; endpointAddress = new EndpointAddress(new Uri( Endpoints.Https_SecModeTrans_ClientCredTypeNone_ServerCertValModeChainTrust_Address)); factory = new ChannelFactory <IWcfService>(binding, endpointAddress); factory.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication(); factory.Credentials.ServiceCertificate.SslCertificateAuthentication.CertificateValidationMode = X509CertificateValidationMode.PeerTrust; serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ try { serviceProxy.Echo(testString); } catch (CommunicationException ce) { communicationException = ce; } // *** VALIDATE *** \\ Assert.True(communicationException != null, "Expected CommunicationException but no exception was thrown."); Assert.True(communicationException.GetType().Name == "SecurityNegotiationException", String.Format("Expected SecurityNegotiationException but received {0}", communicationException.ToString())); // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
public static T FindService <T>() { ChannelFactory <T> chanel = new ChannelFactory <T>(typeof(T).Name); return(chanel.CreateChannel()); }
public ProjectRepository() { _factory = FloorplannerFactory.GetFloorPlannerCatory(); _proxy = _factory.CreateChannel(); }
public TChannel CreateChannel() { return(channelFactory.CreateChannel()); }
public static T CreateChannel() { EndpointAddress address = DiscoveryHelper.DiscoverAddress <T>(Scope); return(ChannelFactory <T> .CreateChannel(Binding, address)); }
public static void Abort_During_Implicit_Open_Closes_Async_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 asynchronous service // calls, but stalls the Opening event to allow them to be queued before // any of them are allowed to proceed. It then closes 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(). Task <string> t = serviceProxy.EchoWithTimeoutAsync(testMessage, serverDelayTimeSpan); lock (tasks) { if (!isClosed) { try { isClosed = true; ((ICommunicationObject)serviceProxy).Abort(); } catch { } } } return(t.GetAwaiter().GetResult()); }; // *** 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)); // --- Here is the test of the actual bug fix --- // 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); } }
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 cf = new ChannelFactory <ICertificateGeneratorChannel>( new NetTcpRelayBinding(), 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); }
static void Main(string[] args) { if (args.Length != 1) { Console.WriteLine("usage: <ip address or host name of service>:<port of service>"); } var awaitDone = new AutoResetEvent(false); var name = ConfigurationManager.AppSettings.Get("Name"); var networkInterface = ConfigurationManager.AppSettings.Get("NetworkInterfaceName"); Assert.True(!string.IsNullOrEmpty(name), "name needs to be specified"); Assert.True(int.TryParse(ConfigurationManager.AppSettings.Get("Port"), out int port), "no valid port was specified"); string serviceConnection = args[0]; var instance = new SchereSteinPapierPlayer(name, port, networkInterface, awaitDone); string baseAddress = "net.tcp://{0}"; baseAddress = string.Format(baseAddress, instance.ConnectionString); var uri = new Uri(baseAddress); using (ServiceHost host = new ServiceHost(instance, uri)) { var binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.None; binding.ReceiveTimeout = TimeSpan.MaxValue; // do not timeout at all! binding.SendTimeout = TimeSpan.MaxValue; var endpoint = host.AddServiceEndpoint( typeof(ISchereSteinPapierPlayer), binding, SchereSteinPapierTools.PlayerService); host.Open(); Console.WriteLine("Schere Stein Papier Player started"); var address = string.Format("net.tcp://{0}/{1}", serviceConnection, SchereSteinPapierTools.ArbiterService); //var instanceContext = new InstanceContext( impl ); var clientBinding = new NetTcpBinding() { SendTimeout = TimeSpan.MaxValue, ReceiveTimeout = TimeSpan.MaxValue }; clientBinding.Security.Mode = SecurityMode.None; using (var serviceFactory = new ChannelFactory <ISchereSteinPapierArbiter>( clientBinding, new EndpointAddress( address))) { var service = serviceFactory.CreateChannel(); if (service.RegisterPlayer(instance.Name, instance.ConnectionString)) { try { UiHandler handler = new UiHandler(instance.Name, awaitDone, service); Console.WriteLine("Player successfully registered - ready to play"); var thread = new Thread( () => handler.UiHandlerActivity()) { IsBackground = true }; thread.Start(); awaitDone.WaitOne(); } catch { service.UnregisterPlayer(instance.Name); awaitDone.Set(); } } } } }
/// <summary> /// 拦截器处理 /// </summary> /// <param name="msg"></param> /// <returns></returns> public override IMessage Invoke(IMessage msg) { IMethodReturnMessage methodReturn = null; IMethodCallMessage methodCall = (IMethodCallMessage)msg; string contract = typeof(T).FullName; //此处使用wcf连接池技术,获取当前wcf连接池 WcfPool pool = isUseWcfPool ? WcfPoolCache.GetWcfPool(this.server_name) : null; //获取的池子索引 int?index = null; T channel = default(T); OperationContextScope scope = null; if (!isUseWcfPool)//不启用连接池 { ChannelFactory <T> factory = WcfCacheData.GetFactory <T>(this.binging, this.address, this.client.MaxItemsInObjectGraph, this.EnableBinaryFormatterBehavior); channel = factory.CreateChannel(); //scope = new OperationContextScope(((IClientChannel)channel)); } else { #region 统模式 //是否超时 bool isouttime = false; //超时计时器 Stopwatch sw = new Stopwatch(); sw.Start(); while (true) { bool isReap = true; //先判断池子中是否有此空闲连接 if (pool.GetFreePoolNums(contract) > 0) { isReap = false; WcfCommunicationObj commobj = pool.GetChannel <T>(); if (commobj != null) { index = commobj.Index; channel = (T)commobj.CommucationObject; //Console.WriteLine(contract + "获取空闲索引:" + index); } } //如果没有空闲连接判断是否池子是否已满,未满,则创建新连接并装入连接池 if (channel == null && !pool.IsPoolFull) { //创建新连接 ChannelFactory <T> factory = WcfCacheData.GetFactory <T>(this.binging, this.address, this.client.MaxItemsInObjectGraph, this.EnableBinaryFormatterBehavior); //装入连接池 bool flag = pool.AddPool <T>(factory, out channel, out index, isReap); //Console.WriteLine(contract + "装入:" + flag + " 索引:" + index); } //如果当前契约无空闲连接,并且队列已满,并且非当前契约有空闲,则踢掉一个非当前契约 if (channel == null && pool.IsPoolFull && pool.GetFreePoolNums(contract) == 0 && pool.GetUsedPoolNums(contract) != this.wcfMaxPoolSize) { //创建新连接 ChannelFactory <T> factory = WcfCacheData.GetFactory <T>(this.binging, this.address, this.client.MaxItemsInObjectGraph, this.EnableBinaryFormatterBehavior); pool.RemovePoolOneNotAt <T>(factory, out channel, out index); } if (channel != null) { break; } //如果还未获取连接判断是否超时,如果超时抛异常 if (sw.Elapsed >= new TimeSpan(wcfOutTime * 1000 * 10000)) { isouttime = true; break; } else { Thread.Sleep(100); } } sw.Stop(); sw = null; if (isouttime) { throw new Exception("获取连接池中的连接超时,请配置WCF客户端常量配置文件中的WcfOutTime属性,Server name=\"" + server_name + "\""); } #endregion #region 反应器 //AutoResetEvent autoEvents = new AutoResetEvent(false); //BusinessException bex = null; //ThreadPool.QueueUserWorkItem(delegate(object param) //{ // //超时计时器 // Stopwatch sw = new Stopwatch(); // sw.Start(); // while (true) // { // #region while // bool isReap = true; // //先判断池子中是否有此空闲连接 // if (pool.GetFreePoolNums(contract) > 0) // { // isReap = false; // try // { // WcfCommunicationObj commobj = pool.GetChannel<T>(); // if (commobj != null) // { // index = commobj.Index; // channel = (T)commobj.CommucationObject; // } // } // catch (Exception ex) // { // bex = new BusinessException(ex.ToString()); // autoEvents.Set(); // break; // } // } // //如果没有空闲连接判断是否池子是否已满,未满,则创建新连接并装入连接池 // if (channel == null && !pool.IsPoolFull) // { // //创建新连接 // ChannelFactory<T> factory = WcfCacheData.GetFactory<T>(this.binging, this.address, this.client.MaxItemsInObjectGraph,this.EnableBinaryFormatterBehavior); // //装入连接池 // try // { // bool flag = pool.AddPool<T>(factory, out channel, out index, isReap); // } // catch (Exception ex) // { // bex = new BusinessException(ex.ToString()); // autoEvents.Set(); // break; // } // } // //如果当前契约无空闲连接,并且队列已满,并且非当前契约有空闲,则踢掉一个非当前契约 // if (channel == null && pool.IsPoolFull && pool.GetFreePoolNums(contract) == 0 && pool.GetUsedPoolNums(contract) != this.wcfMaxPoolSize) // { // //创建新连接 // ChannelFactory<T> factory = WcfCacheData.GetFactory<T>(this.binging, this.address, this.client.MaxItemsInObjectGraph,this.EnableBinaryFormatterBehavior); // try // { // pool.RemovePoolOneNotAt<T>(factory, out channel, out index); // } // catch (Exception ex) // { // bex = new BusinessException(ex.ToString()); // autoEvents.Set(); // break; // } // } // if (channel != null) // { // autoEvents.Set(); // break; // } // //如果还未获取连接判断是否超时,如果超时抛异常 // if (sw.Elapsed >= new TimeSpan(wcfOutTime * 1000 * 10000)) // { // break; // } // else // { // Thread.Sleep(100); // } // #endregion // } // sw.Stop(); // sw = null; // Thread.CurrentThread.Abort(); //}); //if (!autoEvents.WaitOne(new TimeSpan(wcfOutTime * 1000 * 10000))) //{ // throw new NormalException("获取连接池中的连接超时,请配置WCF客户端常量配置文件中的WcfOutTime属性,Server name=\"" + server_name + "\""); //} //if (bex != null) //{ // throw bex; //} #endregion } #region 递上下文 //web.config或app.config中的ApplicationName string wcfappname = ConfigurationManager.AppSettings["ApplicationName"]; if (wcfappname != null) { HeaderOperater.SetClientWcfAppNameHeader(wcfappname); } #endregion try { object[] copiedArgs = Array.CreateInstance(typeof(object), methodCall.Args.Length) as object[]; methodCall.Args.CopyTo(copiedArgs, 0); object returnValue = methodCall.MethodBase.Invoke(channel, copiedArgs); methodReturn = new ReturnMessage(returnValue, copiedArgs, copiedArgs.Length, methodCall.LogicalCallContext, methodCall); //如果启用连接池,使用完后把连接回归连接池 if (isUseWcfPool) { if (index != null) { pool.ReturnPool <T>((int)index); } } } catch (Exception ex) { var exception = ex; if (ex.InnerException != null) { exception = ex.InnerException; } methodReturn = new ReturnMessage(exception, methodCall); //如果启用连接池,出错则关闭连接,并删除连接池中的连接 if (isUseWcfPool) { if (index != null) { pool.RemovePoolAt <T>((int)index); } } } finally { if (!isUseWcfPool)//不启用连接池 { if (scope != null) { scope.Dispose(); } (channel as IDisposable).Dispose(); } //清除wcf应用程序名上下文 if (wcfappname != null) { HeaderOperater.ClearClientWcfAppNameHeader(); } } return(methodReturn); }
private void Form1_Load(object sender, EventArgs e) { var endPoint = new EndpointAddress("http://localhost:9010/CustomerService"); channel = ChannelFactory <ICustomerService> .CreateChannel(new BasicHttpBinding(), endPoint); }
/// <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()); }
private BuildResultCode BuildSlave() { // Mount build path ((FileSystemProvider)VirtualFileSystem.ApplicationData).ChangeBasePath(builderOptions.BuildDirectory); PrepareDatabases(); VirtualFileSystem.CreateDirectory("/data/"); VirtualFileSystem.CreateDirectory("/data/db/"); // 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); Logger 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.MountDatabases(commandContext); 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 } }
public void run() { string Msg; file.WriteLine(Msg = string.Format("{0}\tThread Id: {1} started...", DateTime.Now.ToString("HH:mm:ss.fffffff"), Thread.Name)); Console.WriteLine(Msg); try { IPHostEntry ips = Dns.GetHostEntry(Dns.GetHostName()); IPAddress _ipAddress = ips.AddressList[1]; string _ipAddressStr = TestWCF.Common.Host; // _ipAddress.ToString(); string endPointAddr = "net.tcp://" + _ipAddressStr + ":8000/" + TestWCF.Common.ServiceName; NetTcpBinding tcpBinding = new NetTcpBinding(); tcpBinding.TransactionFlow = false; tcpBinding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign; tcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows; tcpBinding.Security.Mode = SecurityMode.None; EndpointAddress endpointAddress = new EndpointAddress(endPointAddr); file.WriteLine(Msg = string.Format("{0}\tAttempt to connect to: {1} started...", DateTime.Now.ToString("HH:mm:ss.fffffff"), endPointAddr)); Console.WriteLine(Msg); TestWCF.IServiceContract proxy = ChannelFactory <TestWCF.IServiceContract> .CreateChannel(tcpBinding, endpointAddress); file.WriteLine(Msg = string.Format("{0}\tConnected", DateTime.Now.ToString("HH:mm:ss.fffffff"))); Console.WriteLine(Msg); using (proxy as IDisposable) { file.WriteLine(Msg = string.Format("{0}\tDoSmth({1}) started...", DateTime.Now.ToString("HH:mm:ss.fffffff"), Thread.Name)); Console.WriteLine(Msg); file.WriteLine(Msg = string.Format("{0}\tDoSmth({1}) finished (Result: \"{2}\")", DateTime.Now.ToString("HH:mm:ss.fffffff"), Thread.Name, proxy.DoSmth(Thread.Name))); Console.WriteLine(Msg); TestWCF.DataContract dataContract = new TestWCF.DataContract { StringField = Thread.Name }; file.WriteLine(Msg = string.Format("{0}\tDoSmthWithClass({1}) started...", DateTime.Now.ToString("HH:mm:ss.fffffff"), dataContract.StringField)); Console.WriteLine(Msg); file.WriteLine(Msg = string.Format("{0}\tDoSmthWithClass({1}) finished (Result: \"{2}\")", DateTime.Now.ToString("HH:mm:ss.fffffff"), dataContract.StringField, proxy.DoSmthWithClass(dataContract).StringField)); Console.WriteLine(Msg); } } catch (Exception eException) { file.WriteLine("{1}{0}{2}{0}Message: \"{3}\"{4}{0}StackTrace:{0}{5}", Environment.NewLine, DateTime.Now.ToString("HH:mm:ss.fffffff"), eException.GetType().FullName, eException.Message, eException.InnerException != null ? Environment.NewLine + "InnerException.Message: \"" + eException.InnerException.Message + "\"" : string.Empty, eException.StackTrace); } file.WriteLine(Msg = string.Format("{0}\tThread Id: {1} finished", DateTime.Now.ToString("HH:mm:ss.fffffff"), Thread.Name)); Console.WriteLine(Msg); }
protected void Page_Init(object sender, EventArgs e) { // create a channel factory and then instantiate a proxy channel _factory = new ChannelFactory <IWHSMailService>("WHSMailService"); _channel = _factory.CreateChannel(); }
private void button1_Click(object sender, EventArgs e) { var endPoint = new EndpointAddress("http://localhost:4444/MathService"); channel = ChannelFactory <IMathService> .CreateChannel(new BasicHttpBinding(), endPoint); }
public static void Main() { // Get the sender ID from configuration string senderId = ConfigurationManager.AppSettings["sender"]; string recognizedSender = "CN=" + senderId; // Create the sender with the given endpoint configuration // Sender is an instance of the sender side of the broadcast application that has opened a channel to mesh using (ChannelFactory <IQuoteChannel> cf = new ChannelFactory <IQuoteChannel>("BroadcastEndpoint")) { X509Certificate2 senderCredentials = GetCertificate(StoreName.My, StoreLocation.CurrentUser, recognizedSender, X509FindType.FindBySubjectDistinguishedName); cf.Credentials.Peer.Certificate = senderCredentials; cf.Credentials.Peer.MessageSenderAuthentication.CertificateValidationMode = X509CertificateValidationMode.Custom; cf.Credentials.Peer.MessageSenderAuthentication.CustomCertificateValidator = new SenderValidator(senderCredentials); using (IQuoteChannel sender = (IQuoteChannel)cf.CreateChannel()) { // Retrieve the PeerNode associated with the sender and register for online/offline events // PeerNode represents a node in the mesh. Mesh is the named collection of connected nodes. IOnlineStatus ostat = sender.GetProperty <IOnlineStatus>(); ostat.Online += new EventHandler(OnOnline); ostat.Offline += new EventHandler(OnOffline); // Open the sender sender.Open(); Console.WriteLine("** {0} is ready", senderId); //Info that sender sends out to the receivers (mesh)) string name = "InfoSolo"; double currentValue = Double.Parse("100"); double change = Double.Parse("45"); Console.WriteLine("Enter stock value and pass <ENTER> to broadcast update to receivers."); Console.WriteLine("Enter a blank value to terminate application"); while (true) { Console.WriteLine("New Value: "); double newvalue = 0; string value = Console.ReadLine(); if (String.IsNullOrEmpty(value)) { break; } if (!Double.TryParse(value, out newvalue)) { Console.WriteLine("Invalid value entered. Please enter a numeric value."); continue; } change = newvalue - currentValue; currentValue = newvalue; sender.PriceChange(name, change, currentValue); Console.WriteLine("Updated value sent."); } } } }
private void button1_Click(object sender, EventArgs e) { bool b = false; int x = 1; string type = ""; string niveau = ""; string specialite = ""; string grade = ""; if (etudiant.Checked) { type = "etudiant"; if (L1.Checked) { niveau = "L1"; } else if (L2.Checked) { niveau = "L2"; } else if (L3.Checked) { niveau = "L3"; } else if (M1.Checked) { niveau = "M1"; } else if (M2.Checked) { niveau = "M2"; } if (MI.Checked) { specialite = "MI"; } else if (GL.Checked) { specialite = "GL"; } else if (SI.Checked) { specialite = "SI"; } else if (STIC.Checked) { specialite = "STIC"; } else if (RSD.Checked) { specialite = "RSD"; } if (specialite == "" || niveau == "") { x = 0; } } else { type = "enseignant"; if (assistant.Checked) { grade = "maitre assistant"; } else if (conference.Checked) { grade = "maitre conference"; } if (grade == "") { x = 0; } } string name = prenom.Text; string iden = id.Text; string pren = nom.Text; string pass = pwd.Text.ToString(); string pass2 = pwd2.Text.ToString(); if (name == "" || iden == "" || pren == "" || pass == "" || pass2 == "") { x = 0; } if (!pass.Equals(pass2)) { x = 3; } if (x == 0) { result.Text = "Remplissez le formualire "; result.ForeColor = Color.Red; } else { if (x == 3) { result.Text = "verifier le mot de passe "; result.ForeColor = Color.Red; } else { Ensignant ensignant = new Ensignant(); Etudiant etudiant = new Etudiant(); if (type == "etudiant") { etudiant.Nom = name; etudiant.Prenom = pren; etudiant.NumCarte = iden; etudiant.Specialite = specialite; etudiant.Niveau = niveau; etudiant.Password = pass; ChannelFactory <IService1> channelFactory = new ChannelFactory <IService1>("BasicHttpBinding_IService1"); IService1 operation = channelFactory.CreateChannel(); b = operation.CreeComptee(etudiant); if (b) { result.Text = "succes "; result.ForeColor = Color.Green; } else { result.Text = "erreur "; result.ForeColor = Color.Red; } } else { ensignant.Nom = name; ensignant.Prenom = pren; ensignant.Matricule = iden; ensignant.Grade = grade; ensignant.Password = pass; ChannelFactory <IService1> channelFactory = new ChannelFactory <IService1>("BasicHttpBinding_IService1"); IService1 operation = channelFactory.CreateChannel(); b = operation.CreeCompte(ensignant); if (b) { result.Text = "succes "; result.ForeColor = Color.Green; inscription ii = new inscription(); ii.Show(); this.Hide(); } else { result.Text = "erreur "; result.ForeColor = Color.Red; } } } } //Console.WriteLine(type + specialite + niveau + name + pren + iden + pwd + pwd2); }
private void button3_Click(object sender, EventArgs e) { var endPoint2 = new EndpointAddress("http://localhost:5555/CalcService"); channel2 = ChannelFactory <ICalcService> .CreateChannel(new BasicHttpBinding(), endPoint2); }