예제 #1
0
 public override void CloseConnection()
 {
     ((IClientChannel)proxy)?.Close();
     proxy = null;
     factory?.Close();
     factory = null;
 }
예제 #2
0
    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);
        }
    }
예제 #3
0
    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);
        }
    }
예제 #4
0
        /*----< processing for receive thread >------------------------*/

        /*
         * - send thread dequeues send message and posts to channel proxy
         * - thread inspects message and routes to appropriate specified endpoint
         */

        void ThreadProc()
        {
            while (true)
            {
                CommMessage msg = sndQ.DeQ();
                if (msg.Type == CommMessage.MessageType.CloseSender)
                {
                    break;
                }
                if (msg.To == lastUrl)
                {
                    try
                    {
                        channel.PostMessage(msg);
                        if (msg.AutoDisconnect)
                        {
                            factory?.Close();
                            lastUrl = "";
                        }
                    }
                    catch (Exception) { }
                }
                else
                {
                    Close();
                    if (!Connect(msg.To))
                    {
                        Console.WriteLine(msg + "... is lost...");
                        continue;
                    }
                    lastUrl = msg.To;
                    channel.PostMessage(msg);
                }
            }
        }
    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);
        }
    }
예제 #6
0
파일: TextTests.cs 프로젝트: weshaggard/wcf
    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);
        }
    }
예제 #7
0
    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);
        }
    }
예제 #8
0
    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);
        }
    }
예제 #9
0
    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);
        }
    }
예제 #10
0
    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);
        }
    }
예제 #11
0
    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);
        }
    }
예제 #12
0
    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 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);
        }
    }
예제 #14
0
    public static void NetTcp_TransportSecurity_StreamedRequest_RoundTrips_String()
    {
        string testString = "Hello";
        NetTcpBinding binding = null;
        ChannelFactory<IWcfService> factory = null;
        IWcfService serviceProxy = null;
        Stream stream = null;

        try
        {
            // *** SETUP *** \\
            binding = binding = new NetTcpBinding(SecurityMode.Transport);
            binding.TransferMode = TransferMode.StreamedRequest;
            factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Transport_Security_Streamed_Address));
            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);
        }
    }
예제 #15
0
    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);
        }
    }
예제 #16
0
    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);
        }
    }
예제 #17
0
    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));

            string DigestUsernameHeaderName = "DigestUsername";
            string DigestPasswordHeaderName = "DigestPassword";
            string DigestRealmHeaderName = "DigestRealm";
            string username = Guid.NewGuid().ToString("n").Substring(0, 8);
            string password = Guid.NewGuid().ToString("n").Substring(0, 16);
            string realm = Guid.NewGuid().ToString("n").Substring(0, 5);
            factory.Credentials.HttpDigest.ClientCredential = new NetworkCredential(username, password, realm);

            serviceProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            string result = null;
            using (var scope = new OperationContextScope((IContextChannel)serviceProxy))
            {
                HttpRequestMessageProperty requestMessageProperty;
                if (!OperationContext.Current.OutgoingMessageProperties.ContainsKey(HttpRequestMessageProperty.Name))
                {
                    requestMessageProperty = new HttpRequestMessageProperty();
                    OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestMessageProperty;
                }
                else
                {
                    requestMessageProperty = (HttpRequestMessageProperty)OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name];
                }

                requestMessageProperty.Headers[DigestUsernameHeaderName] = username;
                requestMessageProperty.Headers[DigestPasswordHeaderName] = password;
                requestMessageProperty.Headers[DigestRealmHeaderName] = realm;

                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);
        }
    }
예제 #18
0
    public static void WebSocket_Http_RequestReply_BinaryStreamed()
    {
        NetHttpBinding binding = null;
        ChannelFactory<IWSRequestReplyService> channelFactory = null;
        IWSRequestReplyService client = null;
        FlowControlledStream uploadStream = null;

        try
        {
            // *** SETUP *** \\
            binding = new NetHttpBinding()
            {
                MaxReceivedMessageSize = ScenarioTestHelpers.SixtyFourMB,
                MaxBufferSize = ScenarioTestHelpers.SixtyFourMB,
            };
            binding.WebSocketSettings.TransportUsage = WebSocketTransportUsage.Always;
            binding.TransferMode = TransferMode.Streamed;
            binding.MessageEncoding = NetHttpMessageEncoding.Binary;

            channelFactory = new ChannelFactory<IWSRequestReplyService>(binding, new EndpointAddress(Endpoints.WebSocketHttpRequestReplyBinaryStreamed_Address));
            client = channelFactory.CreateChannel();

            // *** EXECUTE *** \\
            using (Stream stream = client.DownloadStream())
            {
                int readResult;
                // Read from the stream, 1000 bytes at a time.
                byte[] buffer = new byte[1000];

                do
                {
                    readResult = stream.Read(buffer, 0, buffer.Length);
                }
                while (readResult != 0);
            }

            uploadStream = new FlowControlledStream();
            uploadStream.ReadThrottle = TimeSpan.FromMilliseconds(500);
            uploadStream.StreamDuration = TimeSpan.FromSeconds(1);
            client.UploadStream(uploadStream);

            // *** VALIDATE *** \\
            foreach (string serverLogItem in client.GetLog())
            {
                //Assert.True(serverLogItem != ScenarioTestHelpers.RemoteEndpointMessagePropertyFailure, ScenarioTestHelpers.RemoteEndpointMessagePropertyFailure);
                Assert.True(!ScenarioTestHelpers.IsLocalHost() || !serverLogItem.Contains(ScenarioTestHelpers.RemoteEndpointMessagePropertyFailure), serverLogItem);
            }

            // *** CLEANUP *** \\
            ((ICommunicationObject)client).Close();
            channelFactory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)client, channelFactory);
        }
    }
예제 #19
0
    public static void CreateChannel_Of_IRequestChannel_Using_CustomBinding()
    {
        ChannelFactory<IRequestChannel> factory = null;
        ChannelFactory<IRequestChannel> factory2 = null;
        IRequestChannel channel = null;
        IRequestChannel channel2 = null;

        try
        {
            CustomBinding binding = new CustomBinding(new BindingElement[] {
                new TextMessageEncodingBindingElement(MessageVersion.Default, Encoding.UTF8),
                new HttpTransportBindingElement() });

            EndpointAddress endpointAddress = new EndpointAddress(BaseAddress.HttpBaseAddress);

            // Create the channel factory for the request-reply message exchange pattern.
            factory = new ChannelFactory<IRequestChannel>(binding, endpointAddress);
            factory2 = new ChannelFactory<IRequestChannel>(binding, endpointAddress);

            // Create the channel.
            channel = factory.CreateChannel();
            Assert.True(typeof(IRequestChannel).GetTypeInfo().IsAssignableFrom(channel.GetType().GetTypeInfo()),
                String.Format("Channel type '{0}' was not assignable to '{1}'", channel.GetType(), typeof(IRequestChannel)));

            channel2 = factory2.CreateChannel();
            Assert.True(typeof(IRequestChannel).GetTypeInfo().IsAssignableFrom(channel2.GetType().GetTypeInfo()),
                String.Format("Channel type '{0}' was not assignable to '{1}'", channel2.GetType(), typeof(IRequestChannel)));

            // Validate ToString()
            string toStringResult = channel.ToString();
            string toStringExpected = "System.ServiceModel.Channels.IRequestChannel";
            Assert.Equal<string>(toStringExpected, toStringResult);

            // Validate Equals()
            Assert.StrictEqual<IRequestChannel>(channel, channel);

            // Validate Equals(other channel) negative
            Assert.NotStrictEqual<IRequestChannel>(channel, channel2);

            // Validate Equals("other") negative
            Assert.NotStrictEqual<object>(channel, "other");

            // Validate Equals(null) negative
            Assert.NotStrictEqual<IRequestChannel>(channel, null);
        }
        finally
        {
            if (factory != null)
            {
                factory.Close();
            }
            if (factory2 != null)
            {
                factory2.Close();
            }
        }
    }
예제 #20
0
    public static void TcpClientCredentialType_Certificate_EchoString()
    {
#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 clientCertThumb = null;
        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.Certificate;

            endpointAddress = new EndpointAddress(new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_Address),
                new DnsEndpointIdentity(Endpoints.Tcp_VerifyDNS_HostName));
            clientCertThumb = ServiceUtilHelper.ClientCertificate.Thumbprint;

            factory = new ChannelFactory<IWcfService>(binding, endpointAddress);
            factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
            factory.Credentials.ClientCertificate.SetCertificate(
                StoreLocation.CurrentUser,
                StoreName.My,
                X509FindType.FindByThumbprint,
                clientCertThumb);

            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);
        }
    }
예제 #21
0
 private void OnClosed(object sender, EventArgs eventArgs)
 {
     if (_factory?.State == CommunicationState.Faulted)
     {
         _factory?.Abort();
     }
     else
     {
         _factory?.Close();
     }
 }
예제 #22
0
    public static void NetTcp_TransportSecurity_StreamedRequest_RoundTrips_String()
    {
#if FULLXUNIT_NOTSUPPORTED
        bool root_Certificate_Installed = Root_Certificate_Installed();
        bool client_Certificate_Installed = Client_Certificate_Installed();
        bool windows_Authentication_Available = Windows_Authentication_Available();
        bool ambient_Credentials_Available = Ambient_Credentials_Available();

        if (!root_Certificate_Installed || 
            !client_Certificate_Installed || 
            !windows_Authentication_Available ||
            !ambient_Credentials_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("Windows_Authentication_Available evaluated as {0}", windows_Authentication_Available);
            Console.WriteLine("Ambient_Credentials_Available evaluated as {0}", ambient_Credentials_Available);
            return;
        }
#endif
        string testString = "Hello";
        NetTcpBinding binding = null;
        ChannelFactory<IWcfService> factory = null;
        IWcfService serviceProxy = null;
        Stream stream = null;

        try
        {
            // *** SETUP *** \\
            binding = binding = new NetTcpBinding(SecurityMode.Transport);
            binding.TransferMode = TransferMode.StreamedRequest;
            factory = new ChannelFactory<IWcfService>(binding, new EndpointAddress(Endpoints.Tcp_Transport_Security_Streamed_Address));
            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);
        }
    }
예제 #23
0
    public static void Message_With_MessageHeaders_RoundTrips()
    {
        BasicHttpBinding binding = null;
        IWcfService_4_4_0 clientProxy = null;
        RequestBankingData_4_4_0 requestData = 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();

            requestData = new RequestBankingData_4_4_0();
            requestData.accountName = "Michael Jordan";
            requestData.transactionDate = DateTime.Now;
            requestData.amount = 100.0M;

            // post-1.1.0 features
            requestData.requestSingleValue = "test single value";
            requestData.requestMultipleValues = "test,multiple,value".Split(',');
            requestData.requestArrayMultipleValues = "test,array,multiple,value".Split(',');

            // *** EXECUTE *** \\
            ReplyBankingData_4_4_0 replyData = clientProxy.MessageContractRequestReply(requestData);

            // *** VALIDATE *** \\
            Assert.True(String.Equals(requestData.accountName, replyData.accountName),
                        String.Format("Expected Customer = '{0}', actual = '{1}'",
                                      requestData.accountName, replyData.accountName));

            Assert.True(requestData.amount == replyData.amount,
                        String.Format("Expected Amount = '{0}', actual = '{1}'",
                                      requestData.amount, requestData.amount));

            Assert.True(String.Equals(requestData.requestSingleValue, replyData.replySingleValue),
                        String.Format("Expected RequestSingleValue = '{0}', actual = '{1}",
                                      requestData.requestSingleValue, replyData.replySingleValue));

            ValidateArray("MultipleValue", requestData.requestMultipleValues, replyData.replyMultipleValues);
            ValidateArray("ArrayMultipleValue", requestData.requestArrayMultipleValues, replyData.replyArrayMultipleValues);

            // *** CLEANUP *** \\
            factory.Close();
            ((ICommunicationObject)clientProxy).Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)clientProxy, factory);
        }
    }
예제 #24
0
    public static void ServiceContract_TypedProxy_AsyncBeginEnd_Call()
    {
        // This test verifies a typed proxy can call a service operation asynchronously using Begin/End
        StringBuilder errorBuilder = new StringBuilder();

        try
        {
            CustomBinding customBinding = new CustomBinding();
            customBinding.Elements.Add(new TextMessageEncodingBindingElement());
            customBinding.Elements.Add(new HttpTransportBindingElement());

            ChannelFactory<IWcfServiceBeginEndGenerated> factory = new ChannelFactory<IWcfServiceBeginEndGenerated>(customBinding, new EndpointAddress(BaseAddress.HttpBaseAddress));
            IWcfServiceBeginEndGenerated serviceProxy = factory.CreateChannel();
            string result = null;
            ManualResetEvent waitEvent = new ManualResetEvent(false);

            // The callback is optional with this Begin call, but we want to test that it works.
            // This delegate should execute when the call has completed, and that is how it gets the result of the call.
            AsyncCallback callback = (iar) =>
            {
                result = serviceProxy.EndEcho(iar);
                waitEvent.Set();
            };

            IAsyncResult ar = serviceProxy.BeginEcho("Hello", callback, null);

            // This test requires the callback to be called.
            // An actual timeout should call the callback, but we still set
            // a maximum wait time in case that does not happen.
            bool success = waitEvent.WaitOne(TestHelpers.TestTimeout);
            if (!success)
            {
                errorBuilder.AppendLine("AsyncCallback was not called.");
            }

            if (!string.Equals(result, "Hello"))
            {
                errorBuilder.AppendLine(String.Format("Expected response from Service: {0} Actual was: {1}", "Hello", result));
            }

            factory.Close();
        }
        catch (Exception ex)
        {
            errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString()));
        }

        Assert.True(errorBuilder.Length == 0, string.Format("Test Scenario: TypedProxy_AsyncBeginEnd_Call FAILED with the following errors: {0}", errorBuilder));
    }
예제 #25
0
    public void Dispose()
    {
        if (Service is ICommunicationObject communicationObject)
        {
            if (communicationObject.State == CommunicationState.Faulted)
            {
                communicationObject.Abort();
            }
            else
            {
                communicationObject.Close();
            }
        }

        _channelFactory?.Close();
    }
예제 #26
0
    public static void DefaultSettings_Tcp_Binary_Echo_RoundTrips_String()
    {
#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";
        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);
        }
    }
예제 #27
0
	static void Main(string[] args)
	{
		NetNamedPipeBinding binding = new NetNamedPipeBinding(NetNamedPipeSecurityMode.None);
		EndpointAddress address = new EndpointAddress("net.pipe://localhost/test");
		using (ChannelFactory<IDownloadManager> factory = new ChannelFactory<IDownloadManager>(binding, address))
		{
		    IDownloadManager dm = factory.CreateChannel();

		    if (dm != null)
		    {
		        string msg = dm.CopyFile("test file");
		        Console.WriteLine(msg);
		    }

		    factory.Close();
		}
	}
예제 #28
0
    public static void TcpClientCredentialType_Certificate_EchoString()
    {
        string clientCertThumb = null;
        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.Certificate;

            endpointAddress = new EndpointAddress(new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_Address),
                new DnsEndpointIdentity(Endpoints.Tcp_VerifyDNS_HostName));
            clientCertThumb = ServiceUtilHelper.ClientCertificate.Thumbprint;

            factory = new ChannelFactory<IWcfService>(binding, endpointAddress);
            factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
            factory.Credentials.ClientCertificate.SetCertificate(
                StoreLocation.CurrentUser,
                StoreName.My,
                X509FindType.FindByThumbprint,
                clientCertThumb);

            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);
        }
    }
예제 #29
0
    public static void DefaultCtor_NetHttps_Echo_RoundTrips_String()
    {
#if FULLXUNIT_NOTSUPPORTED
        bool root_Certificate_Installed = Root_Certificate_Installed();
        bool ssl_Available = SSL_Available();

        if (!root_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("SSL_Available evaluated as {0}", ssl_Available);
            return;
        }
#endif
        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);
        }
    }
예제 #30
0
    public static void CustomBinding_DefaultSettings_Echo_RoundTrips_DataContract()
    {
        // Verifies a typed proxy can call a service operation echoing a DataContract object synchronously
        CustomBinding customBinding = null;
        ChannelFactory<IWcfService> factory = null;
        IWcfService serviceProxy = null;
        EndpointAddress endpointAddress = null;
        CompositeType request = null;
        CompositeType response = null;

        try
        {
            // *** SETUP *** \\
            customBinding = new CustomBinding();
            customBinding.Elements.Add(new TextMessageEncodingBindingElement());
            customBinding.Elements.Add(new HttpTransportBindingElement());

            // Note the service interface used.  It was manually generated with svcutil.
            endpointAddress = new EndpointAddress(Endpoints.DefaultCustomHttp_Address);
            factory = new ChannelFactory<IWcfService>(customBinding, endpointAddress);
            serviceProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            request = new CompositeType() { StringValue = "myString", BoolValue = true };
            response = serviceProxy.GetDataUsingDataContract(request);

            // *** VALIDATE *** \\
            Assert.True(response != null, "GetDataUsingDataContract(request) returned null");
            string expectedStringValue = request.StringValue + "Suffix";
            Assert.True(String.Equals(response.StringValue, expectedStringValue), String.Format("Expected CompositeType.StringValue \"{0}\", actual was \"{1}\"",
                                                        expectedStringValue, response.StringValue));
            Assert.True(response.BoolValue == request.BoolValue, String.Format("Expected CompositeType.BoolValue \"{0}\", actual was \"{1}\"",
                                                        request.BoolValue, response.BoolValue));
            // *** CLEANUP *** \\
            factory.Close();
            ((ICommunicationObject)serviceProxy).Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
예제 #31
0
    public static void ServiceContract_TypedProxy_AsyncEndOperation_IntOutArg()
    {
        string message = "Hello";
        BasicHttpBinding binding = null;
        ChannelFactory<IServiceContractIntOutService> factory = null;
        IServiceContractIntOutService serviceProxy = null;
        int number = 0;

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

            ManualResetEvent waitEvent = new ManualResetEvent(false);

            // *** EXECUTE *** \\
            // This delegate will execute when the call has completed, which is how we get the result of the call.
            AsyncCallback callback = (iar) =>
            {
                serviceProxy.EndRequest(out number, iar);
                waitEvent.Set();
            };

            IAsyncResult ar = serviceProxy.BeginRequest(message, callback, null);

            // *** VALIDATE *** \\
            Assert.True(waitEvent.WaitOne(ScenarioTestHelpers.TestTimeout), "AsyncCallback was not called.");
            Assert.True((number == message.Count<char>()), String.Format("The local int variable was not correctly set, expected {0} but got {1}", message.Count<char>(), number));

            // *** CLEANUP *** \\
            ((ICommunicationObject)serviceProxy).Close();
            factory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
예제 #32
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);
        }
    }
예제 #33
0
    public static void CustomBinding_DefaultSettings_Echo_RoundTrips_DataContract()
    {
        // Verifies a typed proxy can call a service operation echoing a DataContract object synchronously
        StringBuilder errorBuilder = new StringBuilder();
        try
        {
            CustomBinding customBinding = new CustomBinding();
            customBinding.Elements.Add(new TextMessageEncodingBindingElement());
            customBinding.Elements.Add(new HttpTransportBindingElement());

            // Note the service interface used.  It was manually generated with svcutil.
            ChannelFactory<IWcfService> factory = new ChannelFactory<IWcfService>(customBinding, new EndpointAddress(Endpoints.DefaultCustomHttp_Address));
            IWcfService serviceProxy = factory.CreateChannel();

            CompositeType request = new CompositeType() { StringValue = "myString", BoolValue = true };
            CompositeType response = serviceProxy.GetDataUsingDataContract(request);

            Assert.True(response != null, "GetDataUsingDataContract(request) returned null");

            string expectedStringValue = request.StringValue + "Suffix";
            if (!string.Equals(response.StringValue, expectedStringValue))
            {
                errorBuilder.AppendLine(string.Format("Expected CompositeType.StringValue \"{0}\", actual was \"{1}\"",
                                                        expectedStringValue, response.StringValue));
            }
            if (response.BoolValue != request.BoolValue)
            {
                errorBuilder.AppendLine(string.Format("Expected CompositeType.BoolValue \"{0}\", actual was \"{1}\"",
                                                        request.BoolValue, response.BoolValue));
            }

            factory.Close();
        }
        catch (Exception ex)
        {
            errorBuilder.AppendLine(String.Format("Unexpected exception was caught: {0}", ex.ToString()));
        }

        Assert.True(errorBuilder.Length == 0, errorBuilder.ToString());
    }
예제 #34
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);
    }
예제 #35
0
 public void Dispose() => _channelFactory.Close();
예제 #36
0
        private Stream CallWebMethod(
            Stream requestData,
            string serviceUrl,
            string action,
            string username,
            string password,
            Context ctx)
        {
            try
            {
                Stream responseData;
                var    binding = new BasicHttpBinding(BasicHttpSecurityMode.TransportCredentialOnly);
                binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
                binding.UseDefaultWebProxy = true;

                var epa = new EndpointAddress(new Uri(serviceUrl));

                ChannelFactory <genericContract> cf = null;
                genericContract channel;
                Message         request;
                Message         response;
                string          responseString;

                try
                {
                    cf = new ChannelFactory <genericContract>(binding, epa);
                    cf.Credentials.UserName.UserName = username;
                    cf.Credentials.UserName.Password = password;

                    cf.Open();
                    channel = cf.CreateChannel();
                    using (new OperationContextScope((IContextChannel)channel))
                    {
                        XmlReader r = new XmlTextReader(requestData);

                        request = Message.CreateMessage(MessageVersion.Soap11, action, r);

                        foreach (var header in _soapHeaders)
                        {
                            MessageHeader messageHeader = MessageHeader.CreateHeader(header.HeaderName, header.HeaderNameSpace, header.HeaderInstance);
                            OperationContext.Current.OutgoingMessageHeaders.Add(messageHeader);
                        }

                        response = channel.Invoke(request);

                        string responseStr = response.GetReaderAtBodyContents().ReadOuterXml();
                        ctx.LogXmlData("Response", responseStr);
                        responseData = StreamHelper.LoadMemoryStream(responseStr);
                    }
                    request.Close();
                    response.Close();
                    cf.Close();
                }
                catch (CommunicationException ce)
                {
                    ctx.LogException(ce);
                    if (cf != null)
                    {
                        cf.Abort();
                    }
                    throw;
                }
                catch (TimeoutException te)
                {
                    ctx.LogException(te);
                    if (cf != null)
                    {
                        cf.Abort();
                    }
                    throw;
                }
                catch (Exception e)
                {
                    ctx.LogException(e);
                    if (cf != null)
                    {
                        cf.Abort();
                    }
                    throw;
                }

                return(responseData);
            }
            catch (Exception ex)
            {
                ctx.LogException(ex);
                throw;
            }
        }
예제 #37
0
        private void Closer()
        {
            try
            {
                tokens.cancelAll();
            }
            catch (Exception ex1)
            {
                ex(System.Reflection.MethodBase.GetCurrentMethod().Name + " " + ex1.ToString());
            }

            this.Invoke((MethodInvoker) delegate()
            {
                toolStripDropDownButton1.Enabled = false;
                toolStripDropDownButton1.Visible = false;

                toolStrip1.Enabled = false;
                toolStrip1.Hide();
                panel1.Hide();
                richTextBox1.Dock = DockStyle.Fill;
            });

            Stopwatch watch = new Stopwatch();

            watch.Start();

            while (true)
            {
                bool done = true;
                foreach (Thread thr in threads)
                {
                    if (thr.IsAlive)
                    {
                        done = false;

                        if (watch.Elapsed.TotalSeconds > 5)
                        {
                            l("waiting for thread: " + thr.Name);
                        }
                    }
                }

                if (watch.Elapsed.TotalSeconds > 5)
                {
                    watch.Restart();
                }

                if (done)
                {
                    break;
                }
                else
                {
                    this.Invoke((MethodInvoker) delegate()
                    {
                        this.Refresh();
                    });
                }

                Thread.Sleep(500);
            }

            watch.Stop();

            try
            {
                channel.Close();
                channelFactory.Close();
            }
            catch { }

            foreach (KeyValuePair <string, ChromeDriver> kvp in cdrivers)
            {
                try
                {
                    this.Invoke((MethodInvoker) delegate()
                    {
                        try
                        {
                            kvp.Value.Quit();
                        }
                        catch { }
                    });
                }
                catch { }
            }

            g("Ready to exit");

            this.Invoke((MethodInvoker) delegate()
            {
                this.ControlBox = true;
            });
        }
    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);
        }
    }
예제 #39
0
    public static void ClientCertificate_EchoString()
    {
#if FULLXUNIT_NOTSUPPORTED
        bool root_Certificate_Installed   = Root_Certificate_Installed();
        bool client_Certificate_Installed = Client_Certificate_Installed();
        bool server_Accepts_Certificates  = Server_Accepts_Certificates();
        bool ssl_Available = SSL_Available();

        if (!root_Certificate_Installed ||
            !client_Certificate_Installed ||
            !server_Accepts_Certificates ||
            !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("Server_Accepts_Certificates evaluated as {0}", server_Accepts_Certificates);
            Console.WriteLine("SSL_Available evaluated as {0}", ssl_Available);
            return;
        }
#endif
        string          clientCertThumb      = null;
        EndpointAddress endpointAddress      = null;
        string          testString           = "Hello";
        ChannelFactory <IWcfService> factory = null;
        IWcfService serviceProxy             = null;

        try
        {
            // *** SETUP *** \\
            BasicHttpsBinding basicHttpsBinding = new BasicHttpsBinding(BasicHttpsSecurityMode.Transport);
            basicHttpsBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Certificate;

            endpointAddress = new EndpointAddress(new Uri(Endpoints.Https_ClientCertificateAuth_Address));
            clientCertThumb = ServiceUtilHelper.ClientCertificate.Thumbprint;

            factory = new ChannelFactory <IWcfService>(basicHttpsBinding, endpointAddress);
            factory.Credentials.ClientCertificate.SetCertificate(
                StoreLocation.CurrentUser,
                StoreName.My,
                X509FindType.FindByThumbprint,
                clientCertThumb);

            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);
        }
    }
예제 #40
0
 /// <summary>
 /// Close the instance for OpeningStock Factory
 /// </summary>
 public void OpeningStockServiceInstanceClosed()
 {
     _channelFactoryOpeningStock.Close();
 }
예제 #41
0
    public static void BasicHttp_Close_ChannelFactory_Operations_Active()
    {
        // Test creates 2 channels from a single channel factory and
        // closes the channel factory while both channels are executing
        // operations.  This verifies the operations are cancelled and
        // the channel factory is in the correct state.
        BasicHttpBinding             binding        = null;
        TimeSpan                     delayOperation = TimeSpan.FromSeconds(3);
        ChannelFactory <IWcfService> factory        = null;
        IWcfService                  serviceProxy1  = null;
        IWcfService                  serviceProxy2  = null;
        string expectedEcho1 = "first";
        string expectedEcho2 = "second";

        try
        {
            // *** SETUP *** \\
            binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
            binding.CloseTimeout = ScenarioTestHelpers.TestTimeout;
            binding.SendTimeout  = ScenarioTestHelpers.TestTimeout;
            factory       = new ChannelFactory <IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic_Text));
            serviceProxy1 = factory.CreateChannel();
            serviceProxy2 = factory.CreateChannel();

            // *** EXECUTE *** \\
            Task <string> t1 = serviceProxy1.EchoWithTimeoutAsync(expectedEcho1, delayOperation);
            Task <string> t2 = serviceProxy2.EchoWithTimeoutAsync(expectedEcho2, delayOperation);
            factory.Close();

            // *** VALIDATE *** \\
            Assert.True(factory.State == CommunicationState.Closed,
                        String.Format("Expected factory state 'Closed', actual was '{0}'", factory.State));

            Exception exception1  = null;
            Exception exception2  = null;
            string    actualEcho1 = null;
            string    actualEcho2 = null;

            // Verification is slightly more complex for the close with active operations because
            // we don't know which might have completed first and whether the channel factory
            // was able to close and dispose either channel before it completed.  So we just
            // ensure the Tasks complete with an exception or a successful return and have
            // been closed by the factory.
            try
            {
                actualEcho1 = t1.GetAwaiter().GetResult();
            }
            catch (Exception e)
            {
                exception1 = e;
            }

            try
            {
                actualEcho2 = t2.GetAwaiter().GetResult();
            }
            catch (Exception e)
            {
                exception2 = e;
            }

            Assert.True(exception1 != null || actualEcho1 != null, "First operation should have thrown Exception or returned an echo");
            Assert.True(exception2 != null || actualEcho2 != null, "Second operation should have thrown Exception or returned an echo");

            Assert.True(actualEcho1 == null || String.Equals(expectedEcho1, actualEcho1),
                        String.Format("First operation returned '{0}' but expected '{1}'.", expectedEcho1, actualEcho1));

            Assert.True(actualEcho2 == null || String.Equals(expectedEcho2, actualEcho2),
                        String.Format("Second operation returned '{0}' but expected '{1}'.", expectedEcho2, actualEcho2));

            Assert.True(((ICommunicationObject)serviceProxy1).State == CommunicationState.Closed,
                        String.Format("Expected channel 1 state 'Closed', actual was '{0}'", ((ICommunicationObject)serviceProxy1).State));
            Assert.True(((ICommunicationObject)serviceProxy2).State == CommunicationState.Closed,
                        String.Format("Expected channel 2 state 'Closed', actual was '{0}'", ((ICommunicationObject)serviceProxy2).State));

            // *** CLEANUP *** \\
            ((ICommunicationObject)serviceProxy1).Abort();
            ((ICommunicationObject)serviceProxy2).Abort();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy1,
                                                          (ICommunicationObject)serviceProxy2,
                                                          factory);
        }
    }
예제 #42
0
    public static void BasicHttp_Streamed_Async_Delayed_And_Aborted_Request_Throws_TimeoutException()
    {
        // This test is a regression test that verifies an issue discovered where exceeding the timeout
        // and aborting the channel before the client's Task completed led to incorrect error handling.
        BasicHttpBinding             binding = null;
        ChannelFactory <IWcfService> factory = null;
        IWcfService serviceProxy             = null;
        Stream      stream        = null;
        int         sendTimeoutMs = 3000;

        try
        {
            // *** SETUP *** \\
            binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
            binding.TransferMode = TransferMode.Streamed;
            binding.SendTimeout  = TimeSpan.FromMilliseconds(sendTimeoutMs);
            factory      = new ChannelFactory <IWcfService>(binding, new EndpointAddress(Endpoints.HttpBaseAddress_Basic_Text));
            serviceProxy = factory.CreateChannel();

            // Create a read stream that will both timeout and then abort the proxy channel when the
            // async read is called. We also intercept the synchronous read because that path can also
            // be executed during an async read.
            stream = new TestMockStream()
            {
                CopyToAsyncFunc = (Stream destination, int bufferSize, CancellationToken ct) =>
                {
                    // Abort to force the internal HttpClientChannelAsyncRequest.Cleanup()
                    // to clear its data structures before the client's Task completes.
                    Task.Delay(sendTimeoutMs * 2).Wait();
                    ((ICommunicationObject)serviceProxy).Abort();
                    return(null);
                },

                ReadFunc = (byte[] buffer, int offset, int count) =>
                {
                    // Abort to force the internal HttpClientChannelAsyncRequest.Cleanup()
                    // to clear its data structures before the client's Task completes.
                    Task.Delay(sendTimeoutMs * 2).Wait();
                    ((ICommunicationObject)serviceProxy).Abort();
                    return(-1);
                }
            };

            // *** EXECUTE *** \\
            Assert.Throws <TimeoutException>(() =>
            {
                var unused = serviceProxy.EchoStreamAsync(stream).GetAwaiter().GetResult();
            });

            // *** VALIDATE *** \\

            // *** CLEANUP *** \\
            ((ICommunicationObject)serviceProxy).Close();
            factory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
예제 #43
0
 /// <summary>
 /// Close the instance for Category Factory
 /// </summary>
 public void CategoryServiceInstanceClosed()
 {
     _channelFactoryCategory.Close();
 }
 public static void MyClassCleanup()
 {
     // Close Proxy connection
     proxy.Close();
 }
 public static void Close()
 {
     factory?.Close();
 }
        public AutotaskAPIClient(string Username, string Password, AutotaskIntegrationKey IntegrationKey)
        {
            if (string.IsNullOrWhiteSpace(Username))
            {
                throw new ArgumentNullException("Username cannot by empty");
            }

            if (string.IsNullOrWhiteSpace(Password))
            {
                throw new ArgumentNullException("Password cannot by empty");
            }

            string _integrationKey = IntegrationKey.GetIntegrationKey();

            if (string.IsNullOrWhiteSpace(_integrationKey))
            {
                throw new ArgumentNullException("IntegrationKey cannot by empty");
            }

            _atwsUsername       = Username;
            _atwsPassword       = Password;
            _atwsIntegrationKey = _integrationKey;
            _atwsIntegrations.IntegrationCode = _integrationKey;
            NetworkCredential _credential = new NetworkCredential(_atwsUsername, _atwsPassword);

            try
            {
                _atwsHttpBinding = new BasicHttpBinding(BasicHttpSecurityMode.Transport)
                {
                    MaxBufferSize          = int.MaxValue,
                    MaxReceivedMessageSize = int.MaxValue
                };
                _atwsHttpBinding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
                _atwsChannelFactory = new ChannelFactory <ATWSSoapChannel>(_atwsHttpBinding, new EndpointAddress(new Uri("https://webservices.autotask.net/ATServices/1.6/atws.asmx")));
                _atwsChannelFactory.Credentials.UserName.UserName = _atwsUsername;
                _atwsChannelFactory.Credentials.UserName.Password = _atwsPassword;
                _atwsServicesClient = _atwsChannelFactory.CreateChannel();
                _atwsServicesClient.Open();
                _atwsZoneInfo = _atwsServicesClient.getZoneInfo(_atwsUsername);
                if (_atwsZoneInfo.ErrorCode >= 0)
                {
                    _atwsServicesClient.Close();
                    _atwsChannelFactory.Close();
                    _atwsChannelFactory = new ChannelFactory <ATWSSoapChannel>(_atwsHttpBinding, new EndpointAddress(new Uri(_atwsZoneInfo.URL)));
                    _atwsChannelFactory.Credentials.UserName.UserName = _atwsUsername;
                    _atwsChannelFactory.Credentials.UserName.Password = _atwsPassword;
                    _atwsServicesClient = _atwsChannelFactory.CreateChannel();
                    _atwsServicesClient.Open();
                    if (!Preload())
                    {
                        throw new Exception("Error with data Preload()");
                    }
                }
                else
                {
                    throw new Exception("Error with getZoneInfo()");
                }
            }
            catch
            {
                throw new ArgumentException("Username must be invalid, unable to get ZoneInfo");
            }
        }
예제 #47
0
    public static void CustomTextMessageEncoder_Http_RequestReply_Streamed()
    {
        // 84K, larger than any buffers, but won't allocate in LOH
        int streamKBytes    = 84;
        int streamLength    = 1024 * streamKBytes;
        int lowestPrintable = ' ';
        int printableRange  = '~' - lowestPrintable;
        ChannelFactory <IWcfService> factory = null;
        IWcfService serviceProxy             = null;
        Stream      stream = null;

        try
        {
            // *** SETUP *** \\
            CustomBinding binding = new CustomBinding(new CustomTextMessageBindingElement(Encoding.UTF8.WebName),
                                                      new HttpTransportBindingElement
            {
                MaxReceivedMessageSize = ScenarioTestHelpers.SixtyFourMB,
                MaxBufferSize          = ScenarioTestHelpers.SixtyFourMB,
                TransferMode           = TransferMode.Streamed
            });

            factory      = new ChannelFactory <IWcfService>(binding, new EndpointAddress(Endpoints.CustomTextEncoderStreamed_Address));
            serviceProxy = factory.CreateChannel();
            byte[] requestBytes       = new byte[streamLength];
            RandomNumberGenerator rnd = RandomNumberGenerator.Create();
            int pos = 0;
            for (int i = 0; i < streamKBytes; i++)
            {
                byte[] tempBuffer = new byte[1024];
                rnd.GetBytes(tempBuffer);
                for (int j = 0; j < 1024; j++)
                {
                    byte val = tempBuffer[j];
                    if (val < ' ' || val > '~')
                    {
                        // Force the value to be between ' ' and '~'
                        int temp1 = val % printableRange;
                        val = (byte)(temp1 + lowestPrintable);
                    }

                    requestBytes[pos++] = val;
                }
            }
            stream = new MemoryStream(requestBytes);

            // *** EXECUTE *** \\
            var returnStream = serviceProxy.EchoStream(stream);

            // *** VALIDATE *** \\
            MemoryStream ms = new MemoryStream(streamLength);
            returnStream.CopyTo(ms);

            Assert.True(streamLength == ms.Length,
                        String.Format("Expected returned stream length = {0}, actual = {1}",
                                      streamLength, ms.Length));

            ArraySegment <byte> returnedByteArraySegment;
            ms.TryGetBuffer(out returnedByteArraySegment);
            Assert.True(requestBytes.SequenceEqual(returnedByteArraySegment.Array), "Returned bytes are different than sent bytes");

            // *** CLEANUP *** \\
            ((ICommunicationObject)serviceProxy).Close();
            factory.Close();
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
예제 #48
0
 protected void Close()
 {
     _channelFactory.Close();
     _userService = null;
 }
예제 #49
0
 protected override void OnClose(TimeSpan timeout)
 {
     _innerChannelFactory.Close(timeout);
 }
예제 #50
0
        public async Task Run(string connectionString)
        {
            var sbb = new ServiceBusConnectionStringBuilder(connectionString);

            try
            {
                // Create sender to Sequence Service
                using (var sendChannelFactory = new ChannelFactory <ISequenceServiceChannel>("sequenceSendClient"))
                {
                    sendChannelFactory.Endpoint.Address = new EndpointAddress(
                        new Uri(sbb.GetAbsoluteRuntimeEndpoints()[0], SessionQueueName));
                    sendChannelFactory.Endpoint.EndpointBehaviors.Add(
                        new TransportClientEndpointBehavior(TokenProvider.CreateSharedAccessSignatureTokenProvider(sbb.SharedAccessKeyName, sbb.SharedAccessKey)));

                    using (var clientChannel = sendChannelFactory.CreateChannel())
                    {
                        for (int j = 0; j < 3; j++)
                        {
                            var contextId = Guid.NewGuid().ToString();


                            // Send messages
                            var sequenceLength = new Random().Next(5, 10);
                            for (var i = 0; i < sequenceLength; i++)
                            {
                                // Generating a random sequence item
                                var sequenceItem = new SequenceItem(
                                    string.Format("{0:00000}", new Random().Next(0, 10000)),
                                    new Random().Next(1, 100));

                                // set the operation context for the subsequent call, this MUST be a new context
                                OperationContext.Current = new OperationContext(clientChannel)
                                {
                                    OutgoingMessageProperties = { { BrokeredMessageProperty.Name, new BrokeredMessageProperty {
                                                                        SessionId = contextId, TimeToLive = TimeSpan.FromMinutes(5)
                                                                    } } }
                                };
                                // Correlating ServiceBus SessionId to ContextId
                                await clientChannel.SubmitSequenceItemAsync(sequenceItem);

                                Console.WriteLine("Sequence: {0} [{1}] - ContextId {2}.", sequenceItem.ItemId, sequenceItem.Quantity, contextId);
                            }

                            // set the operation context for the subsequent call, this MUST be a new context
                            OperationContext.Current = new OperationContext(clientChannel)
                            {
                                OutgoingMessageProperties = { { BrokeredMessageProperty.Name, new BrokeredMessageProperty {
                                                                    SessionId = contextId, TimeToLive = TimeSpan.FromMinutes(5)
                                                                } } }
                            };
                            await clientChannel.TerminateSequenceAsync();
                        }
                        clientChannel.Close();
                    }
                    // Close sender
                    sendChannelFactory.Close();
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine("Exception occurred: {0}", exception);
            }
        }
예제 #51
0
        public override void RunJob()
        {
            //prepare new jobs
            base.MakeNextJobReady();



            var nextJob = this.azureStorage.GetNextJob();

            if (nextJob == null)
            {
                return;
            }

            //update host information
            hosts = this.azureStorage.GetHosts();

            if (!hosts.All(x => x.ReadyJobs.Split(',').Contains(nextJob.RowKey)))
            {
                azureStorage.WriteLog("Job " + nextJob.RowKey + " not ready on all nodes");
                return;
            }

            //run the job!
            var executable = Path.Combine(GetJobDirectory(nextJob.RowKey), nextJob.Executable);

            azureStorage.WriteLog("Starting " + nextJob.RowKey + " with exe =" + executable + ", params=" + nextJob.Parameters ?? "");

            string blobName = null;

            try
            {
                //connect to runner
                ChannelFactory <IMPIRunner> pipeFactory = new ChannelFactory <IMPIRunner>(
                    new NetNamedPipeBinding(),
                    new EndpointAddress("net.pipe://localhost/MPIRunner")
                    );

                //connect to the MPI Wrapper processs using Interface IMPIRunner
                IMPIRunner runner = pipeFactory.CreateChannel();

                //run the exe using the Wrapper
                switch (nextJob.JobType)
                {
                case (int)JobItem.Type.MPI:
                    runner.RunApplication(executable, nextJob.Parameters, hosts.Select(x => x.Address).ToArray(), nextJob.CorePerNode, nextJob.NumNodes);
                    break;

                case (int)JobItem.Type.Normal:
                    runner.RunApplication(executable, nextJob.Parameters);
                    break;
                }


                //Wait for the exe to terminate
                while (runner.GetState() == RunnerState.Running)
                {
                    azureStorage.WriteLog("Job " + nextJob.RowKey + " running...");

                    //var lastOutput = runner.GetCurrentStandardOutput();
                    //azureStorage.WriteLog(lastOutput);

                    Thread.Sleep(10000);
                }

                //retrieve results and upload to blob storage
                azureStorage.WriteLog("Uploading job results");
                blobName = nextJob.RowKey + "-" + DateTime.Now.ToString("HHMMss") + "-" + nextJob.InfoTag + "-" + nextJob.NumNodes + "n-" + nextJob.CorePerNode + "c-result.zip";
                azureStorage.UploadBlob(blobName, runner.GetResultFilePath());


                azureStorage.WriteLog("Job " + nextJob.RowKey + " finished");
                pipeFactory.Close();
            }
            catch (Exception ex)
            {
                azureStorage.WriteLog("Job " + nextJob.RowKey + " failed ");
                azureStorage.WriteLog(ex.ToString());
            }


            //set job to  finished
            this.azureStorage.SetJobState(nextJob.RowKey, true, blobName != null ? blobName.ToString() : string.Empty);
        }
예제 #52
0
    public static void CustomChannel_Sync_Open_Close_Methods_Called()
    {
        MockChannelFactory <IRequestChannel> mockChannelFactory = null;
        MockRequestChannel mockRequestChannel        = null;
        List <string>      channelOpenMethodsCalled  = new List <string>();
        List <string>      channelCloseMethodsCalled = new List <string>();
        List <string>      factoryOpenMethodsCalled  = new List <string>();
        List <string>      factoryCloseMethodsCalled = new List <string>();
        string             testMessageBody           = "CustomChannelTest_Sync";
        Message            inputMessage = Message.CreateMessage(MessageVersion.Default, action: "Test", body: testMessageBody);

        // *** SETUP *** \\
        // Intercept the creation of the factory so we can intercept creation of the channel
        Func <Type, BindingContext, IChannelFactory> buildFactoryAction = (Type type, BindingContext context) =>
        {
            // Create the channel factory and intercept all open and close method calls
            mockChannelFactory = new MockChannelFactory <IRequestChannel>(context, new TextMessageEncodingBindingElement().CreateMessageEncoderFactory());
            MockCommunicationObject.InterceptAllOpenMethods(mockChannelFactory, factoryOpenMethodsCalled);
            MockCommunicationObject.InterceptAllCloseMethods(mockChannelFactory, factoryCloseMethodsCalled);

            // Override the OnCreateChannel call so we get the mock channel created by the factory
            mockChannelFactory.OnCreateChannelOverride = (EndpointAddress endpoint, Uri via) =>
            {
                // Create the mock channel and intercept all its open and close method calls
                mockRequestChannel = (MockRequestChannel)mockChannelFactory.DefaultOnCreateChannel(endpoint, via);
                MockCommunicationObject.InterceptAllOpenMethods(mockRequestChannel, channelOpenMethodsCalled);
                MockCommunicationObject.InterceptAllCloseMethods(mockRequestChannel, channelCloseMethodsCalled);
                return(mockRequestChannel);
            };
            return(mockChannelFactory);
        };

        MockTransportBindingElement mockBindingElement = new MockTransportBindingElement();

        mockBindingElement.BuildChannelFactoryOverride = buildFactoryAction;

        CustomBinding   binding = new CustomBinding(mockBindingElement);
        EndpointAddress address = new EndpointAddress("myprotocol://localhost:5000");
        var             factory = new ChannelFactory <ICustomChannelServiceInterface>(binding, address);

        // We rely on the implicit open of the channel to be synchronous.
        // This is true for both the full framework and this NET Core version.
        ICustomChannelServiceInterface channel = factory.CreateChannel();

        // *** EXECUTE *** \\
        Message outputMessage = channel.Process(inputMessage);

        // The mock's default behavior is just to loopback what we sent.
        var result = outputMessage.GetBody <string>();

        // Explicitly close the channel factory synchronously.
        // One of the important aspects of this test is that a synchronous
        // close of the factory also synchronously closes the channel.
        factory.Close();

        // *** VALIDATE *** \\
        Assert.True(String.Equals(testMessageBody, result),
                    String.Format("Expected body to be '{0}' but actual was '{1}'", testMessageBody, result));

        string expectedOpens  = "OnOpening,OnOpen,OnOpened";
        string expectedCloses = "OnClosing,OnClose,OnClosed";

        string actualOpens = String.Join(",", channelOpenMethodsCalled);

        Assert.True(String.Equals(expectedOpens, actualOpens, StringComparison.Ordinal),
                    String.Format("Expected channel open methods to be '{0}' but actual was '{1}'.",
                                  expectedOpens, actualOpens));

        string actualCloses = String.Join(",", channelCloseMethodsCalled);

        Assert.True(String.Equals(expectedCloses, actualCloses, StringComparison.Ordinal),
                    String.Format("Expected channel close methods to be '{0}' but actual was '{1}'.",
                                  expectedCloses, actualCloses));

        actualOpens = String.Join(",", factoryOpenMethodsCalled);
        Assert.True(String.Equals(expectedOpens, actualOpens, StringComparison.Ordinal),
                    String.Format("Expected factory open methods to be '{0}' but actual was '{1}'.",
                                  expectedOpens, actualOpens));

        actualCloses = String.Join(",", factoryCloseMethodsCalled);
        Assert.True(String.Equals(expectedCloses, actualCloses, StringComparison.Ordinal),
                    String.Format("Expected factory close methods to be '{0}' but actual was '{1}'.",
                                  expectedCloses, actualCloses));

        Assert.True(factory.State == CommunicationState.Closed,
                    String.Format("Expected factory's final state to be Closed but was '{0}'", factory.State));

        Assert.True(((ICommunicationObject)channel).State == CommunicationState.Closed,
                    String.Format("Expected channel's final state to be Closed but was '{0}'", ((ICommunicationObject)channel).State));
    }
예제 #53
0
 /// <summary>
 /// Close the instance for Coupon Managment channel Factory
 /// </summary>
 public void CouponManegmentServiceInstanceClosed()
 {
     _channelFactoryCouponManagment.Close();
 }
    public static void Certificate_With_CanonicalName_Fqdn_Address_EchoString()
    {
        bool shouldCallSucceed     = false;
        var  domainNameEndpointUri = new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_With_CanonicalName_DomainName_Address);
        // Get just the hostname part of the domainName Uri
        var domainNameHost = domainNameEndpointUri.Host.Split('.')[0];

        var fqdnEndpointUri = new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_With_CanonicalName_Fqdn_Address);
        var endpointAddress = new EndpointAddress(fqdnEndpointUri);

        // If the WCF service's reported FQDN is the same as the services's reported hostname,
        // it means that there the WCF service is set up on a network where FQDNs aren't used, only hostnames.
        // Since our pass/fail detection logic on whether or not this is an FQDN depends on whether the host name has a '.', we don't test this case
        if (string.Compare(domainNameHost, fqdnEndpointUri.Host, StringComparison.OrdinalIgnoreCase) != 0)
        {
            shouldCallSucceed = fqdnEndpointUri.Host.IndexOf('.') > -1;
        }


        string testString = "Hello";
        ChannelFactory <IWcfService> factory = null;
        IWcfService serviceProxy             = null;

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

            factory = new ChannelFactory <IWcfService>(binding, endpointAddress);
            factory.Credentials.ServiceCertificate.Authentication.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();

            var errorBuilder = new StringBuilder();
            errorBuilder.AppendFormat("The call to '{0}' should have failed but succeeded. ", fqdnEndpointUri.Host);
            errorBuilder.AppendFormat("This means that the certificate validation passed when it should have failed. ");
            errorBuilder.AppendFormat("Check the certificate returned by the endpoint at '{0}' ", fqdnEndpointUri);
            errorBuilder.AppendFormat("to see that it is correct; if it is, there is likely an issue with the identity checking logic.");

            Assert.True(shouldCallSucceed, errorBuilder.ToString());
        }
        catch (MessageSecurityException exception)
        {
            // If there's a MessageSecurityException, we assume that the cert validation failed. Unfortunately checking for the
            // message is really brittle and we can't account for loc and how .NET Native will display the exceptions
            // The exception message should look like:
            //
            // System.ServiceModel.Security.MessageSecurityException : Identity check failed for outgoing message. The expected
            // DNS identity of the remote endpoint was 'localhost' but the remote endpoint provided DNS claim 'example.com'.If this
            // is a legitimate remote endpoint, you can fix the problem by explicitly specifying DNS identity 'example.com' as
            // the Identity property of EndpointAddress when creating channel proxy.

            var errorBuilder = new StringBuilder();
            errorBuilder.AppendFormat("The call to '{0}' should have been successful but failed with a MessageSecurityException. ", fqdnEndpointUri.Host);
            errorBuilder.AppendFormat("This usually means that the certificate validation failed when it should have passed. ");
            errorBuilder.AppendFormat("When connecting to host '{0}', the expectation is that the DNSClaim will be for the same hostname. ", fqdnEndpointUri.Host);
            errorBuilder.AppendFormat("Exception message: {0}{1}", Environment.NewLine, exception.Message);

            Assert.True(!shouldCallSucceed, errorBuilder.ToString());
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
예제 #55
0
 /// <summary>
 /// Close the instance for Company Factory
 /// </summary>
 public void CompanyServiceInstanceClosed()
 {
     _channelFactoryCompany.Close();
 }
    public static void Certificate_With_CanonicalName_Localhost_Address_EchoString()
    {
        var  localhostEndpointUri = new Uri(Endpoints.Tcp_ClientCredentialType_Certificate_With_CanonicalName_Localhost_Address);
        var  endpointAddress      = new EndpointAddress(localhostEndpointUri);
        bool shouldCallSucceed    = string.Compare(localhostEndpointUri.Host, "localhost", StringComparison.OrdinalIgnoreCase) == 0;

        string testString = "Hello";
        ChannelFactory <IWcfService> factory = null;
        IWcfService serviceProxy             = null;

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

            factory = new ChannelFactory <IWcfService>(binding, endpointAddress);
            factory.Credentials.ServiceCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.ChainTrust;

            serviceProxy = factory.CreateChannel();

            // *** EXECUTE *** \\
            string result = serviceProxy.Echo(testString);

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

            // *** CLEANUP *** \\
            ((ICommunicationObject)serviceProxy).Close();
            factory.Close();

            var errorBuilder = new StringBuilder();
            errorBuilder.AppendFormat("The call to '{0}' should have failed but succeeded. ", localhostEndpointUri.Host);
            errorBuilder.AppendFormat("This means that the certificate validation passed when it should have failed. ");
            errorBuilder.AppendFormat("Check the certificate returned by the endpoint at '{0}' ", localhostEndpointUri);
            errorBuilder.AppendFormat("to see that it is correct; if it is, there is likely an issue with the identity checking logic.");

            Assert.True(shouldCallSucceed, errorBuilder.ToString());
        }
        catch (Exception exception) when(exception is CommunicationException || exception is MessageSecurityException)
        {
            if ((exception is MessageSecurityException) || (exception is CommunicationException) && !string.Equals(exception.InnerException.GetType().ToString(), "System.ServiceModel.Security.MessageSecurityException"))
            {
                // If there's a MessageSecurityException, we assume that the cert validation failed. Unfortunately checking for the
                // message is really brittle and we can't account for loc and how .NET Native will display the exceptions
                // The exception message should look like:
                //
                // System.ServiceModel.Security.MessageSecurityException : Identity check failed for outgoing message. The expected
                // DNS identity of the remote endpoint was 'localhost' but the remote endpoint provided DNS claim 'example.com'.If this
                // is a legitimate remote endpoint, you can fix the problem by explicitly specifying DNS identity 'example.com' as
                // the Identity property of EndpointAddress when creating channel proxy.

                var errorBuilder = new StringBuilder();
                errorBuilder.AppendFormat("The call to '{0}' should have been successful but failed with a MessageSecurityException. ", localhostEndpointUri.Host);
                errorBuilder.AppendFormat("This usually means that the certificate validation failed when it should have passed. ");
                errorBuilder.AppendFormat("When connecting to host '{0}', the expectation is that the DNSClaim will be for the same hostname. ", localhostEndpointUri.Host);
                errorBuilder.AppendFormat("Exception message: {0}{1}", Environment.NewLine, exception.Message);

                Assert.True(!shouldCallSucceed, errorBuilder.ToString());
            }
        }
        finally
        {
            // *** ENSURE CLEANUP *** \\
            ScenarioTestHelpers.CloseCommunicationObjects((ICommunicationObject)serviceProxy, factory);
        }
    }
예제 #57
0
 /// <summary>
 /// Close the instance for OpeningStock Factory
 /// </summary>
 public void ProductServiceInstanceClosed()
 {
     _channelFactoryProduct.Close();
 }
예제 #58
0
        //----< closes the send channel >--------------------------------

        public void Close()
        {
            ChannelFactory <ICommunicator> temp = (ChannelFactory <ICommunicator>)channel;

            temp.Close();
        }
예제 #59
0
        static void Main()
        {
            // Create the custom binding and an endpoint address for the service.
            Binding         multipleTokensBinding        = BindingHelper.CreateMultiFactorAuthenticationBinding();
            EndpointAddress serviceAddress               = new EndpointAddress("http://localhost/servicemodelsamples/service.svc");
            ChannelFactory <IEchoService> channelFactory = null;
            IEchoService client = null;

            Console.WriteLine("Username authentication required.");
            Console.WriteLine("Provide a valid machine or domain account. [domain\\user]");
            Console.WriteLine("   Enter username:"******"   Enter password:"******"";
            ConsoleKeyInfo info     = Console.ReadKey(true);

            while (info.Key != ConsoleKey.Enter)
            {
                if (info.Key != ConsoleKey.Backspace)
                {
                    if (info.KeyChar != '\0')
                    {
                        password += info.KeyChar;
                    }
                    info = Console.ReadKey(true);
                }
                else if (info.Key == ConsoleKey.Backspace)
                {
                    if (password != "")
                    {
                        password = password.Substring(0, password.Length - 1);
                    }
                    info = Console.ReadKey(true);
                }
            }

            for (int i = 0; i < password.Length; i++)
            {
                Console.Write("*");
            }

            Console.WriteLine();

            try
            {
                // Create a proxy with the previously create binding and endpoint address
                channelFactory = new ChannelFactory <IEchoService>(multipleTokensBinding, serviceAddress);

                // configure the username credentials, the client certificate and the server certificate on the channel factory
                channelFactory.Credentials.UserName.UserName = username;
                channelFactory.Credentials.UserName.Password = password;

                channelFactory.Credentials.ClientCertificate.SetCertificate("CN=client.com", StoreLocation.CurrentUser, StoreName.My);
                channelFactory.Credentials.ServiceCertificate.SetDefaultCertificate("CN=localhost", StoreLocation.LocalMachine, StoreName.My);

                client = channelFactory.CreateChannel();

                Console.WriteLine("Echo service returned: {0}", client.Echo());

                ((IChannel)client).Close();
                channelFactory.Close();
            }
            catch (CommunicationException e)
            {
                Abort((IChannel)client, channelFactory);

                // if there is a fault then print it out
                FaultException fe  = null;
                Exception      tmp = e;
                while (tmp != null)
                {
                    fe = tmp as FaultException;
                    if (fe != null)
                    {
                        break;
                    }
                    tmp = tmp.InnerException;
                }
                if (fe != null)
                {
                    Console.WriteLine("The server sent back a fault: {0}", fe.CreateMessageFault().Reason.GetMatchingTranslation().Text);
                }
                else
                {
                    Console.WriteLine("The request failed with exception: {0}", e);
                }
            }
            catch (TimeoutException)
            {
                Abort((IChannel)client, channelFactory);
                Console.WriteLine("The request timed out");
            }
            catch (Exception e)
            {
                Abort((IChannel)client, channelFactory);
                Console.WriteLine("The request failed with unexpected exception: {0}", e);
            }

            Console.WriteLine();
            Console.WriteLine("Press <ENTER> to terminate client.");
            Console.ReadLine();
        }
    public 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);
            }
        });
    }