public static void HttpMessageHandlerFactory_Success() { 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)); var handlerFactoryBehavior = new HttpMessageHandlerBehavior(); bool handlerCalled = false; handlerFactoryBehavior.OnSending = (message, token) => { handlerCalled = true; return(null); }; factory.Endpoint.Behaviors.Add(handlerFactoryBehavior); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string result = serviceProxy.Echo("Hello"); // *** VALIDATE *** \\ Assert.True(handlerCalled, "Error: expected client to call intercepting handler"); 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); } }
// Verify product throws MessageSecurityException when the Dns identity from the server does not match the expectation public static void TCP_ServiceCertExpired_Throw_MessageSecurityException() { string testString = "Hello"; NetTcpBinding binding = null; EndpointAddress endpointAddress = null; ChannelFactory <IWcfService> factory = null; IWcfService serviceProxy = null; // *** SETUP *** \\ binding = new NetTcpBinding(); binding.Security.Mode = SecurityMode.Transport; binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None; endpointAddress = new EndpointAddress(Endpoints.Tcp_ExpiredServerCertResource_Address); factory = new ChannelFactory <IWcfService>(binding, endpointAddress); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ try { serviceProxy.Echo(testString); Assert.True(false, "Expected: SecurityNegotiationException, Actual: no exception"); } catch (CommunicationException exception) { // *** VALIDATE *** \\ // Cannot explicitly catch a SecurityNegotiationException as it is not in the public contract. string exceptionType = exception.GetType().Name; if (exceptionType != "SecurityNegotiationException") { Assert.True(false, string.Format("Expected type SecurityNegotiationException, Actual: {0}", exceptionType)); } } 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() { #if FULLXUNIT_NOTSUPPORTED bool root_Certificate_Installed = Root_Certificate_Installed(); bool client_Certificate_Installed = Client_Certificate_Installed(); if (!root_Certificate_Installed || !client_Certificate_Installed) { 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); return; } #endif 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 SameBinding_DefaultSettings_EchoString() { string testString = "Hello"; ChannelFactory <IWcfService> factory = null; try { NetTcpBinding binding = new NetTcpBinding(); factory = new ChannelFactory <IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_DefaultBinding_Address)); IWcfService serviceProxy = factory.CreateChannel(); string result = serviceProxy.Echo(testString); Assert.Equal(testString, result); factory.Close(); } finally { ScenarioTestHelpers.CloseCommunicationObjects(factory); } }
public static void NegotiateStream_Tcp_With_ExplicitUserNameAndPassword_With_Upn() { string testString = "Hello"; ChannelFactory <IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ NetTcpBinding binding = new NetTcpBinding(); factory = new ChannelFactory <IWcfService>( binding, new EndpointAddress( new Uri(Endpoints.Tcp_DefaultBinding_Address), new UpnEndpointIdentity(NegotiateStreamTestConfiguration.Instance.NegotiateTestUpn) )); factory.Credentials.Windows.ClientCredential.Domain = NegotiateStreamTestConfiguration.Instance.NegotiateTestDomain; factory.Credentials.Windows.ClientCredential.UserName = NegotiateStreamTestConfiguration.Instance.NegotiateTestUserName; factory.Credentials.Windows.ClientCredential.Password = NegotiateStreamTestConfiguration.Instance.NegotiateTestPassword; 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 SecurityModeTransport_Echo_RoundTrips_String() { #if FULLXUNIT_NOTSUPPORTED bool windows_Authentication_Available = Windows_Authentication_Available(); if (!windows_Authentication_Available) { Console.WriteLine("---- Test SKIPPED --------------"); Console.WriteLine("Attempting to run the test in ToF, a ConditionalFact evaluated as FALSE."); Console.WriteLine("Windows_Authentication_Available evaluated as {0}", windows_Authentication_Available); return; } #endif 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_Echo_RoundTrips_String(WSMessageEncoding messageEncoding) { ChannelFactory <IWcfService> factory = null; IWcfService serviceProxy = null; string testString = "Hello"; try { // *** SETUP *** \\ BasicHttpsBinding basicHttpsBinding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport); basicHttpsBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate; basicHttpsBinding.MessageEncoding = messageEncoding; string clientCertThumb = ServiceUtilHelper.ClientCertificate.Thumbprint; factory = new ChannelFactory <IWcfService>(basicHttpsBinding, new EndpointAddress(Endpoints.Https_DefaultBinding_Address + Enum.GetName(typeof(WSMessageEncoding), messageEncoding))); factory.Credentials.ClientCertificate.SetCertificate( StoreLocation.CurrentUser, StoreName.My, X509FindType.FindByThumbprint, clientCertThumb); 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); } }
// Test Requirements \\ // The following environment variables must be set... // "NegotiateTestRealm" // "NegotiateTestDomain" // "ExplicitUserName" // "ExplicitPassword" // "ServiceUri" (server running as machine context) public static void NegotiateStream_Http_With_ExplicitUserNameAndPasswordForNet50() { string testString = "Hello"; ChannelFactory <IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; string host = TestProperties.GetProperty(TestProperties.ServiceUri_PropertyName); factory = new ChannelFactory <IWcfService>( binding, new EndpointAddress(new Uri(Endpoints.Https_WindowsAuth_Address), new SpnEndpointIdentity($"HTTP/{host}"))); factory.Credentials.Windows.ClientCredential.Domain = GetDomain(); factory.Credentials.Windows.ClientCredential.UserName = GetExplicitUserName(); factory.Credentials.Windows.ClientCredential.Password = GetExplicitPassword(); 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 NotExistentHost_Throws_EndpointNotFoundException() { string nonExistHost = "http://nonexisthost/WcfService/WindowsCommunicationFoundation"; //On .NET Native retail, exception message is stripped to include only parameter string expectExceptionMsg = nonExistHost; try { //This test can also hang for other test infrastructure related reasons, adding clock based timeout in addition to the innner SendTimeout. DateTime start = DateTime.Now; while (DateTime.Now.Subtract(start).Seconds < 15) { BasicHttpBinding binding = new BasicHttpBinding(); //Setting a timeout as this test takes 500 seconds to finish when it fails. binding.SendTimeout = TimeSpan.FromMilliseconds(10000); using (ChannelFactory <IWcfService> factory = new ChannelFactory <IWcfService>(binding, new EndpointAddress(nonExistHost))) { IWcfService serviceProxy = factory.CreateChannel(); string response = serviceProxy.Echo("Hello"); } } } catch (Exception e) { if (e.GetType() != typeof(EndpointNotFoundException)) { Assert.True(false, string.Format("Expected exception: {0}, actual: {1}", "EndpointNotFoundException", e.GetType())); } if (!e.Message.Contains(expectExceptionMsg)) { Assert.True(false, string.Format("Expected exception message: {0}, actual: {1}", expectExceptionMsg, e.Message)); } return; } Assert.True(false, "Expected EndpointNotFoundException, but no exception thrown."); }
// Asking for PeerTrust alone should succeed // if the certificate is in the TrustedPeople store. For this test // we use a certificate we know is in the TrustedPeople store. public static void Https_SecModeTrans_CertValMode_PeerTrust_Succeeds_In_TrustedPeople() { EndpointAddress endpointAddress = null; string testString = "Hello"; ChannelFactory <IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ BasicHttpsBinding binding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.None; endpointAddress = new EndpointAddress( new Uri(Endpoints.Https_SecModeTrans_ClientCredTypeNone_ServerCertValModePeerTrust_Address)); factory = new ChannelFactory <IWcfService>(binding, endpointAddress); factory.Credentials.ServiceCertificate.SslCertificateAuthentication = new X509ServiceCertificateAuthentication(); factory.Credentials.ServiceCertificate.SslCertificateAuthentication.CertificateValidationMode = X509CertificateValidationMode.PeerTrust; 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); } }
// Asking for ChainTrust only should succeed if the certificate is // chain-trusted. public static void NetTcp_SecModeTrans_CertValMode_ChainTrust_Succeeds_ChainTrusted() { EndpointAddress endpointAddress = null; string testString = "Hello"; ChannelFactory <IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport); binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None; endpointAddress = new EndpointAddress(new Uri( Endpoints.Tcp_CustomBinding_SslStreamSecurity_Address)); factory = new ChannelFactory <IWcfService>(binding, endpointAddress); factory.Credentials.ServiceCertificate.Authentication.RevocationMode = X509RevocationMode.NoCheck; 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(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
public static void MessageProperty_HttpRequestMessageProperty_RoundTrip_Verify() { MyClientBase <IWcfService> client = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ CustomBinding customBinding = new CustomBinding(); customBinding.Elements.Add(new TextMessageEncodingBindingElement()); customBinding.Elements.Add(new HttpTransportBindingElement()); client = new MyClientBase <IWcfService>(customBinding, new EndpointAddress(Endpoints.DefaultCustomHttp_Address)); client.Endpoint.EndpointBehaviors.Add(new ClientMessagePropertyBehavior()); serviceProxy = client.ChannelFactory.CreateChannel(); // *** EXECUTE *** \\ TestHttpRequestMessageProperty property = serviceProxy.EchoHttpRequestMessageProperty(); // *** VALIDATE *** \\ Assert.NotNull(property); Assert.True(property.SuppressEntityBody == false, "Expected SuppressEntityBody to be 'false'"); Assert.Equal("POST", property.Method); Assert.Equal("My%20address", property.QueryString); Assert.True(property.Headers.Count > 0, "TestHttpRequestMessageProperty.Headers should not have empty headers"); Assert.Equal("my value", property.Headers["customer"]); // *** CLEANUP *** \\ ((ICommunicationObject)client).Close(); ((ICommunicationObject)serviceProxy).Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, (ICommunicationObject)client); } }
public static async Task ServerCertificateValidationUsingIdentity_EchoString() { EndpointAddress endpointAddress = null; X509Certificate2 serviceCertificate = null; string testString = "Hello"; ChannelFactory <IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ CustomBinding binding = new CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.Soap11, Encoding.UTF8), new HttpsTransportBindingElement()); serviceCertificate = await ServiceUtilHelper.GetServiceMacineCertFromServerAsync(); var identity = new X509CertificateEndpointIdentity(serviceCertificate); endpointAddress = new EndpointAddress(new Uri(Endpoints.Https_DefaultBinding_Address_Text), identity); factory = new ChannelFactory <IWcfService>(binding, endpointAddress); 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 SameBinding_SecurityModeNone_Text_EchoString_Roundtrip() { BindingElement[] bindingElements = null; CustomBinding binding = null; ChannelFactory <IWcfService> factory = null; IWcfService serviceProxy = null; EndpointAddress endpointAddress = null; string result = null; string testString = "Hello"; try { // *** SETUP *** \\ bindingElements = new BindingElement[2]; bindingElements[0] = new TextMessageEncodingBindingElement(); bindingElements[1] = new TcpTransportBindingElement(); binding = new CustomBinding(bindingElements); endpointAddress = new EndpointAddress(Endpoints.Tcp_CustomBinding_NoSecurity_Text_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); } }
static void Main(string[] args) { Console.Write("Enter server address: "); var hostAddress = Console.ReadLine(); var address = new EndpointAddress(new Uri(string.Format("https://{0}:9000/MyService", hostAddress))); var binding = new BasicHttpsBinding(BasicHttpsSecurityMode.TransportWithMessageCredential); var factory = new ChannelFactory <IWcfService>(binding, address); Console.Write("Enter username: "******"Enter password: "******"Please enter some words or press [Esc] to exit the application."); while (true) { var key = Console.ReadKey(); if (key.Key.Equals(ConsoleKey.Escape)) { return; } string input = key.KeyChar.ToString() + Console.ReadLine(); // read input string output = host.Echo(input); // send to host, receive output Console.WriteLine(output); // write output } }
public static void SameBinding_SecurityModeNone_Text_EchoString_Roundtrip() { string variationDetails = "Client:: CustomBinding/TcpTransport/NoWindowsStreamSecurity/TextMessageEncoding = None\nServer:: CustomBinding/TcpTransport/NoWindowsStreamSecurity/TextMessageEncoding = None"; string testString = "Hello"; StringBuilder errorBuilder = new StringBuilder(); bool success = false; try { BindingElement[] bindingElements = new BindingElement[2]; bindingElements[0] = new TextMessageEncodingBindingElement(); bindingElements[1] = new TcpTransportBindingElement(); CustomBinding binding = new CustomBinding(bindingElements); ChannelFactory <IWcfService> factory = new ChannelFactory <IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_CustomBinding_NoSecurity_Text_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 async Task OperationContextScopeAsyncFlow() { // This test lives in the scenario tests as it needs a real channel to test OperationContext // even though nothing is being sent across the wire. ChannelFactory <IWcfService> factory = null; IWcfService serviceProxy = null; var exisitingSyncContext = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(ThreadHoppingSynchronizationContext.Instance); NetTcpBinding binding = new NetTcpBinding(); factory = new ChannelFactory <IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_DefaultBinding_Address)); serviceProxy = factory.CreateChannel(); Assert.Null(OperationContext.Current); using (var scope = new OperationContextScope((IContextChannel)serviceProxy)) { Assert.NotNull(OperationContext.Current); var currentContext = OperationContext.Current; int currentThreadId = Thread.CurrentThread.ManagedThreadId; await Task.Yield(); Assert.NotEqual(currentThreadId, Thread.CurrentThread.ManagedThreadId); Assert.Equal(currentContext, OperationContext.Current); } ((IClientChannel)serviceProxy).Close(); factory.Close(); } finally { SynchronizationContext.SetSynchronizationContext(exisitingSyncContext); await Task.Yield(); // Hop back to original sync context ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
public void MockWcfService2() { string val = "MockedValue"; string actualRetVal; // Initialisation du Mock du service WCF Mock <IWcfService> wcfMock = new Mock <IWcfService>(); // Initialisation de la fonction GetData(int) wcfMock.Setup <string>(s => s.GetData(4)).Returns(val); // Définition de l'objet Mock IWcfService wcfMockObject = wcfMock.Object; // Initialisation de l'agent avec le Mock du service WcfServiceAgent serviceAgent = new WcfServiceAgent(wcfMockObject); // Appel de la fonction actualRetVal = serviceAgent.HitWCFService(); // Vérification des résultats wcfMock.Verify(s => s.GetData(4), Times.Exactly(1)); Assert.AreEqual("MockedValue", actualRetVal, "Not same."); }
public static async Task OperationContextLegacyBehavior() { ChannelFactory <IWcfService> factory = null; IWcfService serviceProxy = null; var exisitingSyncContext = SynchronizationContext.Current; try { SynchronizationContext.SetSynchronizationContext(ThreadHoppingSynchronizationContext.Instance); bool asyncFlowDisabled = AppContext.TryGetSwitch("System.ServiceModel.OperationContext.DisableAsyncFlow", out bool switchEnabled) && switchEnabled; Assert.True(asyncFlowDisabled, "Async flow of Operation Context isn't disabled"); var binding = new BasicHttpBinding(BasicHttpSecurityMode.None); factory = new ChannelFactory <IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); serviceProxy = factory.CreateChannel(); ((IClientChannel)serviceProxy).Open(); Assert.Null(OperationContext.Current); var scope = new OperationContextScope((IContextChannel)serviceProxy); Assert.NotNull(OperationContext.Current); var currentContext = OperationContext.Current; int currentThreadId = Thread.CurrentThread.ManagedThreadId; await Task.Yield(); Assert.NotEqual(currentThreadId, Thread.CurrentThread.ManagedThreadId); Assert.NotEqual(currentContext, OperationContext.Current); Assert.Throws <InvalidOperationException>(() => scope.Dispose()); ((IClientChannel)serviceProxy).Close(); factory.Close(); } finally { SynchronizationContext.SetSynchronizationContext(exisitingSyncContext); await Task.Yield(); // Hop back to original sync context ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
public static void DefaultSettings_Echo_RoundTrips_String_StreamedResponse() { string testString = "Hello"; BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None); binding.TransferMode = TransferMode.StreamedResponse; ChannelFactory <IWcfService> factory = new ChannelFactory <IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); IWcfService serviceProxy = factory.CreateChannel(); try { var returnStream = serviceProxy.GetStreamFromString(testString); var result = StreamToString(returnStream); Assert.Equal(testString, result); } finally { if (factory != null && factory.State != CommunicationState.Closed) { factory.Abort(); } } }
public static bool RunBasicEchoTest(Binding binding, string address, string variation, Action <ChannelFactory> factorySettings = null) { Logger.LogInformation("Starting basic echo test.\nTest variation:...\n{0}\nUsing address: '{1}'", variation, address); ChannelFactory <IWcfService> factory = null; IWcfService serviceProxy = null; bool success = false; try { // *** SETUP *** \\ factory = new ChannelFactory <IWcfService>(binding, new EndpointAddress(address)); if (factorySettings != null) { factorySettings(factory); } serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ string 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); } Logger.LogInformation(" Result: {0} ", success ? "PASS" : "FAIL"); return(success); }
// The product code will check the Dns identity from the server and throw if it does not match what is specified in DnsEndpointIdentity public static void VerifyServiceIdentityMatchDnsEndpointIdentity() { #if FULLXUNIT_NOTSUPPORTED bool root_Certificate_Installed = Root_Certificate_Installed(); bool client_Certificate_Installed = Client_Certificate_Installed(); if (!root_Certificate_Installed || !client_Certificate_Installed) { 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); return; } #endif 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(Endpoints.Tcp_VerifyDNS_HostName)); ChannelFactory <IWcfService> factory = new ChannelFactory <IWcfService>(binding, endpointAddress); IWcfService serviceProxy = factory.CreateChannel(); try { var result = serviceProxy.Echo(testString); Assert.Equal(testString, result); factory.Close(); } finally { ScenarioTestHelpers.CloseCommunicationObjects(factory); } }
public static void NegotiateStream_Http_With_ExplicitUserNameAndPassword() { string testString = "Hello"; ChannelFactory <IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); factory = new ChannelFactory <IWcfService>( binding, new EndpointAddress(Endpoints.Https_WindowsAuth_Address)); factory.Credentials.Windows.ClientCredential.Domain = NegotiateStreamTestConfiguration.Instance.NegotiateTestDomain; factory.Credentials.Windows.ClientCredential.UserName = NegotiateStreamTestConfiguration.Instance.NegotiateTestUserName; factory.Credentials.Windows.ClientCredential.Password = NegotiateStreamTestConfiguration.Instance.NegotiateTestPassword; 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_Async_Open_Proxy() { string testString = "Hello"; BasicHttpBinding binding = null; ChannelFactory <IWcfService> factory = null; IWcfService serviceProxy = null; string result = null; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); factory = new ChannelFactory <IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); serviceProxy = factory.CreateChannel(); // *** EXECUTE *** \\ ICommunicationObject proxyAsCommunicationObject = (ICommunicationObject)serviceProxy; Task t = Task.Factory.FromAsync(proxyAsCommunicationObject.BeginOpen, proxyAsCommunicationObject.EndOpen, TaskCreationOptions.None); // *** VALIDATE *** \\ t.GetAwaiter().GetResult(); Assert.True(proxyAsCommunicationObject.State == CommunicationState.Opened, String.Format("Expected proxy state 'Opened', actual was '{0}'", proxyAsCommunicationObject.State)); result = serviceProxy.Echo(testString); // verifies proxy did open correctly // *** CLEANUP *** \\ ((ICommunicationObject)serviceProxy).Close(); factory.Close(); } finally { // *** ENSURE CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory); } }
public static void NegotiateStream_Http_With_Upn() { string testString = "Hello"; ChannelFactory <IWcfService> factory = null; IWcfService serviceProxy = null; try { // *** SETUP *** \\ BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.Transport); binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows; factory = new ChannelFactory <IWcfService>( binding, new EndpointAddress( new Uri(Endpoints.Https_WindowsAuth_Address), new UpnEndpointIdentity(GetUPN()) )); 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 TextMessageEncoder_QuotedCharSet_In_Response_ContentType() { ChannelFactory <IWcfService> factory = null; IWcfService channel = null; string testQuotedCharSetContentType = "text/xml; param1 = value1; charset=\"utf-8\"; param2 = value2; param3 = \"value3\""; Binding binding = null; try { // *** SETUP *** \\ binding = new BasicHttpBinding(BasicHttpSecurityMode.None); factory = new ChannelFactory <IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic)); channel = factory.CreateChannel(); // *** EXECUTE *** \\ channel.ReturnContentType(testQuotedCharSetContentType); } finally { // *** CLEANUP *** \\ ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)channel, factory); } }
public static void UnexpectedException_Throws_FaultException() { string faultMsg = "This is a test fault msg"; StringBuilder errorBuilder = new StringBuilder(); try { BasicHttpBinding binding = new BasicHttpBinding(); using (ChannelFactory <IWcfService> factory = new ChannelFactory <IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic))) { IWcfService serviceProxy = factory.CreateChannel(); serviceProxy.ThrowInvalidOperationException(faultMsg); } } catch (Exception e) { if (e.GetType() != typeof(FaultException <ExceptionDetail>)) { errorBuilder.AppendLine(string.Format("Expected exception: {0}, actual: {1}", "FaultException<ExceptionDetail>", e.GetType())); } else { FaultException <ExceptionDetail> faultException = (FaultException <ExceptionDetail>)(e); string actualFaultMsg = ((ExceptionDetail)(faultException.Detail)).Message; if (actualFaultMsg != faultMsg) { errorBuilder.AppendLine(string.Format("Expected Fault Message: {0}, actual: {1}", faultMsg, actualFaultMsg)); } } Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: UnexpectedException_Throws_FaultException FAILED with the following errors: {0}", errorBuilder)); return; } Assert.True(false, "Expected FaultException<FaultDetail> exception, but no exception thrown."); }
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); } }); }
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> /// /// </summary> /// <param name="disposing"></param> protected virtual void DoDispose(bool disposing) { if (disposing) { //清理托管对象 _serviceChannel = null; GC.SuppressFinalize(this); } //清理非托管对象 if (_channelFactory != null) { try { IDisposable disposable = _channelFactory as IDisposable; if (disposable != null) { disposable.Dispose(); } else { _channelFactory.Abort(); _channelFactory.Close(); } _channelFactory = null; } catch (Exception) { } } }
public string TestWcfService(IWcfService inputValues) => UpdateManagerProxy.TestWcfService(inputValues);
/// <summary> /// Initializes a new instance of the <see cref="T:System.Object"/> class. /// </summary> public MultiMockComponent(IWcfService service) { _service = service; }
/// <summary> /// 重置连接通道 /// </summary> public void ResetChannel() { _connected = false; if (_channelFactory == null || _channelFactory.State == CommunicationState.Faulted || _channelFactory.State == CommunicationState.Closed) { _channelFactory = BuildChannel(); } _serviceChannel = _channelFactory.CreateChannel(); }
public Server(IKernel kernel, ILogger log, IWcfService wcfService) { this.kernel = kernel; this.log = log; this.host = new ServiceHost(wcfService); }