public async Task<RelayConnection> ConnectAsync()
        {
            var tb = new TransportClientEndpointBehavior(tokenProvider);
            var bindingElement = new TcpRelayTransportBindingElement(
                RelayClientAuthenticationType.RelayAccessToken)
            {
                TransferMode = TransferMode.Buffered,
                ConnectionMode = TcpRelayConnectionMode.Relayed,
                ManualAddressing = true
            };
            bindingElement.GetType()
                .GetProperty("TransportProtectionEnabled",
                    BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic)
                .SetValue(bindingElement, true);

            var rt = new CustomBinding(
                new BinaryMessageEncodingBindingElement(),
                bindingElement);

            var cf = rt.BuildChannelFactory<IDuplexSessionChannel>(tb);
            await Task.Factory.FromAsync(cf.BeginOpen, cf.EndOpen, null);
            var ch = cf.CreateChannel(new EndpointAddress(address));
            await Task.Factory.FromAsync(ch.BeginOpen, ch.EndOpen, null);
            return new RelayConnection(ch)
            {
                WriteTimeout = (int) rt.SendTimeout.TotalMilliseconds,
                ReadTimeout = (int) rt.ReceiveTimeout.TotalMilliseconds
            };
        }
Exemplo n.º 2
0
        public void ReceiveFactory()
        {
            Binding binding = new CustomBinding(new RedisMessageBindingElement(), new RedisReceiveTransportBinding());

            IChannelFactory<IRequestChannel> factory = binding.BuildChannelFactory<IRequestChannel>();
            Assert.IsInstanceOf<RedisReceiveFactory>(factory);
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            try
            {
                BindingElement[] bindingElements = new BindingElement[2];
                bindingElements[0] = new TextMessageEncodingBindingElement();
                bindingElements[1] = new HttpTransportBindingElement();

                CustomBinding binding = new CustomBinding(bindingElements);
                using (Message message = Message.CreateMessage(binding.MessageVersion, "sendMessage", "Message Body"))
                {
                    IChannelFactory<IRequestChannel> factory = binding.BuildChannelFactory<IRequestChannel>(new BindingParameterCollection());
                    factory.Open();

                    IRequestChannel requestChannel = factory.CreateChannel(new EndpointAddress("http://localhost:9090/RequestReplyService"));
                    requestChannel.Open();
                    Message response = requestChannel.Request(message);

                    Console.WriteLine("Successful send message!");

                    Console.WriteLine("Receive a return message, action: {0}, body: {1}", response.Headers.Action, response.GetBody<String>());
                    requestChannel.Close();
                    factory.Close();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally {
                Console.Read();
            }
        }
		public void BuildChannelWithoutProtectionTokenParameters ()
		{
			CustomBinding b = new CustomBinding (
				new SymmetricSecurityBindingElement (),
				new TextMessageEncodingBindingElement (),
				new HttpTransportBindingElement ());
			b.BuildChannelFactory<IRequestChannel> (new BindingParameterCollection ());
		}
Exemplo n.º 5
0
        public void SendChannel()
        {
            Binding binding = new CustomBinding(new RedisMessageBindingElement(), new RedisSendTransportBinding());
            EndpointAddress address = new EndpointAddress("redis://localhost:6379");

            IChannelFactory<IDuplexChannel> factory = binding.BuildChannelFactory<IDuplexChannel>();
            factory.Open();
            IDuplexChannel duplexChannel = factory.CreateChannel(address);
            Assert.IsInstanceOf<RedisSendChannel>(duplexChannel);
        }
    public static void IRequestChannel_Http_CustomBinding()
    {
        try
        {
            BindingElement[] bindingElements = new BindingElement[2];
            bindingElements[0] = new TextMessageEncodingBindingElement();
            bindingElements[1] = new HttpTransportBindingElement();
            CustomBinding binding = new CustomBinding(bindingElements);

            // Create the channel factory for the request-reply message exchange pattern.
            IChannelFactory<IRequestChannel> factory =
            binding.BuildChannelFactory<IRequestChannel>(
                             new BindingParameterCollection());
            factory.Open();

            // Create the channel.
            IRequestChannel channel = factory.CreateChannel(
               new EndpointAddress(Endpoints.DefaultCustomHttp_Address));
            channel.Open();

            // Create the Message object to send to the service.
            Message requestMessage = Message.CreateMessage(
                binding.MessageVersion,
                action,
                new CustomBodyWriter(clientMessage));

            // Send the Message and receive the Response.
            Message replyMessage = channel.Request(requestMessage);
            string replyMessageAction = replyMessage.Headers.Action;

            if (!string.Equals(replyMessageAction, action + "Response"))
            {
                Assert.True(false, String.Format("A response was received from the Service but it was not the expected Action, expected: {0} actual: {1}", action + "Response", replyMessageAction));
            }


            var replyReader = replyMessage.GetReaderAtBodyContents();
            string actualResponse = replyReader.ReadElementContentAsString();
            string expectedResponse = "[client] This is my request.[service] Request received, this is my Reply.";
            if (!string.Equals(actualResponse, expectedResponse))
            {
                Assert.True(false, String.Format("Actual MessageBodyContent from service did not match the expected MessageBodyContent, expected: {0} actual: {1}", expectedResponse, actualResponse));
            }

            replyMessage.Close();
            channel.Close();
            factory.Close();
        }

        catch (Exception ex)
        {
            Assert.True(false, String.Format("Unexpected exception was caught: {0}", ex.ToString()));
        }
    }
Exemplo n.º 7
0
 public IChannelFactory <TChannel> BuildChannelFactory <TChannel>()
 {
     if (_context != null)
     {
         IChannelFactory <TChannel> factory = _context.BuildInnerChannelFactory <TChannel>();
         _context = null;
         return(factory);
     }
     else
     {
         return(_binding.BuildChannelFactory <TChannel>(_bindingParameters));
     }
 }
Exemplo n.º 8
0
        public void ReceiveMessage()
        {
            Binding binding = new CustomBinding(new RedisMessageBindingElement(), new RedisReceiveTransportBinding());
            EndpointAddress address = new EndpointAddress("redis://localhost:6379");

            IChannelFactory<IRequestChannel> factory = binding.BuildChannelFactory<IRequestChannel>();
            factory.Open();
            IRequestChannel channel = factory.CreateChannel(address);
            channel.Open();
            Message requestMessage = Message.CreateMessage(MessageVersion.Default, "http://tempuri", "Key");
            Message replyMessage = channel.Request(requestMessage, TimeSpan.FromSeconds(5));
            StringAssert.Contains("Value",replyMessage.GetBody<string>());
        }
Exemplo n.º 9
0
        private static void SendData()
        {
            Console.WriteLine("Sending data:");
            Binding binding = new CustomBinding(new RedisMessageBindingElement(), new RedisSendTransportBinding());
            EndpointAddress address = new EndpointAddress("redis://localhost:6379");

            IChannelFactory<IDuplexChannel> factory = binding.BuildChannelFactory<IDuplexChannel>();
            factory.Open();
            IDuplexChannel duplexChannel = factory.CreateChannel(address);
            duplexChannel.Open();

            Message requestMessage = Message.CreateMessage(MessageVersion.Default, "http://tempuri", "Key:Value");

            duplexChannel.Send(requestMessage);
        }
Exemplo n.º 10
0
		public static void Main ()
		{
			Console.WriteLine ("Press ENTER when service is ready.");
			Console.ReadLine ();
			
			CustomBinding binding = new CustomBinding ();
			binding.Elements.Add (new TextMessageEncodingBindingElement ());
			binding.Elements.Add (new TcpTransportBindingElement ());
			
			BindingParameterCollection bpcol = 
				new BindingParameterCollection ();
			
//			using (IChannelFactory<IDuplexSessionChannel> factory =
//			binding.BuildChannelFactory<IDuplexSessionChannel>(bpcol))
//			{
				IChannelFactory<IDuplexSessionChannel> factory =
					binding.BuildChannelFactory<IDuplexSessionChannel> (bpcol);
				
				factory.Open ();
				
				IDuplexSessionChannel channel = factory.CreateChannel (
					new EndpointAddress ("net.tcp://localhost/"));
				
				channel.Open ();
				
				Message message = Message.CreateMessage (
					//channel.Manager.MessageVersion, 
					MessageVersion.Default,
					"Action", "Hello, World, from client side");
				
				channel.Send (message);

				message = channel.Receive ();
				
				Console.WriteLine ("Message received.");
				Console.WriteLine ("Message action: {0}", 
					message.Headers.Action);
				Console.WriteLine ("Message content: {0}", 
					message.GetBody<string> ());

				message.Close ();
				channel.Close ();
				factory.Close ();
//			}
		}
Exemplo n.º 11
0
        private static void ReceiveData()
        {
            Console.WriteLine("Receiving data:");
            Binding binding = new CustomBinding(new RedisMessageBindingElement(), new RedisReceiveTransportBinding());
            EndpointAddress address = new EndpointAddress("redis://localhost:6379");

            IChannelFactory<IRequestChannel> factory = binding.BuildChannelFactory<IRequestChannel>();
            factory.Open();
            IRequestChannel channel = factory.CreateChannel(address);
            channel.Open();
            Message requestMessage = Message.CreateMessage(MessageVersion.Default, "http://tempuri", "Key");
            Message replyMessage = channel.Request(requestMessage, TimeSpan.FromSeconds(5));
            using (replyMessage)
            {
                Console.WriteLine("Processing reply: {0}", replyMessage.Headers.Action);
                Console.WriteLine("Reply: {0}", replyMessage.GetBody<string>());
            }
        }
Exemplo n.º 12
0
    // Create the channel factory and open the channel for the request-reply message exchange pattern.
    public static void RequestReplyChannelFactory_Open()
    {
        try
        {
            BindingElement[] bindingElements = new BindingElement[2];
            bindingElements[0] = new TextMessageEncodingBindingElement();
            bindingElements[1] = new HttpTransportBindingElement();
            CustomBinding binding = new CustomBinding(bindingElements);

            // Create the channel factory
            IChannelFactory<IRequestChannel> factory = binding.BuildChannelFactory<IRequestChannel>(new BindingParameterCollection());
            factory.Open();

            // Create the channel and open it.  Success is anything other than an exception.
            IRequestChannel channel = factory.CreateChannel(new EndpointAddress("http://localhost/WcfProjectNService.svc"));
            channel.Open();
        }
        catch (Exception ex)
        {
            Assert.True(false, String.Format("Unexpected exception was caught: {0}", ex.ToString()));
        }
    }
Exemplo n.º 13
0
 internal static IChannelFactory <TChannel> CreateChannelFactory <TChannel>(TransportBindingElement transport)
 {
     System.ServiceModel.Channels.Binding binding = new CustomBinding(new BindingElement[] { transport });
     return(binding.BuildChannelFactory <TChannel>(new object[0]));
 }
        internal static IChannelFactory <TChannel> CreateChannelFactory <TChannel>(TransportBindingElement transport)
        {
            Binding binding = new CustomBinding(transport);

            return(binding.BuildChannelFactory <TChannel>());
        }
Exemplo n.º 15
0
		public void CheckDuplicateAuthenticatorTypesClient ()
		{
			SymmetricSecurityBindingElement be =
				new SymmetricSecurityBindingElement ();
			be.ProtectionTokenParameters =
				new X509SecurityTokenParameters ();
			be.EndpointSupportingTokenParameters.Endorsing.Add (
				new X509SecurityTokenParameters ());
			// This causes multiple supporting token authenticator
			// of the same type.
			be.OptionalEndpointSupportingTokenParameters.Endorsing.Add (
				new X509SecurityTokenParameters ());
			Binding b = new CustomBinding (be, new HttpTransportBindingElement ());
			ClientCredentials cred = new ClientCredentials ();
			cred.ClientCertificate.Certificate =
				new X509Certificate2 ("Test/Resources/test.pfx", "mono");
			IChannelFactory<IReplyChannel> ch = b.BuildChannelFactory<IReplyChannel> (new Uri ("http://localhost:" + NetworkHelpers.FindFreePort ()), cred);
			try {
				ch.Open ();
			} finally {
				if (ch.State == CommunicationState.Closed)
					ch.Close ();
			}
		}
		public void MessageSecurityManualProtection ()
		{
			SymmetricSecurityBindingElement sbe =
				new SymmetricSecurityBindingElement ();
			sbe.ProtectionTokenParameters =
				new X509SecurityTokenParameters ();
			RequestSender sender = delegate (Message input) {
				MessageBuffer buf = input.CreateBufferedCopy (0x10000);
				using (XmlWriter w = XmlWriter.Create (Console.Error)) {
					buf.CreateMessage ().WriteMessage (w);
				}
				return buf.CreateMessage ();
			};

			CustomBinding binding = new CustomBinding (
				sbe,
				new TextMessageEncodingBindingElement (),
				new HandlerTransportBindingElement (sender));

			EndpointAddress address = new EndpointAddress (
				new Uri ("http://localhost:8080"),
				new X509CertificateEndpointIdentity (new X509Certificate2 ("Test/Resources/test.pfx", "mono")));

			ChannelProtectionRequirements reqs =
				new ChannelProtectionRequirements ();
			reqs.OutgoingSignatureParts.AddParts (
				new MessagePartSpecification (new XmlQualifiedName ("SampleValue", "urn:foo")), "urn:myaction");
			BindingParameterCollection parameters =
				new BindingParameterCollection ();
			parameters.Add (reqs);
/*
			SymmetricSecurityBindingElement innersbe =
				new SymmetricSecurityBindingElement ();
			innersbe.ProtectionTokenParameters =
				new X509SecurityTokenParameters ();
			sbe.ProtectionTokenParameters =
				new SecureConversationSecurityTokenParameters (
					innersbe, false, reqs);
*/

			IChannelFactory<IRequestChannel> cf =
				binding.BuildChannelFactory<IRequestChannel> (parameters);
			cf.Open ();
			IRequestChannel ch = cf.CreateChannel (address);

			ch.Open ();
			try {
				ch.Request (Message.CreateMessage (MessageVersion.None, "urn:myaction", new SampleValue ()));
			} finally {
				ch.Close ();
			}
		}
		public void CustomTransportDoesNotRequireMessageEncoding ()
		{
			ReplyHandler replier = delegate (Message msg) {
				resmsg = msg;
			};

			RequestReceiver receiver = delegate () {
				return reqmsg;
			};

			RequestSender sender = delegate (Message msg) {
				reqmsg = msg;

				CustomBinding br = new CustomBinding (
					new HandlerTransportBindingElement (replier, receiver));
				IChannelListener<IReplyChannel> l =
					br.BuildChannelListener<IReplyChannel> (
						new BindingParameterCollection ());
				l.Open ();
				IReplyChannel rch = l.AcceptChannel ();
				rch.Open ();
				Message res = Message.CreateMessage (MessageVersion.Default, "urn:succeeded");
				rch.ReceiveRequest ().Reply (res);
				rch.Close ();
				l.Close ();

				return resmsg;
			};

			CustomBinding bs = new CustomBinding (
				new HandlerTransportBindingElement (sender));

			IChannelFactory<IRequestChannel> f =
				bs.BuildChannelFactory<IRequestChannel> (
					new BindingParameterCollection ());
			f.Open ();
			IRequestChannel ch = f.CreateChannel (new EndpointAddress ("urn:dummy"));
			ch.Open ();
			Message result = ch.Request (Message.CreateMessage (MessageVersion.Default, "urn:request"));
		}
		public void OpenRequestNonAuthenticatable ()
		{
			SymmetricSecurityBindingElement sbe = 
				new SymmetricSecurityBindingElement ();
			sbe.ProtectionTokenParameters =
				new UserNameSecurityTokenParameters ();
			Binding binding = new CustomBinding (sbe, new HandlerTransportBindingElement (null));
			BindingParameterCollection pl =
				new BindingParameterCollection ();
			ClientCredentials cred = new ClientCredentials ();
			cred.UserName.UserName = "******";
			pl.Add (cred);
			IChannelFactory<IRequestChannel> f =
				binding.BuildChannelFactory<IRequestChannel> (pl);
			f.Open ();
			IRequestChannel ch = f.CreateChannel (new EndpointAddress ("stream:dummy"));
			try {
				ch.Open ();
				Assert.Fail ("NotSupportedException is expected.");
			} catch (NotSupportedException) {
			}
		}
        public static ServiceChannelFactory BuildChannelFactory(ServiceEndpoint serviceEndpoint, bool useActiveAutoClose)
        {
            if (serviceEndpoint == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serviceEndpoint");
            }

            serviceEndpoint.EnsureInvariants();
            serviceEndpoint.ValidateForClient();

            ChannelRequirements requirements;
            ContractDescription contractDescription = serviceEndpoint.Contract;

            ChannelRequirements.ComputeContractRequirements(contractDescription, out requirements);

            BindingParameterCollection parameters;
            ClientRuntime clientRuntime = DispatcherBuilder.BuildProxyBehavior(serviceEndpoint, out parameters);

            Binding binding = serviceEndpoint.Binding;

            Type[] requiredChannels = ChannelRequirements.ComputeRequiredChannels(ref requirements);

            CustomBinding  customBinding = new CustomBinding(binding);
            BindingContext context       = new BindingContext(customBinding, parameters);

            InternalDuplexBindingElement internalDuplexBindingElement = null;

            InternalDuplexBindingElement.AddDuplexFactorySupport(context, ref internalDuplexBindingElement);

            customBinding = new CustomBinding(context.RemainingBindingElements);
            customBinding.CopyTimeouts(serviceEndpoint.Binding);

            foreach (Type type in requiredChannels)
            {
                if (type == typeof(IOutputChannel) && customBinding.CanBuildChannelFactory <IOutputChannel>(parameters))
                {
                    return(new ServiceChannelFactoryOverOutput(customBinding.BuildChannelFactory <IOutputChannel>(parameters), clientRuntime, binding));
                }

                if (type == typeof(IRequestChannel) && customBinding.CanBuildChannelFactory <IRequestChannel>(parameters))
                {
                    return(new ServiceChannelFactoryOverRequest(customBinding.BuildChannelFactory <IRequestChannel>(parameters), clientRuntime, binding));
                }

                if (type == typeof(IDuplexChannel) && customBinding.CanBuildChannelFactory <IDuplexChannel>(parameters))
                {
                    if (requirements.usesReply &&
                        binding.CreateBindingElements().Find <TransportBindingElement>().ManualAddressing)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                                                                                      SR.GetString(SR.CantCreateChannelWithManualAddressing)));
                    }

                    return(new ServiceChannelFactoryOverDuplex(customBinding.BuildChannelFactory <IDuplexChannel>(parameters), clientRuntime, binding));
                }

                if (type == typeof(IOutputSessionChannel) && customBinding.CanBuildChannelFactory <IOutputSessionChannel>(parameters))
                {
                    return(new ServiceChannelFactoryOverOutputSession(customBinding.BuildChannelFactory <IOutputSessionChannel>(parameters), clientRuntime, binding, false));
                }

                if (type == typeof(IRequestSessionChannel) && customBinding.CanBuildChannelFactory <IRequestSessionChannel>(parameters))
                {
                    return(new ServiceChannelFactoryOverRequestSession(customBinding.BuildChannelFactory <IRequestSessionChannel>(parameters), clientRuntime, binding, false));
                }

                if (type == typeof(IDuplexSessionChannel) && customBinding.CanBuildChannelFactory <IDuplexSessionChannel>(parameters))
                {
                    if (requirements.usesReply &&
                        binding.CreateBindingElements().Find <TransportBindingElement>().ManualAddressing)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                                                                                      SR.GetString(SR.CantCreateChannelWithManualAddressing)));
                    }

                    return(new ServiceChannelFactoryOverDuplexSession(customBinding.BuildChannelFactory <IDuplexSessionChannel>(parameters), clientRuntime, binding, useActiveAutoClose));
                }
            }

            foreach (Type type in requiredChannels)
            {
                // For SessionMode.Allowed or SessionMode.NotAllowed we will accept session-ful variants as well
                if (type == typeof(IOutputChannel) && customBinding.CanBuildChannelFactory <IOutputSessionChannel>(parameters))
                {
                    return(new ServiceChannelFactoryOverOutputSession(customBinding.BuildChannelFactory <IOutputSessionChannel>(parameters), clientRuntime, binding, true));
                }

                if (type == typeof(IRequestChannel) && customBinding.CanBuildChannelFactory <IRequestSessionChannel>(parameters))
                {
                    return(new ServiceChannelFactoryOverRequestSession(customBinding.BuildChannelFactory <IRequestSessionChannel>(parameters), clientRuntime, binding, true));
                }

                // and for SessionMode.Required, it is possible that the InstanceContextProvider is handling the session management, so
                // accept datagram variants if that is the case
                if (type == typeof(IRequestSessionChannel) && customBinding.CanBuildChannelFactory <IRequestChannel>(parameters) &&
                    customBinding.GetProperty <IContextSessionProvider>(parameters) != null)
                {
                    return(new ServiceChannelFactoryOverRequest(customBinding.BuildChannelFactory <IRequestChannel>(parameters), clientRuntime, binding));
                }
            }

            // we put a lot of work into creating a good error message, as this is a common case
            Dictionary <Type, byte> supportedChannels = new Dictionary <Type, byte>();

            if (customBinding.CanBuildChannelFactory <IOutputChannel>(parameters))
            {
                supportedChannels.Add(typeof(IOutputChannel), 0);
            }
            if (customBinding.CanBuildChannelFactory <IRequestChannel>(parameters))
            {
                supportedChannels.Add(typeof(IRequestChannel), 0);
            }
            if (customBinding.CanBuildChannelFactory <IDuplexChannel>(parameters))
            {
                supportedChannels.Add(typeof(IDuplexChannel), 0);
            }
            if (customBinding.CanBuildChannelFactory <IOutputSessionChannel>(parameters))
            {
                supportedChannels.Add(typeof(IOutputSessionChannel), 0);
            }
            if (customBinding.CanBuildChannelFactory <IRequestSessionChannel>(parameters))
            {
                supportedChannels.Add(typeof(IRequestSessionChannel), 0);
            }
            if (customBinding.CanBuildChannelFactory <IDuplexSessionChannel>(parameters))
            {
                supportedChannels.Add(typeof(IDuplexSessionChannel), 0);
            }

            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ChannelRequirements.CantCreateChannelException(
                                                                          supportedChannels.Keys, requiredChannels, binding.Name));
        }
Exemplo n.º 20
0
        public static ServiceChannelFactory BuildChannelFactory(ServiceEndpoint serviceEndpoint, bool useActiveAutoClose)
        {
            ChannelRequirements        requirements;
            BindingParameterCollection parameters;

            if (serviceEndpoint == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("serviceEndpoint");
            }
            serviceEndpoint.EnsureInvariants();
            serviceEndpoint.ValidateForClient();
            ChannelRequirements.ComputeContractRequirements(serviceEndpoint.Contract, out requirements);
            System.ServiceModel.Dispatcher.ClientRuntime clientRuntime = DispatcherBuilder.BuildProxyBehavior(serviceEndpoint, out parameters);
            Binding binding = serviceEndpoint.Binding;

            System.Type[]  requiredChannels = ChannelRequirements.ComputeRequiredChannels(ref requirements);
            CustomBinding  binding2         = new CustomBinding(binding);
            BindingContext context          = new BindingContext(binding2, parameters);
            InternalDuplexBindingElement internalDuplexBindingElement = null;

            InternalDuplexBindingElement.AddDuplexFactorySupport(context, ref internalDuplexBindingElement);
            binding2 = new CustomBinding(context.RemainingBindingElements);
            binding2.CopyTimeouts(serviceEndpoint.Binding);
            foreach (System.Type type in requiredChannels)
            {
                if ((type == typeof(IOutputChannel)) && binding2.CanBuildChannelFactory <IOutputChannel>(parameters))
                {
                    return(new ServiceChannelFactoryOverOutput(binding2.BuildChannelFactory <IOutputChannel>(parameters), clientRuntime, binding));
                }
                if ((type == typeof(IRequestChannel)) && binding2.CanBuildChannelFactory <IRequestChannel>(parameters))
                {
                    return(new ServiceChannelFactoryOverRequest(binding2.BuildChannelFactory <IRequestChannel>(parameters), clientRuntime, binding));
                }
                if ((type == typeof(IDuplexChannel)) && binding2.CanBuildChannelFactory <IDuplexChannel>(parameters))
                {
                    if (requirements.usesReply && binding.CreateBindingElements().Find <TransportBindingElement>().ManualAddressing)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("CantCreateChannelWithManualAddressing")));
                    }
                    return(new ServiceChannelFactoryOverDuplex(binding2.BuildChannelFactory <IDuplexChannel>(parameters), clientRuntime, binding));
                }
                if ((type == typeof(IOutputSessionChannel)) && binding2.CanBuildChannelFactory <IOutputSessionChannel>(parameters))
                {
                    return(new ServiceChannelFactoryOverOutputSession(binding2.BuildChannelFactory <IOutputSessionChannel>(parameters), clientRuntime, binding, false));
                }
                if ((type == typeof(IRequestSessionChannel)) && binding2.CanBuildChannelFactory <IRequestSessionChannel>(parameters))
                {
                    return(new ServiceChannelFactoryOverRequestSession(binding2.BuildChannelFactory <IRequestSessionChannel>(parameters), clientRuntime, binding, false));
                }
                if ((type == typeof(IDuplexSessionChannel)) && binding2.CanBuildChannelFactory <IDuplexSessionChannel>(parameters))
                {
                    if (requirements.usesReply && binding.CreateBindingElements().Find <TransportBindingElement>().ManualAddressing)
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(System.ServiceModel.SR.GetString("CantCreateChannelWithManualAddressing")));
                    }
                    return(new ServiceChannelFactoryOverDuplexSession(binding2.BuildChannelFactory <IDuplexSessionChannel>(parameters), clientRuntime, binding, useActiveAutoClose));
                }
            }
            foreach (System.Type type2 in requiredChannels)
            {
                if ((type2 == typeof(IOutputChannel)) && binding2.CanBuildChannelFactory <IOutputSessionChannel>(parameters))
                {
                    return(new ServiceChannelFactoryOverOutputSession(binding2.BuildChannelFactory <IOutputSessionChannel>(parameters), clientRuntime, binding, true));
                }
                if ((type2 == typeof(IRequestChannel)) && binding2.CanBuildChannelFactory <IRequestSessionChannel>(parameters))
                {
                    return(new ServiceChannelFactoryOverRequestSession(binding2.BuildChannelFactory <IRequestSessionChannel>(parameters), clientRuntime, binding, true));
                }
                if (((type2 == typeof(IRequestSessionChannel)) && binding2.CanBuildChannelFactory <IRequestChannel>(parameters)) && (binding2.GetProperty <IContextSessionProvider>(parameters) != null))
                {
                    return(new ServiceChannelFactoryOverRequest(binding2.BuildChannelFactory <IRequestChannel>(parameters), clientRuntime, binding));
                }
            }
            Dictionary <System.Type, byte> dictionary = new Dictionary <System.Type, byte>();

            if (binding2.CanBuildChannelFactory <IOutputChannel>(parameters))
            {
                dictionary.Add(typeof(IOutputChannel), 0);
            }
            if (binding2.CanBuildChannelFactory <IRequestChannel>(parameters))
            {
                dictionary.Add(typeof(IRequestChannel), 0);
            }
            if (binding2.CanBuildChannelFactory <IDuplexChannel>(parameters))
            {
                dictionary.Add(typeof(IDuplexChannel), 0);
            }
            if (binding2.CanBuildChannelFactory <IOutputSessionChannel>(parameters))
            {
                dictionary.Add(typeof(IOutputSessionChannel), 0);
            }
            if (binding2.CanBuildChannelFactory <IRequestSessionChannel>(parameters))
            {
                dictionary.Add(typeof(IRequestSessionChannel), 0);
            }
            if (binding2.CanBuildChannelFactory <IDuplexSessionChannel>(parameters))
            {
                dictionary.Add(typeof(IDuplexSessionChannel), 0);
            }
            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(ChannelRequirements.CantCreateChannelException(dictionary.Keys, requiredChannels, binding.Name));
        }
    public static void IRequestChannel_Http_CustomBinding()
    {
        IChannelFactory<IRequestChannel> factory = null;
        IRequestChannel channel = null;
        Message replyMessage = null;

        try
        {
            // *** SETUP *** \\
            BindingElement[] bindingElements = new BindingElement[2];
            bindingElements[0] = new TextMessageEncodingBindingElement();
            bindingElements[1] = new HttpTransportBindingElement();
            CustomBinding binding = new CustomBinding(bindingElements);

            // Create the channel factory for the request-reply message exchange pattern.
            factory = binding.BuildChannelFactory<IRequestChannel>(new BindingParameterCollection());
            factory.Open();

            // Create the channel.
            channel = factory.CreateChannel(new EndpointAddress(Endpoints.DefaultCustomHttp_Address));
            channel.Open();

            // Create the Message object to send to the service.
            Message requestMessage = Message.CreateMessage(
                binding.MessageVersion,
                action,
                new CustomBodyWriter(clientMessage));

            // *** EXECUTE *** \\
            // Send the Message and receive the Response.
            replyMessage = channel.Request(requestMessage);

            // *** VALIDATE *** \\
            string replyMessageAction = replyMessage.Headers.Action;
            Assert.Equal(action + "Response", replyMessageAction);

            var replyReader = replyMessage.GetReaderAtBodyContents();
            string actualResponse = replyReader.ReadElementContentAsString();
            string expectedResponse = "[client] This is my request.[service] Request received, this is my Reply.";
            Assert.Equal(expectedResponse, actualResponse);

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