Exemple #1
0
    public static void SameBinding_SecurityModeTransport_EchoString()
    {
        string testString = "Hello";
        ChannelFactory <IWcfService> factory = null;

        try
        {
            NetTcpBinding binding = new NetTcpBinding(SecurityMode.Transport);
            factory = new ChannelFactory <IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_Address));
            IWcfService serviceProxy = factory.CreateChannel();

            string result = serviceProxy.Echo(testString);
            Assert.Equal(testString, result);

            factory.Close();
        }
        finally
        {
            ScenarioTestHelpers.CloseCommunicationObjects(factory);
        }
    }
Exemple #2
0
 public static void Test_Negative_Calling_Terminating_Twice()
 {
     using (var factory = CreateChannelFactoryHelper <ISessionTestsDefaultService>(Endpoints.Tcp_Session_Tests_Default_Service))
     {
         ISessionTestsDefaultService channel3 = null;
         try
         {
             channel3 = factory.CreateChannel();
             channel3.MethodAInitiating(3);
             channel3.MethodCTerminating();
             Assert.Throws <InvalidOperationException>(() =>
             {
                 channel3.MethodCTerminating();
             });
         }
         finally
         {
             ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)channel3);
         }
     }
 }
Exemple #3
0
    public static void WebSocket_WSScheme_WSTransportUsageAlways_DuplexCallback_GuidRoundtrip()
    {
        DuplexChannelFactory <IWcfDuplexService> factory = null;
        IWcfDuplexService proxy = null;
        Guid guid = Guid.NewGuid();

        try
        {
            // *** SETUP *** \\
            NetHttpBinding binding = new NetHttpBinding();
            binding.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always;

            WcfDuplexServiceCallback callbackService = new WcfDuplexServiceCallback();
            InstanceContext          context         = new InstanceContext(callbackService);

            UriBuilder builder = new UriBuilder(Endpoints.NetHttpWebSocketTransport_Address);
            // Replacing "http" with "ws" as the uri scheme.
            builder.Scheme = "ws";

            factory = new DuplexChannelFactory <IWcfDuplexService>(context, binding, new EndpointAddress(Endpoints.NetHttpWebSocketTransport_Address));
            proxy   = factory.CreateChannel();

            // *** EXECUTE *** \\
            Task.Run(() => proxy.Ping(guid));
            Guid returnedGuid = callbackService.CallbackGuid;

            // *** VALIDATE *** \\
            Assert.True(guid == returnedGuid,
                        string.Format("The sent GUID does not match the returned GUID. Sent '{0}', Received: '{1}'", guid, returnedGuid));

            // *** CLEANUP *** \\
            factory.Close();
            ((ICommunicationObject)proxy).Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)proxy, factory);
        }
    }
Exemple #4
0
    // Confirm that the Validate method of the custom X509CertificateValidator is called and that an exception thrown there is handled correctly.
    public static void TCP_ServiceCertFailedCustomValidate_Throw_Exception()
    {
        string          testString           = "Hello";
        NetTcpBinding   binding              = null;
        EndpointAddress endpointAddress      = null;
        ChannelFactory <IWcfService> factory = null;
        IWcfService serviceProxy             = null;

        // *** VALIDATE *** \\
        var exception = Assert.Throws <Exception>(() =>
        {
            // *** SETUP *** \\
            binding = new NetTcpBinding();
            binding.Security.Mode = SecurityMode.Transport;
            binding.Security.Transport.ClientCredentialType = TcpClientCredentialType.None;
            endpointAddress = new EndpointAddress(new Uri(Endpoints.Tcp_VerifyDNS_Address), new DnsEndpointIdentity(Endpoints.Tcp_VerifyDNS_HostName));
            factory         = new ChannelFactory <IWcfService>(binding, endpointAddress);
            factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode  = X509CertificateValidationMode.Custom;
            factory.Credentials.ServiceCertificate.Authentication.CustomCertificateValidator = new MyCertificateValidator();
            serviceProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            try
            {
                var result = serviceProxy.Echo(testString);

                // *** CLEANUP *** \\
                ((ICommunicationObject)serviceProxy).Close();
                factory.Close();
            }
            finally
            {
                // *** ENSURE CLEANUP *** \\
                ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
            }
        });

        // *** ADDITIONAL VALIDATION *** \\
        Assert.Equal(MyCertificateValidator.exceptionMsg, exception.Message);
    }
Exemple #5
0
    public static void NegotiateStream_Http_With_ExplicitUserNameAndPassword_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())
                    ));

            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 Message_With_XmlElementMessageHeader_RoundTrip()
    {
        BasicHttpBinding  binding     = null;
        IWcfService_4_4_0 clientProxy = null;
        ChannelFactory <IWcfService_4_4_0> factory = null;

        // *** SETUP *** \\
        try
        {
            binding     = new BasicHttpBinding();
            factory     = new ChannelFactory <IWcfService_4_4_0>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_4_4_0_Basic));
            clientProxy = factory.CreateChannel();

            string testString = "test string";
            var    header     = new XmlElementMessageHeader()
            {
                HeaderValue = testString
            };
            var request = new XmlElementMessageHeaderRequest(header);

            // *** EXECUTE *** \\
            XmlElementMessageHeaderResponse response = clientProxy.SendRequestWithXmlElementMessageHeader(request);

            // *** VALIDATE *** \\
            Assert.True(response != null,
                        $"Expected {nameof(response)} not to be null , but it was null");

            Assert.True(String.Equals(testString, response.TestResult),
                        $"Expected {nameof(response.TestResult)} = {testString}, actual was {response.TestResult}");

            // *** CLEANUP *** \\
            factory.Close();
            ((ICommunicationObject)clientProxy).Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)clientProxy, factory);
        }
    }
Exemple #7
0
    public static void HttpMessageHandlerFactory_Success(WSMessageEncoding messageEncoding)
    {
        ChannelFactory <IWcfService> factory = null;
        IWcfService      serviceProxy        = null;
        string           testString          = "Hello";
        BasicHttpBinding binding             = null;

        try
        {
            // *** SETUP *** \\
            binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
            binding.MessageEncoding = messageEncoding;
            factory = new ChannelFactory <IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic + Enum.GetName(typeof(WSMessageEncoding), messageEncoding)));
            var  handlerFactoryBehavior = new HttpMessageHandlerBehavior();
            bool handlerCalled          = false;
            handlerFactoryBehavior.OnSendingAsync = (message, token) =>
            {
                handlerCalled = true;
                return(Task.FromResult((HttpResponseMessage)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);
        }
    }
Exemple #8
0
    public static void ServiceContract_TypedProxy_SyncOperation_UniqueTypeOutArg()
    {
        string           message = "Hello";
        BasicHttpBinding binding = null;
        ChannelFactory <IServiceContractUniqueTypeOutSyncService> factory = null;
        IServiceContractUniqueTypeOutSyncService serviceProxy             = null;
        UniqueType uniqueType = null;

        try
        {
            // *** SETUP *** \\
            binding      = new BasicHttpBinding();
            factory      = new ChannelFactory <IServiceContractUniqueTypeOutSyncService>(binding, new EndpointAddress(Endpoints.ServiceContractSyncUniqueTypeOut_Address));
            serviceProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            serviceProxy.Request(message, out uniqueType);

            // *** VALIDATE *** \\
            Assert.True((uniqueType.stringValue == message),
                        String.Format("The value of the 'stringValue' field in the UniqueType instance was not as expected. expected {0} but got {1}", message, uniqueType.stringValue));

            // *** EXECUTE *** \\
            uniqueType = null;
            serviceProxy.Request2(out uniqueType, message);

            // *** VALIDATE *** \\
            Assert.True((uniqueType.stringValue == message),
                        String.Format("The value of the 'stringValue' field in the UniqueType instance was not as expected. expected {0} but got {1}", message, uniqueType.stringValue));

            // *** CLEANUP *** \\
            ((ICommunicationObject)serviceProxy).Close();
            factory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
    private static void ServiceContract_TypedProxy_AsyncBeginEnd_Call_WithNoCallback_TestImpl(Binding binding, string endpoint, string testName)
    {
        // This test verifies a typed proxy can call a service operation asynchronously using Begin/End
        ChannelFactory <IWcfServiceBeginEndGenerated> factory = null;
        EndpointAddress endpointAddress           = null;
        IWcfServiceBeginEndGenerated serviceProxy = null;
        string result = null;

        try
        {
            // *** SETUP *** \\
            endpointAddress = new EndpointAddress(endpoint);
            factory         = new ChannelFactory <IWcfServiceBeginEndGenerated>(binding, endpointAddress);
            serviceProxy    = factory.CreateChannel();

            // *** EXECUTE *** \\
            IAsyncResult ar = serviceProxy.BeginEcho("Hello", null, null);
            // An actual timeout should complete the ar, but we still set
            // a maximum wait time in case that does not happen.
            bool success = ar.AsyncWaitHandle.WaitOne(ScenarioTestHelpers.TestTimeout);

            // *** VALIDATE *** \\
            Assert.True(success, String.Format("The IAsyncResult was not called. If the IAsyncResult had been called the AsyncWaitHandle would have been set to 'True', but the value of AsyncWaitHandle was: {0}", success));

            // *** EXECUTE *** \\
            result = serviceProxy.EndEcho(ar);

            // *** VALIDATE *** \\
            Assert.True(String.Equals(result, "Hello"), String.Format("Expected response from Service: {0} Actual was: {1}", "Hello", result));

            // *** CLEANUP *** \\
            factory.Close();
            ((ICommunicationObject)serviceProxy).Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
Exemple #10
0
    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);
        }
    }
Exemple #11
0
    // 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);
        }
    }
Exemple #12
0
    // 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);
        }
    }
Exemple #13
0
    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);
        }
    }
Exemple #14
0
    public static void DataContractResolverTest()
    {
        IDataContractResolverService client = null;
        ChannelFactory <IDataContractResolverService> factory = null;

        try
        {
            factory = new ChannelFactory <IDataContractResolverService>(new BasicHttpBinding(), new EndpointAddress(Endpoints.DataContractResolver_Address));
            ContractDescription cd = factory.Endpoint.Contract;

            foreach (var operation in factory.Endpoint.Contract.Operations)
            {
                DataContractSerializerOperationBehavior behavior =
                    operation.OperationBehaviors.FirstOrDefault(
                        x => x.GetType() == typeof(DataContractSerializerOperationBehavior)) as DataContractSerializerOperationBehavior;
                behavior.DataContractResolver = new ManagerDataContractResolver();
            }

            client = factory.CreateChannel();
            client.AddEmployee(new Manager()
            {
                Age = "10", Name = "jone", OfficeId = 1
            });
            var results = client.GetAllEmployees();
            Assert.Equal(1, results.Count());
            var manager = results.First();
            Assert.True(manager.GetType() == (typeof(Manager)), string.Format("Expected type: {0}, Actual type: {1}", typeof(Manager), manager.GetType()));
            Assert.True(((Manager)manager).Name == "jone", string.Format("Expected Name: {0}, Actual Name: {1}", "jone", ((Manager)manager).Name));
            Assert.True(((Manager)manager).Age == "10", string.Format("Expected Age: {0}, Actual Age: {1}", "10", ((Manager)manager).Age));
            Assert.True(((Manager)manager).OfficeId == 1, string.Format("Expected Id: {0}, Actual Id: {1}", 1, ((Manager)manager).OfficeId));
            factory.Close();
            ((ICommunicationObject)client).Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)client, 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);
        }
    }
Exemple #16
0
    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);
        }
    }
    public static void XmlSFAttributeRpcEncMessageHeaderTest()
    {
        BasicHttpBinding binding         = null;
        EndpointAddress  endpointAddress = null;
        ChannelFactory <IEchoRpcEncWithHeadersService> factory1 = null;
        IEchoRpcEncWithHeadersService serviceProxy1             = null;
        string echoText           = "Hello";
        string headerText         = "WCF is Cool!";
        string expectedHeaderText = headerText + headerText;

        // *** SETUP *** \\
        binding         = new BasicHttpBinding();
        endpointAddress = new EndpointAddress(Endpoints.BasicHttpRpcEncWithHeaders_Address);
        factory1        = new ChannelFactory <IEchoRpcEncWithHeadersService>(binding, endpointAddress);
        serviceProxy1   = factory1.CreateChannel();

        // *** EXECUTE Variation *** \\
        try
        {
            var response = serviceProxy1.Echo(new EchoRequest {
                message = "Hello", StringHeader = new StringHeader {
                    HeaderValue = "WCF is Cool!"
                }
            });

            Assert.Equal(echoText, response.EchoResult);
            Assert.Equal(expectedHeaderText, response.StringHeader.HeaderValue);
        }
        catch (Exception ex)
        {
            Assert.True(false, ex.Message);
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy1);
        }
    }
Exemple #18
0
    // 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);
        }
    }
    public static void DigestAuthentication_RoundTrips_Echo()
    {
        StringBuilder errorBuilder = new StringBuilder();

        try
        {
            BasicHttpBinding basicHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport);
            basicHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Digest;
            Action <ChannelFactory> credentials = (factory) =>
            {
                factory.Credentials.HttpDigest.ClientCredential.UserName = s_username;
                factory.Credentials.HttpDigest.ClientCredential.Password = s_password;
            };

            ScenarioTestHelpers.RunBasicEchoTest(basicHttpBinding, Endpoints.Https_DigestAuth_Address, "BasicHttpBinding - Digest auth ", errorBuilder, credentials);
        }
        catch (Exception ex)
        {
            errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString()));
        }

        Assert.True(errorBuilder.Length == 0, String.Format("Test Case: DigestAuthentication FAILED with the following errors: {0}", errorBuilder));
    }
Exemple #20
0
    public static void DuplexClientBaseOfT_OverNetTcp_Synchronous_Call()
    {
        DuplexClientBase <IWcfDuplexService> duplexService = null;
        IWcfDuplexService proxy = null;
        Guid guid = Guid.NewGuid();

        try
        {
            // *** SETUP *** \\
            NetTcpBinding binding = new NetTcpBinding();
            binding.Security.Mode = SecurityMode.None;

            WcfDuplexServiceCallback callbackService = new WcfDuplexServiceCallback();
            InstanceContext          context         = new InstanceContext(callbackService);

            duplexService = new MyDuplexClientBase <IWcfDuplexService>(context, binding, new EndpointAddress(Endpoints.Tcp_NoSecurity_Callback_Address));
            proxy         = duplexService.ChannelFactory.CreateChannel();

            // *** EXECUTE *** \\
            // Ping on another thread.
            Task.Run(() => proxy.Ping(guid));
            Guid returnedGuid = callbackService.CallbackGuid;

            // *** VALIDATE *** \\
            Assert.True(guid == returnedGuid,
                        string.Format("The sent GUID does not match the returned GUID. Sent '{0}', Received: '{1}'", guid, returnedGuid));

            // *** CLEANUP *** \\
            ((ICommunicationObject)duplexService).Close();
            ((ICommunicationObject)proxy).Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)proxy, (ICommunicationObject)duplexService);
        }
    }
Exemple #21
0
    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);
        }
    }
Exemple #22
0
    public static async Task DuplexEchoCall(ReliableMessagingVersion rmVersion, bool ordered, string endpointSuffix)
    {
        string testString = "Hello";
        DuplexChannelFactory <IWcfReliableDuplexService> factory = null;
        IWcfReliableDuplexService serviceProxy = null;
        NetTcpBinding             binding      = null;

        try
        {
            // *** SETUP *** \\
            binding = new NetTcpBinding(SecurityMode.None, true);
            binding.ReliableSession.Ordered = ordered;
            var customBinding = new CustomBinding(binding);
            var reliableSessionBindingElement = customBinding.Elements.Find <ReliableSessionBindingElement>();
            reliableSessionBindingElement.ReliableMessagingVersion = rmVersion;
            var callbackService = new ReliableDuplexCallbackService();
            var instanceContext = new InstanceContext(callbackService);
            factory      = new DuplexChannelFactory <IWcfReliableDuplexService>(instanceContext, customBinding, new EndpointAddress(Endpoints.ReliableDuplexSession_NetTcp + endpointSuffix));
            serviceProxy = factory.CreateChannel();
            // *** EXECUTE *** \\
            ((IClientChannel)serviceProxy).Open(); // This will establish a reliable session
            var result = await serviceProxy.DuplexEchoAsync(testString);

            // *** VALIDATE *** \\
            Assert.Equal(testString, result);
            Assert.Equal(testString, callbackService.LastReceivedEcho);

            // *** CLEANUP *** \\
            ((IClientChannel)serviceProxy).Close();
            factory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
Exemple #23
0
    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);
        }
    }
    public static async Task OperationContextCallbackAsyncFlow()
    {
        ChannelFactory <IDuplexChannelService> factory = null;
        IDuplexChannelService serviceProxy             = null;
        Guid guid = Guid.NewGuid();

        try
        {
            // *** SETUP *** \\
            NetTcpBinding binding = new NetTcpBinding();
            binding.Security.Mode = SecurityMode.None;
            DuplexChannelServiceCallback callbackService = new DuplexChannelServiceCallback();
            InstanceContext context         = new InstanceContext(callbackService);
            EndpointAddress endpointAddress = new EndpointAddress(Endpoints.Tcp_NoSecurity_DuplexCallback_Address);
            factory      = new DuplexChannelFactory <IDuplexChannelService>(context, binding, endpointAddress);
            serviceProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            serviceProxy.Ping(guid);
            await callbackService.CallCompletedTask;

            // *** VALIDATE *** \\
            if (callbackService.Exception != null)
            {
                ExceptionDispatchInfo.Capture(callbackService.Exception).Throw();
            }

            // *** CLEANUP *** \\
            ((ICommunicationObject)serviceProxy).Close();
            factory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
Exemple #26
0
    public static void WebSocket_Http_WSTransportUsageAlways_DuplexCallback_GuidRoundtrip()
    {
        DuplexChannelFactory <IWcfDuplexService> factory = null;
        IWcfDuplexService duplexProxy = null;
        Guid guid = Guid.NewGuid();

        try
        {
            // *** SETUP *** \\
            NetHttpBinding binding = new NetHttpBinding();
            // Verifying the scenario works when explicitly setting the transport to use WebSockets.
            binding.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always;

            WcfDuplexServiceCallback callbackService = new WcfDuplexServiceCallback();
            InstanceContext          context         = new InstanceContext(callbackService);

            factory     = new DuplexChannelFactory <IWcfDuplexService>(context, binding, new EndpointAddress(Endpoints.NetHttpWebSocketTransport_Address));
            duplexProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            Task.Run(() => duplexProxy.Ping(guid));
            Guid returnedGuid = callbackService.CallbackGuid;

            // *** VALIDATE *** \\
            Assert.True(guid == returnedGuid, string.Format("The sent GUID does not match the returned GUID. Sent '{0}', Received: '{1}'", guid, returnedGuid));

            // *** CLEANUP *** \\
            factory.Close();
            ((ICommunicationObject)duplexProxy).Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)duplexProxy, factory);
        }
    }
Exemple #27
0
    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);
        }
    }
Exemple #28
0
    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 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 MessageHeader_RequestTypeWithUsesMessageHeaderAttribute()
    {
        // *** SETUP *** \\
        var binding         = new BasicHttpBinding();
        var endpointAddress = new EndpointAddress(Endpoints.HttpBaseAddress_Basic_Text);
        var factory         = new ChannelFactory <IXmlMessageContarctTestService>(binding, endpointAddress);
        IXmlMessageContarctTestService serviceProxy = factory.CreateChannel();
        var input = new XmlMessageContractTestRequestWithMessageHeader("1");

        try
        {
            // *** EXECUTE *** \\
            XmlMessageContractTestResponse response = serviceProxy.EchoMessageResquestWithMessageHeader(input);

            // *** VALIDATE *** \\
            Assert.NotNull(response);
            Assert.Equal(input.Message, response.Message);
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }