Beispiel #1
0
 private static void PrintReceivedMessage(ServiceBusReceivedMessage message)
 {
     Console.ForegroundColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), message.Subject);
     Console.WriteLine($"Received message with color: {message.ApplicationProperties["Color"]}, CorrelationId: {message.CorrelationId}");
     Console.ResetColor();
 }
Beispiel #2
0
        /// <summary>
        /// Sets the <see cref="ServiceBusReceivedMessage.ReplyTo"/>.
        /// </summary>
        /// <param name="message">The message to modify.</param>
        /// <param name="replyTo">The reply to value to set on the message.</param>

        protected void SetReplyTo(ServiceBusReceivedMessage message, string replyTo)
        {
            message.AmqpMessage.Properties.ReplyTo = new AmqpAddress(replyTo);
        }
        public async Task CrossEntityTransactionReceivesFirstRollback()
        {
            await using var client = CreateCrossEntityTxnClient();
            await using var queueA = await ServiceBusScope.CreateWithQueue(enablePartitioning : false, enableSession : false);

            await using var queueB = await ServiceBusScope.CreateWithQueue(enablePartitioning : false, enableSession : false);

            await using var topicC = await ServiceBusScope.CreateWithTopic(enablePartitioning : false, enableSession : false);

            await using var noTxClient = CreateClient();
            var senderA   = noTxClient.CreateSender(queueA.QueueName);
            var receiverA = client.CreateReceiver(queueA.QueueName);
            var senderB   = client.CreateSender(queueB.QueueName);
            var senderC   = client.CreateSender(topicC.TopicName);

            var message = new ServiceBusMessage();

            await senderA.SendMessageAsync(message);

            ServiceBusReceivedMessage receivedMessage = await receiverA.ReceiveMessageAsync();

            using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                await receiverA.CompleteMessageAsync(receivedMessage);

                await senderB.SendMessageAsync(message);

                await senderC.SendMessageAsync(message);
            }
            await receiverA.AbandonMessageAsync(receivedMessage);

            // transaction wasn't committed - verify that it was rolled back
            receivedMessage = await receiverA.ReceiveMessageAsync();

            Assert.IsNotNull(receivedMessage);
            await receiverA.AbandonMessageAsync(receivedMessage);

            var receiverB = noTxClient.CreateReceiver(queueB.QueueName);

            receivedMessage = await receiverB.ReceiveMessageAsync(TimeSpan.FromSeconds(10));

            Assert.IsNull(receivedMessage);

            var receiverC = noTxClient.CreateReceiver(topicC.TopicName, topicC.SubscriptionNames.First());

            receivedMessage = await receiverC.ReceiveMessageAsync(TimeSpan.FromSeconds(10));

            Assert.IsNull(receivedMessage);

            receivedMessage = await receiverA.ReceiveMessageAsync();

            // now commit the transaction
            using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                await receiverA.CompleteMessageAsync(receivedMessage);

                await senderB.SendMessageAsync(message);

                await senderC.SendMessageAsync(message);

                ts.Complete();
            }
            receivedMessage = await receiverA.ReceiveMessageAsync(TimeSpan.FromSeconds(10));

            Assert.IsNull(receivedMessage);
            receivedMessage = await receiverB.ReceiveMessageAsync();

            Assert.IsNotNull(receivedMessage);
            receivedMessage = await receiverC.ReceiveMessageAsync();

            Assert.IsNotNull(receivedMessage);
        }
Beispiel #4
0
 public override async Task CompleteProcessingMessageAsync(ServiceBusReceiver receiver, ServiceBusReceivedMessage message, Executors.FunctionResult result, CancellationToken cancellationToken)
 {
     _logger?.LogInformation("Custom processor End called!");
     await base.CompleteProcessingMessageAsync(receiver, message, result, cancellationToken);
 }
Beispiel #5
0
 /// <summary>
 /// Sets the <see cref="ServiceBusReceivedMessage.To"/>.
 /// </summary>
 /// <param name="message">The message to modify.</param>
 /// <param name="to">The to value to set on the message.</param>
 protected void SetTo(ServiceBusReceivedMessage message, string to)
 {
     message.AmqpMessage.Properties.To = new AmqpAddress(to);
 }
Beispiel #6
0
 /// <summary>
 /// This operation is called after a message is received, but before it is returned to the <see cref="ServiceBusReceiver"/>.
 /// It can be overridden to alter the body and the properties of an
 /// incoming message.
 /// </summary>
 /// <param name="message">The <see cref="ServiceBusReceivedMessage"/> to be modified by the plugin.</param>
 public virtual ValueTask AfterMessageReceiveAsync(ServiceBusReceivedMessage message) =>
 default;
Beispiel #7
0
        public void UserSettledPropertySetCorrectlyOnException()
        {
            var msg          = new ServiceBusReceivedMessage();
            var mockReceiver = new Mock <ServiceBusReceiver>();

            mockReceiver
            .Setup(receiver => receiver.AbandonMessageAsync(
                       It.IsAny <ServiceBusReceivedMessage>(),
                       It.IsAny <IDictionary <string, object> >(),
                       It.IsAny <CancellationToken>()))
            .Throws(new Exception());

            mockReceiver
            .Setup(receiver => receiver.DeferMessageAsync(
                       It.IsAny <ServiceBusReceivedMessage>(),
                       It.IsAny <IDictionary <string, object> >(),
                       It.IsAny <CancellationToken>()))
            .Throws(new Exception());

            mockReceiver
            .Setup(receiver => receiver.CompleteMessageAsync(
                       It.IsAny <ServiceBusReceivedMessage>(),
                       It.IsAny <CancellationToken>()))
            .Throws(new Exception());

            mockReceiver
            .Setup(receiver => receiver.DeadLetterMessageAsync(
                       It.IsAny <ServiceBusReceivedMessage>(),
                       It.IsAny <IDictionary <string, object> >(),
                       It.IsAny <CancellationToken>()))
            .Throws(new Exception());

            mockReceiver
            .Setup(receiver => receiver.DeadLetterMessageAsync(
                       It.IsAny <ServiceBusReceivedMessage>(),
                       It.IsAny <string>(),
                       It.IsAny <string>(),
                       It.IsAny <CancellationToken>()))
            .Throws(new Exception());

            var args = new ProcessMessageEventArgs(
                msg,
                mockReceiver.Object,
                CancellationToken.None);

            Assert.IsFalse(msg.IsSettled);

            msg.IsSettled = false;
            Assert.That(async() => await args.AbandonMessageAsync(msg),
                        Throws.InstanceOf <Exception>());
            Assert.IsFalse(msg.IsSettled);

            Assert.That(async() => await args.CompleteMessageAsync(msg),
                        Throws.InstanceOf <Exception>());
            Assert.IsFalse(msg.IsSettled);

            msg.IsSettled = false;
            Assert.That(async() => await args.DeadLetterMessageAsync(msg),
                        Throws.InstanceOf <Exception>());
            Assert.IsFalse(msg.IsSettled);

            msg.IsSettled = false;
            Assert.That(async() => await args.DeadLetterMessageAsync(msg, "reason"),
                        Throws.InstanceOf <Exception>());
            Assert.IsFalse(msg.IsSettled);

            msg.IsSettled = false;
            Assert.That(async() => await args.DeferMessageAsync(msg),
                        Throws.InstanceOf <Exception>());
            Assert.IsFalse(msg.IsSettled);
        }
Beispiel #8
0
 /// <summary>
 /// Sets the <see cref="ServiceBusReceivedMessage.ScheduledEnqueueTime"/>.
 /// </summary>
 /// <param name="message">The message to modify.</param>
 /// <param name="scheduledEnqueueTime">The scheduled enqueue time to set on the message.</param>
 protected void SetScheduledEnqueueTime(ServiceBusReceivedMessage message, DateTimeOffset scheduledEnqueueTime)
 {
     message.AmqpMessage.MessageAnnotations[AmqpMessageConstants.ScheduledEnqueueTimeUtcName] = scheduledEnqueueTime.UtcDateTime;
 }
Beispiel #9
0
        public async Task GetQueueRuntimeInfo()
        {
            var queueName  = nameof(GetQueueRuntimeInfo).ToLower() + Recording.Random.NewGuid().ToString("D").Substring(0, 8);
            var mgmtClient = GetClient();

            await using var sbClient = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);

            QueueProperties queue = await mgmtClient.CreateQueueAsync(queueName);

            queue = await mgmtClient.GetQueueAsync(queueName);

            // Changing Last Updated Time
            queue.AutoDeleteOnIdle = TimeSpan.FromMinutes(100);
            QueueProperties updatedQueue = await mgmtClient.UpdateQueueAsync(queue);

            // Populating 1 active message, 1 dead letter message and 1 scheduled message
            // Changing Last Accessed Time

            ServiceBusSender sender = sbClient.CreateSender(queueName);
            await sender.SendMessageAsync(new ServiceBusMessage()
            {
                MessageId = "1"
            });

            await sender.SendMessageAsync(new ServiceBusMessage()
            {
                MessageId = "2"
            });

            await sender.SendMessageAsync(new ServiceBusMessage()
            {
                MessageId = "3", ScheduledEnqueueTime = DateTime.UtcNow.AddDays(1)
            });

            ServiceBusReceiver        receiver = sbClient.CreateReceiver(queueName);
            ServiceBusReceivedMessage msg      = await receiver.ReceiveMessageAsync();

            await receiver.DeadLetterMessageAsync(msg.LockToken);

            List <QueueRuntimeProperties> runtimeInfoList = new List <QueueRuntimeProperties>();

            await foreach (QueueRuntimeProperties queueRuntimeInfo in mgmtClient.GetQueuesRuntimePropertiesAsync())
            {
                runtimeInfoList.Add(queueRuntimeInfo);
            }
            runtimeInfoList = runtimeInfoList.Where(e => e.Name.StartsWith(nameof(GetQueueRuntimeInfo).ToLower())).ToList();
            Assert.True(runtimeInfoList.Count == 1, $"Expected 1 queue but {runtimeInfoList.Count} queues returned");
            QueueRuntimeProperties runtimeInfo = runtimeInfoList.First();

            Assert.NotNull(runtimeInfo);

            Assert.AreEqual(queueName, runtimeInfo.Name);
            Assert.True(runtimeInfo.CreatedAt < runtimeInfo.UpdatedAt);
            Assert.True(runtimeInfo.UpdatedAt < runtimeInfo.AccessedAt);
            Assert.AreEqual(1, runtimeInfo.ActiveMessageCount);
            Assert.AreEqual(1, runtimeInfo.DeadLetterMessageCount);
            Assert.AreEqual(1, runtimeInfo.ScheduledMessageCount);
            Assert.AreEqual(3, runtimeInfo.TotalMessageCount);
            Assert.True(runtimeInfo.SizeInBytes > 0);

            QueueRuntimeProperties singleRuntimeInfo = await mgmtClient.GetQueueRuntimePropertiesAsync(runtimeInfo.Name);

            Assert.AreEqual(runtimeInfo.AccessedAt, singleRuntimeInfo.AccessedAt);
            Assert.AreEqual(runtimeInfo.CreatedAt, singleRuntimeInfo.CreatedAt);
            Assert.AreEqual(runtimeInfo.UpdatedAt, singleRuntimeInfo.UpdatedAt);
            Assert.AreEqual(runtimeInfo.TotalMessageCount, singleRuntimeInfo.TotalMessageCount);
            Assert.AreEqual(runtimeInfo.ActiveMessageCount, singleRuntimeInfo.ActiveMessageCount);
            Assert.AreEqual(runtimeInfo.DeadLetterMessageCount, singleRuntimeInfo.DeadLetterMessageCount);
            Assert.AreEqual(runtimeInfo.ScheduledMessageCount, singleRuntimeInfo.ScheduledMessageCount);
            Assert.AreEqual(runtimeInfo.SizeInBytes, singleRuntimeInfo.SizeInBytes);

            await mgmtClient.DeleteQueueAsync(queueName);
        }
Beispiel #10
0
        public async Task GetSubscriptionRuntimeInfoTest()
        {
            var topicName        = nameof(GetSubscriptionRuntimeInfoTest).ToLower() + Recording.Random.NewGuid().ToString("D").Substring(0, 8);
            var subscriptionName = Recording.Random.NewGuid().ToString("D").Substring(0, 8);
            var client           = GetClient();

            await using var sbClient = new ServiceBusClient(TestEnvironment.ServiceBusConnectionString);

            await client.CreateTopicAsync(topicName);

            TopicProperties getTopic = await client.GetTopicAsync(topicName);

            // Changing Last Updated Time
            getTopic.AutoDeleteOnIdle = TimeSpan.FromMinutes(100);
            await client.UpdateTopicAsync(getTopic);

            SubscriptionProperties subscriptionDescription = await client.CreateSubscriptionAsync(topicName, subscriptionName);

            // Changing Last Updated Time for subscription
            subscriptionDescription.AutoDeleteOnIdle = TimeSpan.FromMinutes(100);
            await client.UpdateSubscriptionAsync(subscriptionDescription);

            // Populating 1 active message, 1 dead letter message and 1 scheduled message
            // Changing Last Accessed Time

            ServiceBusSender sender = sbClient.CreateSender(topicName);
            await sender.SendMessageAsync(new ServiceBusMessage()
            {
                MessageId = "1"
            });

            await sender.SendMessageAsync(new ServiceBusMessage()
            {
                MessageId = "2"
            });

            await sender.SendMessageAsync(new ServiceBusMessage()
            {
                MessageId = "3", ScheduledEnqueueTime = DateTime.UtcNow.AddDays(1)
            });

            ServiceBusReceiver        receiver = sbClient.CreateReceiver(topicName, subscriptionName);
            ServiceBusReceivedMessage msg      = await receiver.ReceiveMessageAsync();

            await receiver.DeadLetterMessageAsync(msg.LockToken);

            List <SubscriptionRuntimeProperties> runtimeInfoList = new List <SubscriptionRuntimeProperties>();

            await foreach (SubscriptionRuntimeProperties subscriptionRuntimeInfo in client.GetSubscriptionsRuntimePropertiesAsync(topicName))
            {
                runtimeInfoList.Add(subscriptionRuntimeInfo);
            }
            runtimeInfoList = runtimeInfoList.Where(e => e.TopicName.StartsWith(nameof(GetSubscriptionRuntimeInfoTest).ToLower())).ToList();
            Assert.True(runtimeInfoList.Count == 1, $"Expected 1 subscription but {runtimeInfoList.Count} subscriptions returned");
            SubscriptionRuntimeProperties runtimeInfo = runtimeInfoList.First();

            Assert.NotNull(runtimeInfo);

            Assert.AreEqual(topicName, runtimeInfo.TopicName);
            Assert.AreEqual(subscriptionName, runtimeInfo.SubscriptionName);

            Assert.True(runtimeInfo.CreatedAt < runtimeInfo.UpdatedAt);
            Assert.True(runtimeInfo.UpdatedAt < runtimeInfo.AccessedAt);

            Assert.AreEqual(1, runtimeInfo.ActiveMessageCount);
            Assert.AreEqual(1, runtimeInfo.DeadLetterMessageCount);
            Assert.AreEqual(2, runtimeInfo.TotalMessageCount);

            SubscriptionRuntimeProperties singleRuntimeInfo = await client.GetSubscriptionRuntimePropertiesAsync(topicName, subscriptionName);

            Assert.AreEqual(runtimeInfo.CreatedAt, singleRuntimeInfo.CreatedAt);
            Assert.AreEqual(runtimeInfo.AccessedAt, singleRuntimeInfo.AccessedAt);
            Assert.AreEqual(runtimeInfo.UpdatedAt, singleRuntimeInfo.UpdatedAt);
            Assert.AreEqual(runtimeInfo.SubscriptionName, singleRuntimeInfo.SubscriptionName);
            Assert.AreEqual(runtimeInfo.TotalMessageCount, singleRuntimeInfo.TotalMessageCount);
            Assert.AreEqual(runtimeInfo.ActiveMessageCount, singleRuntimeInfo.ActiveMessageCount);
            Assert.AreEqual(runtimeInfo.DeadLetterMessageCount, singleRuntimeInfo.DeadLetterMessageCount);
            Assert.AreEqual(runtimeInfo.TopicName, singleRuntimeInfo.TopicName);

            List <TopicRuntimeProperties> topicRuntimePropertiesList = new List <TopicRuntimeProperties>();

            await foreach (TopicRuntimeProperties topicRuntime in client.GetTopicsRuntimePropertiesAsync())
            {
                topicRuntimePropertiesList.Add(topicRuntime);
            }
            topicRuntimePropertiesList = topicRuntimePropertiesList.Where(e => e.Name.StartsWith(nameof(GetSubscriptionRuntimeInfoTest).ToLower())).ToList();
            Assert.True(topicRuntimePropertiesList.Count == 1, $"Expected 1 subscription but {topicRuntimePropertiesList.Count} subscriptions returned");
            TopicRuntimeProperties topicRuntimeProperties = topicRuntimePropertiesList.First();

            Assert.NotNull(topicRuntimeProperties);

            Assert.AreEqual(topicName, topicRuntimeProperties.Name);
            Assert.True(topicRuntimeProperties.CreatedAt < topicRuntimeProperties.UpdatedAt);
            Assert.True(topicRuntimeProperties.UpdatedAt < topicRuntimeProperties.AccessedAt);

            Assert.AreEqual(1, topicRuntimeProperties.ScheduledMessageCount);

            TopicRuntimeProperties singleTopicRuntimeProperties = await client.GetTopicRuntimePropertiesAsync(topicName);

            Assert.AreEqual(topicRuntimeProperties.CreatedAt, singleTopicRuntimeProperties.CreatedAt);
            Assert.AreEqual(topicRuntimeProperties.AccessedAt, singleTopicRuntimeProperties.AccessedAt);
            Assert.AreEqual(topicRuntimeProperties.UpdatedAt, singleTopicRuntimeProperties.UpdatedAt);
            Assert.AreEqual(topicRuntimeProperties.ScheduledMessageCount, singleTopicRuntimeProperties.ScheduledMessageCount);
            Assert.AreEqual(topicRuntimeProperties.Name, singleTopicRuntimeProperties.Name);

            await client.DeleteTopicAsync(topicName);
        }
 protected override async Task SettleAsync(ServiceBusReceivedMessage message, CancellationToken cancellationToken)
 {
     await Receiver.DeadLetterMessageAsync(message, "reason", cancellationToken : cancellationToken);
 }
        public async Task CrossEntityTransactionSendsFirstRollback()
        {
            await using var client = CreateCrossEntityTxnClient();
            await using var queueA = await ServiceBusScope.CreateWithQueue(enablePartitioning : false, enableSession : false);

            await using var queueB = await ServiceBusScope.CreateWithQueue(enablePartitioning : false, enableSession : false);

            await using var queueC = await ServiceBusScope.CreateWithQueue(enablePartitioning : false, enableSession : false);

            await using var noTxClient = CreateClient();
            var senderA   = noTxClient.CreateSender(queueA.QueueName);
            var receiverA = client.CreateReceiver(queueA.QueueName);
            var receiverB = client.CreateReceiver(queueB.QueueName);
            var senderB   = client.CreateSender(queueB.QueueName);
            var senderC   = client.CreateSender(queueC.QueueName);
            var receiverC = noTxClient.CreateReceiver(queueC.QueueName);

            var message = new ServiceBusMessage();

            // B is the send via entity since it is first
            await senderB.SendMessageAsync(message);

            await senderA.SendMessageAsync(message);

            // you can't use a receiver after a sender (for a different entity) when using a Transaction Group because it would be
            // saying that you want to receive via the sender entity which isn't possible

            Assert.ThrowsAsync <InvalidOperationException>(async() => await receiverA.ReceiveMessageAsync());

            // After the above throws, the session gets closed by the AMQP lib, so we are testing whether the fault tolerant session/controller
            // objects get re-created correctly.

            ServiceBusReceivedMessage receivedMessageB = await receiverB.ReceiveMessageAsync();

            // If the transaction succeeds, then all the operations occurred on the same partition.
            var transaction = new CommittableTransaction();

            using (var ts = new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled))
            {
                // this is allowed because it is on B
                await receiverB.CompleteMessageAsync(receivedMessageB);

                // send to C via B - this is allowed because we are sending
                await senderC.SendMessageAsync(message);

                ts.Complete();
            }
            transaction.Rollback();
            // Adding delay since transaction Commit/Rollback is an asynchronous operation.
            await Task.Delay(TimeSpan.FromSeconds(2));

            await receiverB.AbandonMessageAsync(receivedMessageB);

            receivedMessageB = await receiverB.ReceiveMessageAsync();

            Assert.IsNotNull(receivedMessageB);
            await receiverB.AbandonMessageAsync(receivedMessageB);

            var receivedMessageC = await receiverC.ReceiveMessageAsync();

            Assert.IsNull(receivedMessageC);

            // If the transaction succeeds, then all the operations occurred on the same partition.
            using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                receivedMessageB = await receiverB.ReceiveMessageAsync();

                // this is allowed because it is on B
                await receiverB.CompleteMessageAsync(receivedMessageB);

                // this will fail because it is not part of txn group
                Assert.ThrowsAsync <ServiceBusException>(async() => await senderA.SendMessageAsync(message));

                ts.Complete();
            }

            receivedMessageB = await receiverB.ReceiveMessageAsync();

            Assert.IsNull(receivedMessageB);
        }
        public async Task CrossEntityTransactionSendsFirst(bool partitioned, bool enableSessions)
        {
            await using var client = CreateCrossEntityTxnClient();
            await using var queueA = await ServiceBusScope.CreateWithQueue(enablePartitioning : partitioned, enableSession : enableSessions);

            await using var queueB = await ServiceBusScope.CreateWithQueue(enablePartitioning : partitioned, enableSession : enableSessions);

            await using var queueC = await ServiceBusScope.CreateWithQueue(enablePartitioning : partitioned, enableSession : enableSessions);

            await using var noTxClient = CreateClient();

            var senderA = noTxClient.CreateSender(queueA.QueueName);
            ServiceBusReceiver receiverA = null;
            ServiceBusReceiver receiverB = null;
            ServiceBusReceiver receiverC = null;

            if (!enableSessions)
            {
                receiverA = client.CreateReceiver(queueA.QueueName);
                receiverB = client.CreateReceiver(queueB.QueueName);
                receiverC = noTxClient.CreateReceiver(queueC.QueueName);
            }
            var senderB = client.CreateSender(queueB.QueueName);
            var senderC = client.CreateSender(queueC.QueueName);

            var message = new ServiceBusMessage
            {
                SessionId = enableSessions ? "sessionId" : null,
                TransactionPartitionKey = partitioned ? "sessionId" : null
            };

            // B is the send via entity since it is first
            await senderB.SendMessageAsync(message);

            await senderA.SendMessageAsync(message);

            if (enableSessions)
            {
                // you can't use a receiver after a sender (for a different entity) when using a Transaction Group because it would be
                // saying that you want to receive via the sender entity which isn't possible

                Assert.ThrowsAsync <InvalidOperationException>(
                    async() =>
                    await client.AcceptNextSessionAsync(queueA.QueueName));

                receiverB = await client.AcceptNextSessionAsync(queueB.QueueName);
            }
            else
            {
                Assert.ThrowsAsync <InvalidOperationException>(async() => await receiverA.ReceiveMessageAsync());
            }
            // After the above throws, the session gets closed by the AMQP lib, so we are testing whether the fault tolerant session/controller
            // objects get re-created correctly.

            ServiceBusReceivedMessage receivedMessageB = await receiverB.ReceiveMessageAsync();

            // If the transaction succeeds, then all the operations occurred on the same partition.
            using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                // this is allowed because it is on B
                await receiverB.CompleteMessageAsync(receivedMessageB);

                // send to C via B - this is allowed because we are sending
                await senderC.SendMessageAsync(message);

                ts.Complete();
            }

            if (enableSessions)
            {
                receiverC = await noTxClient.AcceptNextSessionAsync(queueC.QueueName);
            }

            var receivedMessageC = await receiverC.ReceiveMessageAsync();

            Assert.IsNotNull(receivedMessageC);

            receivedMessageB = await receiverB.ReceiveMessageAsync();

            Assert.IsNull(receivedMessageB);

            await senderB.SendMessageAsync(message);

            // If the transaction succeeds, then all the operations occurred on the same partition.
            using (var ts = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled))
            {
                receivedMessageB = await receiverB.ReceiveMessageAsync();

                // this is allowed because it is on B
                await receiverB.CompleteMessageAsync(receivedMessageB);

                // this will fail because it is not part of txn group
                Assert.ThrowsAsync <ServiceBusException>(async() => await senderA.SendMessageAsync(message));

                ts.Complete();
            }
        }
Beispiel #14
0
        /// <summary>
        /// Sets the <see cref="ServiceBusReceivedMessage.ReplyToSessionId"/>.
        /// </summary>
        /// <param name="message">The message to modify.</param>
        /// <param name="replyToSessionId">The reply to session ID value to set on the message.</param>

        protected void SetReplyToSessionId(ServiceBusReceivedMessage message, string replyToSessionId)
        {
            message.AmqpMessage.Properties.ReplyToGroupId = replyToSessionId;
        }
 protected internal override async Task <bool> BeginProcessingMessageAsync(ServiceBusMessageActions messageActions, ServiceBusReceivedMessage message, CancellationToken cancellationToken)
 {
     _logger?.LogInformation("Custom processor Begin called!");
     return(await base.BeginProcessingMessageAsync(messageActions, message, cancellationToken));
 }
Beispiel #16
0
 /// <summary>
 /// Sets the <see cref="ServiceBusReceivedMessage.SessionId"/>.
 /// </summary>
 /// <param name="message">The message to modify.</param>
 /// <param name="sessionId">The session ID to set on the message.</param>
 protected void SetSessionId(ServiceBusReceivedMessage message, string sessionId)
 {
     message.AmqpMessage.Properties.GroupId = sessionId;
 }
Beispiel #17
0
 protected static void SBTopicListener2Impl(ServiceBusReceivedMessage message)
 {
     _resultMessage2 = message.Body.ToString() + "-topic-2";
     _topicSubscriptionCalled2.Set();
 }
Beispiel #18
0
        /// <summary>
        /// Sets the <see cref="ServiceBusReceivedMessage.TimeToLive"/>.
        /// </summary>
        /// <param name="message">The message to modify.</param>
        /// <param name="timeToLive">The time to live to set on the message.</param>

        protected void SetTimeToLive(ServiceBusReceivedMessage message, TimeSpan timeToLive)
        {
            message.AmqpMessage.Header.TimeToLive = timeToLive;
        }
Beispiel #19
0
 public static void SBTopicListener2(
     [ServiceBusTrigger(TopicNameKey, SecondSubscriptionNameKey)] ServiceBusReceivedMessage message)
 {
     SBTopicListener2Impl(message);
 }
Beispiel #20
0
 /// <summary>
 /// Sets the <see cref="ServiceBusReceivedMessage.ViaPartitionKey"/>.
 /// </summary>
 /// <param name="message">The message to modify.</param>
 /// <param name="viaPartitionKey">The via partition key to set on the message.</param>
 protected void SetViaPartitionKey(ServiceBusReceivedMessage message, string viaPartitionKey)
 {
     message.AmqpMessage.MessageAnnotations[AmqpMessageConstants.ViaPartitionKeyName] = viaPartitionKey;
 }
Beispiel #21
0
 public override async Task <bool> BeginProcessingMessageAsync(ServiceBusReceiver receiver, ServiceBusReceivedMessage message, CancellationToken cancellationToken)
 {
     _logger?.LogInformation("Custom processor Begin called!");
     return(await base.BeginProcessingMessageAsync(receiver, message, cancellationToken));
 }
Beispiel #22
0
        /// <summary>
        /// Set the <see cref="ServiceBusReceivedMessage.Body"/>.
        /// </summary>
        /// <param name="message">The message to modify.</param>
        /// <param name="body">The body to set on the message. This will overwrite any existing body.</param>
#pragma warning disable CA1822 // Mark members as static
        protected void SetBody(ServiceBusReceivedMessage message, BinaryData body)
        {
            message.AmqpMessage.Body = new AmqpMessageBody(new ReadOnlyMemory <byte>[] { body });
        }
        public async Task TransactionThrowsWhenOperationsOfDifferentPartitionsAreInSameTransaction()
        {
            await using (var scope = await ServiceBusScope.CreateWithQueue(enablePartitioning: true, enableSession: false))
            {
                await using var client = CreateClient();
                ServiceBusSender   sender   = client.CreateSender(scope.QueueName);
                ServiceBusReceiver receiver = client.CreateReceiver(scope.QueueName);

                string            body     = Guid.NewGuid().ToString("N");
                ServiceBusMessage message1 = GetMessage(partitionKey: "1");
                ServiceBusMessage message2 = GetMessage(partitionKey: "2");

                // Two send operations to different partitions.
                var transaction = new CommittableTransaction();
                using (TransactionScope ts = new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled))
                {
                    await sender.SendMessageAsync(message1);

                    Assert.ThrowsAsync <InvalidOperationException>(
                        async() => await sender.SendMessageAsync(message2));
                    ts.Complete();
                }

                transaction.Rollback();

                // 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));

                // Two complete operations to different partitions.
                await sender.SendMessageAsync(message1);

                await sender.SendMessageAsync(message2);

                ServiceBusReceivedMessage receivedMessage1 = await receiver.ReceiveMessageAsync();

                Assert.NotNull(receivedMessage1);
                ServiceBusReceivedMessage receivedMessage2 = await receiver.ReceiveMessageAsync();

                Assert.NotNull(receivedMessage2);

                transaction = new CommittableTransaction();
                using (TransactionScope ts = new TransactionScope(transaction, TransactionScopeAsyncFlowOption.Enabled))
                {
                    await receiver.CompleteMessageAsync(receivedMessage1);

                    Assert.ThrowsAsync <InvalidOperationException>(
                        async() => await receiver.CompleteMessageAsync(receivedMessage2));
                    ts.Complete();
                }

                transaction.Rollback();

                // 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));

                await receiver.CompleteMessageAsync(receivedMessage1);

                // the service seems to abandon the message that
                // triggered the InvalidOperationException
                // in the transaction
                Assert.That(
                    async() =>
                    await receiver.CompleteMessageAsync(receivedMessage2), Throws.InstanceOf <ServiceBusException>()
                    .And.Property(nameof(ServiceBusException.Reason))
                    .EqualTo(ServiceBusFailureReason.MessageLockLost));
            }
        }