public IReplyChannel AcceptChannel()
        {
            var inner = _innerListener.AcceptChannel();

            if (inner != null)
            {
                return(new BasicAuthenticationChannel(this, inner));
            }

            return(null);
        }
Example #2
0
        /// <summary>
        /// OnAcceptChannel event
        /// </summary>
        /// <param name="timeout"></param>
        /// <returns></returns>
        protected override TChannel OnAcceptChannel(TimeSpan timeout)
        {
            WCFLogger.Write(TraceEventType.Verbose, "ChannelListener accepts channel");
            TChannel innerChannel = innerChannelListener.AcceptChannel(timeout);

            return(WrapChannel(innerChannel));
        }
Example #3
0
    public static void Main()
    {
        HttpTransportBindingElement el =
            new HttpTransportBindingElement();
        BindingContext bc = new BindingContext(
            new CustomBinding(),
            new BindingParameterCollection(),
            new Uri("http://localhost:37564"),
            String.Empty, ListenUriMode.Explicit);
        IChannelListener <IReplyChannel> listener =
            el.BuildChannelListener <IReplyChannel> (bc);

        listener.Open();

        IReplyChannel reply = listener.AcceptChannel();

        reply.Open();

        if (!reply.WaitForRequest(TimeSpan.FromSeconds(10)))
        {
            Console.WriteLine("No request reached here.");
            return;
        }
        Console.WriteLine("Receiving request ...");
        RequestContext ctx = reply.ReceiveRequest();

        if (ctx == null)
        {
            return;
        }
        Console.WriteLine("Starting reply ...");
        ctx.Reply(Message.CreateMessage(MessageVersion.Default, "Ack"));
    }
Example #4
0
        private TObjectType ReceiveMessage <TObjectType>()
        {
            Uri endpoint = new Uri("amqp:message_queue");
            IChannelListener <IInputChannel> listener = Util.GetBinding().BuildChannelListener <IInputChannel>(endpoint, new BindingParameterCollection());

            listener.Open();
            IInputChannel service = listener.AcceptChannel(TimeSpan.FromSeconds(10));

            service.Open();
            Message receivedMessage = service.Receive(TimeSpan.FromSeconds(10));

            Assert.NotNull(receivedMessage, "Message was not received");
            try
            {
                TObjectType receivedObject = receivedMessage.GetBody <TObjectType>();
                return(receivedObject);
            }
            catch (SerializationException)
            {
                Assert.Fail("Deserialized object not of correct type");
            }
            finally
            {
                receivedMessage.Close();
                service.Close();
                listener.Close();
            }

            return(default(TObjectType));
        }
Example #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();
     }
 }
Example #6
0
        static void Main(string[] args)
        {
            Uri     listenUri = new Uri("http://127.0.0.1:1357/listener");
            Binding binding   = new BasicHttpBinding();

            //创建,开启信道监听器
            IChannelListener <IReplyChannel> channelListener = binding.BuildChannelListener <IReplyChannel>(listenUri);

            channelListener.Open();

            //创建,开启回复信道
            IReplyChannel channel = channelListener.AcceptChannel(TimeSpan.MaxValue);

            channel.Open();

            //监听
            while (true)
            {
                //接收请求消息
                RequestContext requestContext = channel.ReceiveRequest(TimeSpan.MaxValue);
                Console.WriteLine(requestContext.RequestMessage);
                //消息回复
                requestContext.Reply(CreateReplyMessage(binding));
            }
        }
Example #7
0
        private void ReceiveTryMessages(TimeSpan channelAcceptTimeout, TimeSpan messageReceiveTimeout)
        {
            IChannelListener <IInputChannel> listener = Util.GetBinding().BuildChannelListener <IInputChannel>(this.endpoint, new BindingParameterCollection());

            listener.Open();
            IInputChannel inputChannel  = listener.AcceptChannel(channelAcceptTimeout);
            IAsyncResult  channelResult = inputChannel.BeginOpen(channelAcceptTimeout, null, null);

            Thread.Sleep(TimeSpan.FromMilliseconds(50.0));
            inputChannel.EndOpen(channelResult);

            IAsyncResult[] resultArray = new IAsyncResult[MessageCount];

            for (int i = 0; i < MessageCount; i++)
            {
                resultArray[i] = inputChannel.BeginTryReceive(messageReceiveTimeout, null, null);
            }

            for (int j = 0; j < MessageCount; j++)
            {
                Message tempMessage;
                Assert.True(inputChannel.EndTryReceive(resultArray[j], out tempMessage), "Did not successfully receive message #{0}", j);
            }

            inputChannel.Close();
            listener.Close();
        }
Example #8
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();
     }
 }
        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>
        }
Example #10
0
        /// <summary>
        /// 网络监听任务ChannelListener管道创建的消息处理管道最终实现了对请求的接收和响应的发送
        /// </summary>
        /// <param name="args"></param>
        public static void Main(string[] args)
        {
            //1、httpselfhost openAsync开启之后逻辑
            Uri     listenUri = new Uri("http://127.0.0.1:3721");
            Binding binding   = new HttpBinding();

            //创建 开启 信道监听器
            IChannelListener <IReplyChannel> channelListener = binding.BuildChannelListener <IReplyChannel>(listenUri);

            //可以使用异步的方式开启
            //channelListener.BeginOpen();
            channelListener.Open();


            //创建 开启 回复信道
            IReplyChannel channel = channelListener.AcceptChannel(TimeSpan.FromDays(24));

            channel.Open();

            while (true)
            {
                RequestContext requestContext = channel.ReceiveRequest(TimeSpan.MaxValue);
                PrintRequestMessage(requestContext.RequestMessage);
                //消息回复
                requestContext.Reply(CreateResponseMessage());
            }
        }
        public void ReceiveRequest()
        {
            // Seems like this method is invoked to send a reply
            // with related to "already created" SOAP fault.
            //
            // It is still not understandable that this delegate
            // is invoked as an infinite loop ...
            ReplyHandler handler = delegate(Message input) {
                Console.Error.WriteLine("Processing a reply.");
                // a:InvalidSecurity
                // An error occurred when verifying security for the message.
                Assert.IsTrue(input.IsFault);
                throw new ApplicationException();
            };
            Message         msg      = Message.CreateMessage(MessageVersion.Default, "myAction");
            RequestReceiver receiver = delegate() {
                return(msg);
            };
            IChannelListener <IReplyChannel> listener = CreateListener(handler, receiver);

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

            reply.Open();
            RequestContext ctx = reply.EndReceiveRequest(reply.BeginReceiveRequest(null, null));
        }
Example #12
0
        static void Main(string[] args)
        {
            Uri     listenUri = new Uri("http://127.0.0.1:3721");
            Binding binding   = new HttpBinding();

            //创建、开启信道监听器
            IChannelListener <IReplyChannel> channelListener = binding.BuildChannelListener <IReplyChannel>(listenUri);

            channelListener.Open();

            //创建、开启回复信道
            IReplyChannel channel = channelListener.AcceptChannel(TimeSpan.MaxValue);

            channel.Open();

            //开始监听
            while (true)
            {
                //接收输出请求消息
                RequestContext requestContext =
                    channel.ReceiveRequest(TimeSpan.MaxValue);
                PrintRequestMessage(requestContext.RequestMessage);
                //消息回复
                requestContext.Reply(CreateResponseMessage());
            }
        }
Example #13
0
        public static void Snippet17()
        {
            // <Snippet17>
            CustomBinding binding = new CustomBinding();
            HttpTransportBindingElement element    = new HttpTransportBindingElement();
            BindingParameterCollection  parameters = new BindingParameterCollection();
            Uri            baseAddress             = new Uri("http://localhost:8000/ChannelApp");
            String         relAddress = "http://localhost:8000/ChannelApp/service";
            BindingContext context    = new BindingContext(binding, parameters, baseAddress, relAddress, ListenUriMode.Explicit);

            IChannelListener <IReplyChannel> listener = element.BuildChannelListener <IReplyChannel>(context);

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

            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();
            // </Snippet17>
        }
        public void FullRequest()
        {
            EndpointIdentity identity =
                new X509CertificateEndpointIdentity(new X509Certificate2("Test/Resources/test.pfx", "mono"));
            EndpointAddress address =
                new EndpointAddress(new Uri("stream:dummy"), identity);

            Message mreq   = Message.CreateMessage(MessageVersion.Default, "myAction");
            Message mreply = null;

            XmlWriterSettings settings = new XmlWriterSettings();

            settings.Indent = true;

            // listener setup
            ReplyHandler replyHandler = delegate(Message rinput)
            {
                mreply = rinput;
            };
            RequestReceiver receiver = delegate()
            {
                return(mreq);
            };
            IChannelListener <IReplyChannel> listener = CreateListener(replyHandler, receiver);

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

            reply.Open();

            RequestSender reqHandler = delegate(Message input)
            {
                try
                {
                    // sync version somehow causes an infinite loop (!?)
                    RequestContext ctx = reply.EndReceiveRequest(reply.BeginReceiveRequest(TimeSpan.FromSeconds(5), null, null));
//					RequestContext ctx = reply.ReceiveRequest (TimeSpan.FromSeconds (5));
                    Console.Error.WriteLine("Acquired RequestContext.");
                    ctx.Reply(input);
                }
                catch (Exception ex)
                {
                    Console.Error.WriteLine("ERROR during processing a request in FullRequest()");
                    Console.Error.WriteLine(ex);
                    Console.Error.Flush();
                    throw;
                }
                return(mreply);
            };
            CustomBinding b = CreateBinding(reqHandler);

            IRequestChannel ch = ChannelFactory <IRequestChannel> .CreateChannel(b, address);

            ch.Open();
            Console.Error.WriteLine("**** starting a request  ****");
            IAsyncResult async = ch.BeginRequest(mreq, null, null);

            Console.Error.WriteLine("**** request started. ****");
            Message res = ch.EndRequest(async);
        }
Example #15
0
        static void Main(string[] args)
        {
            //创建监听地址和绑定
            Uri     listenUri = new Uri("http://localhost:9999/listener");
            Binding binding   = new BasicHttpBinding();
            //通过监听地址创建信道监听器
            IChannelListener <IReplyChannel> channelListener = binding.BuildChannelListener <IReplyChannel>(listenUri);

            //开启信道监听器
            channelListener.Open();

            //通过信道监听器对象创建回复信道对象
            IReplyChannel channel = channelListener.AcceptChannel(TimeSpan.MaxValue);

            //开启回复信道
            channel.Open();

            Console.WriteLine("开始监听...");

            while (true)
            {
                //通过回复信道创建请求文本对象
                RequestContext requestContext = channel.ReceiveRequest(TimeSpan.MaxValue);
                //输出请求文本对象里存储的从请求端发送的请求信息
                Console.WriteLine("接收到请求消息:\n{0}", requestContext.RequestMessage);
                //通过请求文本对象的Reply()方法向请求端发送回复信息
                requestContext.Reply(CreateReplyMessage(binding));
            }
        }
Example #16
0
		protected override TChannel OnAcceptChannel (TimeSpan timeout)
		{
			if (typeof (TChannel) == typeof (IReplyChannel))
				return (TChannel) (object) new InterceptorReplyChannel (
					(InterceptorChannelListener<IReplyChannel>) (object) this,
					(IReplyChannel) (object) inner.AcceptChannel (timeout));
			throw new NotImplementedException ();
		}
        public void ReceiveRequestWithoutOpenChannel()
        {
            IChannelListener <IReplyChannel> listener = CreateListener(null, null);

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

            reply.ReceiveRequest();
        }
Example #18
0
        private static void ReceiveMessages()
        {
            // Read messages from queue until queue is empty
            Console.WriteLine("Reading messages from queue {0}...", SampleManager.SessionlessQueueName);
            Console.WriteLine("Receiver Type: Receive and Delete");

            // Create channel listener and channel using NetMessagingBinding
            NetMessagingBinding             messagingBinding = new NetMessagingBinding("messagingBinding");
            EndpointAddress                 address          = SampleManager.GetEndpointAddress(SampleManager.SessionlessQueueName, serviceBusNamespace);
            TransportClientEndpointBehavior securityBehavior = new TransportClientEndpointBehavior();

            securityBehavior.TokenProvider = TokenProvider.CreateSharedAccessSignatureTokenProvider(serviceBusKeyName, serviceBusKey);

            IChannelListener <IInputChannel> inputChannelListener = null;
            IInputChannel inputChannel = null;

            try
            {
                inputChannelListener = messagingBinding.BuildChannelListener <IInputChannel>(address.Uri, securityBehavior);
                inputChannelListener.Open();
                inputChannel = inputChannelListener.AcceptChannel();
                inputChannel.Open();

                while (true)
                {
                    try
                    {
                        // Receive message from queue. If no more messages available, the operation throws a TimeoutException.
                        Message receivedMessage = inputChannel.Receive(receiveMessageTimeout);
                        SampleManager.OutputMessageInfo("Receive", receivedMessage);

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

                // Close
                inputChannel.Close();
                inputChannelListener.Close();
            }
            catch (Exception)
            {
                if (inputChannel != null)
                {
                    inputChannel.Abort();
                }
                if (inputChannelListener != null)
                {
                    inputChannelListener.Abort();
                }
                throw;
            }
        }
Example #19
0
            public IChannelBinder Accept(TimeSpan timeout)
            {
                IDuplexChannel channel = _listener.AcceptChannel(timeout);

                if (channel == null)
                {
                    return(null);
                }

                return(new DuplexChannelBinder(channel, _correlator, _listener.Uri));
            }
Example #20
0
            public IChannelBinder Accept(TimeSpan timeout)
            {
                IReplySessionChannel channel = _listener.AcceptChannel(timeout);

                if (channel == null)
                {
                    return(null);
                }

                return(new ReplyChannelBinder(channel, _listener.Uri));
            }
Example #21
0
            public IChannelBinder Accept(TimeSpan timeout)
            {
                IInputSessionChannel channel = _listener.AcceptChannel(timeout);

                if (null == channel)
                {
                    return(null);
                }

                return(new InputChannelBinder(channel, _listener.Uri));
            }
Example #22
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();
        }
        public IChannelListenerPage()
        {
            InitializeComponent();
            ///监听者
            IChannelListener <IReplyChannel> listener = binding.BuildChannelListener <IReplyChannel>(new Uri("http://localhost:9090/RequestReplyService"), new BindingParameterCollection());

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

            replyChannel.Open();//打开IReplyChannel应答通道
        }
Example #24
0
        public override TChannel AcceptChannel(TimeSpan timeout)
        {
            TInnerChannel innerChannel = _innerListener.AcceptChannel(timeout);

            if (innerChannel == null)
            {
                return(null);
            }
            else
            {
                return(OnAcceptChannel(innerChannel));
            }
        }
Example #25
0
        static void Main(string[] args)
        {
            Uri     listenUri = new Uri("http://localhost:9999/listener");
            Binding binding   = new BasicHttpBinding();
            IChannelListener <SimpleReplyChannel> channelListener = binding.BuildChannelListener <SimpleReplyChannel>(listenUri);

            channelListener.Open();

            SimpleReplyChannel channel = channelListener.AcceptChannel(TimeSpan.MaxValue);

            channel.Open();

            Console.WriteLine("开始监听");
        }
Example #26
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();
            }
        }
Example #27
0
        public static void Snippet6()
        {
            MsmqIntegrationBindingElement msmqBindingElement = new MsmqIntegrationBindingElement();
            CustomBinding binding = new CustomBinding(msmqBindingElement);

            BindingParameterCollection bindingParameterCollection = new BindingParameterCollection();

            BindingContext bindingContext             = new BindingContext(binding, bindingParameterCollection);
            IChannelListener <IInputChannel> listener = msmqBindingElement.BuildChannelListener <IInputChannel>(bindingContext);

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

            channel.Open();
        }
Example #28
0
        void AcceptCallback(object state)
        {
            IChannelListener <IReplyChannel> listener = (IChannelListener <IReplyChannel>)state;

            this.acceptedChannel = listener.AcceptChannel(TimeSpan.MaxValue);
            if (this.acceptedChannel != null)
            {
                this.acceptedChannel.Open();
                ReceiveRequest(this.acceptedChannel);
            }
            else
            {
                listener.Close();
            }
        }
Example #29
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();
//			}
        }
Example #30
0
        private void ReceiveMessage <TObjectType>(TObjectType objectToMatch, AmqpProperties expectedProperties)
        {
            Uri receiveFromUri = new Uri("amqp:message_queue");
            IChannelListener <IInputChannel> listener = Util.GetBinding().BuildChannelListener <IInputChannel>(receiveFromUri, new BindingParameterCollection());

            listener.Open();
            IInputChannel service = listener.AcceptChannel(TimeSpan.FromSeconds(10));

            service.Open();
            Message receivedMessage = service.Receive(TimeSpan.FromSeconds(10));

            try
            {
                TObjectType receivedObject = receivedMessage.GetBody <TObjectType>();
                Assert.True(receivedObject.Equals(objectToMatch), "Original and deserialized objects do not match");

                AmqpProperties receivedProperties = (AmqpProperties)receivedMessage.Properties["AmqpProperties"];
                PropertyInfo[] propInfo           = typeof(AmqpProperties).GetProperties();

                for (int i = 0; i < propInfo.Length; i++)
                {
                    string propertyName = propInfo[i].Name;
                    if (propertyName.Equals("RoutingKey", StringComparison.InvariantCultureIgnoreCase))
                    {
                        Assert.AreEqual(RoutingKey, Convert.ToString(propInfo[i].GetValue(receivedProperties, null)));
                    }
                    else
                    {
                        Assert.AreEqual(Convert.ToString(propInfo[i].GetValue(expectedProperties, null)), Convert.ToString(propInfo[i].GetValue(receivedProperties, null)));
                    }
                }
            }
            catch (NullReferenceException)
            {
                Assert.Fail("Message not received");
            }
            catch (SerializationException)
            {
                Assert.Fail("Deserialized object not of correct type");
            }
            finally
            {
                receivedMessage.Close();
                service.Close();
                listener.Close();
            }
        }
Example #31
0
        private IReplyChannel OpenChannel(bool customBinding, out IChannelListener<IReplyChannel> listener)
        {
            var binding = TestServiceHost.CreateBinding(customBinding, new HttpMessageHandlerFactory(typeof(TestHandler)));
            listener = binding.BuildChannelListener<IReplyChannel>(TestServiceCommon.ServiceAddress);
            Assert.IsNotNull(listener);
            listener.Open();
            Assert.AreEqual(CommunicationState.Opened, listener.State);

            var channel = listener.AcceptChannel();
            Assert.IsNotNull(channel);
            channel.Open();
            Assert.AreEqual(CommunicationState.Opened, channel.State);

            return channel;
        }
Example #32
0
        private void AcceptChannelAndReceive(IChannelListener<IInputChannel> listener)
        {
            IInputChannel channel;
            TransactionScope transactionToAbortOnAccept = null;

            if (this.Parameters.AbortTxDatagramAccept)
            {
                transactionToAbortOnAccept = new TransactionScope(TransactionScopeOption.RequiresNew);
            }

            if (this.Parameters.AsyncAccept)
            {
                IAsyncResult result = listener.BeginAcceptChannel(null, null);
                channel = listener.EndAcceptChannel(result);
            }
            else
            {
                channel = listener.AcceptChannel();
            }

            if (this.Parameters.AbortTxDatagramAccept)
            {
                transactionToAbortOnAccept.Dispose();
            }

            channel.Open();
            Message message;

            if (this.Parameters.CloseListenerEarly)
            {
                listener.Close();
            }

            try
            {
                using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew))
                {
                    Message firstMessage = channel.Receive(this.Parameters.ReceiveTimeout);

                    lock (this.Results)
                    {
                        this.Results.Add(String.Format("Received message with Action '{0}'", firstMessage.Headers.Action));
                    }

                    ts.Complete();
                }
            }
            catch (TimeoutException)
            {
                lock (this.Results)
                {
                    this.Results.Add("Receive timed out.");
                }

                channel.Abort();
                return;
            }

            AutoResetEvent doneReceiving = new AutoResetEvent(false);
            int threadsCompleted = 0;

            for (int i = 0; i < this.Parameters.NumberOfThreads; ++i)
            {
                ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object unused)
                {
                    do
                    {
                        if (this.Parameters.ReceiverShouldAbort)
                        {
                            this.ReceiveMessage(channel, false);
                            Thread.Sleep(200);
                        }

                        message = this.ReceiveMessage(channel, true);
                    }
                    while (message != null);

                    if (Interlocked.Increment(ref threadsCompleted) == this.Parameters.NumberOfThreads)
                    {
                        doneReceiving.Set();
                    }
                }));
            }

            TimeSpan threadTimeout = TimeSpan.FromMinutes(2.0);
            if (!doneReceiving.WaitOne(threadTimeout, false))
            {
                this.Results.Add(String.Format("Threads did not complete within {0}.", threadTimeout));
            }

            channel.Close();
        }