Пример #1
0
        static async Task Main()
        {
            var connection = await Connection.Factory.CreateAsync(
                new Address("amqp://*****:*****@localhost:5672"));

            Session      session  = new Session(connection);
            ReceiverLink receiver = new ReceiverLink(session, "reciever-link", "q1");

            Console.WriteLine("Reciever connected to broker.");
            while (true)
            {
                Message message = await receiver.ReceiveAsync();

                var ship = message.GetBody <Ship>();

                Console.WriteLine(ship.Name);
                receiver.Accept(message);

                if (ship.Name.Equals("Vessel is 999"))
                {
                    break;
                }
            }

            await receiver.CloseAsync();

            await session.CloseAsync();

            await connection.CloseAsync();

            Console.ReadLine();
        }
Пример #2
0
        static async Task RunSampleAsync()
        {
            ConnectionFactory factory = new ConnectionFactory();

            factory.SASL.Profile = SaslProfile.External;

            Trace.WriteLine(TraceLevel.Information, "Establishing a connection...");
            Address address    = new Address(sbNamespace, 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", 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", 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();
        }
Пример #3
0
        public async Task Process_CompleteWithError_WhenOutgoingLinkQueueNotFound()
        {
            const string     linkName        = "abcd";
            const string     entity          = "entity";
            ISecurityContext securityContext = Substitute.For <ISecurityContext>();
            IEntityLookup    entityLookup    = Substitute.For <IEntityLookup>();
            ILoggerProvider  loggerProvider  = Substitute.For <ILoggerProvider>();

            Entities.IEntity fakeEntity = Substitute.For <Entities.IEntity>();
            var linkProcessor           = new LinkProcessor(securityContext, entityLookup, loggerProvider);

            fakeEntity.DeliveryQueue.Returns((DeliveryQueue)null);
            entityLookup.Find(Arg.Any <string>()).Returns(fakeEntity);
            securityContext.IsAuthorized(Arg.Any <Connection>()).Returns(true);
            AmqpException exception = null;
            Session       session   = await TestAmqpHost.OpenAndLinkProcessorAsync(linkProcessor);

            try
            {
                var receiver = new ReceiverLink(session, linkName, entity);

                Func <Task> action = async() => await receiver.ReceiveAsync();

                linkProcessor.ShouldSatisfyAllConditions(
                    () => exception = action.ShouldThrow <AmqpException>(),
                    () => exception.Error.Condition.ShouldBe((Symbol)ErrorCode.NotFound),
                    () => exception.Error.Description.ShouldBe("Queue not found.")
                    );
            }
            finally
            {
                await session.Connection.CloseAsync();
            }
        }
Пример #4
0
        public async Task Start()
        {
            Running         = true;
            Connection      = new Connection(new Address(ConnectionString));
            ReceiverSession = new Session(Connection);
            var receiverLink = new ReceiverLink(ReceiverSession, $"{ClientName}-rc", Queue);

            while (Running)
            {
                var message = await receiverLink.ReceiveAsync(TimeSpan.FromMilliseconds(500));

                if (message == null)
                {
                    continue;
                }
                Console.WriteLine("Received Message");
                if (string.IsNullOrEmpty(message.Properties?.Subject) ||
                    string.IsNullOrEmpty(message.Properties.ReplyTo))
                {
                    receiverLink.Reject(message);
                    continue;
                }
                receiverLink.Accept(message);
                await ProcessMessage(message);
            }
        }
        static private async void ReceiveCommandsLoop()
        {
            string entity = Fx.Format("/devices/{0}/messages/deviceBound", deviceId);

            ReceiverLink receiveLink = new ReceiverLink(session, "receive-link", entity);

            while (true)
            {
                Message received = await receiveLink.ReceiveAsync();

                if (received != null)
                {
                    Data data = (Data)received.BodySection;

                    Console.WriteLine(UTF8Encoding.UTF8.GetString(data.Binary));
                    if (received.ApplicationProperties != null)
                    {
                        foreach (var property in received.ApplicationProperties.Map)
                        {
                            Console.WriteLine($" Key:{property.Key} Value:{property.Value}");
                        }
                    }
                    receiveLink.Accept(received);
                }
            }
            //await receiveLink.CloseAsync();
        }
Пример #6
0
        public async Task Process_CompleteSuccessfully_WhenOutgoingLinkQueueFound()
        {
            const string     linkName        = "abcd";
            const string     entity          = "entity";
            ISecurityContext securityContext = Substitute.For <ISecurityContext>();
            IEntityLookup    entityLookup    = Substitute.For <IEntityLookup>();
            ILoggerProvider  loggerProvider  = Substitute.For <ILoggerProvider>();

            Entities.IEntity fakeEntity = Substitute.For <Entities.IEntity>();
            var deliveryQueue           = new DeliveryQueue();
            var linkProcessor           = new LinkProcessor(securityContext, entityLookup, loggerProvider);

            entityLookup.Find(Arg.Any <string>()).Returns(fakeEntity);
            securityContext.IsAuthorized(Arg.Any <Connection>()).Returns(true);
            fakeEntity.DeliveryQueue.Returns(deliveryQueue);
            Session session = await TestAmqpHost.OpenAndLinkProcessorAsync(linkProcessor);

            try
            {
                var receiver = new ReceiverLink(session, linkName, entity);
                deliveryQueue.Enqueue(new Delivery(new Message {
                    Properties = new Properties {
                        MessageId = "msgid6746"
                    }
                }));

                Message message = await receiver.ReceiveAsync();

                message.Properties.MessageId.ShouldBe("msgid6746");
            }
            finally
            {
                await session.Connection.CloseAsync();
            }
        }
Пример #7
0
        public async Task OnFlow_SendsMessageToReceiverLink()
        {
            var message = new Message("x")
            {
                Properties = new Properties
                {
                    CorrelationId = "abc123"
                }
            };
            IDeliveryQueue fakeDeliveryQueue = Substitute.For <IDeliveryQueue>();

            fakeDeliveryQueue
            .Dequeue(Arg.Any <CancellationToken>())
            .Returns(message);
            var          endpoint = new OutgoingLinkEndpoint(fakeDeliveryQueue);
            ReceiverLink receiver = await TestAmqpHost.OpenAndLinkReceiverAsync(endpoint);

            try
            {
                receiver.SetCredit(1, CreditMode.Manual);

                Message receivedMessage = await receiver.ReceiveAsync();

                receivedMessage.Properties.CorrelationId
                .ShouldBe(message.Properties.CorrelationId);
            }
            finally
            {
                await receiver.Session.Connection.CloseAsync();
            }
        }
Пример #8
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();
        }
Пример #9
0
        public async Task ReceiverSenderAsync()
        {
            string testName = "ReceiverSenderAsync";

            ConnectionFactory connectionFactory = new ConnectionFactory();

            // Creating first ReceiverLink
            Connection firstReceiverConnection = await connectionFactory.CreateAsync(this.testTarget.Address);

            Session      firstReceiverSession = new Session(firstReceiverConnection);
            ReceiverLink firstReceiverLink    = new ReceiverLink(firstReceiverSession, "receiver-link", testName);

            // Does not work when creating SenderLink after first ReceiverLink
            var senderConnection = await connectionFactory.CreateAsync(this.testTarget.Address);

            var senderSession = new Session(senderConnection);
            var senderLink    = new SenderLink(senderSession, "sender-link", testName);

            // Send and receive message
            await senderLink.SendAsync(new Message(testName));

            Message firstMessageReceived = await firstReceiverLink.ReceiveAsync(TimeSpan.FromMilliseconds(1000));

            // Close first reveiver link
            await firstReceiverLink.CloseAsync();

            await firstReceiverSession.CloseAsync();

            await firstReceiverConnection.CloseAsync();

            // Creating second ReceiverLink
            Connection secondReceiverConnection = await connectionFactory.CreateAsync(this.testTarget.Address);

            Session      secondReceiverSession = new Session(secondReceiverConnection);
            ReceiverLink secondReceiverLink    = new ReceiverLink(secondReceiverSession, "receiver-link", testName);

            // Send and receive message
            await senderLink.SendAsync(new Message(testName));

            Message message = await secondReceiverLink.ReceiveAsync(TimeSpan.FromMilliseconds(1000));

            Assert.IsTrue(message != null, "No message received");
            secondReceiverLink.Accept(message);

            // Close second reveiver link
            await secondReceiverLink.CloseAsync();

            await secondReceiverSession.CloseAsync();

            await secondReceiverConnection.CloseAsync();

            // Close sender link
            await senderLink.CloseAsync();

            await senderSession.CloseAsync();

            await senderConnection.CloseAsync();
        }
Пример #10
0
        private async Task RunMessageProcessorAsync()
        {
            do
            {
                if (CancellationToken.IsCancellationRequested)
                {
                    break;
                }

                if (_receiverLink == null || _receiverLink.IsClosed)
                {
                    await InitializeAsync().ConfigureAwait(false);
                }

                try
                {
                    using (var message = await _receiverLink.ReceiveAsync(TimeSpan.FromSeconds(10)).ConfigureAwait(false))
                    {
                        if (message != null)
                        {
                            try
                            {
                                await _messenger.ProcessMessageAsync(Address, (string)message.Body).ConfigureAwait(false);

                                _receiverLink.Accept(message);
                            }
                            catch (RescheduleException)
                            {
                                // no log, this is "wanted"

                                _receiverLink.Release(message);
                            }
                            catch (Exception exception)
                            {
                                Console.WriteLine($"Exception during processing AMQP message, rejecting: {exception}");

                                _receiverLink.Release(message);
                            }
                        }
                    }
                }
                catch (AmqpException e)
                {
                    if (!CancellationToken.IsCancellationRequested)
                    {
                        Console.WriteLine($"AMQP exception in receiver link for address {Address}: {e}");
                    }

                    await CloseAsync().ConfigureAwait(false);
                }
            } while (!CancellationToken.IsCancellationRequested);

            // normal end

            await CloseAsync().ConfigureAwait(false);
        }
Пример #11
0
        /// <summary>
        /// renews the cbs token
        /// </summary>
        /// <param name="sharedAccessToken">token to renew</param>
        /// <returns>Task to wait on</returns>
        private async Task RenewTokenAsync(string sharedAccessToken)
        {
            var    session          = new Session(m_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);

            // construct the put-token message
            var request = new Message(sharedAccessToken);

            request.Properties            = new Properties();
            request.Properties.MessageId  = "1";
            request.Properties.ReplyTo    = cbsClientAddress;
            request.ApplicationProperties = new ApplicationProperties();

            request.ApplicationProperties["operation"] = "put-token";
            request.ApplicationProperties["type"]      = TokenType;
            request.ApplicationProperties["name"]      = TokenScope;

            await cbsSender.SendAsync(request);

            // receive the response
            var response = await cbsReceiver.ReceiveAsync();

            if (response == null || response.Properties == null || response.ApplicationProperties == null)
            {
                throw new Exception("invalid response received");
            }

            int statusCode = (int)response.ApplicationProperties["status-code"];

            await cbsSender.CloseAsync();

            await cbsReceiver.CloseAsync();

            await session.CloseAsync();

            if (statusCode != (int)HttpStatusCode.Accepted && statusCode != (int)HttpStatusCode.OK)
            {
                throw new Exception("put-token message was not accepted. Error code: " + statusCode);
            }

            // Now create new link
            await ResetLinkAsync();
        }
Пример #12
0
        private static async Task <bool> PutCbsToken(Connection connection, string shareAccessSignature, string audience)
        {
            Log.Debug("Sending authentication token");
            bool result  = true;
            var  session = new Session(connection);

            const 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)
            {
                Properties = new Properties
                {
                    MessageId = Guid.NewGuid().ToString(),
                    ReplyTo   = cbsReplyToAddress
                },
                ApplicationProperties = new ApplicationProperties
                {
                    ["operation"] = "put-token",
                    ["type"]      = "azure-devices.net:sastoken",
                    ["name"]      = audience
                }
            };
            await cbsSender.SendAsync(request);

            // receive the response
            var response = await cbsReceiver.ReceiveAsync();

            if (response?.Properties == null || response.ApplicationProperties == null)
            {
                result = false;
            }
            else
            {
                var statusCode            = (int)response.ApplicationProperties["status-code"];
                var statusCodeDescription = (string)response.ApplicationProperties["status-description"];
                if (statusCode != 202 && statusCode != 200)
                {
                    result = false;
                    Log.ErrorFormat("Authentication failure {status}", statusCodeDescription);
                }
            }

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

            await cbsReceiver.CloseAsync();

            await session.CloseAsync();

            Log.Debug("Authentication complete");

            return(result);
        }
        async Task SendReceiveAsync(int count)
        {
            // it is also possible to create the Address object form a Uri string as follows,
            //   wss://[sas-policy]:[sas-key]@[ns].servicebus.windows.net/$servicebus/websocket
            // note that [sas-policy] and [sas-key] should be URL encoded
            Address wsAddress = new Address(this.Namespace, 443, this.KeyName, this.KeyValue, "/$servicebus/websocket", "wss");
            WebSocketTransportFactory wsFactory = new WebSocketTransportFactory("AMQPWSB10");

            Trace.WriteLine(TraceLevel.Information, "Establishing a connection...");
            ConnectionFactory connectionFactory = new ConnectionFactory(new TransportProvider[] { wsFactory });
            Connection        connection        = await connectionFactory.CreateAsync(wsAddress);

            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, "websocket-sender-link", this.Entity);

            Trace.WriteLine(TraceLevel.Information, "Sending {0} messages...", count);
            for (int i = 0; i < count; i++)
            {
                Message message = new Message("testing");
                message.Properties = new Properties()
                {
                    MessageId = "websocket-test-" + i
                };
                await sender.SendAsync(message);
            }

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

            Trace.WriteLine(TraceLevel.Information, "Receiving messages...");
            ReceiverLink receiver = new ReceiverLink(session, "websocket-receiver-link", this.Entity);

            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();
        }
Пример #14
0
        public void ReceiveWithLinkDetachErrorTest()
        {
            this.testListener.RegisterTarget(TestPoint.Flow, (stream, channel, fields) =>
            {
                // detach link with error. receive calls should throw
                TestListener.FRM(stream, 0x16UL, 0, channel, fields[0], true, new Error()
                {
                    Condition = ErrorCode.InternalError
                });
                return(TestOutcome.Stop);
            });
            this.testListener.RegisterTarget(TestPoint.Detach, (stream, channel, fields) =>
            {
                return(TestOutcome.Stop);
            });

            string testName = "ReceiveWithLinkDetachErrorTest";

            Trace.WriteLine(TraceLevel.Information, "sync test");
            {
                Connection   connection = new Connection(this.address);
                Session      session    = new Session(connection);
                ReceiverLink receiver   = new ReceiverLink(session, "receiver-" + testName, "any");
                try
                {
                    receiver.Receive();
                    Assert.IsTrue(false, "Receive should fail with error");
                }
                catch (AmqpException exception)
                {
                    Assert.AreEqual((Symbol)ErrorCode.InternalError, exception.Error.Condition);
                }
                connection.Close();
                Assert.AreEqual((Symbol)ErrorCode.InternalError, receiver.Error.Condition);
            }

            Trace.WriteLine(TraceLevel.Information, "async test");
            Task.Factory.StartNew(async() =>
            {
                Connection connection = await Connection.Factory.CreateAsync(this.address);
                Session session       = new Session(connection);
                ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "any");
                try
                {
                    await receiver.ReceiveAsync();
                    Assert.IsTrue(false, "Receive should fail with error");
                }
                catch (AmqpException exception)
                {
                    Assert.AreEqual((Symbol)ErrorCode.InternalError, exception.Error.Condition);
                }
                await connection.CloseAsync();
                Assert.AreEqual((Symbol)ErrorCode.InternalError, receiver.Error.Condition);
            }).Unwrap().GetAwaiter().GetResult();
        }
Пример #15
0
        public static void PutCsbToken(Connection connection, ServiceBusConfiguration config, string audience)
        {
            var tokenProvider = new ManagedIdentityTokenProvider();
            var token         = tokenProvider.GetTokenAsync($"sb://{config.Host}/");

            var session = new Session(connection);

            var cbsClientAddress = "cbs-client-reply-to";
            var cbsSender        = new SenderLink(session, config.Subscription, "$cbs");
            var cbsReceiver      = new ReceiverLink(session, cbsClientAddress, "$cbs");

            // construct the put-token message
            var request = new Message(token.TokenValue)
            {
                Properties = new Properties
                {
                    MessageId = Guid.NewGuid().ToString(),
                    ReplyTo   = cbsClientAddress
                },
                ApplicationProperties = new ApplicationProperties
                {
                    ["operation"]  = "put-token",
                    ["type"]       = token.TokenType,
                    ["expiration"] = token.ExpiresAtUtc,
                    ["name"]       = audience
                }
            };

            cbsSender.SendAsync(request).Wait();
            Trace.WriteLine(TraceLevel.Information, " request: {0}", request.Properties);
            Trace.WriteLine(TraceLevel.Information, " request: {0}", request.ApplicationProperties);

            // receive the response
            var response = cbsReceiver.ReceiveAsync().Result;

            if (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
            cbsSender.Close();
            cbsReceiver.Close();
            session.Close();
        }
Пример #16
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, "topic-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();
        }
Пример #17
0
        /// <summary>
        /// Receive messages from specified azure iothub on specified partition. The MessageManager parses the received message and displays it accordingly
        /// </summary>
        /// <param name="partition"></param>
        /// <param name="offset"></param>
        /// <param name="msgman"></param>
        /// <param name="hubData"></param>
        /// <returns></returns>
        public static async Task ReceiveMessages(string partition, DateTime offset, MessageManager msgman, IoTAccountData hubData)
        {
            string port = hubData.EventHubInfo.EventHubPort.Replace("sb://", "");

            port = port.Replace("/", "");
            Address    address    = new Address(port, 5671, hubData.SharedAccessPolicy, hubData.PrimaryKey, "/", "amqps");
            Connection connection = await Connection.Factory.CreateAsync(address);

            Session session           = new Session(connection);
            string  totalMilliseconds = ((long)(offset - new DateTime(StartOfEpoch, DateTimeKind.Utc)).TotalMilliseconds).ToString();
            Map     filters           = new Map();

            filters.Add(new Amqp.Types.Symbol("apache.org:selector-filter:string"),
                        new DescribedValue(
                            new Amqp.Types.Symbol("apache.org:selector-filter:string"),
                            "amqp.annotation.x-opt-enqueuedtimeutc > " + totalMilliseconds + ""));
            ReceiverLink receiver = new ReceiverLink(session,
                                                     "my-receiver",
                                                     new global::Amqp.Framing.Source()
            {
                Address =
                    hubData.EventHubInfo.EventHubEntity + "/ConsumerGroups/$Default/Partitions/" + partition,
                FilterSet = filters
            }, null);

            Amqp.Types.Symbol deviceIdKey = new Amqp.Types.Symbol("iothub-connection-device-id");
            string            deviceId    = hubData.DeviceName;

            while (true)
            {
                Amqp.Message m = await receiver.ReceiveAsync(10000);

                if (m != null)
                {
                    var id = m.MessageAnnotations.Map[deviceIdKey].ToString();
                    if (id == deviceId)
                    {
                        Data   data    = (Data)m.BodySection;
                        string msg     = System.Text.Encoding.UTF8.GetString(data.Binary, 0, data.Binary.Length);
                        bool   isValid = msgman.parseMessage(msg);
                        if (isValid)
                        {
                            receiver.Accept(m);
                        }
                        else
                        {
                            receiver.Release(m);
                        }
                    }
                }
            }
        }
Пример #18
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();
        }
Пример #19
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();
        }
Пример #20
0
        public void ReceiveWithConnectionResetTest()
        {
            this.testListener.RegisterTarget(TestPoint.Flow, (stream, channel, fields) =>
            {
                stream.Dispose();
                return(TestOutcome.Continue);
            });

            string testName = "ReceiveWithConnectionResetTest";

            Trace.WriteLine(TraceLevel.Information, "sync test");
            {
                Connection   connection = new Connection(this.address);
                Session      session    = new Session(connection);
                ReceiverLink receiver   = new ReceiverLink(session, "receiver-" + testName, "any");
                try
                {
                    receiver.Receive();
                    Assert.IsTrue(false, "Receive should fail with error");
                }
                catch (AmqpException exception)
                {
                    Assert.AreEqual((Symbol)ErrorCode.ConnectionForced, exception.Error.Condition);
                }
                connection.Close();
                Assert.AreEqual(ErrorCode.ConnectionForced, (string)connection.Error.Condition);
            }

            Trace.WriteLine(TraceLevel.Information, "async test");
            Task.Factory.StartNew(async() =>
            {
                Connection connection = await Connection.Factory.CreateAsync(this.address);
                Session session       = new Session(connection);
                ReceiverLink receiver = new ReceiverLink(session, "receiver-" + testName, "any");
                try
                {
                    await receiver.ReceiveAsync();
                    Assert.IsTrue(false, "Receive should fail with error");
                }
                catch (AmqpException exception)
                {
                    Assert.AreEqual((Symbol)ErrorCode.ConnectionForced, exception.Error.Condition);
                }
                await connection.CloseAsync();
                Assert.AreEqual(ErrorCode.ConnectionForced, (string)connection.Error.Condition);
            }).Unwrap().GetAwaiter().GetResult();
        }
Пример #21
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);
        }
Пример #22
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);
                }
            }
        }
        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);
            }
        }
Пример #24
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(message2);

            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);
        }
Пример #25
0
        public async Task <bool> GetNextStateStatusAsync()
        {
            var receiver = new ReceiverLink(session, "receive-link",
                                            "/messages/servicebound/feedback");

            while (true)
            {
                var message = await receiver.ReceiveAsync();

                if (message == null)
                {
                    continue;
                }
                receiver.Accept(message);

                return(true);
            }
        }
Пример #26
0
        public static async Task <Message> SendControlRequestAsync(this Session session, string controller, Message request)
        {
            if (request.Properties == null)
            {
                request.Properties = new Properties();
            }
            request.Properties.ReplyTo = "c-client-reply-to";
            var cbsSender   = new SenderLink(session, "c-sender", controller);
            var cbsReceiver = new ReceiverLink(session, "c-receiver", new Attach
            {
                Source = new Source {
                    Address = controller
                },
                Target = new Target {
                    Address = "c-client-reply-to"
                }
            }, null);

            try
            {
                cbsReceiver.SetCredit(200, true);
                await cbsSender.SendAsync(request);

                return(await cbsReceiver.ReceiveAsync());
            }
            finally
            {
                try
                {
                    try
                    {
                        await cbsSender.CloseAsync();
                    }
                    finally
                    {
                        await cbsReceiver.CloseAsync();
                    }
                }
                catch (AmqpException)
                {
                    // ignore for closeasync
                }
            }
        }
Пример #27
0
        public async Task TestHelloWorld()
        {
            Connection.DisableServerCertValidation = true;
            Trace.TraceLevel    = TraceLevel.Frame;
            Trace.TraceListener = (l, f, a) =>
                                  _output.WriteLine(DateTime.Now.ToString("[hh:mm:ss.fff]") + " " + string.Format(f, a));

            //strange, works using regular activeMQ and the amqp test broker from here: http://azure.github.io/amqpnetlite/articles/hello_amqp.html
            //but this does not work in ActiveMQ Artemis
            var address    = new Address(_fixture.HostName, _fixture.AmqpPort, _fixture.UserName, _fixture.Password, scheme: "AMQP");
            var connection = new Connection(address);
            var session    = new Session(connection);

            var message = new Message("Hello AMQP");

            var target = new Target
            {
                Address      = "q1",
                Capabilities = new Symbol[] { new Symbol("queue") }
            };

            var sender = new SenderLink(session, "sender-link", target, null);
            await sender.SendAsync(message);

            var source = new Source
            {
                Address      = "q1",
                Capabilities = new Symbol[] { new Symbol("queue") }
            };

            var receiver = new ReceiverLink(session, "receiver-link", source, null);

            message = await receiver.ReceiveAsync();

            receiver.Accept(message);

            await sender.CloseAsync();

            await receiver.CloseAsync();

            await session.CloseAsync();

            await connection.CloseAsync();
        }
Пример #28
0
        public async Task WebSocketSendReceiveAsync()
        {
            string testName = "WebSocketSendReceiveAsync";

            // assuming it matches the broker's setup and port is not taken
            Address wsAddress = new Address(address);
            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();
        }
Пример #29
0
        private static async Task SendMessage()
        {
            var edxUrl = ConfigurationManager.AppSettings["EdxUrl"];

            var readQueue = ConfigurationManager.AppSettings["EdxOutboxReplyQueue"];

            var connection = new Connection(new Address(edxUrl));
            var session    = new Session(connection);
            var inbox      = new ReceiverLink(session, "inbox", readQueue);

            // App settings
            var timeout = int.Parse(ConfigurationManager.AppSettings["TimeoutMs"]);



            try
            {
                var result = await inbox.ReceiveAsync(TimeSpan.FromMilliseconds(timeout));

                ToConsole(result); // Print received message

                if (result != null)
                {
                    inbox.Accept(result);
                    Console.WriteLine("Message accepted");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
            }
            finally
            {
                // Close all connections
                await inbox.CloseAsync();

                await session.CloseAsync();

                await connection.CloseAsync();
            }
        }
Пример #30
0
        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();
        }