コード例 #1
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();
        }
コード例 #2
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();
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: sansindia85/activemq
        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();
        }
コード例 #4
0
 public async ValueTask DisposeAsync()
 {
     await ActionUtil.ExecuteAll(
         () => _receiverLink.CloseAsync(),
         () => _senderLink.CloseAsync(),
         () => _senderLink.Session.CloseAsync()
         ).ConfigureAwait(false);
 }
コード例 #5
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();
        }
コード例 #6
0
ファイル: AmqpConnection.cs プロジェクト: fr830/OPCUA.NET
        /// <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();
        }
コード例 #7
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);
        }
コード例 #8
0
        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();
        }
コード例 #9
0
        public override async Task StopAsync(CancellationToken stoppingToken)
        {
            _logger.LogDebug($"QueueListener stopping.");

            await _receiverLink.CloseAsync();

            await _session.CloseAsync();

            await _connection.CloseAsync();

            _logger.LogDebug($"QueueListener stopped.");
        }
コード例 #10
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();
        }
コード例 #11
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();
        }
コード例 #12
0
ファイル: TaskTests.cs プロジェクト: szehetner/amqpnetlite
        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();
        }
コード例 #13
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);
        }
コード例 #14
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);
                }
            }
        }
コード例 #15
0
ファイル: TaskTests.cs プロジェクト: szehetner/amqpnetlite
        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);
        }
コード例 #16
0
 public async Task CloseAsync()
 {
     if (info.IsDurable)
     {
         if (receiverLink != null)
         {
             await receiverLink.DetachAsync().AwaitRunContinuationAsync();
         }
     }
     else
     {
         if (receiverLink != null)
         {
             await receiverLink.CloseAsync().AwaitRunContinuationAsync();
         }
     }
 }
コード例 #17
0
ファイル: TestAmqpHost.cs プロジェクト: tonto7973/xim
        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
                }
            }
        }
コード例 #18
0
ファイル: SimpleAmqpTest.cs プロジェクト: vkulikov/Alpakka
        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();
        }
コード例 #19
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();
        }
コード例 #20
0
        static async Task <int> SslReConnectionTestAsync()
        {
            try{
                ConnectionFactory factory = new ConnectionFactory();

                String certFile = "C:\\location\\certification.cer";
                factory.SSL.RemoteCertificateValidationCallback = ValidateServerCertificate;
                factory.SSL.LocalCertificateSelectionCallback   = (a, b, c, d, e) => X509Certificate.CreateFromCertFile(certFile);
                factory.SSL.ClientCertificates.Add(X509Certificate.CreateFromCertFile(certFile));

                factory.SASL.Profile = SaslProfile.External;
                Connection.DisableServerCertValidation = false;

                Address    address    = new Address("amqps://*****:*****@host:5671");
                Connection connection = await factory.CreateAsync(address);

                Session      session  = new Session(connection);
                ReceiverLink receiver = new ReceiverLink(session, "receiver-link", "amqp");
                Message      message  = receiver.Receive();;

                while (message != null)
                {
                    Console.WriteLine("Received " + message.Body);
                    receiver.Accept(message);
                    message = receiver.Receive();
                }

                await receiver.CloseAsync();

                await session.CloseAsync();

                await connection.CloseAsync();

                return(0);
            }
            catch (Exception e)
            {
                Console.WriteLine("Exception {0}.", e);
                return(1);
            }
        }
コード例 #21
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();
            }
        }
コード例 #22
0
ファイル: TaskTests.cs プロジェクト: szehetner/amqpnetlite
        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();
        }
コード例 #23
0
        static 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(keyName, keyValue, string.Format("http://{0}/{1}", sbNamespace, 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}", sbNamespace, 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();
        }
コード例 #24
0
        public async Task TestDynamicRequestManuallyAsync()
        {
            var Namespace     = "test";
            var CorrelationId = "42";
            var ServiceName   = "integrationtest";
            var Timeout       = TimeSpan.FromSeconds(10);
            var LinkId        = Guid.NewGuid();


            var obj = new
            {
                context = new { },
                domain  = Domain
            };
            var jsonText     = JsonConvert.SerializeObject(obj);
            var bytes        = Encoding.UTF8.GetBytes(jsonText);
            var requestQueue = "ToDo";
            var subject      = "ToDoFind";

            // AmqpDynamicRequest:
            var    responseQueue = $"{Namespace}.{ServiceName}.{LinkId}";
            Source source        = new Source
            {
                Address      = responseQueue,
                Capabilities = new Symbol[] { new Symbol("topic") } //TODO why topic? This should work with queue! Presumably it's the Api's fault.
            };
            var _senderSession   = Fixture.AmqpService.GetSession();
            var _receiverSession = Fixture.AmqpService.GetSession();
            var _sender          = new SenderLink(_senderSession, $"dyn-sender-{LinkId}", requestQueue);
            var _receiver        = new ReceiverLink(_receiverSession, $"dyn-receiver-{LinkId}", source, null);

            Message       response = null;
            SemaphoreSlim sem      = new SemaphoreSlim(0);

            System.Diagnostics.Trace.WriteLine(string.Format("T{0}: Creating second Thread", Thread.CurrentThread.ManagedThreadId));
            var thread = new Thread(() =>
            {
                Message rmsg;
                try
                {
                    System.Diagnostics.Trace.WriteLine(string.Format("T{0}-Receiver: Start Listening", Thread.CurrentThread.ManagedThreadId));
                    rmsg = _receiver.Receive(Timeout);
                    System.Diagnostics.Trace.WriteLine(string.Format("T{0}-Receiver: Received something: {1}", Thread.CurrentThread.ManagedThreadId, rmsg));

                    if (rmsg != null)
                    {
                        //no Timeout occurred
                        _receiver.Accept(rmsg);
                        //                        response = DeserializeMessage(rmsg.Body);
                        response = rmsg;
                    }
                    sem.Release();
                }
                catch (Exception e)
                {
                    Logger.Warn("Error in AmqpDynamicRequestListener!", e);
                }
            });

            thread.Start();

            //send request
            var msg = new Message(bytes)
            {
                Properties = new Properties
                {
                    ReplyTo       = responseQueue,
                    Subject       = subject,
                    CorrelationId = CorrelationId,
                }
            };

            System.Diagnostics.Trace.WriteLine(string.Format("T{0}-Sender: Sending message", Thread.CurrentThread.ManagedThreadId));
            await _sender.SendAsync(msg);

            Trace.WriteLine(string.Format("T{0}-Sender: Wait until receiving message", Thread.CurrentThread.ManagedThreadId));
            await sem.WaitAsync();


            await _sender?.CloseAsync();

            await _receiver?.CloseAsync();


            Assert.NotNull(response);
        }
コード例 #25
0
        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-{i}");
                message.Properties = new Properties()
                {
                    MessageId = "websocket-test-" + i
                };
                message.MessageAnnotations = new MessageAnnotations();
                //       message.MessageAnnotations.Map.Add("x-opt-scheduled-enqueue-time", DateTime.UtcNow.AddMinutes(1));
                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();

                if (message == null)
                {
                    Console.WriteLine("No more messages received");
                    break;
                }
                var msgpayLoad = message.GetBody <string>();
                Console.WriteLine($"RECEIVED {msgpayLoad}");
                receiver.Accept(message);
            }

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

            Trace.WriteLine(TraceLevel.Information, "Shutting down...");
            await session.CloseAsync();

            Console.WriteLine("Done");
            Console.ReadLine();
            await connection.CloseAsync();
        }
コード例 #26
0
        static async Task Main(string[] args)
        {
            Amqp.Trace.TraceLevel    = Amqp.TraceLevel.Frame | Amqp.TraceLevel.Verbose;
            Amqp.Trace.TraceListener = (l, f, a) => System.Diagnostics.Trace.WriteLine(DateTime.Now.ToString("[hh:ss.fff]") + " " + Fx.Format(f, a));

            if (args.Length != 4)
            {
                Console.WriteLine("[MQTT Server] [DeviceId] [AccessKey] [payload]");
                Console.WriteLine("Press <enter> to exit");
                Console.ReadLine();
                return;
            }

            server    = args[0];
            deviceId  = args[1];
            accessKey = args[2];
            payload   = args[3];

            Console.WriteLine($"MQTT Server:{server} DeviceID:{deviceId} Payload:{payload}");
            Console.WriteLine();

            address    = new Address(server, AmqpsPort, null, null);
            connection = new Connection(address);

            string audience    = Fx.Format("{0}/devices/{1}", server, deviceId);
            string resourceUri = Fx.Format("{0}/devices/{1}", server, deviceId);

            string sasToken = GenerateSasToken(resourceUri, accessKey, null, new TimeSpan(1, 0, 0));
            bool   cbs      = PutCbsToken(connection, sasToken, audience);

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

#if RECEIVE_THREAD
                receiverThread = new Thread(ReceiveCommandsLoop);
                receiverThread.Start();

                receiverThread.Join();
#endif
                string entity = Fx.Format("/devices/{0}/messages/deviceBound", deviceId);

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

                receiveLink.Start(200, OnMessage);
#endif
                DateTime LastSentAt = DateTime.UtcNow;
                Console.WriteLine("Press any key to exit");
                while (!Console.KeyAvailable)
                {
                    await Task.Delay(100);

                    if ((DateTime.UtcNow - LastSentAt) > new TimeSpan(0, 0, 30))
                    {
                        Console.WriteLine($"{DateTime.UtcNow:HH:mm:ss} SendEvent Start");
                        await SendEvent();

                        Console.WriteLine($"{DateTime.UtcNow:HH:mm:ss} SendEvent Finish");

                        LastSentAt = DateTime.UtcNow;
                    }
                }

#if RECEIVE_EVENT
                await receiveLink.CloseAsync();
#endif
                await session.CloseAsync();

                await connection.CloseAsync();
            }
            Console.WriteLine("Press <ENTER> to exit");
            Console.ReadLine();
        }