The Session class represents an AMQP session.
Inheritance: Amqp.AmqpObject
Beispiel #1
0
 /// <summary>
 /// Initializes a sender link.
 /// </summary>
 /// <param name="session">The session within which to create the link.</param>
 /// <param name="name">The link name.</param>
 /// <param name="attach">The attach frame to send for this link.</param>
 /// <param name="onAttached">The callback to invoke when an attach is received from peer.</param>
 public SenderLink(Session session, string name, Attach attach, OnAttached onAttached)
     : base(session, name, onAttached)
 {
     this.settleMode = attach.SndSettleMode;
     this.outgoingList = new LinkedList();
     this.SendAttach(false, this.deliveryCount, attach);
 }
        public async Task WebSocketSendReceiveAsync()
        {
            string testName = "WebSocketSendReceiveAsync";

            // assuming it matches the broker's setup and port is not taken
            Address wsAddress = new Address("ws://*****:*****@localhost:18080");
            int nMsgs = 50;

            Connection connection = await Connection.Factory.CreateAsync(wsAddress);
            Session session = new Session(connection);
            SenderLink sender = new SenderLink(session, "sender-" + testName, "q1");

            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = new Message();
                message.Properties = new Properties() { MessageId = "msg" + i, GroupId = testName };
                message.ApplicationProperties = new ApplicationProperties();
                message.ApplicationProperties["sn"] = i;
                await sender.SendAsync(message);
            }

            ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "q1");
            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = await receiver.ReceiveAsync();
                Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.ApplicationProperties["sn"]);
                receiver.Accept(message);
            }

            await sender.CloseAsync();
            await receiver.CloseAsync();
            await session.CloseAsync();
            await connection.CloseAsync();
        }
Beispiel #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");
        }
Beispiel #4
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();
        }
Beispiel #5
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();
        }
Beispiel #6
0
        public async Task CustomMessgeBody()
        {
            string testName = "CustomMessgeBody";

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

            Student student = new Student("Tom");
            student.Age = 16;
            student.Address = new StreetAddress() { FullAddress = "100 Main St. Small Town" };
            student.DateOfBirth = new System.DateTime(1988, 5, 1, 1, 2, 3, 100, System.DateTimeKind.Utc);

            Message message = new Message(student);
            message.Properties = new Properties() { MessageId = "student" };
            await sender.SendAsync(message);

            ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
            Message message2 = await receiver.ReceiveAsync();
            Trace.WriteLine(TraceLevel.Information, "receive: {0}", message2.Properties);
            receiver.Accept(message);

            await sender.CloseAsync();
            await receiver.CloseAsync();
            await session.CloseAsync();
            await connection.CloseAsync();

            Student student2 = message2.GetBody<Student>();
            Assert.AreEqual(student.Age, student2.Age - 1); // incremented in OnDeserialized
            Assert.AreEqual(student.DateOfBirth, student2.DateOfBirth);
            Assert.AreEqual(student.Address.FullAddress, student2.Address.FullAddress);
        }
        async Task RunSampleAsync()
        {
            ConnectionFactory factory = new ConnectionFactory();
            factory.SASL.Profile = SaslProfile.External;

            Trace.WriteLine(TraceLevel.Information, "Establishing a connection...");
            Address address = new Address(this.Namespace, 5671, null, null, "/", "amqps");
            var connection = await factory.CreateAsync(address);

            // before any operation can be performed, a token must be put to the $cbs node
            Trace.WriteLine(TraceLevel.Information, "Putting a token to the $cbs node...");
            await PutTokenAsync(connection);

            Trace.WriteLine(TraceLevel.Information, "Sending a message...");
            var session = new Session(connection);
            var sender = new SenderLink(session, "ServiceBus.Cbs:sender-link", this.Entity);
            await sender.SendAsync(new Message("test"));
            await sender.CloseAsync();

            Trace.WriteLine(TraceLevel.Information, "Receiving the message back...");
            var receiver = new ReceiverLink(session, "ServiceBus.Cbs:receiver-link", this.Entity);
            var message = await receiver.ReceiveAsync();
            receiver.Accept(message);
            await receiver.CloseAsync();

            Trace.WriteLine(TraceLevel.Information, "Closing the connection...");
            await session.CloseAsync();
            await connection.CloseAsync();
        }
Beispiel #8
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();
        }
Beispiel #9
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();
        }
Beispiel #10
0
        public void PerfAtLeastOnceSend()
        {
            string testName = "PerfAtLeastOnceSend";
            Connection connection = new Connection(address);
            Session session = new Session(connection);
            this.sender = new SenderLink(session, "sender-" + testName, "q1");

            this.onOutcome = OnSendComplete;
            this.done = new ManualResetEvent(false);
            this.totalCount = 1000000;
            this.completedCount = 0;
            this.initialCount = 300;
            this.batchCount = 100;
            Trace.TraceLevel = TraceLevel.Information;

            var watch = new System.Diagnostics.Stopwatch();
            watch.Start();

            this.SendMessages(initialCount);

            this.done.WaitOne();
            watch.Stop();
            Trace.WriteLine(TraceLevel.Information, "total: {0}, time: {1}ms", this.totalCount, watch.ElapsedMilliseconds);

            connection.Close();
        }
Beispiel #11
0
        public static void Main()
        {
            // write your code here

            // wait for DHCP-allocated IP address
            // while (IPAddress.GetDefaultLocalAddress() == IPAddress.Any) ;

            // wait for network connectivity
            // while (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()) ;

            Microsoft.SPOT.Net.NetworkInformation.NetworkChange.NetworkAvailabilityChanged += NetworkChange_NetworkAvailabilityChanged;
            Microsoft.SPOT.Net.NetworkInformation.NetworkChange.NetworkAddressChanged += NetworkChange_NetworkAddressChanged;

            networkAvailableEvent.WaitOne();
            Debug.Print("link is up!");
            networkAddressChangedEvent.WaitOne();
            Debug.Print("address acquired: " + Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IPAddress);

            Debug.Print("\r\n*** GET NETWORK INTERFACE SETTINGS ***");
            Microsoft.SPOT.Net.NetworkInformation.NetworkInterface[] networkInterfaces = Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
            Debug.Print("Found " + networkInterfaces.Length + " network interfaces.");

            // get date/time via NTP
            DateTime dateTime = MFToolkit.Net.Ntp.NtpClient.GetNetworkTime();
            Utility.SetLocalTime(dateTime);

            Amqp.Trace.TraceLevel = Amqp.TraceLevel.Frame | Amqp.TraceLevel.Verbose;
            #if NETMF
            Amqp.Trace.TraceListener = (f, a) => Debug.Print(DateTime.Now.ToString("[hh:ss.fff]") + " " + Fx.Format(f, a));
            #else
            Amqp.Trace.TraceListener = (f, a) => System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString("[hh:ss.fff]") + " " + Fx.Format(f, a));
            #endif
            address = new Address(HOST, PORT, null, null);
            connection = new Connection(address);

            string audience = Fx.Format("/devices/{0}/events", DEVICE_ID);
            string resourceUri = Fx.Format("{0}/devices/{1}", HOST, DEVICE_ID);

            string sasToken = GetSharedAccessSignature(null, DEVICE_KEY, resourceUri, new TimeSpan(1, 0, 0));
            bool cbs = PutCbsToken(connection, HOST, sasToken, audience);

            if (cbs)
            {
                session = new Session(connection);

                SendEvent();
                receiverThread = new Thread(ReceiveCommands);
                receiverThread.Start();
            }

            // just as example ...
            // the application ends only after received a command or timeout on receiving
            receiverThread.Join();

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

            Thread.Sleep(Timeout.Infinite);
        }
Beispiel #12
0
 /// <summary>
 /// Initializes a receiver link.
 /// </summary>
 /// <param name="session">The session within which to create the link.</param>
 /// <param name="name">The link name.</param>
 /// <param name="attach">The attach frame to send for this link.</param>
 /// <param name="onAttached">The callback to invoke when an attach is received from peer.</param>
 public ReceiverLink(Session session, string name, Attach attach, OnAttached onAttached)
     : base(session, name, onAttached)
 {
     this.totalCredit = -1;
     this.receivedMessages = new LinkedList();
     this.waiterList = new LinkedList();
     this.SendAttach(true, 0, attach);
 }
Beispiel #13
0
 /// <summary>
 /// Initializes the link.
 /// </summary>
 /// <param name="session">The session.</param>
 /// <param name="name">The link name.</param>
 /// <param name="onAttached">The callback to handle received attach.</param>
 protected Link(Session session, string name, OnAttached onAttached)
 {
     this.session = session;
     this.name = name;
     this.onAttached = onAttached;
     this.handle = session.AddLink(this);
     this.state = LinkState.Start;
 }
        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();
        }
        //
        // 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;
        }
Beispiel #16
0
        void Connect()
        {
            _address = new Amqp.Address(
                string.Format("{0}.servicebus.windows.net", _servicebusNamespace),
                5671, _saPolicyName, _saKey);

            _connection = new Amqp.Connection(_address);
            _session    = new Amqp.Session(_connection);
            _senderlink = new Amqp.SenderLink(_session,
                                              string.Format("send-link:{0}", _saPolicyName), _eventHubName);
        }
Beispiel #17
0
        /// <summary>
        /// Creates the transport
        /// </summary>
        public AmqpLiteTransport(string inputQueueName) : base(inputQueueName)
        {
            amqpAddress = new AmqpLite.Address("rebustest.servicebus.windows.net", 5671, "rebustest", "SomeSecretKey");
            amqpConnection = new AmqpLite.Connection(amqpAddress);
            amqpSession = new AmqpLite.Session(amqpConnection);

            if (inputQueueName != null)
            {
                amqpReceiver = new AmqpLite.ReceiverLink(amqpSession, "rebus-receiver", inputQueueName);
            }
        }
        //
        // Sample invocation: Interop.Drain.exe --broker localhost:5672 --timeout 30 --address my-queue
        //
        static int Main(string[] args)
        {
            const int ERROR_SUCCESS = 0;
            const int ERROR_NO_MESSAGE = 1;
            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);
                ReceiverLink receiver = new ReceiverLink(session, "receiver-drain", options.Address);
                int timeout = int.MaxValue;
                if (!options.Forever)
                    timeout = 1000 * options.Timeout;
                Message message = new Message();
                int nReceived = 0;
                receiver.SetCredit(options.InitialCredit);
                while ((message = receiver.Receive(timeout)) != null)
                {
                    nReceived++;
                    if (!options.Quiet)
                    {
                        Console.WriteLine("Message(Properties={0}, ApplicationProperties={1}, Body={2}",
                                      message.Properties, message.ApplicationProperties, message.Body);
                    }
                    receiver.Accept(message);
                    if (options.Count > 0 && nReceived == options.Count)
                    {
                        break;
                    }
                }
                if (message == null)
                {
                    exitCode = ERROR_NO_MESSAGE;
                }
                receiver.Close();
                session.Close();
                connection.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception {0}.", e);
                if (null != connection)
                    connection.Close();
                exitCode = ERROR_OTHER;
            }
            return exitCode;
        }
Beispiel #19
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();
            }
        }
Beispiel #20
0
        public MainPage()
        {
            this.InitializeComponent();

            Amqp.Trace.TraceLevel = Amqp.TraceLevel.Frame | Amqp.TraceLevel.Verbose;
            Amqp.Trace.TraceListener = (f, a) => System.Diagnostics.Debug.WriteLine(DateTime.Now.ToString("[hh:ss.fff]") + " " + Fx.Format(f, a));

            address = new Address(HOST, PORT, null, null);
            connection = new Connection(address);

            session = new Session(connection);
        }
Beispiel #21
0
        public override void Send(BrokeredMessage brokeredMessage)
        {
            if (this.factory.OpenConnection())
            {
                if (this.session == null)
                {
                    this.session = new Session(this.factory.Connection);
                    this.link = new SenderLink(this.session, "amqp-send-link " + this.entity, entity);
                }

                Message message = brokeredMessage.ToAmqpMessage();
                this.link.Send(message);
            }
        }
Beispiel #22
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;
        }
Beispiel #23
0
        public SenderLink GetMessageSender(string topic)
        {
            if (_senders.ContainsKey(topic))
                return _senders[topic];

            Address address = new Address("amqp://*****:*****@localhost:5672");
            Connection connection = Connection.Factory.CreateAsync(address).Result;
            Session session = new Session(connection);
            SenderLink sender = new SenderLink(session, "sender", topic);

            _senders.TryAdd(topic, sender);
            sender.Closed += Sender_Closed;
            return sender;
        }
        async Task PutTokenAsync(Connection connection)
        {
            var session = new Session(connection);

            string cbsClientAddress = "cbs-client-reply-to";
            var cbsSender = new SenderLink(session, "cbs-sender", "$cbs");
            var receiverAttach = new Attach()
            {
                Source = new Source() { Address = "$cbs" },
                Target = new Target() { Address = cbsClientAddress }
            };
            var cbsReceiver = new ReceiverLink(session, "cbs-receiver", receiverAttach, null);
            var sasToken = GetSASToken(this.KeyName, this.KeyValue, string.Format("http://{0}/{1}", this.Namespace, this.Entity), TimeSpan.FromMinutes(20));
            Trace.WriteLine(TraceLevel.Information, " sas token: {0}", sasToken);

            // construct the put-token message
            var request = new Message(sasToken);
            request.Properties = new Properties();
            request.Properties.MessageId = "1";
            request.Properties.ReplyTo = cbsClientAddress;
            request.ApplicationProperties = new ApplicationProperties();
            request.ApplicationProperties["operation"] = "put-token";
            request.ApplicationProperties["type"] = "servicebus.windows.net:sastoken";
            request.ApplicationProperties["name"] = string.Format("amqp://{0}/{1}", this.Namespace, this.Entity);
            await cbsSender.SendAsync(request);
            Trace.WriteLine(TraceLevel.Information, " request: {0}", request.Properties);
            Trace.WriteLine(TraceLevel.Information, " request: {0}", request.ApplicationProperties);

            // receive the response
            var response = await cbsReceiver.ReceiveAsync();
            if (response == null || response.Properties == null || response.ApplicationProperties == null)
            {
                throw new Exception("invalid response received");
            }

            // validate message properties and status code.
            Trace.WriteLine(TraceLevel.Information, " response: {0}", response.Properties);
            Trace.WriteLine(TraceLevel.Information, " response: {0}", response.ApplicationProperties);
            int statusCode = (int)response.ApplicationProperties["status-code"];
            if (statusCode != (int)HttpStatusCode.Accepted && statusCode != (int)HttpStatusCode.OK)
            {
                throw new Exception("put-token message was not accepted. Error code: " + statusCode);
            }

            // the sender/receiver may be kept open for refreshing tokens
            await cbsSender.CloseAsync();
            await cbsReceiver.CloseAsync();
            await session.CloseAsync();
        }
        public async Task StartNewCup(Maker.Interfaces.DTOs.RequestCup requestCup)
        {
            Connection connection = await Connection.Factory.CreateAsync(await GetAmqpAddressAsync());

            Amqp.Session session = new Amqp.Session(connection);
            SenderLink   sender  = new SenderLink(session, "barista-sender", "StartNewCup");

            //create message
            Message message = new Message(JsonConvert.SerializeObject(requestCup));
            await sender.SendAsync(message);

            await sender.CloseAsync();

            await connection.CloseAsync();
        }
Beispiel #26
0
            void Setup()
            {
                this.connection = new Connection(new Address(address));
                this.session = new Session(connection);

                Attach recvAttach = new Attach()
                {
                    Source = new Source() { Address = "request_processor" },
                    Target = new Target() { Address = this.replyTo }
                };

                this.receiver = new ReceiverLink(session, "request-client-receiver", recvAttach, null);
                this.receiver.Start(300);
                this.sender = new SenderLink(session, "request-client-sender", "request_processor");
            }
        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();
        }
Beispiel #28
0
        private async Task BackgroundProcessing(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                try
                {
                    Connection connection = await Connection.Factory.CreateAsync(await GetAmqpAddressAsync());

                    Amqp.Session session  = new Amqp.Session(connection);
                    ReceiverLink receiver = new ReceiverLink(session, "coffeemachine-receiver", "StartNewCup");

                    //receive message
                    Message message = await receiver.ReceiveAsync();

                    if (message == null)
                    {
                        continue;
                    }


                    //handle message
                    _logger.LogInformation(message.ToString());
                    _logger.LogInformation(message.Body.ToString());
                    var requestCup = JsonConvert.DeserializeObject <RequestCup>(message.Body.ToString());
                    Maker.Controllers.MakerController.WorkingOrders.Add(new Order()
                    {
                        Id      = requestCup.Id,
                        Coffee  = requestCup.Coffee,
                        Started = DateTime.UtcNow
                    });

                    receiver.Accept(message);


                    await receiver.CloseAsync();

                    await session.CloseAsync();

                    await connection.CloseAsync();
                }
                catch (Exception ex)
                {
                    _logger.LogError(ex,
                                     ex.Message);
                }
            }
        }
Beispiel #29
0
        private static Message ReceiveMessage(string queue)
        {
            var connection = new Connection(new Address("localhost", 5672, "user", "pass", "/", "AMQP"));

            var session = new Amqp.Session(connection);

            Amqp.Framing.Attach rcvAttach = new Amqp.Framing.Attach()
            {
                Source = new Amqp.Framing.Source()
                {
                    Address = "/queue/" + queue,
                    Durable = 1
                },

                Target = new Amqp.Framing.Target()
                {
                    Durable = 1
                }
            };

            var receiver = new Amqp.ReceiverLink(session, "foo-receiver", rcvAttach, null);

            Amqp.Message amqpMessage = null;

            try
            {
                amqpMessage = receiver.Receive(new TimeSpan(0, 0, 5)); // wait - timeout 5 seconds

                if (amqpMessage == null)
                {
                    // nothing received - timeout expired
                    // queue is empty !
                    Console.WriteLine("No message received, queue is empty ...");
                    return(null);
                }
                else
                {
                    receiver.Accept(amqpMessage);
                    return(amqpMessage);
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    static async Task<int> SslConnectionTestAsync(string brokerUrl, string address, string certfile)
    {
      try
      {
        ConnectionFactory factory = new ConnectionFactory();
        factory.TCP.NoDelay = true;
        factory.TCP.SendBufferSize = 16 * 1024;
        factory.TCP.SendTimeout = 30000;
        factory.TCP.ReceiveBufferSize = 16 * 1024;
        factory.TCP.ReceiveTimeout = 30000;
          
        factory.SSL.RemoteCertificateValidationCallback = (a, b, c, d) => true;
        factory.SSL.ClientCertificates.Add(X509Certificate.CreateFromCertFile(certfile));
        factory.SSL.CheckCertificateRevocation = false;
          
        factory.AMQP.MaxFrameSize = 64 * 1024;
        factory.AMQP.HostName = "host.example.com";
        factory.AMQP.ContainerId = "amq.topic";
           
        Address sslAddress = new Address(brokerUrl);
        Connection connection = await factory.CreateAsync(sslAddress);

        Session session = new Session(connection);
        SenderLink sender = new SenderLink(session, "sender1", address);
        ReceiverLink receiver = new ReceiverLink(session, "helloworld-receiver", address);
           
        Message helloOut = new Message("Hello - using client cert");
        await sender.SendAsync(helloOut);

        Message helloIn = await receiver.ReceiveAsync();
        receiver.Accept(helloIn);

        await connection.CloseAsync();

        Console.WriteLine("{0}", helloIn.Body.ToString());

        Console.WriteLine("Press enter key to exit...");
        Console.ReadLine();
        return 0;
      }
      catch (Exception e)
      {
        Console.WriteLine("Exception {0}.", e);
        return 1;
      }
    }
Beispiel #31
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);
        }
        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();
            }
        }
Beispiel #33
0
        async Task SendReceiveAsync(int count)
        {
            Trace.WriteLine(TraceLevel.Information, "Establishing a connection...");
            Connection connection = await Connection.Factory.CreateAsync(this.GetAddress());

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

            Trace.WriteLine(TraceLevel.Information, "Creating a sender link...");
            SenderLink sender = new SenderLink(session, "sessionful-sender-link", this.Entity);

            Trace.WriteLine(TraceLevel.Information, "Sending {0} messages...", count);
            for (int i = 0; i < count; i++)
            {
                Message message = new Message();
                message.Properties = new Properties() { MessageId = "topic-test-" + i };
                message.BodySection = new Data() { Binary = Encoding.UTF8.GetBytes("message #" + i) };
                await sender.SendAsync(message);
            }

            Trace.WriteLine(TraceLevel.Information, "Closing sender...");
            await sender.CloseAsync();

            Trace.WriteLine(TraceLevel.Information, "Receiving messages from subscription...");
            ReceiverLink receiver = new ReceiverLink(session, "receiver-link", this.Entity + "/Subscriptions/sub1");
            for (int i = 0; i < count; i++)
            {
                Message message = await receiver.ReceiveAsync(30000);
                if (message == null)
                {
                    break;
                }

                receiver.Accept(message);
            }

            Trace.WriteLine(TraceLevel.Information, "Closing receiver...");
            await receiver.CloseAsync();

            Trace.WriteLine(TraceLevel.Information, "Shutting down...");
            await session.CloseAsync();
            await connection.CloseAsync();
        }
Beispiel #34
0
        static void ReceiveMessages(string node, int count, string sessionId)
        {
            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);

            Trace.WriteLine(TraceLevel.Information, "Accepting a message session '{0}'...", sessionId ?? "<any>");
            Map filters = new Map();
            filters.Add(new Symbol("com.microsoft:session-filter"), sessionId);

            ReceiverLink receiver = new ReceiverLink(
                session,
                "sessionful-receiver-link",
                new Source() { Address = node, FilterSet = filters },
                null);

            for (int i = 0; i < count; i++)
            {
                Message message = receiver.Receive(30000);
                if (message == null)
                {
                    break;
                }

                if (i == 0)
                {
                    Trace.WriteLine(TraceLevel.Information, "Received message from session '{0}'", message.Properties.GroupId);
                }

                receiver.Accept(message);
            }

            Trace.WriteLine(TraceLevel.Information, "Finished receiving. Shutting down...");
            Trace.WriteLine(TraceLevel.Information, "");

            receiver.Close();
            session.Close();
            connection.Close();
        }
Beispiel #35
-1
        public async Task BasicSendReceiveAsync()
        {
            string testName = "BasicSendReceiveAsync";
            int nMsgs = 100;

            Connection connection = await Connection.Factory.CreateAsync(this.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, GroupId = testName };
                message.ApplicationProperties = new ApplicationProperties();
                message.ApplicationProperties["sn"] = i;
                await sender.SendAsync(message);
            }

            ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, testTarget.Path);
            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = await receiver.ReceiveAsync();
                Trace.WriteLine(TraceLevel.Information, "receive: {0}", message.ApplicationProperties["sn"]);
                receiver.Accept(message);
            }

            await sender.CloseAsync();
            await receiver.CloseAsync();
            await session.CloseAsync();
            await connection.CloseAsync();
        }