Exemple #1
0
 static void Init()
 {
     try
     {
         _managementClient = new ManagementClient(_connectionString);
         if (!_managementClient.TopicExistsAsync(_topicName).Result)
         {
             _managementClient.CreateTopicAsync(new TopicDescription(_topicName)
             {
                 AutoDeleteOnIdle = TimeSpan.FromHours(1)
             }).Wait();
         }
         _senderTopicClient = new TopicClient(_connectionString, _topicName);
         if (!_managementClient.SubscriptionExistsAsync(_topicName, _subscriptionName).Result)
         {
             _managementClient.CreateSubscriptionAsync(new SubscriptionDescription(_topicName, _subscriptionName)
             {
                 AutoDeleteOnIdle = TimeSpan.FromMinutes(45),
                 EnableDeadLetteringOnMessageExpiration = true
             }).Wait();
         }
         string deadLetterPath = EntityNameHelper.FormatDeadLetterPath(_subscriptionName);
         _subscriptionClient           = new SubscriptionClient(_connectionString, _topicName, _subscriptionName);
         _deadLetterSubscriptionClient = new SubscriptionClient(_connectionString, _topicName, deadLetterPath);
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex);
     }
 }
        public void Create_Dead_Letter_Message_Receiver_With_Expected_NonDefault_Properties()
        {
            var config = new MyEndpointHandlingConfig
            {
                ConnectionString            = "Endpoint=sb://your-sb.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx=",
                EntityPath                  = "unittests.singlemessagetype/Subscriptions/MessageReceiverFactoryShould",
                MaxConcurrentCalls          = 2,
                MaxAutoRenewDurationSeconds = 60,
                AutoComplete                = true,
            };

            var expectedServiceBusEndpoint = "sb://your-sb.windows.net/";
            var expectedDeadLetterPath     = EntityNameHelper.FormatDeadLetterPath(config.EntityPath);
            var expectedReceiveMode        = ReceiveMode.ReceiveAndDelete;
            var expectedRetryPolicy        = new NoRetry();
            var expectedPrefetchCount      = 1;

            var messageReceiver = _messageReceiverFactory.CreateDeadLetterMessageReceiver(config, expectedReceiveMode, expectedRetryPolicy, expectedPrefetchCount);

            (messageReceiver as MessageReceiver).ServiceBusConnection.Endpoint.Should().Be(expectedServiceBusEndpoint);
            (messageReceiver as MessageReceiver).Path.Should().Be(expectedDeadLetterPath);
            (messageReceiver as MessageReceiver).ReceiveMode.Should().Be(expectedReceiveMode);
            (messageReceiver as MessageReceiver).RetryPolicy.Should().Be(expectedRetryPolicy);
            (messageReceiver as MessageReceiver).PrefetchCount.Should().Be(expectedPrefetchCount);
        }
Exemple #3
0
        private void InitializeClients(ChannelType channelType)
        {
            var channelName      = _configuration.GetServiceBusChannelName(channelType, _channel);
            var retryPolicy      = new RetryExponential(TimeSpan.FromSeconds(5), TimeSpan.FromSeconds(30), 10);
            var connectionString = _configuration.GetServiceBusConnectionString();

            switch (channelType)
            {
            case ChannelType.PublishSubscribe:
                _receiverClient = new SubscriptionClient(connectionString, channelName, _subscriptionName, retryPolicy: retryPolicy);
                _senderClient   = new TopicClient(connectionString, channelName, retryPolicy);
                break;

            case ChannelType.PointToPoint:
                var queueClient = new QueueClient(connectionString, channelName, ReceiveMode.PeekLock, retryPolicy);
                _receiverClient = queueClient;
                _senderClient   = queueClient;
                break;

            default:
                throw new Exception($"Unkown channel type {channelType}");
            }

            string deadPath = EntityNameHelper.FormatDeadLetterPath(_receiverClient.Path);

            _deadLetterQueue = new MessageReceiver(connectionString, deadPath, ReceiveMode.PeekLock);
        }
Exemple #4
0
        public MessageReceiver GetTopicDeadLetterClient()
        {
            string subscriptionPath = EntityNameHelper.FormatSubscriptionPath(_config.Topic, _config.Subscription);
            string deadLetterPath   = EntityNameHelper.FormatDeadLetterPath(subscriptionPath);

            return(new MessageReceiver(_config.Connection, deadLetterPath, ReceiveMode.PeekLock, RetryPolicy.Default, 0));
        }
Exemple #5
0
 string GetEntityPath(bool deadLetterQueue)
 {
     if (deadLetterQueue)
     {
         if (queueDescription != null)
         {
             return(EntityNameHelper.FormatDeadLetterPath(queueDescription.Path));
         }
         else
         {
             var subscriptionPath = EntityNameHelper.FormatSubscriptionPath(subscriptionWrapper.TopicDescription.Path,
                                                                            subscriptionWrapper.SubscriptionDescription.SubscriptionName);
             return(EntityNameHelper.FormatDeadLetterPath(subscriptionPath));
         }
     }
     else
     {
         if (queueDescription != null)
         {
             return(queueDescription.Path);
         }
         else
         {
             return(EntityNameHelper.FormatSubscriptionPath(subscriptionWrapper.TopicDescription.Path,
                                                            subscriptionWrapper.SubscriptionDescription.SubscriptionName));
         }
     }
 }
        public async Task <long> PurgeMessages(string connectionString, string topicPath, string subscriptionPath,
                                               bool isDlq)
        {
            var path = EntityNameHelper.FormatSubscriptionPath(topicPath, subscriptionPath);

            path = isDlq ? EntityNameHelper.FormatDeadLetterPath(path) : path;

            long purgedCount      = 0;
            var  receiver         = new MessageReceiver(connectionString, path, ReceiveMode.ReceiveAndDelete);
            var  operationTimeout = TimeSpan.FromSeconds(5);

            while (true)
            {
                var messages = await receiver.ReceiveAsync(_maxMessageCount, operationTimeout);

                if (messages == null || messages.Count == 0)
                {
                    break;
                }

                purgedCount += messages.Count;
            }

            await receiver.CloseAsync();

            return(purgedCount);
        }
Exemple #7
0
 public Resender(string connectionString, ResenderArguments a) :
     base(connectionString, EntityNameHelper.FormatDeadLetterPath(a.Type == BusType.Queue ? a.TopicQueueName : EntityNameHelper.FormatSubscriptionPath(a.TopicQueueName, a.Name)))
 {
     Sender = a.Type == BusType.Queue ?
              (ISenderClient) new QueueClient(connectionString, a.TopicQueueName) :
              new TopicClient(connectionString, a.TopicQueueName);
 }
        private static async Task MainAsync()
        {
            var client = new QueueClient("<connection-string>",
                                         "myfirstqueue");

            client.RegisterSessionHandler((session, message, ct) => Task.FromResult(new SessionHandler()), args => Task.CompletedTask);

            var receiver =
                new MessageReceiver(
                    "<connection-string>",
                    "myfirstqueue");

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

                if (message == null)
                {
                    continue;
                }

                Console.WriteLine($"New message: [{message.ScheduledEnqueueTimeUtc}] {Encoding.UTF8.GetString(message.Body)}");

                await receiver.DeadLetterAsync(message.SystemProperties.LockToken, "HandsOnAzure - test");

                await Task.Delay(100);

                var dtqname = EntityNameHelper.FormatDeadLetterPath("myfirstqueue");
            }
        }
Exemple #9
0
        public async Task <List <DeadLetterQueueMessage> > GetSubscriptionMessages(string topicName, string subscriptionName)
        {
            var deadLetterName = EntityNameHelper.FormatDeadLetterPath(EntityNameHelper.FormatSubscriptionPath(topicName, subscriptionName));
            var messages       = await GetMessages(deadLetterName);

            return(messages);
        }
Exemple #10
0
        public async Task DeleteMessage(string connectionString, string queue,
                                        Message message, bool isDlq)
        {
            var path = isDlq ? EntityNameHelper.FormatDeadLetterPath(queue) : queue;

            var receiver = new MessageReceiver(connectionString, path, ReceiveMode.PeekLock);

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

                if (messages == null || messages.Count == 0)
                {
                    break;
                }

                var foundMessage = messages.FirstOrDefault(m => m.MessageId.Equals(message.MessageId));
                if (foundMessage != null)
                {
                    await receiver.CompleteAsync(foundMessage.SystemProperties.LockToken);

                    break;
                }
            }

            await receiver.CloseAsync();
        }
        async Task TopicClientPeekLockWithDeadLetterTestCase(bool partitioned, bool sessionEnabled, int messageCount = 10)
        {
            await ServiceBusScope.UsingTopicAsync(partitioned, sessionEnabled, async (topicName, subscriptionName) =>
            {
                var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
                var subscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicName,
                    subscriptionName);

                // Create DLQ Client To Receive DeadLetteredMessages
                var subscriptionDeadletterPath   = EntityNameHelper.FormatDeadLetterPath(subscriptionName);
                var deadLetterSubscriptionClient = new SubscriptionClient(
                    TestUtility.NamespaceConnectionString,
                    topicName,
                    subscriptionDeadletterPath);

                try
                {
                    await
                    this.PeekLockWithDeadLetterTestCase(
                        topicClient.InnerSender,
                        subscriptionClient.InnerSubscriptionClient.InnerReceiver,
                        deadLetterSubscriptionClient.InnerSubscriptionClient.InnerReceiver,
                        messageCount);
                }
                finally
                {
                    await deadLetterSubscriptionClient.CloseAsync();
                    await topicClient.CloseAsync();
                    await subscriptionClient.CloseAsync();
                }
            });
        }
Exemple #12
0
        public async Task <List <DeadLetterQueueMessage> > GetQueueMessages(string queueName)
        {
            var deadLetterName = EntityNameHelper.FormatDeadLetterPath(queueName);
            var messages       = await GetMessages(deadLetterName);

            return(messages);
        }
Exemple #13
0
        public async virtual Task RequeueAllDeadLettersAsync(string filter = null)
        {
            _logger?.LogDebug($"Requeuing messages to {QueueName}.");
            var queueClient       = new QueueClient(ConnectionString, QueueName);
            var deadQueuePath     = EntityNameHelper.FormatDeadLetterPath(QueueName);
            var deadQueueReceiver = new MessageReceiver(ConnectionString, deadQueuePath);
            var messages          = await deadQueueReceiver.ReceiveAsync(100, new System.TimeSpan(0, 0, 10));

            var remainingMessages = new List <Message>();
            var targetMessages    = new List <Message>();

            while (messages != null && messages.Any())
            {
                targetMessages.AddRange(string.IsNullOrWhiteSpace(filter) ? messages.ToList() : messages.AsQueryable().Where(filter).ToList());
                remainingMessages.AddRange(messages.Where(a => !targetMessages.Exists(b => b.SystemProperties.LockToken == a.SystemProperties.LockToken)));
                messages = await deadQueueReceiver.ReceiveAsync(100, new System.TimeSpan(0, 0, 10));
            }

            remainingMessages.ForEach(a => deadQueueReceiver.AbandonAsync(a.SystemProperties.LockToken));
            targetMessages.ToList().ForEach(async a =>
            {
                await queueClient.SendAsync(a.Clone());
                await deadQueueReceiver.CompleteAsync(a.SystemProperties.LockToken);
            });
        }
Exemple #14
0
        private Task PickUpAndFixDeadletters(string connectionString, string queueName, CancellationToken cancellationToken)
        {
            var doneReceiving = new TaskCompletionSource <bool>();

            // here, we create a receiver on the Deadletter queue
            var dlqReceiver = new MessageReceiver(connectionString, EntityNameHelper.FormatDeadLetterPath(queueName), ReceiveMode.PeekLock);

            // close the receiver and factory when the CancellationToken fires
            cancellationToken.Register(
                async() =>
            {
                await dlqReceiver.CloseAsync();
                doneReceiving.SetResult(true);
            });

            // register the RegisterMessageHandler callback
            dlqReceiver.RegisterMessageHandler(
                async(message, cancellationToken1) =>
            {
                // first, we create a clone of the picked up message
                // that we can resubmit.
                var resubmitMessage = message.Clone();

                // finally complete the original message and remove it from the DLQ
                await dlqReceiver.CompleteAsync(message.SystemProperties.LockToken);
            },
                new MessageHandlerOptions((e) => LogMessageHandlerException(e))
            {
                AutoComplete = false, MaxConcurrentCalls = 1
            });

            return(doneReceiving.Task);
        }
        /// <summary>
        /// Tries receiving a single dead lettered message on the Azure Service Bus dead letter queue.
        /// </summary>
        /// <param name="connectionString">The connection string to connect to the Azure Service Bus.</param>
        public async Task AssertDeadLetterMessageAsync(string connectionString)
        {
            var connectionStringBuilder = new ServiceBusConnectionStringBuilder(connectionString);

            connectionStringBuilder.EntityPath = EntityNameHelper.FormatDeadLetterPath(connectionStringBuilder.EntityPath);
            var messageReceiver = new MessageReceiver(connectionStringBuilder, ReceiveMode.ReceiveAndDelete);

            try
            {
                bool received = false;
                messageReceiver.RegisterMessageHandler(
                    async(message, ct) =>
                {
                    received = true;
                    _logger.LogInformation("Received dead lettered message in test suite");
                    await messageReceiver.CompleteAsync(message.SystemProperties.LockToken);
                },
                    new MessageHandlerOptions(exception =>
                {
                    _logger.LogError(exception.Exception, "Failure during receiving dead lettered messages");
                    return(Task.CompletedTask);
                }));

                Policy.Timeout(TimeSpan.FromMinutes(2))
                .Wrap(Policy.HandleResult <bool>(result => !result)
                      .WaitAndRetryForever(i => TimeSpan.FromSeconds(1)))
                .Execute(() => received);
            }
            finally
            {
                await messageReceiver.CloseAsync();
            }
        }
        async Task TopicClientPeekLockWithDeadLetterTestCase(string topicName, int messageCount = 10)
        {
            var topicClient        = new TopicClient(TestUtility.NamespaceConnectionString, topicName);
            var subscriptionClient = new SubscriptionClient(
                TestUtility.NamespaceConnectionString,
                topicName,
                this.SubscriptionName);

            // Create DLQ Client To Receive DeadLetteredMessages
            var subscriptionDeadletterPath   = EntityNameHelper.FormatDeadLetterPath(this.SubscriptionName);
            var deadLetterSubscriptionClient = new SubscriptionClient(
                TestUtility.NamespaceConnectionString,
                topicName,
                subscriptionDeadletterPath);

            try
            {
                await
                this.PeekLockWithDeadLetterTestCase(
                    topicClient.InnerSender,
                    subscriptionClient.InnerSubscriptionClient.InnerReceiver,
                    deadLetterSubscriptionClient.InnerSubscriptionClient.InnerReceiver,
                    messageCount);
            }
            finally
            {
                await deadLetterSubscriptionClient.CloseAsync();

                await topicClient.CloseAsync();

                await subscriptionClient.CloseAsync();
            }
        }
        async Task DeadLetterFireEvents()
        {
            await ServiceBusScope.UsingQueueAsync(partitioned : false, sessionEnabled : false, async queueName =>
            {
                this.queueClient = new QueueClient(TestUtility.NamespaceConnectionString, queueName, ReceiveMode.PeekLock);
                await TestUtility.SendMessagesAsync(this.queueClient.InnerSender, 1);
                var messages = await TestUtility.ReceiveMessagesAsync(this.queueClient.InnerReceiver, 1);

                this.listener.Enable((name, queue, arg) => name.Contains("DeadLetter"));
                await TestUtility.DeadLetterMessagesAsync(this.queueClient.InnerReceiver, messages);
                this.listener.Disable();

                QueueClient deadLetterQueueClient = null;
                try
                {
                    deadLetterQueueClient = new QueueClient(TestUtility.NamespaceConnectionString,
                                                            EntityNameHelper.FormatDeadLetterPath(this.queueClient.QueueName), ReceiveMode.ReceiveAndDelete);
                    await TestUtility.ReceiveMessagesAsync(deadLetterQueueClient.InnerReceiver, 1);
                }
                finally
                {
                    deadLetterQueueClient?.CloseAsync().Wait(TimeSpan.FromSeconds(maxWaitSec));
                }

                Assert.True(this.events.TryDequeue(out var deadLetterStart));
                AssertDeadLetterStart(queueName, deadLetterStart.eventName, deadLetterStart.payload, deadLetterStart.activity, null);

                Assert.True(this.events.TryDequeue(out var deadLetterStop));
                AssertDeadLetterStop(queueName, deadLetterStop.eventName, deadLetterStop.payload, deadLetterStop.activity,
                                     deadLetterStart.activity);

                Assert.True(this.events.IsEmpty);
            });
        }
        private void btnConnect_Click(object sender, RoutedEventArgs e)
        {
            //clear the messages since we're switching queues.
            _messages.Clear();

            if (!string.IsNullOrWhiteSpace(tbxConnStrings.Text) && !string.IsNullOrWhiteSpace(tbxQueue.Text))
            {
                try
                {
                    string queueName = cbxDeadLetter.IsChecked.Value ? EntityNameHelper.FormatDeadLetterPath(tbxQueue.Text) : $"{tbxQueue.Text}";

                    queueClient = new QueueClient(tbxConnStrings.Text, queueName, ReceiveMode.PeekLock);
                    RegisterOnMessageHandlerAndReceiveMessages();
                    MessageBox.Show("Connection Successful!");
                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.Message, "Error!", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            else
            {
                MessageBox.Show("Connection String and Queue Name Required!", "Error!");
            }
        }
Exemple #19
0
        internal async Task <string> GetDeadLetterMessage()
        {
            var dlqName = EntityNameHelper.FormatDeadLetterPath(queuePath);
            var message = await(new MessageReceiver(connectionString, dlqName, receiveMode: ReceiveMode.ReceiveAndDelete).ReceiveAsync(maxMessageCount: 1, operationTimeout: TimeSpan.FromSeconds(1)));
            var msg     = message?.FirstOrDefault();

            return(msg == null ? null : UTF8Encoding.UTF8.GetString(msg.Body));
        }
Exemple #20
0
        public IMessageReceiver Create(string queueName, ReceiveMode receiveMode, bool isDeadLetterQueue = false)
        {
            string path = EntityNameHelper.FormatSubscriptionPath(_connectionDetails.TopicName, queueName);

            if (isDeadLetterQueue)
            {
                path = EntityNameHelper.FormatDeadLetterPath(path);
            }
            return(new MessageReceiver(_connectionDetails.ServiceBusConnectionString, path, receiveMode, RetryPolicy.NoRetry, 0));
        }
        async Task ExceedMaxDelivery(string connectionString, string queueName)
        {
            var receiver = new MessageReceiver(connectionString, queueName, ReceiveMode.PeekLock);

            while (true)
            {
                // Ask the broker to return any message readily available or return with no
                // result after 2 seconds (allowing for clients with great network latency)
                var msg = await receiver.ReceiveAsync(TimeSpan.FromSeconds(2));

                if (msg != null)
                {
                    // Now we immediately abandon the message, which increments the DeliveryCount
                    Console.WriteLine("Picked up message; DeliveryCount {0}", msg.SystemProperties.DeliveryCount);
                    await receiver.AbandonAsync(msg.SystemProperties.LockToken);
                }
                else
                {
                    // Once the system moves the message to the DLQ, the main queue is empty
                    // and the loop exits as ReceiveAsync returns null.
                    break;
                }
            }

            // For picking up the message from a DLQ, we make a receiver just like for a
            // regular queue. We could also use QueueClient and a registered handler here.
            // The required path is constructed with the EntityNameHelper.FormatDeadLetterPath()
            // helper method, and always follows the pattern "{entity}/$DeadLetterQueue",
            // meaning that for a queue "Q1", the path is "Q1/$DeadLetterQueue" and for a
            // topic "T1" and subscription "S1", the path is "T1/Subscriptions/S1/$DeadLetterQueue"
            var deadletterReceiver = new MessageReceiver(connectionString, EntityNameHelper.FormatDeadLetterPath(queueName), ReceiveMode.PeekLock);

            while (true)
            {
                // receive a message
                var msg = await deadletterReceiver.ReceiveAsync(TimeSpan.FromSeconds(10));

                if (msg != null)
                {
                    // write out the message and its user properties
                    Console.WriteLine("Deadletter message:");
                    foreach (var prop in msg.UserProperties)
                    {
                        Console.WriteLine("{0}={1}", prop.Key, prop.Value);
                    }
                    // complete and therefore remove the message from the DLQ
                    await deadletterReceiver.CompleteAsync(msg.SystemProperties.LockToken);
                }
                else
                {
                    // DLQ was empty on last receive attempt
                    break;
                }
            }
        }
Exemple #22
0
        public async Task <IList <Message> > GetDlqMessages(string connectionString, string queueName)
        {
            var deadletterPath = EntityNameHelper.FormatDeadLetterPath(queueName);

            var receiver         = new MessageReceiver(connectionString, deadletterPath, ReceiveMode.PeekLock);
            var receivedMessages = await receiver.PeekAsync(_maxMessageCount);

            await receiver.CloseAsync();

            return(receivedMessages.Select(message => new Message(message, true)).ToList());
        }
Exemple #23
0
        private async Task <AzureMessage> PeekDlqMessageBySequenceNumber(string connectionString, string queue, long sequenceNumber)
        {
            var deadletterPath = EntityNameHelper.FormatDeadLetterPath(queue);

            var receiver     = new MessageReceiver(connectionString, deadletterPath, ReceiveMode.PeekLock);
            var azureMessage = await receiver.PeekBySequenceNumberAsync(sequenceNumber);

            await receiver.CloseAsync();

            return(azureMessage);
        }
Exemple #24
0
        public async Task MessagesCanBeDeferred(int messageSizeKb, int timesToDefer, int timesToAbandon, bool complete, int expectedCalls)
        {
            var settings = TestHelpers.GetSettings();
            var handlers = new Dictionary <string, IMessageHandler>();

            handlers.Add(typeof(DeferralTestMessage).FullName, new DeferralTestMessageHandler());
            var mhf       = new GenericMessageHandlerFactory(handlers);
            var container = TestHelpers.GetContainer(settings, mhf);

            var factory = container.GetInstance <IMessagingFactory>();
            var handler = factory.MessageHandlerFactory.CreateMessageHandler(typeof(DeferralTestMessage)) as DeferralTestMessageHandler;

            var queueName = "my-first-queue";

            var sender = factory.CreateMessageSender(queueName);

            var message = new DeferralTestMessage()
            {
                NumberOfTimesToDefer   = timesToDefer,
                NumberOfTimesToAbandon = timesToAbandon,
                Complete = complete,
            };

            // Pad the ALongString property out to meet the required message size
            for (int i = 0; i < messageSizeKb * 16; ++i)
            {
                message.ALongString += "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
            }

            // Send a message to be deferred, then abandoned, then deadlettered or completed
            await sender.Send(message).ConfigureAwait(false);

            await TestHelpers.PumpQueueUntil(factory, queueName, async() =>
            {
                if (handler.Calls.Count != expectedCalls)
                {
                    return(false);
                }

                // if we deferred any messages, there should be 2 raw messages in the DLQ - 1 actual message and 1 control message from the deferral
                var expectedDeadLetteredItems = 0;
                if (complete == false)
                {
                    expectedDeadLetteredItems = timesToDefer > 0 ? 2 : 1;
                }
                var deadLetterQueue   = EntityNameHelper.FormatDeadLetterPath(queueName);
                var deadLetteredItems = await TestHelpers.GetAllRawMessagesByContextId(settings, deadLetterQueue).ConfigureAwait(false);
                return(expectedDeadLetteredItems == deadLetteredItems.Count);
            }).ConfigureAwait(false);

            Assert.AreEqual(expectedCalls, handler.Calls.Count);
        }
Exemple #25
0
        static async Task QueueFunction()
        {
            _client = new QueueClient(_bus_connectionstring, EntityNameHelper.FormatDeadLetterPath(_queue_name));

            var _options = new MessageHandlerOptions(ExceptionReceived)
            {
                MaxConcurrentCalls = 1,
                AutoComplete       = false
            };

            _client.RegisterMessageHandler(Process_Message, _options);
            Console.ReadKey();
        }
        Task PickUpAndFixDeadletters(string connectionString, string queueName, MessageSender resubmitSender, CancellationToken cancellationToken)
        {
            var doneReceiving = new TaskCompletionSource <bool>();

            // here, we create a receiver on the Deadletter queue
            var dlqReceiver = new MessageReceiver(connectionString, EntityNameHelper.FormatDeadLetterPath(queueName), ReceiveMode.PeekLock);

            // close the receiver and factory when the CancellationToken fires
            cancellationToken.Register(
                async() =>
            {
                await dlqReceiver.CloseAsync();
                doneReceiving.SetResult(true);
            });

            // register the RegisterMessageHandler callback
            dlqReceiver.RegisterMessageHandler(
                async(message, cancellationToken1) =>
            {
                // first, we create a clone of the picked up message
                // that we can resubmit.
                var resubmitMessage = message.Clone();
                // if the cloned message has an "error" we know the main loop
                // can't handle, let's fix the message
                if (resubmitMessage.Label != null && resubmitMessage.Label.Equals("Physicist"))
                {
                    lock (Console.Out)
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine(
                            "\t\tFixing: \n\t\t\tMessageId = {0}, \n\t\t\tSequenceNumber = {1}, \n\t\t\tLabel = {2}",
                            message.MessageId,
                            message.SystemProperties.SequenceNumber,
                            message.Label);
                        Console.ResetColor();
                    }
                    // set the label to "Scientist"
                    resubmitMessage.Label = "Scientist";
                    // and re-enqueue the cloned message
                    await resubmitSender.SendAsync(resubmitMessage);
                }
                // finally complete the original message and remove it from the DLQ
                await dlqReceiver.CompleteAsync(message.SystemProperties.LockToken);
            },
                new MessageHandlerOptions((e) => LogMessageHandlerException(e))
            {
                AutoComplete = false, MaxConcurrentCalls = 1
            });

            return(doneReceiving.Task);
        }
Exemple #27
0
        public async virtual Task DeleteAllDeadLettersAsync()
        {
            _logger?.LogDebug($"Sending message to {QueueName}.");
            var deadQueuePath     = EntityNameHelper.FormatDeadLetterPath(QueueName);
            var deadQueueReceiver = new MessageReceiver(ConnectionString, deadQueuePath);
            var messages          = await deadQueueReceiver.ReceiveAsync(100, new System.TimeSpan(0, 0, 10));

            while (messages != null && messages.Any())
            {
                await deadQueueReceiver.CompleteAsync(messages.Select(a => a.SystemProperties.LockToken));

                messages = await deadQueueReceiver.ReceiveAsync(100, new System.TimeSpan(0, 0, 10));
            }
        }
        static async Task MainAsync()
        {
            //This sample uses the EntityNameHelper.FormatDeadLetterPath method for getting the DLQ path for a given queue name/subscription path. A mesage receiver can then be configured using this DLQ path.
            deadLetterReceiver = new MessageReceiver(ServiceBusConnectionString, EntityNameHelper.FormatDeadLetterPath(EntityPath), ReceiveMode.PeekLock);

            Console.WriteLine("==========================================================================");
            Console.WriteLine("Press any key to exit after processing all the dead letter queue messages.");
            Console.WriteLine("==========================================================================");

            // Register QueueClient's DLQ MessageHandler
            RegisterDeadLetterQueueMessageHandler();

            Console.ReadKey();

            await deadLetterReceiver.CloseAsync();
        }
        static void Main(string[] args)
        {
            Utils.WriteLine("DeadLetterReceiverConsole", ConsoleColor.White);
            Console.WriteLine();
            Thread.Sleep(3000);

            var deadLetterPath = EntityNameHelper.FormatDeadLetterPath(Settings.QueuePath);

            Utils.WriteLine($"Dead letter queue path { deadLetterPath }", ConsoleColor.Cyan);
            QueueClient = new QueueClient(Settings.ConnectionString, deadLetterPath);
            ReceiveDeadLetterMessages();

            Utils.WriteLine("Receiving dead letter messages", ConsoleColor.Cyan);
            Console.WriteLine();
            Console.ReadLine();
        }
Exemple #30
0
        private static void Run(BaseOptions opts)
        {
            var loggerFactory = LoggerFactory.Create(builder => {
                builder
                .AddFilter("Microsoft", LogLevel.Warning)
                .AddFilter("System", LogLevel.Warning)
                .SetMinimumLevel(LogLevel.Debug)
                .AddConsole();
            });

            logger = loggerFactory.CreateLogger <Program>();
            var handler = new AmqpMessageHandler(loggerFactory.CreateLogger <AmqpMessageHandler>(), opts);

            logger.LogInformation($"Shoveling messages for {EntityNameHelper.FormatDeadLetterPath(opts.Queue)}");
            ResendDeadLetters(handler, opts);
            logger.LogInformation("Messages shoveled");
        }