Exemplo n.º 1
0
 static void Main(string[] args)
 {
     try
     {
         //建立和发送端相同的通道栈
         BindingElement[] bindingElements = new BindingElement[3];
         bindingElements[0] = new TextMessageEncodingBindingElement();//文本编码
         //oneWayBindingElement() 传输通道支持数据报模式
         bindingElements[1] = new OneWayBindingElement();
         bindingElements[2] = new NamedPipeTransportBindingElement();//命名管道
         CustomBinding binding = new CustomBinding(bindingElements);
         //建立ChannelListner倾听者,接收数据
         IChannelListener <IInputChannel> listener = binding.BuildChannelListener <IInputChannel>(new Uri("net.pipe://localhost/InputService"), new BindingParameterCollection());
         listener.Open();//打开ChannelListner
         IInputChannel inputChannel = listener.AcceptChannel();
         //创建IInputChannel
         inputChannel.Open();                      //打开IInputChannel
         Console.WriteLine("开始接受消息..");
         Message message = inputChannel.Receive(); //接受并打印
         Console.WriteLine($"接收一条消息,action为{message.Headers.Action},Body为{message.GetBody<string>()}");
         message.Close();                          //关闭消息
         inputChannel.Close();                     //关闭通道
         listener.Close();                         //关闭监听器
         Console.Read();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
     }
     finally
     {
         Console.Read();
     }
 }
Exemplo n.º 2
0
        public static void Snippet1()
        {
            // <Snippet1>
            CustomBinding binding = new CustomBinding();

            binding.Elements.Add(new HttpTransportBindingElement());
            BindingParameterCollection       paramCollection = new BindingParameterCollection();
            IChannelListener <IReplyChannel> listener        = binding.BuildChannelListener <IReplyChannel>
                                                                   (new Uri("http://localhost:8000/ChannelApp"), paramCollection);

            listener.Open();
            IReplyChannel channel = listener.AcceptChannel();

            Console.WriteLine("Listening for messages");
            channel.Open();
            RequestContext request = channel.ReceiveRequest();
            Message        msg     = request.RequestMessage;

            Console.WriteLine("Message Received");
            Console.WriteLine("Message Action: {0}", msg.Headers.Action);

            if (msg.Headers.Action == "hello")
            {
                Message reply = Message.CreateMessage(MessageVersion.Default, "wcf");
                request.Reply(reply);
            }

            msg.Close();
            channel.Close();
            listener.Close();
            // </Snippet1>
        }
        public void OpenListenerWithoutServiceCertificate()
        {
            CustomBinding rb = CreateBinding();
            IChannelListener <IReplyChannel> listener = rb.BuildChannelListener <IReplyChannel> (new BindingParameterCollection());

            listener.Open();
        }
Exemplo n.º 4
0
        public void CheckDuplicateAuthenticatorTypesService()
        {
            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());
            ServiceCredentials cred = new ServiceCredentials();

            cred.ServiceCertificate.Certificate =
                new X509Certificate2(TestResourceHelper.GetFullPathOfResource("Test/Resources/test.pfx"), "mono");
            IChannelListener <IReplyChannel> ch = b.BuildChannelListener <IReplyChannel> (new Uri("http://localhost:" + NetworkHelpers.FindFreePort()), cred);

            try {
                ch.Open();
            } finally {
                if (ch.State == CommunicationState.Closed)
                {
                    ch.Close();
                }
            }
        }
Exemplo n.º 5
0
 static void Main(string[] args)
 {
     try
     {
         //建立和发送端相同的通道栈
         BindingElement[] bindingElements = new BindingElement[3];
         bindingElements[0] = new TextMessageEncodingBindingElement();
         bindingElements[1] = new OneWayBindingElement();
         bindingElements[2] = new HttpTransportBindingElement();
         CustomBinding binding = new CustomBinding(bindingElements);
         //建立ChannelListner
         IChannelListener <IInputChannel> listener = binding.BuildChannelListener <IInputChannel>(new Uri("http://localhost/InputService"), new BindingParameterCollection());
         listener.Open();
         //创建IInputChannel
         IInputChannel inputChannel = listener.AcceptChannel();
         inputChannel.Open();
         Console.WriteLine("开始接受消息。。。");
         //接受并打印消息
         Message message = inputChannel.Receive();
         Console.WriteLine("接受到一条消息,action为:{0},body为:{1}", message.Headers.Action, message.GetBody <String>());
         message.Close();
         inputChannel.Close();
         listener.Close();
         Console.Read();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
     }
     finally
     {
         Console.Read();
     }
 }
Exemplo n.º 6
0
        public void ServiceRecipientHasNoKeys()
        {
            AsymmetricSecurityBindingElement sbe =
                new AsymmetricSecurityBindingElement();

            sbe.InitiatorTokenParameters =
                new X509SecurityTokenParameters();
            sbe.RecipientTokenParameters =
                new UserNameSecurityTokenParameters();
            //sbe.SetKeyDerivation (false);
            //sbe.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncrypt;
            CustomBinding binding = new CustomBinding(sbe,
                                                      new HttpTransportBindingElement());
            IChannelListener <IReplyChannel> l =
                binding.BuildChannelListener <IReplyChannel> (new Uri("http://localhost:37564"), new BindingParameterCollection());

            try {
                l.Open();
            } finally {
                if (l.State == CommunicationState.Opened)
                {
                    l.Close();
                }
            }
        }
        public void BuildListenerWithoutProtectionTokenParameters()
        {
            CustomBinding b = new CustomBinding(
                new SymmetricSecurityBindingElement(),
                new TextMessageEncodingBindingElement(),
                new HttpTransportBindingElement());

            b.BuildChannelListener <IReplyChannel> (new BindingParameterCollection());
        }
Exemplo n.º 8
0
        public static void Snippet7()
        {
            // <Snippet7>
            CustomBinding binding = new CustomBinding();

            binding.Elements.Add(new HttpTransportBindingElement());
            BindingParameterCollection       paramCollection = new BindingParameterCollection();
            IChannelListener <IReplyChannel> listener        = binding.BuildChannelListener <IReplyChannel>
                                                                   (new Uri("http://localhost:8000/ChannelApp"), "http://localhost:8000/ChannelApp/service", paramCollection);
            // </Snippet7>
        }
Exemplo n.º 9
0
        public static void Snippet6()
        {
            // <Snippet6>
            CustomBinding binding = new CustomBinding();

            binding.Elements.Add(new HttpTransportBindingElement());
            Object[] bindingParameters = new Object[2];
            IChannelListener <IReplyChannel> listener = binding.BuildChannelListener <IReplyChannel>
                                                            (new Uri("http://localhost:8000/ChannelApp"), bindingParameters);
            // </Snippet6>
        }
Exemplo n.º 10
0
        static void RunService()
        {
            //Step1: Create a custom binding with just TCP.
            BindingElement[] bindingElements = new BindingElement[2];
            bindingElements[0] = new TextMessageEncodingBindingElement();
            bindingElements[1] = new HttpTransportBindingElement();

            CustomBinding binding = new CustomBinding(bindingElements);


            //Step2: Use the binding to build the channel listener.
            IChannelListener <IReplyChannel> listener =
                binding.BuildChannelListener <IReplyChannel>(
                    new Uri("http://localhost:8080/channelapp"),
                    new BindingParameterCollection());

            //Step3: Listening for messages.
            listener.Open();
            Console.WriteLine(
                "Listening for incoming channel connections");
            //Wait for and accept incoming connections.
            IReplyChannel channel = listener.AcceptChannel();

            Console.WriteLine("Channel accepted. Listening for messages");
            //Open the accepted channel.
            channel.Open();
            //Wait for and receive a message from the channel.
            RequestContext request = channel.ReceiveRequest();
            //Step4: Reading the request message.
            Message message = request.RequestMessage;

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

            Console.WriteLine("Message content: {0}", data);
            //Send a reply.
            Message replymessage = Message.CreateMessage(
                binding.MessageVersion,
                "http://contoso.com/someotheraction",
                data);

            request.Reply(replymessage);
            //Step5: Closing objects.
            //Do not forget to close the message.
            message.Close();
            //Do not forget to close RequestContext.
            request.Close();
            //Do not forget to close channels.
            channel.Close();
            //Do not forget to close listeners.
            listener.Close();
        }
Exemplo n.º 11
0
        /// <summary>
        /// Initializes a new instance of the RequestReplyFrontEnd class
        /// </summary>
        /// <param name="listenUri">uri the frontend listen to</param>
        /// <param name="binding">binding that the frontend uses</param>
        public OutputInputFrontEnd(Uri listenUri, Binding binding, BrokerObserver observer, BrokerClientManager clientManager, BrokerAuthorization brokerAuth, SharedData sharedData)
            : base(listenUri.AbsoluteUri, observer, clientManager, brokerAuth, sharedData)
        {
            List <BindingElement> elements = new List <BindingElement>();

            elements.Add(new OneWayBindingElement());
            elements.AddRange(binding.CreateBindingElements());
            CustomBinding shapedBinding = new CustomBinding(elements);

            this.listener       = shapedBinding.BuildChannelListener <T>(listenUri);
            this.acceptChannel  = new ReferencedThreadHelper <IAsyncResult>(new AsyncCallback(this.AcceptChannel), this).CallbackRoot;
            this.receiveRequest = new ReferencedThreadHelper <IAsyncResult>(new AsyncCallback(this.ReceiveRequest), this).CallbackRoot;
        }
Exemplo n.º 12
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);

                //建立ChannelListener
                IChannelListener <IReplyChannel> listener = binding.BuildChannelListener <IReplyChannel>(
                    new Uri("http://localhost:9090/RequestReplyService"),
                    new BindingParameterCollection());
                listener.Open();       //打开监听

                //创建IReplyChannel
                IReplyChannel replyChannel = listener.AcceptChannel();
                replyChannel.Open();   //打开通道

                Console.WriteLine("开始接收消息");

                //接收并打印消息
                RequestContext requestContext = replyChannel.ReceiveRequest();     //会堵塞在这里

                Console.WriteLine("接收到一条消息, action为{0}, body为{1}",
                                  requestContext.RequestMessage.Headers.Action,
                                  requestContext.RequestMessage.GetBody <string>());

                //创建返回消息
                Message response = Message.CreateMessage(binding.MessageVersion, "response", "response body");

                //发送返回消息
                requestContext.Reply(response);

                requestContext.Close();
                replyChannel.Close();
                listener.Close();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally
            {
                Console.WriteLine("Press any key to exit...");
                Console.ReadKey();
            }
        }
        public void OpenListenerNoPrivateKeyInServiceCertificate()
        {
            CustomBinding rb = CreateBinding();
            BindingParameterCollection bpl =
                new BindingParameterCollection();
            ServiceCredentials cred = new ServiceCredentials();

            cred.ServiceCertificate.Certificate =
                new X509Certificate2("Test/Resources/test.cer");
            IServiceBehavior sb = cred;

            sb.AddBindingParameters(null, null, null, bpl);
            IChannelListener <IReplyChannel> listener = rb.BuildChannelListener <IReplyChannel> (bpl);

            listener.Open();
        }
        IChannelListener <IReplyChannel> CreateListener(ReplyHandler handler, RequestReceiver receiver)
        {
            CustomBinding rb = CreateBinding(handler, receiver);
            BindingParameterCollection bpl =
                new BindingParameterCollection();
            ServiceCredentials cred = new ServiceCredentials();

            cred.ServiceCertificate.Certificate =
                new X509Certificate2("Test/Resources/test.pfx", "mono");
            IServiceBehavior sb = cred;

            sb.AddBindingParameters(null, null, null, bpl);
            IChannelListener <IReplyChannel> listener = rb.BuildChannelListener <IReplyChannel> (bpl);

            return(listener);
        }
Exemplo n.º 15
0
        public static void Main()
        {
            CustomBinding binding = new CustomBinding();

            binding.Elements.Add(new TextMessageEncodingBindingElement());
            binding.Elements.Add(new TcpTransportBindingElement());

            BindingParameterCollection bpcol =
                new BindingParameterCollection();

//			using (IChannelListener<IDuplexSessionChannel> listener =
//				binding.BuildChannelListener<IDuplexSessionChannel> (
//					new Uri ("net.tcp://localhost/Server"), bpcol))
//			{
            IChannelListener <IDuplexSessionChannel> listener =
                binding.BuildChannelListener <IDuplexSessionChannel> (
                    new Uri("net.tcp://localhost/"), bpcol);

            listener.Open();

            IDuplexSessionChannel channel =
                listener.AcceptChannel();

            Console.WriteLine("Listening for messages...");

            channel.Open();

            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 = Message.CreateMessage(
                //channel.Manager.MessageVersion,
                MessageVersion.Default,
                "Action", "Hello, World, from service side");

            channel.Send(message);

            message.Close();
            channel.Close();
            listener.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"));
        }
Exemplo n.º 17
0
        private static void CreateHttpGetChannelDispatcher(ServiceHostBase host, Uri listenUri, MetadataSet metadata)
        {
            //创建Binding
            TextMessageEncodingBindingElement messageEncodingElement = new TextMessageEncodingBindingElement()
            {
                MessageVersion = MessageVersion.None
            };
            HttpTransportBindingElement transportElement = new HttpTransportBindingElement();

            Utility.SetPropertyValue(transportElement, "Method", "GET");
            Binding binding = new CustomBinding(messageEncodingElement, transportElement);

            //创建ChannelListener
            IChannelListener  listener   = binding.BuildChannelListener <IReplyChannel>(listenUri, string.Empty, ListenUriMode.Explicit, new BindingParameterCollection());
            ChannelDispatcher dispatcher = new ChannelDispatcher(listener, "ServiceMetadataBehaviorHttpGetBinding", binding)
            {
                MessageVersion = binding.MessageVersion
            };

            //创建EndpointDispatcher
            EndpointDispatcher endpoint = new EndpointDispatcher(new EndpointAddress(listenUri), "IHttpGetMetadata", "http://www.artech.com/");

            //创建DispatchOperation,并设置DispatchMessageFormatter和OperationInvoker
            DispatchOperation operation = new DispatchOperation(endpoint.DispatchRuntime, "Get", "*", "*");

            operation.Formatter = Utility.CreateInstance <IDispatchMessageFormatter>(MessageOperationFormatterType, Type.EmptyTypes, new object[0]);
            MethodInfo method = typeof(IHttpGetMetadata).GetMethod("Get");

            operation.Invoker = Utility.CreateInstance <IOperationInvoker>(SyncMethodInvokerType, new Type[] { typeof(MethodInfo) }, new object[] { method });
            endpoint.DispatchRuntime.Operations.Add(operation);

            //设置SingletonInstanceContext和InstanceContextProvider
            MetadataProvisionService serviceInstance = new MetadataProvisionService(metadata);

            endpoint.DispatchRuntime.SingletonInstanceContext = new InstanceContext(host, serviceInstance);
            endpoint.DispatchRuntime.InstanceContextProvider  = Utility.CreateInstance <IInstanceContextProvider>(SingletonInstanceContextProviderType, new Type[] { typeof(DispatchRuntime) }, new object[] { endpoint.DispatchRuntime });
            dispatcher.Endpoints.Add(endpoint);

            //设置ContractFilter和AddressFilter
            endpoint.ContractFilter = new MatchAllMessageFilter();
            endpoint.AddressFilter  = new MatchAllMessageFilter();

            host.ChannelDispatchers.Add(dispatcher);
        }
Exemplo n.º 18
0
        TestConsole()
        {
            CustomBinding binding = new CustomBinding();
            MtomMessageEncodingBindingElement mtomBindingElement = new MtomMessageEncodingBindingElement();

            mtomBindingElement.MessageVersion = MessageVersion.Soap11WSAddressingAugust2004;
            binding.Elements.Add(mtomBindingElement);
            binding.Elements.Add(new WseTcpTransportBindingElement());

            // WSE sample uses a logical endpoint. So we need to set the physical via separately.
            EndpointAddress address = new EndpointAddress("soap://stockservice.contoso.com/wse/samples/2003/06/TcpSyncStockService");

            // INSERT your HOSTNAME here:
            string hostname = "localhost";
            Uri    via      = new Uri(string.Format("soap.tcp://{0}/StockService", hostname));
            StockServicePortTypeClient client = new StockServicePortTypeClient(binding, address);

            client.Endpoint.Behaviors.Add(new ClientViaBehavior(via));
            Console.WriteLine("Calling {0}", client.Endpoint.Address.Uri.AbsoluteUri);

            StockQuoteRequest quoteRequest = new StockQuoteRequest();

            quoteRequest.symbols = new ArrayOfString();
            quoteRequest.symbols.Add("FABRIKAM");
            quoteRequest.symbols.Add("CONTOSO");
            StockQuotes stocks = client.GetStockQuotes(quoteRequest);

            foreach (StockQuote quote in stocks)
            {
                Console.WriteLine("");
                Console.WriteLine("Symbol: " + quote.Symbol);
                Console.WriteLine("\tName: " + quote.Name);
                Console.WriteLine("\tLast Price: " + quote.Last);
            }
            Console.WriteLine("Press enter.");
            Console.ReadLine();

            binding             = new CustomBinding(new WseTcpTransportBindingElement());
            this.uri            = new Uri("wse.tcp://localhost:9000/a/b/");
            this.channelFactory = binding.BuildChannelFactory <IDuplexSessionChannel>();
            this.listener       = binding.BuildChannelListener <IDuplexSessionChannel>(this.uri);
        }
Exemplo n.º 19
0
        static void RunClient()
        {
            CustomBinding binding = new CustomBinding();

            binding.Elements.Add(new TcpTransportBindingElement());
            CustomBinding customBinding             = new CustomBinding();
            BindingParameterCollection bpCollection =
                new BindingParameterCollection();

            // <Snippet9>
            BindingContext bContext = new BindingContext(customBinding, bpCollection);
            IChannelFactory <IOutputChannel> factory =
                binding.BuildChannelFactory <IOutputChannel>(bContext);
            // </Snippet9>

            // <Snippet10>
            IChannelListener <IOutputChannel> listener =
                binding.BuildChannelListener <IOutputChannel>(bContext);
            // </Snippet10>
        }
Exemplo n.º 20
0
 static void Main(string[] args)
 {
     try
     {
         //使用说明先启动input,然后在启动启动output。
         //记得使用管理员启动VS,我在程序清单中添加了管理员权限。
         //建立和发送端相同的通道栈
         BindingElement[] bindingElements = new BindingElement[2];
         bindingElements[0] = new TextMessageEncodingBindingElement(); //文本编码
         bindingElements[1] = new HttpTransportBindingElement();       //HTTP传输
         CustomBinding binding = new CustomBinding(bindingElements);
         //建立ChannelListner
         IChannelListener <IReplyChannel> listener = binding.BuildChannelListener <IReplyChannel>(new Uri("http://localhost:9090/RequestReplyService"), new BindingParameterCollection());
         listener.Open();//打开监听
         //创建IRepllyChannel
         IReplyChannel replyChannel = listener.AcceptChannel();
         replyChannel.Open();//打开通道
         Console.WriteLine("开始接受消息..");
         //接收打印
         RequestContext requestContext = replyChannel.ReceiveRequest();
         Console.WriteLine($"接收到一条消息,action为:{requestContext.RequestMessage.Headers.Action},body为{requestContext.RequestMessage.GetBody<string>()}");
         //创建返回消息
         Message response = Message.CreateMessage(binding.MessageVersion, "response", "reponse body");
         //发送返回消息
         requestContext.Reply(response);
         //关闭
         requestContext.Close(); //关闭通道
         listener.Close();       //关闭监听
         Console.Read();
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
     }
     finally
     {
         Console.Read();
     }
 }
Exemplo n.º 21
0
        public async Task StartAsync()
        {
            if (listener != null)
            {
                throw new InvalidOperationException(ExceptionMessageListenerHasAlreadyBeenStarted);
            }

            try
            {
                var tcpRelayTransportBindingElement =
                    new TcpRelayTransportBindingElement(RelayClientAuthenticationType.RelayAccessToken)
                {
                    TransferMode     = TransferMode.Buffered,
                    ConnectionMode   = TcpRelayConnectionMode.Relayed,
                    IsDynamic        = (relayAddressType == RelayAddressType.Dynamic),
                    ManualAddressing = true
                };
                tcpRelayTransportBindingElement.GetType()
                .GetProperty("TransportProtectionEnabled",
                             BindingFlags.GetProperty | BindingFlags.Instance | BindingFlags.NonPublic)
                .SetValue(tcpRelayTransportBindingElement, true);

                var tb = new TransportClientEndpointBehavior(tokenProvider);
                this.listenerBinding = new CustomBinding(
                    new BinaryMessageEncodingBindingElement(),
                    tcpRelayTransportBindingElement);

                listener = listenerBinding.BuildChannelListener <IDuplexSessionChannel>(new Uri(address), tb);
                await Task.Factory.FromAsync(listener.BeginOpen, listener.EndOpen, null);
            }
            catch
            {
                listener = null;
                throw;
            }
        }
Exemplo n.º 22
0
        void AddMetadataEndpoint(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher, bool debugMode)
        {
            Uri baseAddress = endpoint.Address.Uri;

            if (baseAddress == null)
            {
                return;
            }

            ServiceHostBase host = endpointDispatcher.ChannelDispatcher.Host;

            UriBuilder builder = new UriBuilder(baseAddress);

            builder.Path += builder.Path.EndsWith("/", StringComparison.OrdinalIgnoreCase)
                ? (WebScriptClientGenerator.GetMetadataEndpointSuffix(debugMode))
                : ("/" + WebScriptClientGenerator.GetMetadataEndpointSuffix(debugMode));
            EndpointAddress metadataAddress = new EndpointAddress(builder.Uri);

            foreach (ServiceEndpoint serviceEndpoint in host.Description.Endpoints)
            {
                if (EndpointAddress.UriEquals(serviceEndpoint.Address.Uri, metadataAddress.Uri, true, false))//  ignoreCase //  includeHostNameInComparison
                {
                    throw System.ServiceModel.DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                              new InvalidOperationException(SR2.GetString(SR2.JsonNoEndpointAtMetadataAddress, this.GetType().ToString(), serviceEndpoint.Address, serviceEndpoint.Name, host.Description.Name)));
                }
            }

            HttpTransportBindingElement transportBindingElement;
            HttpTransportBindingElement existingTransportBindingElement = endpoint.Binding.CreateBindingElements().Find <HttpTransportBindingElement>();

            if (existingTransportBindingElement != null)
            {
                transportBindingElement = (HttpTransportBindingElement)existingTransportBindingElement.Clone();
            }
            else
            {
                if (baseAddress.Scheme == "https")
                {
                    transportBindingElement = new HttpsTransportBindingElement();
                }
                else
                {
                    transportBindingElement = new HttpTransportBindingElement();
                }
            }

            transportBindingElement.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
            transportBindingElement.TransferMode           = TransferMode.Buffered;
            transportBindingElement.MaxBufferSize          = MaxMetadataEndpointBufferSize;
            transportBindingElement.MaxReceivedMessageSize = MaxMetadataEndpointBufferSize;
            Binding metadataBinding = new CustomBinding(
                new WebScriptMetadataMessageEncodingBindingElement(),
                transportBindingElement);
            BindingParameterCollection parameters = host.GetBindingParameters(endpoint);

            // build endpoint dispatcher
            ContractDescription  metadataContract           = ContractDescription.GetContract(typeof(ServiceMetadataExtension.IHttpGetMetadata));
            OperationDescription metadataOperation          = metadataContract.Operations[0];
            EndpointDispatcher   metadataEndpointDispatcher = new EndpointDispatcher(metadataAddress, metadataContract.Name, metadataContract.Namespace);
            DispatchOperation    dispatchOperation          = new DispatchOperation(metadataEndpointDispatcher.DispatchRuntime, metadataOperation.Name, metadataOperation.Messages[0].Action, metadataOperation.Messages[1].Action);

            dispatchOperation.Formatter = new WebScriptMetadataFormatter();
            dispatchOperation.Invoker   = new SyncMethodInvoker(metadataOperation.SyncMethod);
            metadataEndpointDispatcher.DispatchRuntime.Operations.Add(dispatchOperation);
            metadataEndpointDispatcher.DispatchRuntime.SingletonInstanceContext = new InstanceContext(host, new WebScriptClientGenerator(endpoint, debugMode, !String.IsNullOrEmpty(this.JavascriptCallbackParameterName)));
            metadataEndpointDispatcher.DispatchRuntime.InstanceContextProvider  = new SingletonInstanceContextProvider(metadataEndpointDispatcher.DispatchRuntime);

            // build channel dispatcher
            IChannelListener <IReplyChannel> listener = null;

            if (metadataBinding.CanBuildChannelListener <IReplyChannel>(parameters))
            {
                listener = metadataBinding.BuildChannelListener <IReplyChannel>(metadataAddress.Uri, parameters);
            }
            ChannelDispatcher metadataChannelDispatcher = new ChannelDispatcher(listener);

            metadataChannelDispatcher.MessageVersion = MessageVersion.None;
            metadataChannelDispatcher.Endpoints.Add(metadataEndpointDispatcher);

            host.ChannelDispatchers.Add(metadataChannelDispatcher);
        }
Exemplo n.º 23
0
        static void ReceiveSessionMessages()
        {
            // Read messages from queue until queue is empty:
            Console.WriteLine("Reading messages from queue {0}...", SampleManager.SessionQueueName);
            Console.WriteLine("Receiver Type: PeekLock");

            // Create listener and channel using custom binding
            CustomBinding   customBinding = new CustomBinding("customBinding");
            EndpointAddress address       = SampleManager.GetEndpointAddress(SampleManager.SessionQueueName, serviceBusNamespace);
            TransportClientEndpointBehavior securityBehavior = new TransportClientEndpointBehavior();

            securityBehavior.TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(serviceBusKeyName, serviceBusKey);
            customBinding.GetProperty <IReceiveContextSettings>(new BindingParameterCollection()).Enabled = true;

            IChannelListener <IInputSessionChannel> inputSessionChannelListener = null;

            try
            {
                inputSessionChannelListener = customBinding.BuildChannelListener <IInputSessionChannel>(address.Uri, securityBehavior);
                inputSessionChannelListener.Open();

                while (true)
                {
                    IInputSessionChannel inputSessionChannel = null;
                    try
                    {
                        // Create a new session channel for every new session available. If no more sessions available,
                        // then the operation throws a TimeoutException.
                        inputSessionChannel = inputSessionChannelListener.AcceptChannel(acceptSessionReceiverTimeout);
                        inputSessionChannel.Open();

                        // TryReceive operation returns true if message is available otherwise it returns false.
                        Message receivedMessage;
                        while (inputSessionChannel.TryReceive(receiveSessionMessageTimeout, out receivedMessage))
                        {
                            if (receivedMessage != null)
                            {
                                SampleManager.OutputMessageInfo("Receive", receivedMessage);

                                // Since the message body contains a serialized string one can access it like this:
                                //string soapBody = receivedMessage.GetBody<string>();

                                // Since the binding has ReceiveContext enabled, a manual complete operation is mandatory
                                // if the message was processed successfully.
                                ReceiveContext rc;
                                if (ReceiveContext.TryGet(receivedMessage, out rc))
                                {
                                    rc.Complete(TimeSpan.FromSeconds(10.0d));
                                }
                                else
                                {
                                    throw new InvalidOperationException("Receiver is in peek lock mode but receive context is not available!");
                                }
                            }
                            else
                            {
                                // This IInputSessionChannel doesn't have any more messages
                                break;
                            }
                        }

                        // Close session channel
                        inputSessionChannel.Close();
                        inputSessionChannel = null;
                    }
                    catch (TimeoutException)
                    {
                        break;
                    }
                    finally
                    {
                        if (inputSessionChannel != null)
                        {
                            inputSessionChannel.Abort();
                        }
                    }
                }

                // Close channel listener
                inputSessionChannelListener.Close();
            }
            catch (Exception)
            {
                if (inputSessionChannelListener != null)
                {
                    inputSessionChannelListener.Abort();
                }
                throw;
            }
        }