Send() private method

private Send ( Amqp.Message message, Amqp.Framing.DeliveryState deliveryState, OutcomeCallback callback, object state ) : void
message Amqp.Message
deliveryState Amqp.Framing.DeliveryState
callback OutcomeCallback
state object
return void
Exemplo n.º 1
0
        public void TransactedPosting()
        {
            string testName = "TransactedPosting";
            int nMsgs = 5;

            Connection connection = new Connection(this.address);
            Session session = new Session(connection);
            SenderLink sender = new SenderLink(session, "sender-" + testName, "q1");

            // commit
            using (var ts = new TransactionScope())
            {
                for (int i = 0; i < nMsgs; i++)
                {
                    Message message = new Message("test");
                    message.Properties = new Properties() { MessageId = "commit" + i, GroupId = testName };
                    sender.Send(message);
                }

                ts.Complete();
            }

            // rollback
            using (var ts = new TransactionScope())
            {
                for (int i = nMsgs; i < nMsgs * 2; i++)
                {
                    Message message = new Message("test");
                    message.Properties = new Properties() { MessageId = "rollback" + i, GroupId = testName };
                    sender.Send(message);
                }
            }

            // commit
            using (var ts = new TransactionScope())
            {
                for (int i = 0; i < nMsgs; i++)
                {
                    Message message = new Message("test");
                    message.Properties = new Properties() { MessageId = "commit" + i, GroupId = testName };
                    sender.Send(message);
                }

                ts.Complete();
            }

            ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1");
            for (int i = 0; i < nMsgs * 2; i++)
            {
                Message message = receiver.Receive();
                Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.Properties.MessageId);
                receiver.Accept(message);
                Assert.IsTrue(message.Properties.MessageId.StartsWith("commit"));
            }

            connection.Close();
        }
Exemplo n.º 2
0
        public void TestMethod_BasicSendReceive()
        {
            string testName = "BasicSendReceive";
            const int nMsgs = 200;
            Connection connection = new Connection(testTarget.Address);
            Session session = new Session(connection);
            SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);

            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = new Message("msg" + i);
                message.Properties = new Properties() { GroupId = "abcdefg" };
                message.ApplicationProperties = new ApplicationProperties();
                message.ApplicationProperties["sn"] = i;
                sender.Send(message, null, null);
            }

            ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = receiver.Receive();
                Trace.WriteLine(TraceLevel.Verbose, "receive: {0}", message.ApplicationProperties["sn"]);
                receiver.Accept(message);
            }
            
            sender.Close();
            receiver.Close();
            session.Close();
            connection.Close();
        }
Exemplo n.º 3
0
        static void Main(string[] args)
        {
            //Create host and register custom transport listener
            var uri = new Uri(address);
            var host = new ContainerHost(new List<Uri>() { uri }, null, uri.UserInfo);
            host.CustomTransports.Add("pipe", NamedPipeTransport.Listener);
            host.RegisterMessageProcessor(nodeName, new MessageProcessor());
            host.Open();
            Console.WriteLine("Listener: running");

            //Create factory with custom transport factory
            var factory = new ConnectionFactory(new TransportProvider[] { NamedPipeTransport.Factory });
            var connection = factory.CreateAsync(new Address(address)).GetAwaiter().GetResult();
            var session = new Session(connection);
            var sender = new SenderLink(session, "message-client", nodeName);
            Console.WriteLine("Client: sending a message");
            sender.Send(new Message("Hello Pipe!"));
            sender.Close();
            session.Close();
            connection.Close();
            Console.WriteLine("Client: closed");

            host.Close();
            Console.WriteLine("Listener: closed");
        }
Exemplo n.º 4
0
        static void Main(string[] args)
        {
            string brokerUrl = "amqp://localhost:5672";
              string address   = "my_queue";

              Address    brokerAddr = new Address(brokerUrl);
              Connection connection = new Connection(brokerAddr);
              Session    session    = new Session(connection);

              SenderLink   sender   = new   SenderLink(session, "sender",   address);
              ReceiverLink receiver = new ReceiverLink(session, "receiver", address);

              Message helloOut = new Message("Hello World!");
              sender.Send(helloOut);

              Message helloIn = receiver.Receive();
              receiver.Accept(helloIn);

              Console.WriteLine(helloIn.Body.ToString());

              receiver.Close();
              sender.Close();
              session.Close();
              connection.Close();
        }
Exemplo n.º 5
0
        public void SendData(string data)
        {
            if (_connection == null)
            {
                Connect();
            }

            Amqp.Message message = new Amqp.Message()
            {
                BodySection = new Amqp.Framing.Data()
                {
                    Binary = System.Text.Encoding.UTF8.GetBytes(data)
                }
            };

            ManualResetEvent acked = new ManualResetEvent(false);

            message.MessageAnnotations = new Amqp.Framing.MessageAnnotations();
            message.MessageAnnotations[new Amqp.Types.Symbol("x-opt-partition-key")] =
                string.Format("pk:", _partitionkey);

            try {
                _senderlink.Send(message);
            } catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Sending failed");
                _connection = null;
            }
        }
Exemplo n.º 6
0
        public void CloseConnectionWithDetachTest()
        {
            this.testListener.RegisterTarget(TestPoint.Close, (stream, channel, fields) =>
            {
                // send a detach
                TestListener.FRM(stream, 0x16UL, 0, channel, 0u, true);
                return TestOutcome.Continue;
            });

            string testName = "CloseConnectionWithDetachTest";

            Trace.WriteLine(TraceLevel.Information, "sync test");
            {
                Connection connection = new Connection(this.address);
                Session session = new Session(connection);
                SenderLink sender = new SenderLink(session, "sender-" + testName, "any");
                sender.Send(new Message("test") { Properties = new Properties() { MessageId = testName } });
                connection.Close();
                Assert.IsTrue(connection.Error == null, "connection has error!" + connection.Error);
            }

            Trace.WriteLine(TraceLevel.Information, "async test");
            Task.Factory.StartNew(async () =>
            {
                Connection connection = await Connection.Factory.CreateAsync(this.address);
                Session session = new Session(connection);
                SenderLink sender = new SenderLink(session, "sender-" + testName, "any");
                await sender.SendAsync(new Message("test") { Properties = new Properties() { MessageId = testName } });
                await connection.CloseAsync();
                Assert.IsTrue(connection.Error == null, "connection has error!" + connection.Error);

            }).Unwrap().GetAwaiter().GetResult();
        }
Exemplo n.º 7
0
        static void RunRequestClient(string address)
        {
            Connection connection = new Connection(new Address(address));
            Session session = new Session(connection);

            string replyTo = "client-reply-to";
            Attach recvAttach = new Attach()
            {
                Source = new Source() { Address = "request_processor" },
                Target = new Target() { Address = replyTo }
            };

            ReceiverLink receiver = new ReceiverLink(session, "request-client-receiver", recvAttach, null);
            SenderLink sender = new SenderLink(session, "request-client-sender", "request_processor");

            Message request = new Message("hello");
            request.Properties = new Properties() { MessageId = "request1", ReplyTo = replyTo };
            sender.Send(request, null, null);
            Console.WriteLine("Sent request {0} body {1}", request.Properties, request.Body);

            Message response = receiver.Receive();
            Console.WriteLine("Received response: {0} body {1}", response.Properties, response.Body);
            receiver.Accept(response);

            receiver.Close();
            sender.Close();
            session.Close();
            connection.Close();
        }
Exemplo n.º 8
0
        //
        // Sample invocation: Interop.Spout.exe --broker localhost:5672 --timeout 30 --address my-queue
        //
        static int Main(string[] args)
        {
            const int ERROR_SUCCESS = 0;
            const int ERROR_OTHER = 2;

            int exitCode = ERROR_SUCCESS;
            Connection connection = null;
            try
            {
                Options options = new Options(args);

                Address address = new Address(options.Url);
                connection = new Connection(address);
                Session session = new Session(connection);
                SenderLink sender = new SenderLink(session, "sender-spout", options.Address);
                // TODO: ReplyTo

                Stopwatch stopwatch = new Stopwatch();
                TimeSpan timespan = new TimeSpan(0, 0, options.Timeout);
                stopwatch.Start();
                for (int nSent = 0;
                    (0 == options.Count || nSent < options.Count) &&
                    (0 == options.Timeout || stopwatch.Elapsed <= timespan);
                    nSent++)
                {
                    string id = options.Id;
                    if (id.Equals(""))
                    {
                        Guid g = Guid.NewGuid();
                        id = g.ToString();
                    }
                    id += ":" + nSent.ToString();

                    Message message = new Message(options.Content);
                    message.Properties = new Properties() { MessageId = id };
                    sender.Send(message);
                    if (options.Print)
                    {
                        Console.WriteLine("Message(Properties={0}, ApplicationProperties={1}, Body={2}",
                                      message.Properties, message.ApplicationProperties, message.Body);
                    }
                }
                sender.Close();
                session.Close();
                connection.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception {0}.", e);
                if (null != connection)
                    connection.Close();
                exitCode = ERROR_OTHER;
            }
            return exitCode;
        }
Exemplo n.º 9
0
        protected void GetPartitions(Session session)
        {
            ReceiverLink receiverLink = null;
            SenderLink senderLink = null;

            try
            {
                // create a pair of links for request/response
                Trace.WriteLine(TraceLevel.Information, "Creating a request and a response link...");
                string clientNode = "client-temp-node";
                senderLink = new SenderLink(session, "mgmt-sender", "$management");
                receiverLink = new ReceiverLink(
                    session,
                    "mgmt-receiver",
                    new Attach()
                    {
                        Source = new Source() { Address = "$management" },
                        Target = new Target() { Address = clientNode }
                    },
                    null);

                var request = new Amqp.Message();
                request.Properties = new Properties() { MessageId = "request1", ReplyTo = clientNode };
                request.ApplicationProperties = new ApplicationProperties();
                request.ApplicationProperties["operation"] = "READ";
                request.ApplicationProperties["name"] = settings.EventHubName;
                request.ApplicationProperties["type"] = "com.microsoft:eventhub";
                senderLink.Send(request, null, null);

                var response = receiverLink.Receive(15000); // time out after 15 seconds
                if (response == null)
                {
                    throw new Exception("No get partitions response was received.");
                }

                receiverLink.Accept(response);

                Trace.WriteLine(TraceLevel.Information, "Partition info {0}", response.Body.ToString());
                var partitionStrings = (string[])((Map)response.Body)["partition_ids"];
                Trace.WriteLine(TraceLevel.Information, "Partitions {0}", string.Join(",", partitionStrings));
                this.partitions = new List<string>(partitionStrings);
            }
            catch (Exception x)
            {
                Trace.WriteLine(TraceLevel.Error, "Error retrieving partitions:\r\n{0}", x.ToString());
                throw x;
            }
            finally
            {
                if (receiverLink != null) receiverLink.Close();
                if (senderLink != null) senderLink.Close();
            }
        }
Exemplo n.º 10
0
        static string[] GetPartitions()
        {
            Trace.WriteLine(TraceLevel.Information, "Retrieving partitions...");
            Trace.WriteLine(TraceLevel.Information, "Establishing a connection...");
            Address address = new Address(sbNamespace, 5671, keyName, keyValue);
            Connection connection = new Connection(address);

            Trace.WriteLine(TraceLevel.Information, "Creating a session...");
            Session session = new Session(connection);

            // create a pair of links for request/response
            Trace.WriteLine(TraceLevel.Information, "Creating a request and a response link...");
            string clientNode = "client-temp-node";
            SenderLink sender = new SenderLink(session, "mgmt-sender", "$management");
            ReceiverLink receiver = new ReceiverLink(
                session,
                "mgmt-receiver",
                new Attach()
                {
                    Source = new Source() { Address = "$management" },
                    Target = new Target() { Address = clientNode }
                },
                null);

            Message request = new Message();
            request.Properties = new Properties() { MessageId = "request1", ReplyTo = clientNode };
            request.ApplicationProperties = new ApplicationProperties();
            request.ApplicationProperties["operation"] = "READ";
            request.ApplicationProperties["name"] = entity;
            request.ApplicationProperties["type"] = "com.microsoft:eventhub";
            sender.Send(request, null, null);

            Message response = receiver.Receive();
            if (response == null)
            {
                throw new Exception("No response was received.");
            }

            receiver.Accept(response);
            receiver.Close();
            sender.Close();
            connection.Close();

            Trace.WriteLine(TraceLevel.Information, "Partition info {0}", response.Body.ToString());
            string[] partitions = (string[])((Map)response.Body)["partition_ids"];
            Trace.WriteLine(TraceLevel.Information, "Partitions {0}", string.Join(",", partitions));
            Trace.WriteLine(TraceLevel.Information, "");

            return partitions;
        }
Exemplo n.º 11
0
        public void ContainerHostCloseTest()
        {
            string name = MethodInfo.GetCurrentMethod().Name;
            this.host.RegisterMessageProcessor(name, new TestMessageProcessor());

            //Create a client to send data to the host message processor
            var closedEvent = new ManualResetEvent(false);
            var connection = new Connection(Address);
            connection.Closed += (AmqpObject obj, Error error) =>
            {
                closedEvent.Set();
            };

            var session = new Session(connection);
            var sender = new SenderLink(session, "sender-link", name);

            //Send one message while the host is open
            sender.Send(new Message("Hello"), SendTimeout);

            //Close the host. this should close existing connections
            this.host.Close();

            Assert.IsTrue(closedEvent.WaitOne(10000), "connection is not closed after host is closed.");

            try
            {
                sender.Send(new Message("test"));
                Assert.IsTrue(false, "exception not thrown");
            }
            catch (AmqpException exception)
            {
                Assert.IsTrue(exception.Error != null, "Error is null");
                Assert.AreEqual((Symbol)ErrorCode.ConnectionForced, exception.Error.Condition, "Wrong error code");
            }

            connection.Close();

            // Reopen the host and send again
            this.host = new ContainerHost(new List<Uri>() { Uri }, null, Uri.UserInfo);
            this.host.RegisterMessageProcessor(name, new TestMessageProcessor());
            this.host.Open();

            connection = new Connection(Address);
            session = new Session(connection);
            sender = new SenderLink(session, "sender-link", name);
            sender.Send(new Message("Hello"), SendTimeout);
            connection.Close();
        }
Exemplo n.º 12
0
        public void CloseConnectionWithEndTest()
        {
            this.testListener.RegisterTarget(TestPoint.Close, (stream, channel, fields) =>
            {
                // send an end
                TestListener.FRM(stream, 0x17UL, 0, channel);
                return TestOutcome.Continue;
            });

            string testName = "CloseConnectionWithEndTest";
            Connection connection = new Connection(new Address("amqp://localhost:" + port));
            Session session = new Session(connection);
            SenderLink sender = new SenderLink(session, "sender-" + testName, "any");
            sender.Send(new Message("test") { Properties = new Properties() { MessageId = testName } });
            connection.Close();
            Assert.IsTrue(connection.Error == null, "connection has error!" + connection.Error);
        }
Exemplo n.º 13
0
        public void Send(OutgoingTransportMessage transportMessage, IEnumerable<string> addresses)
        {
            var messageBuffer = messageEncoder.Encode(transportMessage.Message);

            var message = new Message(messageBuffer);
            message.Header = new Header();
            message.Header.Durable = true;
            message.Properties = new Properties();
            message.Properties.CreationTime = DateTime.UtcNow;
            message.Properties.MessageId = Guid.NewGuid().ToString();
            message.Properties.ReplyTo = "TODO";
            message.ApplicationProperties = new ApplicationProperties();
            message.ApplicationProperties["LightRail.ContentType"] = messageEncoder.ContentType;
            message.ApplicationProperties["LightRail.EnclosedMessageTypes"] = string.Join(",", messageMapper.GetEnclosedMessageTypes(transportMessage.Message.GetType()).Distinct());
            foreach (var pair in transportMessage.Headers)
            {
                message.ApplicationProperties[pair.Key] = pair.Value;
            }

            var connection = new Connection(amqpAddress);
            var session = new Session(connection);
            // Azure does not support Amqp transactions "The server was unable to process the request; please retry the operation. If the problem persists, please contact your Service Bus administrator and provide the tracking id..TrackingId:583da4f8d58d4fa59dc9521c6f799cb8_GWIN-AN5B307EEHM,TimeStamp:11.7.2014. 7:44:17"
            try
            {
                foreach (var address in addresses)
                {
                    logger.Info("Sending Message {0} to {1}", message.Properties.MessageId, address);
                    var senderLink = new SenderLink(session, Guid.NewGuid().ToString(), address);
                    try
                    {
                        senderLink.Send(message);
                    }
                    finally
                    {
                        senderLink.Close();
                    }
                }
            }
            finally
            {
                session.Close();
                connection.Close();
            }
        }
Exemplo n.º 14
0
        static void RunMessageClient(string address)
        {
            const int nMsgs = 10;
            Connection connection = new Connection(new Address(address));
            Session session = new Session(connection);
            SenderLink sender = new SenderLink(session, "message-client", "message_processor");

            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = new Message("hello");
                message.Properties = new Properties() { MessageId = "msg" + i };
                message.ApplicationProperties = new ApplicationProperties();
                message.ApplicationProperties["sn"] = i;
                sender.Send(message);
                Console.WriteLine("Sent message {0} body {1}", message.Properties, message.Body);
            }

            sender.Close();
            session.Close();
            connection.Close();
        }
Exemplo n.º 15
0
        string[] GetPartitions()
        {
            Address address = new Address(sbNamespace, 5671, ReckeyName, ReckeyValue);
            Connection connection = new Connection(address);
            Session session = new Session(connection);

            // create a pair of links for request/response
            string clientNode = "client-temp-node";
            SenderLink sender = new SenderLink(session, "mgmt-sender", "$management");
            ReceiverLink receiver = new ReceiverLink(
                session,
                "mgmt-receiver",
                new Attach()
                {
                    Source = new Source() { Address = "$management" },
                    Target = new Target() { Address = clientNode }
                },
                null);

            Message request = new Message();
            request.Properties = new Properties() { MessageId = "request1", ReplyTo = clientNode };
            request.ApplicationProperties = new ApplicationProperties();
            request.ApplicationProperties["operation"] = "READ";
            request.ApplicationProperties["name"] = entity;
            request.ApplicationProperties["type"] = "com.microsoft:eventhub";
            sender.Send(request, null, null);

            Message response = receiver.Receive();
            if (response == null)
            {
                throw new Exception("No response was received.");
            }
            receiver.Accept(response);
            receiver.Close();
            sender.Close();
            connection.Close();
            string[] partitions = (string[])((Map)response.Body)["partition_ids"];
            return partitions;
        }
Exemplo n.º 16
0
        static void Main(string[] args)
        {
            //Create host and register message processor
            var uri = new Uri(Address);
            var host = new ContainerHost(new List<Uri>() { uri }, null, uri.UserInfo);
            host.RegisterMessageProcessor(MsgProcName, new MessageProcessor());
            host.Open();

            //Create client
            var connection = new Connection(new Address(Address));
            var session = new Session(connection);
            var sender = new SenderLink(session, "message-client", MsgProcName);

            //Send message with an object of custom type as the body
            var person = new Person() { EyeColor = "brown", Height = 175, Weight = 75 };
            sender.Send(new Message(person));

            sender.Close();
            session.Close();
            connection.Close();

            host.Close();
        }
Exemplo n.º 17
0
        static void Main(string[] args)
        {
            //Trace.TraceLevel = TraceLevel.Frame;
            //Trace.TraceListener = (f, a) => Console.WriteLine(DateTime.Now.ToString("[hh:ss.fff]") + " " + string.Format(f, a));

            string address = "amqps://localhost:5671";

            // start a host with custom SSL and SASL settings
            Console.WriteLine("Starting server...");
            Uri addressUri = new Uri(address);
            ContainerHost host = new ContainerHost(addressUri);
            var listener = host.Listeners[0];
            listener.SSL.Certificate = GetCertificate("localhost");
            listener.SSL.ClientCertificateRequired = true;
            listener.SSL.RemoteCertificateValidationCallback = ValidateServerCertificate;
            listener.SASL.EnableExternalMechanism = true;
            host.Open();
            Console.WriteLine("Container host is listening on {0}:{1}", addressUri.Host, addressUri.Port);

            string messageProcessor = "message_processor";
            host.RegisterMessageProcessor(messageProcessor, new MessageProcessor());
            Console.WriteLine("Message processor is registered on {0}", messageProcessor);

            Console.WriteLine("Starting client...");
            ConnectionFactory factory = new ConnectionFactory();
            factory.SSL.ClientCertificates.Add(GetCertificate("localhost"));
            factory.SSL.RemoteCertificateValidationCallback = ValidateServerCertificate;
            factory.SASL.Profile = SaslProfile.External;
            Console.WriteLine("Sending message...");
            Connection connection = factory.CreateAsync(new Address(address)).Result;
            Session session = new Session(connection);
            SenderLink sender = new SenderLink(session, "certificate-example-sender", "message_processor");
            sender.Send(new Message("hello world"));
            sender.Close();
            session.Close();
            connection.Close();
            Console.WriteLine("client done");

            host.Close();
            Console.WriteLine("server stopped");
        }
Exemplo n.º 18
0
        public void TestMethod_ConnectionFrameSize()
        {
            string testName = "ConnectionFrameSize";
            const int nMsgs = 200;
            int frameSize = 4 * 1024;
            Connection connection = new Connection(testTarget.Address, null, new Open() { ContainerId = "c1", MaxFrameSize = (uint)frameSize }, null);
            Session session = new Session(connection);
            SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);

            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = new Message(new string('A', frameSize + (i - nMsgs / 2)));
                sender.Send(message, null, null);
            }

            ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = receiver.Receive();
                string value = (string)message.Body;
                Trace.WriteLine(TraceLevel.Verbose, "receive: {0}x{1}", value[0], value.Length);
                receiver.Accept(message);
            }

            sender.Close();
            receiver.Close();
            session.Close();
            connection.Close();
        }
Exemplo n.º 19
0
        public void TestMethod_LinkReopen()
        {
            string testName = "LinkReopen";

            Connection connection = new Connection(testTarget.Address);
            Session session = new Session(connection);
            SenderLink sender = new SenderLink(session, "sender", testTarget.Path);
            sender.Send(new Message("test") { Properties = new Properties() { MessageId = testName } });
            sender.Close();

            sender = new SenderLink(session, "sender", testTarget.Path);
            sender.Send(new Message("test2") { Properties = new Properties() { MessageId = testName } });
            sender.Close();

            ReceiverLink receiver = new ReceiverLink(session, "receiver", testTarget.Path);
            for (int i = 1; i <= 2; i++)
            {
                var m = receiver.Receive();
                Assert.IsTrue(m != null, "Didn't receive message " + i);
                receiver.Accept(m);
            }

            session.Close(0);
            connection.Close();
            Assert.IsTrue(connection.Error == null, "connection has error!");
        }
Exemplo n.º 20
0
        public void TestMethod_SendEmptyMessage()
        {
            string testName = "SendEmptyMessage";

            Connection connection = new Connection(testTarget.Address);
            Session session = new Session(connection);
            SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);

            bool threwArgEx = false;
            try
            {
                sender.Send(new Message());
            }
            catch (ArgumentException)
            {
                threwArgEx = true;
            }
            finally
            {
                sender.Close();
                session.Close();
                connection.Close();
            }

            Assert.IsTrue(threwArgEx, "Should throw an argument exception when sending an empty message.");
        }
Exemplo n.º 21
0
 public SendTask(SenderLink link, Message message, DeliveryState state, TimeSpan timeout)
 {
     this.timer = new Timer(onTimer, this, (int)timeout.TotalMilliseconds, -1);
     link.Send(message, state, onOutcome, this);
 }
Exemplo n.º 22
0
        public void ContainerHostUnknownProcessorTest()
        {
            string name = MethodInfo.GetCurrentMethod().Name;
            this.host.RegisterMessageProcessor("message" + name, new TestMessageProcessor());
            this.host.RegisterRequestProcessor("request" + name, new TestRequestProcessor());

            var connection = new Connection(Address);
            var session = new Session(connection);
            var sender = new SenderLink(session, "send-link", name);

            try
            {
                sender.Send(new Message("test"));
                Assert.IsTrue(false, "exception not thrown");
            }
            catch(AmqpException exception)
            {
                Assert.IsTrue(exception.Error != null, "Error is null");
                Assert.AreEqual((Symbol)ErrorCode.NotFound, exception.Error.Condition, "Wrong error code");
            }

            sender.Close();
            session.Close();
            connection.Close();
        }
Exemplo n.º 23
0
        public void ContainerHostRequestProcessorTest()
        {
            string name = MethodInfo.GetCurrentMethod().Name;
            var processor = new TestRequestProcessor();
            this.host.RegisterRequestProcessor(name, processor);

            int count = 500;
            var connection = new Connection(Address);
            var session = new Session(connection);

            string replyTo = "client-reply-to";
            Attach recvAttach = new Attach()
            {
                Source = new Source() { Address = name },
                Target = new Target() { Address = replyTo }
            };

            var doneEvent = new ManualResetEvent(false);
            List<string> responses = new List<string>();
            ReceiverLink receiver = new ReceiverLink(session, "request-client-receiver", recvAttach, null);
            receiver.Start(
                20,
                (link, message) =>
                {
                    responses.Add(message.GetBody<string>());
                    link.Accept(message);
                    if (responses.Count == count)
                    {
                        doneEvent.Set();
                    }
                });

            SenderLink sender = new SenderLink(session, "request-client-sender", name);
            for (int i = 0; i < count; i++)
            {
                Message request = new Message("Hello");
                request.Properties = new Properties() { MessageId = "request" + i, ReplyTo = replyTo };
                sender.Send(request, SendTimeout);
            }

            Assert.IsTrue(doneEvent.WaitOne(10000), "Not completed in time");

            receiver.Close();
            sender.Close();
            session.Close();
            connection.Close();

            Assert.AreEqual(count, processor.TotalCount);
            Assert.AreEqual(count, responses.Count);
            for (int i = 1; i <= count; i++)
            {
                Assert.AreEqual("OK" + i, responses[i - 1]);
            }
        }
Exemplo n.º 24
0
        public void TestMethod_DynamicSenderLink()
        {
            string testName = "DynamicSenderLink";
            Connection connection = new Connection(testTarget.Address);
            Session session = new Session(connection);

            string targetAddress = null;
            OnAttached onAttached = (link, attach) =>
            {
                targetAddress = ((Target)attach.Target).Address;
            };

            SenderLink sender = new SenderLink(session, "sender-" + testName, new Target() { Dynamic = true }, onAttached);
            Message message = new Message("hello");
            sender.Send(message, 60000);

            Assert.IsTrue(targetAddress != null, "dynamic target not attached");
            ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, targetAddress);
            message = receiver.Receive();
            Assert.IsTrue(message != null, "no message was received.");
            receiver.Accept(message);

            sender.Close();
            receiver.Close();
            session.Close();
            connection.Close();
        }
Exemplo n.º 25
0
        public void TestMethod_SynchronousSend()
        {
            string testName = "SynchronousSend";
            Connection connection = new Connection(testTarget.Address);
            Session session = new Session(connection);
            SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
            Message message = new Message("hello");
            sender.Send(message, 60000);

            ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
            message = receiver.Receive();
            Assert.IsTrue(message != null, "no message was received.");
            receiver.Accept(message);

            sender.Close();
            receiver.Close();
            session.Close();
            connection.Close();
        }
Exemplo n.º 26
0
        public void ContainerHostMessageProcessorTest()
        {
            string name = MethodInfo.GetCurrentMethod().Name;
            var processor = new TestMessageProcessor();
            this.host.RegisterMessageProcessor(name, processor);

            int count = 500;
            var connection = new Connection(Address);
            var session = new Session(connection);
            var sender = new SenderLink(session, "send-link", name);

            for (int i = 0; i < count; i++)
            {
                var message = new Message("msg" + i);
                message.Properties = new Properties() { GroupId = name };
                sender.Send(message, SendTimeout);
            }

            sender.Close();
            session.Close();
            connection.Close();

            Assert.AreEqual(count, processor.Messages.Count);
            for (int i = 0; i < count; i++)
            {
                var message = processor.Messages[i];
                Assert.AreEqual("msg" + i, message.GetBody<string>());
            }
        }
Exemplo n.º 27
0
        public void ContainerHostProcessorOrderTest()
        {
            string name = MethodInfo.GetCurrentMethod().Name;
            this.host.RegisterMessageProcessor(name, new TestMessageProcessor());
            this.host.RegisterLinkProcessor(new TestLinkProcessor());

            int count = 80;
            var connection = new Connection(Address);
            var session = new Session(connection);
            var sender = new SenderLink(session, "send-link", name);

            for (int i = 0; i < count; i++)
            {
                var message = new Message("msg" + i);
                message.Properties = new Properties() { GroupId = name };
                sender.Send(message, SendTimeout);
            }

            sender.Close();

            sender = new SenderLink(session, "send-link", TestLinkProcessor.Name);
            for (int i = 0; i < count; i++)
            {
                var message = new Message("msg" + i);
                message.Properties = new Properties() { GroupId = name };
                sender.Send(message, SendTimeout);
            }

            sender.Close();
            session.Close();
            connection.Close();
        }
Exemplo n.º 28
0
        public void TestMethod_DynamicReceiverLink()
        {
            string testName = "DynamicReceiverLink";
            Connection connection = new Connection(testTarget.Address);
            Session session = new Session(connection);

            string remoteSource = null;
            ManualResetEvent attached = new ManualResetEvent(false);
            OnAttached onAttached = (link, attach) => { remoteSource = ((Source)attach.Source).Address; attached.Set(); };
            ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, new Source() { Dynamic = true }, onAttached);

            attached.WaitOne(10000);

            Assert.IsTrue(remoteSource != null, "dynamic source not attached");

            SenderLink sender = new SenderLink(session, "sender-" + testName, remoteSource);
            Message message = new Message("hello");
            sender.Send(message, 60000);

            message = receiver.Receive();
            Assert.IsTrue(message != null, "no message was received.");
            receiver.Accept(message);

            sender.Close();
            receiver.Close();
            session.Close();
            connection.Close();
        }
Exemplo n.º 29
0
        public void ContainerHostSessionFlowControlTest()
        {
            string name = MethodInfo.GetCurrentMethod().Name;
            this.host.RegisterMessageProcessor(name, new TestMessageProcessor(500000, null));

            // this test assumes that nMsgs is greater than session's window size
            int nMsgs = 10000;
            var connection = new Connection(Address);
            var session = new Session(connection);
            var sender = new SenderLink(session, "send-link", name);
            for (int i = 0; i < nMsgs; i++)
            {
                var message = new Message("msg" + i);
                message.Properties = new Properties() { GroupId = name };
                sender.Send(message, SendTimeout);
            }

            sender.Close();
            session.Close();
            connection.Close();
        }
Exemplo n.º 30
0
        public void TestMethod_RequestResponse()
        {
            string testName = "RequestResponse";
            Connection connection = new Connection(testTarget.Address);
            Session session = new Session(connection);

            // server app: the request handler
            ReceiverLink requestLink = new ReceiverLink(session, "srv.requester-" + testName, testTarget.Path);
            requestLink.Start(10, (l, m) =>
                {
                    l.Accept(m);

                    // got a request, send back a reply
                    SenderLink sender = new SenderLink(session, "srv.replier-" + testName, m.Properties.ReplyTo);
                    Message reply = new Message("received");
                    reply.Properties = new Properties() { CorrelationId = m.Properties.MessageId };
                    sender.Send(reply, (a, b, c) => ((Link)c).Close(0), sender);
                });

            // client: setup a temp queue and waits for responses
            OnAttached onAttached = (l, at) =>
                {
                    // client: sends a request to the request queue, specifies the temp queue as the reply queue
                    SenderLink sender = new SenderLink(session, "cli.requester-" + testName, testTarget.Path);
                    Message request = new Message("hello");
                    request.Properties = new Properties() { MessageId = "request1", ReplyTo = ((Source)at.Source).Address };
                    sender.Send(request, (a, b, c) => ((Link)c).Close(0), sender);
                };
            ReceiverLink responseLink = new ReceiverLink(session, "cli.responder-" + testName, new Source() { Dynamic = true }, onAttached);
            Message response = responseLink.Receive();
            Assert.IsTrue(response != null, "no response was received");
            responseLink.Accept(response);

            requestLink.Close();
            responseLink.Close();
            session.Close();
            connection.Close();
        }
Exemplo n.º 31
0
        public void TestMethod_LinkCloseWithPendingSend()
        {
            string testName = "LinkCloseWithPendingSend";
            Connection connection = new Connection(testTarget.Address);
            Session session = new Session(connection);
            SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);

            bool cancelled = false;
            Message message = new Message("released");
            sender.Send(message, (m, o, s) => cancelled = true, null);
            sender.Close(0);

            // assume that Close is called before connection/link is open so message is still queued in link
            // but this is not very reliable, so just do a best effort check
            if (cancelled)
            {
                Trace.WriteLine(TraceLevel.Verbose, "The send was cancelled as expected");
            }
            else
            {
                Trace.WriteLine(TraceLevel.Verbose, "The send was not cancelled as expected. This can happen if close call loses the race");
            }

            try
            {
                message = new Message("failed");
                sender.Send(message, (m, o, s) => cancelled = true, null);
                Assert.IsTrue(false, "Send should fail after link is closed");
            }
            catch (AmqpException exception)
            {
                Trace.WriteLine(TraceLevel.Verbose, "Caught exception: ", exception.Error);
            }

            session.Close();
            connection.Close();
        }
Exemplo n.º 32
0
        public void TestMethod_AdvancedLinkFlowControl()
        {
            string testName = "AdvancedLinkFlowControl";
            int nMsgs = 20;
            Connection connection = new Connection(testTarget.Address);
            Session session = new Session(connection);

            SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);
            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = new Message();
                message.Properties = new Properties() { MessageId = "msg" + i };
                sender.Send(message, null, null);
            }

            ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
            receiver.SetCredit(2, false);
            Message m1 = receiver.Receive();
            Message m2 = receiver.Receive();
            Assert.AreEqual("msg0", m1.Properties.MessageId);
            Assert.AreEqual("msg1", m2.Properties.MessageId);
            receiver.Accept(m1);
            receiver.Accept(m2);

            ReceiverLink receiver2 = new ReceiverLink(session, "receiver2-" + testName, testTarget.Path);
            receiver2.SetCredit(2, false);
            Message m3 = receiver2.Receive();
            Message m4 = receiver2.Receive();
            Assert.AreEqual("msg2", m3.Properties.MessageId);
            Assert.AreEqual("msg3", m4.Properties.MessageId);
            receiver2.Accept(m3);
            receiver2.Accept(m4);

            receiver.SetCredit(4);
            for (int i = 4; i < nMsgs; i++)
            {
                Message m = receiver.Receive();
                Assert.AreEqual("msg" + i, m.Properties.MessageId);
                receiver.Accept(m);
            }

            sender.Close();
            receiver.Close();
            receiver2.Close();
            session.Close();
            connection.Close();
        }