3
votes

How do you delete the dead letters in an Azure Service Bus queue?

I can process the messages in the queue ...

var queueClient = QueueClient.CreateFromConnectionString(sbConnectionString, queueName);
while (queueClient.Peek() != null)
{
    var brokeredMessage = queueClient.Receive();
    brokeredMessage.Complete();
}

but can't see anyway to handle the dead letter messages

3

3 Answers

4
votes

The trick is to get the deadletter path for the queue which you can get by using QueueClient.FormatDeadLetterPath(queueName).

Please try the following:

var queueClient = QueueClient.CreateFromConnectionString(sbConnectionString, QueueClient.FormatDeadLetterPath(queueName));
while (queueClient.Peek() != null)
{
    var brokeredMessage = queueClient.Receive();
    brokeredMessage.Complete();
}
2
votes

There are some great samples available in our GitHub sample repo (https://github.com/Azure-Samples/azure-servicebus-messaging-samples). The DeadletterQueue project should show you an example of how to do this in your code:

    var dead-letterReceiver = await receiverFactory.CreateMessageReceiverAsync(
            QueueClient.FormatDeadLetterPath(queueName), ReceiveMode.PeekLock);
    while (true)
    {
        var msg = await dead-letterReceiver.ReceiveAsync(TimeSpan.Zero);
        if (msg != null)
        {
            foreach (var prop in msg.Properties)
            {
                Console.WriteLine("{0}={1}", prop.Key, prop.Value);
            }
            await msg.CompleteAsync();
        }
        else
        {
            break;
        }
    }
}

Hope that helps!

2
votes
using System;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Microsoft.Azure.ServiceBus;
using Microsoft.Azure.ServiceBus.Core;
using System.Text;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace ClearDeadLetterQ
{
    [TestClass]
    public class UnitTest1
    {

        const string ServiceBusConnectionString = "Endpoint=sb://my-domain.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=youraccesskeyhereyouraccesskeyhere";


        [TestMethod]
        public async Task TestMethod1()
        {
            await this.ClearDeadLetters("my.topic.name", "MySubscriptionName/$DeadLetterQueue");
        }

        public async Task ClearDeadLetters(string topicName, string subscriptionName)
        {
            var messageReceiver = new MessageReceiver(ServiceBusConnectionString, EntityNameHelper.FormatSubscriptionPath(topicName, subscriptionName), ReceiveMode.PeekLock);
            var message = await messageReceiver.ReceiveAsync();
            while ((message = await messageReceiver.ReceiveAsync()) != null)
            {
                await messageReceiver.CompleteAsync(message.SystemProperties.LockToken);
            }
            await messageReceiver.CloseAsync();
        }
    }
}