コード例 #1
0
        public async Task ClientThrowsObjectDisposedExceptionWhenUserCloseConnectionAndWouldUseOldSeviceBusConnection()
        {
            var sender   = new MessageSender(TestUtility.NamespaceConnectionString, TestConstants.PartitionedQueueName);
            var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, TestConstants.PartitionedQueueName, receiveMode: ReceiveMode.ReceiveAndDelete);

            try
            {
                var messageBody = Encoding.UTF8.GetBytes("Message");
                var message     = new Message(messageBody);

                await sender.SendAsync(message);

                await sender.CloseAsync();

                var recivedMessage = await receiver.ReceiveAsync().ConfigureAwait(false);

                Assert.True(Encoding.UTF8.GetString(recivedMessage.Body) == Encoding.UTF8.GetString(messageBody));

                var connection = sender.ServiceBusConnection;
                Assert.Throws <ObjectDisposedException>(() => new MessageSender(connection, TestConstants.PartitionedQueueName));
            }
            finally
            {
                await sender.CloseAsync().ConfigureAwait(false);

                await receiver.CloseAsync().ConfigureAwait(false);
            }
        }
コード例 #2
0
 async Task StopSender()
 {
     try
     {
         await _sender.CloseAsync().ConfigureAwait(false);
     }
     catch (Exception exception)
     {
         _log.Error($"Failed to close message sender: {_sender.Path}", exception);
         throw;
     }
 }
コード例 #3
0
        /// <inheritdoc />
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                Receiver.CloseAsync().ConfigureAwait(false).GetAwaiter().GetResult();
                Sender.CloseAsync().ConfigureAwait(false).GetAwaiter().GetResult();

                ReadTimer?.Dispose();
            }

            base.Dispose(disposing);
        }
コード例 #4
0
ファイル: Program.cs プロジェクト: sunxudongyaya/MyAzureZone
        // This sample shows a successful transaction.
        private async Task TransactionSample(string SBCS, string QueueName)
        {
            // Note: A transaction cannot span more than one connection, hence you need to create your connection object
            // always before and then pass it to sender and receiver.
            var connection = new ServiceBusConnection(SBCS);
            var sender     = new MessageSender(connection, QueueName);
            var receiver   = new MessageReceiver(connection, QueueName);
            // Receive not part of transaction. Only operations which actually do something with the message on the broker are part of the transaction.
            // These are: Send, Complete, Deadletter, Defer. Receive itself already utilizes the peeklock concept on the broker.
            // Note the receive timeout of 2 seconds is just for demo purposes to not let the user wait in case no message is there.
            // Run twice to see the sample in full.

            var receivedMessage = await receiver.ReceiveAsync(TimeSpan.FromSeconds(5));

            if (receivedMessage != null)
            {
                var msg = receivedMessage.DeserializeMsg <MyMessage>();
                Console.WriteLine($"MessageId: {receivedMessage.MessageId} \n Name: {msg.Name} \n Address: {msg.Address} \n ZipCode {msg.ZipCode}");
            }
            else
            {
                Console.WriteLine($"No message received.");
            }


            using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                try
                {
                    if (receivedMessage != null)
                    {
                        await receiver.CompleteAsync(receivedMessage.SystemProperties.LockToken);
                    }

                    var myMsgBody = new MyMessage
                    {
                        Name    = "Some name",
                        Address = "Some street address",
                        ZipCode = "Some zip code"
                    };

                    var message = myMsgBody.AsMessage();
                    await sender.SendAsync(message).ConfigureAwait(false);

                    Console.WriteLine("Message has been sent");

                    ts.Complete();
                }
                catch (Exception ex)
                {
                    // This rolls back send and complete in case an exception happens
                    ts.Dispose();
                    Console.WriteLine(ex.ToString());
                }
            }

            await sender.CloseAsync();

            await receiver.CloseAsync();
        }
コード例 #5
0
        /// <summary>
        ///     Forcefully terminate the specified orchestration instance with a reason
        /// </summary>
        /// <param name="orchestrationInstance">Instance to terminate</param>
        /// <param name="reason">Reason for terminating the instance</param>
        public async Task TerminateInstanceAsync(OrchestrationInstance orchestrationInstance, string reason)
        {
            if (orchestrationInstance == null || string.IsNullOrWhiteSpace(orchestrationInstance.InstanceId))
            {
                throw new ArgumentException("orchestrationInstance");
            }

            string instanceId = orchestrationInstance.InstanceId;

            var taskMessage = new TaskMessage
            {
                OrchestrationInstance = orchestrationInstance,
                Event = new ExecutionTerminatedEvent(-1, reason)
            };

            BrokeredMessage brokeredMessage = Utils.GetBrokeredMessageFromObject(taskMessage,
                                                                                 settings.MessageCompressionSettings);

            brokeredMessage.SessionId = instanceId;

            MessageSender sender =
                await messagingFactory.CreateMessageSenderAsync(orchestratorEntityName).ConfigureAwait(false);

            await sender.SendAsync(brokeredMessage).ConfigureAwait(false);

            await sender.CloseAsync().ConfigureAwait(false);
        }
コード例 #6
0
        /// <summary>
        ///     Raises an event in the specified orchestration instance, which eventually causes the OnEvent() method in the
        ///     orchestration to fire.
        /// </summary>
        /// <param name="orchestrationInstance">Instance in which to raise the event</param>
        /// <param name="eventName">Name of the event</param>
        /// <param name="eventData">Data for the event</param>
        public async Task RaiseEventAsync(OrchestrationInstance orchestrationInstance, string eventName,
                                          object eventData)
        {
            if (orchestrationInstance == null || string.IsNullOrWhiteSpace(orchestrationInstance.InstanceId))
            {
                throw new ArgumentException("orchestrationInstance");
            }

            string serializedInput = defaultConverter.Serialize(eventData);
            var    taskMessage     = new TaskMessage
            {
                OrchestrationInstance = orchestrationInstance,
                Event = new EventRaisedEvent(-1, serializedInput)
                {
                    Name = eventName
                }
            };

            BrokeredMessage brokeredMessage = Utils.GetBrokeredMessageFromObject(taskMessage,
                                                                                 settings.MessageCompressionSettings);

            brokeredMessage.SessionId = orchestrationInstance.InstanceId;

            MessageSender sender =
                await messagingFactory.CreateMessageSenderAsync(orchestratorEntityName).ConfigureAwait(false);

            await sender.SendAsync(brokeredMessage).ConfigureAwait(false);

            await sender.CloseAsync().ConfigureAwait(false);
        }
コード例 #7
0
        public async Task ReceiveDeferredMessageForSessionTest(string qName)
        {
            var sessionId = Guid.NewGuid().ToString("N").Substring(0, 8);
            var messageId = Guid.NewGuid().ToString("N").Substring(0, 8);

            var sender = new MessageSender(TestUtility.NamespaceConnectionString, qName);
            await sender.SendAsync(new Message()
            {
                SessionId = sessionId, MessageId = messageId
            });

            var sessionClient  = new SessionClient(TestUtility.NamespaceConnectionString, qName);
            var messageSession = await sessionClient.AcceptMessageSessionAsync(sessionId);

            var msg = await messageSession.ReceiveAsync();

            var seqNum = msg.SystemProperties.SequenceNumber;
            await messageSession.DeferAsync(msg.SystemProperties.LockToken);

            var msg2 = await messageSession.ReceiveDeferredMessageAsync(seqNum);

            Assert.Equal(seqNum, msg2.SystemProperties.SequenceNumber);
            Assert.Equal(messageId, msg2.MessageId);

            await sender.CloseAsync();

            await sessionClient.CloseAsync();

            await messageSession.CloseAsync();
        }
コード例 #8
0
        public async Task TransactionalSendRollbackTest(string queueName)
        {
            var sender   = new MessageSender(ConnectionString, queueName);
            var receiver = new MessageReceiver(ConnectionString, queueName);

            try
            {
                string body    = Guid.NewGuid().ToString("N");
                var    message = new Message(body.GetBytes())
                {
                    PartitionKey = "pk"
                };
                using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    await sender.SendAsync(message).ConfigureAwait(false);

                    ts.Dispose();
                }

                var receivedMessage = await receiver.ReceiveAsync(ReceiveTimeout);

                Assert.Null(receivedMessage);
            }
            finally
            {
                await sender.CloseAsync();

                await receiver.CloseAsync();
            }
        }
コード例 #9
0
        public async Task TransactionalCompleteRollbackTest(string queueName)
        {
            var sender   = new MessageSender(ConnectionString, queueName);
            var receiver = new MessageReceiver(ConnectionString, queueName);

            try
            {
                string body    = Guid.NewGuid().ToString("N");
                var    message = new Message(body.GetBytes());
                await sender.SendAsync(message).ConfigureAwait(false);

                var receivedMessage = await receiver.ReceiveAsync(ReceiveTimeout);

                Assert.NotNull(receivedMessage);
                Assert.Equal(body, receivedMessage.Body.GetString());

                using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                {
                    await receiver.CompleteAsync(receivedMessage.SystemProperties.LockToken);

                    ts.Dispose();
                }

                await receiver.CompleteAsync(receivedMessage.SystemProperties.LockToken);
            }
            finally
            {
                await sender.CloseAsync();

                await receiver.CloseAsync();
            }
        }
コード例 #10
0
        private static async Task SendToQueue()
        {
            q1Sender = new MessageSender(SBConnectionString, AzureRiyadh_Queue_01);
            //q1Sender.RegisterPlugin(new MeetupSendPlugin());
            //q1Sender.RegisterPlugin(new FixedMessageIdSendPlugin("1122"));


            // 1. Text
            var txtMsg = $"Azure Riyadh Meetup :: Test Message #{DateTime.Now.Ticks}"; //txtMsg = new StringBuilder().Append('M', 1500000).ToString();

            await Send(q1Sender, txtMsg);
            await Schedule(q1Sender, txtMsg);

            // 2. Serialize Object
            dynamic address = new { Country = "SA", City = "Riyadh", Street = "Olaya St" };

            await Send(q1Sender, Json.SerializeD(address));

            // 3. Image
            //await SendBlob(q1Sender, Blob01);

            // 4. Object
            await SendAttendee(q1Sender);

            await q1Sender.CloseAsync();
        }
コード例 #11
0
        public async Task <bool> ReadMessageTest1()
        {
            var messageReceiver = new MessageReceiver(ConnectionString, "non-partitioned-queue", ReceiveMode.PeekLock);
            var messageSender   = new MessageSender(ConnectionString, "non-partitioned-queue");

            try
            {
                var firstPlugin  = new FirstSendPlugin();
                var secondPlugin = new SecondSendPlugin();

                messageSender.RegisterPlugin(firstPlugin);
                messageSender.RegisterPlugin(secondPlugin);

                var sendMessage = new Message(Encoding.UTF8.GetBytes("Test message>>>>>>"));
                await messageSender.SendAsync(sendMessage);

                var receivedMessage = await messageReceiver.ReceiveAsync(TimeSpan.FromMinutes(1));

                var receivedMessage_body = receivedMessage.Body.ToString();

                //var firstSendPluginUserProperty = receivedMessage.First().UserProperties["FirstSendPlugin"];
                //var secondSendPluginUserProperty = receivedMessage.First().UserProperties["SecondSendPlugin"];

                //Assert.True((bool)firstSendPluginUserProperty);
                //Assert.True((bool)secondSendPluginUserProperty);
            }
            finally
            {
                await messageSender.CloseAsync();

                await messageReceiver.CloseAsync();
            }

            return(true);
        }
コード例 #12
0
        static async Task Main(string[] args)
        {
            var connectionString = Environment.GetEnvironmentVariable("AzureServiceBus_ConnectionString");

            var management = new ManagementClient(connectionString);

            if (!await management.QueueExistsAsync("queue"))
            {
                await management.CreateQueueAsync("queue");
            }

            var sender = new MessageSender(connectionString, "queue");

            while (true)
            {
                using (var tx = new TransactionScope(TransactionScopeOption.RequiresNew, TransactionScopeAsyncFlowOption.Enabled))
                {
                    Debugger.Break();
                    await sender.SendAsync(new Message(Encoding.Default.GetBytes(DateTime.Now.ToString("s"))));

                    Console.WriteLine("message sent");

                    tx.Complete();

                    Console.WriteLine("tx completed");
                }
            }

            await management.CloseAsync();

            await sender.CloseAsync();
        }
        async Task SessionLockLostExceptionTest()
        {
            var sender        = new MessageSender(TestUtility.NamespaceConnectionString, TestConstants.SessionNonPartitionedQueueName);
            var sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, TestConstants.SessionNonPartitionedQueueName);

            try
            {
                var messageId = "test-message1";
                var sessionId = Guid.NewGuid().ToString();
                await sender.SendAsync(new Message { MessageId = messageId, SessionId = sessionId });

                TestUtility.Log($"Sent Message: {messageId} to Session: {sessionId}");

                var sessionReceiver = await sessionClient.AcceptMessageSessionAsync(sessionId);

                Assert.NotNull(sessionReceiver);
                TestUtility.Log($"Received Session: SessionId: {sessionReceiver.SessionId}: LockedUntilUtc: {sessionReceiver.LockedUntilUtc}");

                var message = await sessionReceiver.ReceiveAsync();

                Assert.True(message.MessageId == messageId);
                TestUtility.Log($"Received Message: MessageId: {message.MessageId}");

                // Let the Session expire with some buffer time
                TestUtility.Log($"Waiting for session lock to time out...");
                await Task.Delay((sessionReceiver.LockedUntilUtc - DateTime.UtcNow) + TimeSpan.FromSeconds(10));

                await Assert.ThrowsAsync <SessionLockLostException>(async() => await sessionReceiver.ReceiveAsync());

                await Assert.ThrowsAsync <SessionLockLostException>(async() => await sessionReceiver.RenewSessionLockAsync());

                await Assert.ThrowsAsync <SessionLockLostException>(async() => await sessionReceiver.GetStateAsync());

                await Assert.ThrowsAsync <SessionLockLostException>(async() => await sessionReceiver.SetStateAsync(null));

                await Assert.ThrowsAsync <SessionLockLostException>(async() => await sessionReceiver.CompleteAsync(message.SystemProperties.LockToken));

                await sessionReceiver.CloseAsync();

                TestUtility.Log($"Closed Session Receiver...");

                //Accept a new Session and Complete the message
                sessionReceiver = await sessionClient.AcceptMessageSessionAsync(sessionId);

                Assert.NotNull(sessionReceiver);
                TestUtility.Log($"Received Session: SessionId: {sessionReceiver.SessionId}");
                message = await sessionReceiver.ReceiveAsync();

                TestUtility.Log($"Received Message: MessageId: {message.MessageId}");
                await sessionReceiver.CompleteAsync(message.SystemProperties.LockToken);

                await sessionReceiver.CloseAsync();
            }
            finally
            {
                await sender.CloseAsync();

                await sessionClient.CloseAsync();
            }
        }
コード例 #14
0
        async Task Plugin_with_ShouldContinueOnException_should_continue()
        {
            await ServiceBusScope.UsingQueueAsync(partitioned : false, sessionEnabled : false, async queueName =>
            {
                var messageSender = new MessageSender(TestUtility.NamespaceConnectionString, queueName);
                try
                {
                    var plugin = new ShouldCompleteAnywayExceptionPlugin();

                    messageSender.RegisterPlugin(plugin);

                    var sendMessage = new Message(Encoding.UTF8.GetBytes("Test message"));
                    await messageSender.SendAsync(sendMessage);
                }
                finally
                {
                    await messageSender.CloseAsync();
                }

                var messageReceiver = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete);
                try
                {
                    await messageReceiver.ReceiveAsync();
                }
                finally
                {
                    await messageReceiver.CloseAsync();
                }
            });
        }
コード例 #15
0
        public async Task CompleteOnPeekedMessagesShouldThrowTest()
        {
            await ServiceBusScope.UsingQueueAsync(partitioned : false, sessionEnabled : false, async queueName =>
            {
                var sender   = new MessageSender(TestUtility.NamespaceConnectionString, queueName);
                var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName, receiveMode: ReceiveMode.ReceiveAndDelete);

                try
                {
                    await TestUtility.SendMessagesAsync(sender, 1);
                    var message = await receiver.PeekAsync();
                    Assert.NotNull(message);
                    await
                    Assert.ThrowsAsync <InvalidOperationException>(
                        async() => await receiver.CompleteAsync(message.SystemProperties.LockToken));

                    message = await receiver.ReceiveAsync();
                    Assert.NotNull(message);
                }
                finally
                {
                    await sender.CloseAsync();
                    await receiver.CloseAsync();
                }
            });
        }
コード例 #16
0
        async Task Multiple_plugins_should_run_in_order()
        {
            var messageSender   = new MessageSender(TestUtility.NamespaceConnectionString, TestConstants.NonPartitionedQueueName);
            var messageReceiver = new MessageReceiver(TestUtility.NamespaceConnectionString, TestConstants.NonPartitionedQueueName, ReceiveMode.ReceiveAndDelete);

            try
            {
                var firstPlugin  = new FirstSendPlugin();
                var secondPlugin = new SecondSendPlugin();

                messageSender.RegisterPlugin(firstPlugin);
                messageSender.RegisterPlugin(secondPlugin);

                var sendMessage = new Message(Encoding.UTF8.GetBytes("Test message"));
                await messageSender.SendAsync(sendMessage);

                var receivedMessage = await messageReceiver.ReceiveAsync(1, TimeSpan.FromMinutes(1));

                var firstSendPluginUserProperty  = receivedMessage.First().UserProperties["FirstSendPlugin"];
                var secondSendPluginUserProperty = receivedMessage.First().UserProperties["SecondSendPlugin"];

                Assert.True((bool)firstSendPluginUserProperty);
                Assert.True((bool)secondSendPluginUserProperty);
            }
            finally
            {
                await messageSender.CloseAsync();

                await messageReceiver.CloseAsync();
            }
        }
コード例 #17
0
ファイル: Program.cs プロジェクト: 19balazs86/AzureServiceBus
        private static async Task sendMessagesAsync()
        {
            var messageSender = new MessageSender(_connString, _queueName);

            for (int i = 0; i < _lineCount; i++)
            {
                string sessionId = $"Line-{i}";

                var messages = new List <Message>(_lineSize);

                for (int j = 0; j < _lineSize; j++)
                {
                    byte[] body = Encoding.UTF8.GetBytes($"Pos-{j}");

                    messages.Add(new Message(body)
                    {
                        SessionId = sessionId
                    });
                }

                await messageSender.SendAsync(messages);

                Console.WriteLine($"Sent: {sessionId}.");
            }

            await messageSender.CloseAsync();
        }
コード例 #18
0
        async Task Multiple_plugins_should_be_able_to_manipulate_message()
        {
            var messageSender   = new MessageSender(TestUtility.NamespaceConnectionString, TestConstants.NonPartitionedQueueName);
            var messageReceiver = new MessageReceiver(TestUtility.NamespaceConnectionString, TestConstants.NonPartitionedQueueName, ReceiveMode.ReceiveAndDelete);

            try
            {
                var sendReceivePlugin = new SendReceivePlugin();
                messageSender.RegisterPlugin(sendReceivePlugin);
                messageReceiver.RegisterPlugin(sendReceivePlugin);

                var sendMessage = new Message(Encoding.UTF8.GetBytes("Test message"))
                {
                    MessageId = Guid.NewGuid().ToString()
                };
                await messageSender.SendAsync(sendMessage);

                // Ensure the plugin is called.
                Assert.True(sendReceivePlugin.MessageBodies.ContainsKey(sendMessage.MessageId));

                var receivedMessage = await messageReceiver.ReceiveAsync(TimeSpan.FromMinutes(1));

                Assert.Equal(sendMessage.Body, receivedMessage.Body);
            }

            finally
            {
                await messageSender.CloseAsync();

                await messageReceiver.CloseAsync();
            }
        }
コード例 #19
0
        public async Task TransactionalSendCommitTest(bool partitioned, bool sessionEnabled)
        {
            await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueName =>
            {
                var sender   = new MessageSender(ConnectionString, queueName);
                var receiver = new MessageReceiver(ConnectionString, queueName);

                try
                {
                    string body = Guid.NewGuid().ToString("N");
                    var message = new Message(body.GetBytes())
                    {
                        PartitionKey = "pk"
                    };
                    using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                    {
                        await sender.SendAsync(message).ConfigureAwait(false);
                        ts.Complete();
                    }

                    var receivedMessage = await receiver.ReceiveAsync(ReceiveTimeout);

                    Assert.NotNull(receivedMessage);
                    Assert.Equal(body, receivedMessage.Body.GetString());
                    await receiver.CompleteAsync(receivedMessage.SystemProperties.LockToken);
                }
                finally
                {
                    await sender.CloseAsync();
                    await receiver.CloseAsync();
                }
            });
        }
コード例 #20
0
        public async Task TransactionalSendRollbackTest(bool partitioned, bool sessionEnabled)
        {
            await ServiceBusScope.UsingQueueAsync(partitioned, sessionEnabled, async queueName =>
            {
                var sender   = new MessageSender(ConnectionString, queueName);
                var receiver = new MessageReceiver(ConnectionString, queueName);

                try
                {
                    string body = Guid.NewGuid().ToString("N");
                    var message = new Message(body.GetBytes())
                    {
                        PartitionKey = "pk"
                    };
                    using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
                    {
                        await sender.SendAsync(message).ConfigureAwait(false);
                    }

                    // Adding delay since transaction Commit/Rollback is an asynchronous operation.
                    // Operating on the same message should not be done.
                    await Task.Delay(TimeSpan.FromSeconds(2));

                    var receivedMessage = await receiver.ReceiveAsync(ReceiveTimeout);
                    Assert.Null(receivedMessage);
                }
                finally
                {
                    await sender.CloseAsync();
                    await receiver.CloseAsync();
                }
            });
        }
コード例 #21
0
        public async Task ClientsUseGlobalConnectionCloseFirstClientSecoundClientShouldSendMessage()
        {
            await ServiceBusScope.UsingQueueAsync(partitioned : true, sessionEnabled : false, async queueName =>
            {
                var csb        = new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString);
                var connection = new ServiceBusConnection(csb);
                var sender     = new MessageSender(connection, queueName);
                var receiver   = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName, receiveMode: ReceiveMode.ReceiveAndDelete);
                try
                {
                    var messageBody = Encoding.UTF8.GetBytes("Message");
                    var message     = new Message(messageBody);

                    await sender.SendAsync(message);
                    await sender.CloseAsync();

                    var recivedMessage = await receiver.ReceiveAsync().ConfigureAwait(false);
                    Assert.True(Encoding.UTF8.GetString(recivedMessage.Body) == Encoding.UTF8.GetString(messageBody));

                    connection  = sender.ServiceBusConnection;
                    sender      = new MessageSender(connection, queueName);
                    messageBody = Encoding.UTF8.GetBytes("Message 2");
                    message     = new Message(messageBody);
                    await sender.SendAsync(message);
                    recivedMessage = await receiver.ReceiveAsync().ConfigureAwait(false);
                    Assert.True(Encoding.UTF8.GetString(recivedMessage.Body) == Encoding.UTF8.GetString(messageBody));
                }
                finally
                {
                    await sender.CloseAsync();
                    await receiver.CloseAsync();
                }
            });
        }
コード例 #22
0
        public async Task DeadLetterReasonShouldPropagateToTheReceivedMessage()
        {
            await ServiceBusScope.UsingQueueAsync(partitioned : false, sessionEnabled : false, async queueName =>
            {
                var sender      = new MessageSender(TestUtility.NamespaceConnectionString, queueName);
                var receiver    = new MessageReceiver(TestUtility.NamespaceConnectionString, queueName);
                var dlqReceiver = new MessageReceiver(TestUtility.NamespaceConnectionString, EntityNameHelper.FormatDeadLetterPath(queueName), ReceiveMode.ReceiveAndDelete);

                try
                {
                    await sender.SendAsync(new Message(Encoding.UTF8.GetBytes("deadLetterTest2")));
                    var message = await receiver.ReceiveAsync();
                    Assert.NotNull(message);

                    await receiver.DeadLetterAsync(
                        message.SystemProperties.LockToken,
                        "deadLetterReason",
                        "deadLetterDescription");
                    var dlqMessage = await dlqReceiver.ReceiveAsync();

                    Assert.NotNull(dlqMessage);
                    Assert.True(dlqMessage.UserProperties.ContainsKey(Message.DeadLetterReasonHeader));
                    Assert.True(dlqMessage.UserProperties.ContainsKey(Message.DeadLetterErrorDescriptionHeader));
                    Assert.Equal("deadLetterReason", dlqMessage.UserProperties[Message.DeadLetterReasonHeader]);
                    Assert.Equal("deadLetterDescription", dlqMessage.UserProperties[Message.DeadLetterErrorDescriptionHeader]);
                }
                finally
                {
                    await sender.CloseAsync();
                    await receiver.CloseAsync();
                    await dlqReceiver.CloseAsync();
                }
            });
        }
コード例 #23
0
        public async Task ClientThrowsUnauthorizedExceptionWhenUserDoesntHaveAccess()
        {
            await ServiceBusScope.UsingQueueAsync(partitioned : false, sessionEnabled : false, async queueName =>
            {
                var csb        = new ServiceBusConnectionStringBuilder(TestUtility.NamespaceConnectionString);
                csb.SasKeyName = "nonExistingKey";
                csb.EntityPath = queueName;

                var sender = new MessageSender(csb);

                try
                {
                    await Assert.ThrowsAsync <UnauthorizedException>(
                        async() => await sender.SendAsync(new Message()));

                    long nonExistingSequenceNumber = 1000;
                    await Assert.ThrowsAsync <UnauthorizedException>(
                        async() => await sender.CancelScheduledMessageAsync(nonExistingSequenceNumber));
                }
                finally
                {
                    await sender.CloseAsync();
                }
            });
        }
コード例 #24
0
        async Task PeekSessionAsyncTest(string queueName, int messageCount = 10)
        {
            var sender        = new MessageSender(TestUtility.NamespaceConnectionString, queueName);
            var sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.ReceiveAndDelete);

            try
            {
                var messageId1 = "test-message1";
                var sessionId1 = "sessionId1";
                await sender.SendAsync(new Message { MessageId = messageId1, SessionId = sessionId1 });

                TestUtility.Log($"Sent Message: {messageId1} to Session: {sessionId1}");

                var messageId2 = "test-message2";
                var sessionId2 = "sessionId2";
                await sender.SendAsync(new Message { MessageId = messageId2, SessionId = sessionId2 });

                TestUtility.Log($"Sent Message: {messageId2} to Session: {sessionId2}");

                // Peek Message, Receive and Delete with SessionId - sessionId 1
                await this.PeekAndDeleteMessageAsync(sessionClient, sessionId1, messageId1);

                // Peek Message, Receive and Delete with SessionId - sessionId 2
                await this.PeekAndDeleteMessageAsync(sessionClient, sessionId2, messageId2);
            }
            finally
            {
                await sender.CloseAsync().ConfigureAwait(false);

                await sessionClient.CloseAsync().ConfigureAwait(false);
            }
        }
コード例 #25
0
        static async Task Send(string connectionString)
        {
            // Create a sender over the previously configured duplicate-detection
            // enabled queue.
            var sender = new MessageSender(connectionString, DupdetectQueueName);

            // Create the message-id
            string messageId = Guid.NewGuid().ToString();

            Console.WriteLine("\tSending messages to {0} ...", sender.Path);
            // send the first message using the message-id
            var message = new Message
            {
                MessageId  = messageId,
                TimeToLive = TimeSpan.FromMinutes(1)
            };
            await sender.SendAsync(message);

            Console.WriteLine("\t=> Sent a message with messageId {0}", message.MessageId);

            // send the second message using the message-id
            var message2 = new Message
            {
                MessageId  = messageId,
                TimeToLive = TimeSpan.FromMinutes(1)
            };
            await sender.SendAsync(message2);

            Console.WriteLine("\t=> Sent a duplicate message with messageId {0}", message.MessageId);
            await sender.CloseAsync();
        }
        async Task CompleteOnPeekedMessagesShouldThrowTest()
        {
            var sender   = new MessageSender(TestUtility.NamespaceConnectionString, TestConstants.NonPartitionedQueueName);
            var receiver = new MessageReceiver(TestUtility.NamespaceConnectionString, TestConstants.NonPartitionedQueueName, receiveMode: ReceiveMode.ReceiveAndDelete);

            try
            {
                await TestUtility.SendMessagesAsync(sender, 1);

                var message = await receiver.PeekAsync();

                Assert.NotNull(message);
                await
                Assert.ThrowsAsync <InvalidOperationException>(
                    async() => await receiver.CompleteAsync(message.SystemProperties.LockToken));

                message = await receiver.ReceiveAsync();

                Assert.NotNull((object)message);
            }
            finally
            {
                await sender.CloseAsync().ConfigureAwait(false);

                await receiver.CloseAsync().ConfigureAwait(false);
            }
        }
コード例 #27
0
        async Task SessionRenewLockTest(string queueName)
        {
            var sender        = new MessageSender(TestUtility.NamespaceConnectionString, queueName);
            var sessionClient = new SessionClient(TestUtility.NamespaceConnectionString, queueName);

            try
            {
                var messageId = "test-message1";
                var sessionId = Guid.NewGuid().ToString();
                await sender.SendAsync(new Message()
                {
                    MessageId = messageId, SessionId = sessionId
                });

                TestUtility.Log($"Sent Message: {messageId} to Session: {sessionId}");

                var sessionReceiver = await sessionClient.AcceptMessageSessionAsync(sessionId);

                Assert.NotNull(sessionReceiver);
                TestUtility.Log($"Session LockedUntilUTC: {sessionReceiver.LockedUntilUtc} for Session: {sessionReceiver.SessionId}");
                Message message = await sessionReceiver.ReceiveAsync();

                TestUtility.Log($"Received Message: {message.MessageId} from Session: {sessionReceiver.SessionId}");
                Assert.True(message.MessageId == messageId);

                TestUtility.Log("Sleeping 10 seconds...");
                await Task.Delay(TimeSpan.FromSeconds(10));

                // For session it looks like when the session is received, sometimes the session LockedUntil UTC
                // is turning out slightly more than the Default Lock Duration(lock is for 1 minute, but the session was locked
                // for 1 min and 2 seconds. We will need to look at if this is an issue on service or some kind of time SKU.
                // Temporarily changing this test to look at the renew request time instead.
                DateTime renewRequestTime = DateTime.UtcNow;
                await sessionReceiver.RenewSessionLockAsync();

                DateTime firstLockedUntilUtcTime = sessionReceiver.LockedUntilUtc;
                TestUtility.Log($"After Renew Session LockedUntilUTC: {firstLockedUntilUtcTime} for Session: {sessionReceiver.SessionId}");
                Assert.True(firstLockedUntilUtcTime >= renewRequestTime + TimeSpan.FromSeconds(10));

                TestUtility.Log("Sleeping 5 seconds...");
                await Task.Delay(TimeSpan.FromSeconds(5));

                renewRequestTime = DateTime.UtcNow;
                await sessionReceiver.RenewSessionLockAsync();

                TestUtility.Log($"After Second Renew Session LockedUntilUTC: {sessionReceiver.LockedUntilUtc} for Session: {sessionReceiver.SessionId}");
                Assert.True(sessionReceiver.LockedUntilUtc >= renewRequestTime + TimeSpan.FromSeconds(5));
                await sessionReceiver.CompleteAsync(message.SystemProperties.LockToken);

                TestUtility.Log($"Completed Message: {message.MessageId} for Session: {sessionReceiver.SessionId}");
                await sessionReceiver.CloseAsync();
            }
            finally
            {
                await sender.CloseAsync().ConfigureAwait(false);

                await sessionClient.CloseAsync().ConfigureAwait(false);
            }
        }
コード例 #28
0
 public void Dispose()
 {
     // a bit unnecessary, but good to remember if using different patters of Start / Stop
     _failureEmitter?.CloseAsync();
     _successEmitter?.CloseAsync();
     _failureConn?.CloseAsync();
     _successConn?.CloseAsync();
 }
コード例 #29
0
        private static async Task SendTo_Attendee_Topic()
        {
            var orderTopicSender = new MessageSender(SBConnectionString, AttendeeTopic.TopicName);

            await SendAttendee(orderTopicSender);

            await orderTopicSender.CloseAsync();
        }
コード例 #30
0
        public Task CloseAsync(CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            return(Task.WhenAll(
                       _messageSender.CloseAsync(),
                       _messageReceiver.CloseAsync()));
        }