Ejemplo n.º 1
0
        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();
        }
Ejemplo n.º 2
0
        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();
        }
Ejemplo n.º 3
0
		public async Task SendMessageToDevice(string messageToDevice)
		{
			var sender = new SenderLink(session, "sender-link", "/messages/devicebound");

			var message = new Message(System.Text.Encoding.UTF8.GetBytes(messageToDevice));
			message.Properties = new Properties();
			message.Properties.To = $"/devices/{Constants.DeviceId}/messages/devicebound";
			message.Properties.MessageId = Guid.NewGuid().ToString();
			message.ApplicationProperties = new ApplicationProperties();
			message.ApplicationProperties["iothub-ack"] = "full";

			await sender.SendAsync(message);
			await sender.CloseAsync();
		}
Ejemplo n.º 4
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();
        }
Ejemplo n.º 5
0
        static async Task Run()
        {
            string address = "amqp://*****:*****@localhost:5672";

            Connection connection = await Connection.Factory.CreateAsync(new Address(address));
            Session session = new Session(connection);
            SenderLink sender = new SenderLink(session, "test-sender", "q1");

            Message message1 = new Message("Hello AMQP!");
            await sender.SendAsync(message1);

            ReceiverLink receiver = new ReceiverLink(session, "test-receiver", "q1");
            Message message2 = await receiver.ReceiveAsync();
            Console.WriteLine(message2.GetBody<string>());
            receiver.Accept(message2);

            await sender.CloseAsync();
            await receiver.CloseAsync();
            await session.CloseAsync();
            await connection.CloseAsync();
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Sends all of the outgoing messages buffered as part of the transaction context
        /// </summary>
        protected override async Task SendOutgoingMessages(IEnumerable<OutgoingMessage> outgoingMessages, ITransactionContext context)
        {
            if (context == null) throw new ArgumentNullException(nameof(context));

            foreach (var message in outgoingMessages)
            {
                if (message.DestinationAddress == null) throw new ArgumentNullException(nameof(message.DestinationAddress));
                if (message == null) throw new ArgumentNullException(nameof(message));
                if(amqpSession == null) throw new ArgumentNullException(nameof(amqpSession));

                var amqpSender = new AmqpLite.SenderLink(amqpSession, "rebus-sender", message.DestinationAddress);

                var body = Encoding.UTF8.GetString(message.TransportMessage.Body);

                var msg = new AmqpLite.Message(body);
                msg.Properties = new AmqpLite.Framing.Properties { MessageId = message.TransportMessage.GetMessageId() };

                if (message.TransportMessage.Headers.TryGetValue(Headers.SentTime, out var sentTime))
                {
                    msg.Properties.CreationTime = DateTime.Parse(sentTime);


                    if (message.TransportMessage.Headers.TryGetValue(Headers.TimeToBeReceived, out var timeToBeReceived))
                    {
                        msg.Properties.AbsoluteExpiryTime = msg.Properties.CreationTime + TimeSpan.Parse(timeToBeReceived);
                    }
                }

                msg.ApplicationProperties = new AmqpLite.Framing.ApplicationProperties();

                foreach (var item in message.TransportMessage.Headers)
                {
                    msg.ApplicationProperties.Map.Add(item.Key, item.Value);
                } 


                await amqpSender.SendAsync(msg);
                await amqpSender.CloseAsync();
            } 
        }
Ejemplo n.º 7
0
        public async Task WebSocketSendReceiveAsync()
        {
            if (Environment.GetEnvironmentVariable("CoreBroker") == "1")
            {
                // No Websocket listener on .Net Core
                return;
            }

            string testName = "WebSocketSendReceiveAsync";

            // assuming it matches the broker's setup and port is not taken
            Address wsAddress = new Address(address);
            int nMsgs = 50;

            ConnectionFactory connectionFactory = new ConnectionFactory(
                new TransportProvider[] { new WebSocketTransportFactory() });
            Connection connection = await connectionFactory.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();
        }
Ejemplo n.º 8
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);
        }
Ejemplo n.º 9
0
        public async Task LargeMessageSendReceiveAsync()
        {
            string testName = "LargeMessageSendReceiveAsync";
            int nMsgs = 50;

            Connection connection = await Connection.Factory.CreateAsync(
                this.testTarget.Address, new Open() { ContainerId = "c1", MaxFrameSize = 4096 }, null);
            Session session = new Session(connection);
            SenderLink sender = new SenderLink(session, "sender-" + testName, testTarget.Path);

            int messageSize = 100 * 1024;
            for (int i = 0; i < nMsgs; ++i)
            {
                Message message = new Message(new string('D', messageSize));
                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();
                string value = message.GetBody<string>();
                Trace.WriteLine(TraceLevel.Information, "receive: {0} body {1}x{2}",
                    message.ApplicationProperties["sn"], value[0], value.Length);
                receiver.Accept(message);
            }

            await sender.CloseAsync();
            await receiver.CloseAsync();
            await session.CloseAsync();
            await connection.CloseAsync();
        }
Ejemplo n.º 10
0
		async static Task<bool> PutCbsToken(Connection connection, string host, string shareAccessSignature, string audience)
		{
			bool result = true;
			Session session = new Session(connection);

			string cbsReplyToAddress = "cbs-reply-to";
			var cbsSender = new SenderLink(session, "cbs-sender", "$cbs");
			var cbsReceiver = new ReceiverLink(session, cbsReplyToAddress, "$cbs");

			// construct the put-token message
			var request = new Message(shareAccessSignature);
			request.Properties = new Properties();
			request.Properties.MessageId = Guid.NewGuid().ToString();
			request.Properties.ReplyTo = cbsReplyToAddress;
			request.ApplicationProperties = new ApplicationProperties();
			request.ApplicationProperties["operation"] = "put-token";
			request.ApplicationProperties["type"] = "azure-devices.net:sastoken";
			request.ApplicationProperties["name"] = audience;
			await cbsSender.SendAsync(request);

			// receive the response
			var response = await cbsReceiver.ReceiveAsync();
			if (response == null || response.Properties == null || response.ApplicationProperties == null)
			{
				result = false;
			}
			else {
				int statusCode = (int)response.ApplicationProperties["status-code"];
				string statusCodeDescription = (string)response.ApplicationProperties["status-description"];
				if (statusCode != (int)202 && statusCode != (int)200) // !Accepted && !OK
				{
					result = false;
				}
			}

			// the sender/receiver may be kept open for refreshing tokens
			await cbsSender.CloseAsync();
			await cbsReceiver.CloseAsync();
			await session.CloseAsync();

			return result;
		}
Ejemplo n.º 11
0
        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();
        }
Ejemplo n.º 12
-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();
        }