Search code examples
c#azure-storagemessage-queuedead-lettermessage-bus

How to retrieve Dead Letter Queue count?


Question

How do i get the dead letter queue length without receiving each message and counting how many message I received?

My Current Implementation

 public int GetDeadLetterQueueCount()
    {
        //Ref:http://stackoverflow.com/questions/22681954/how-do-you-access-the-dead-letter-sub-queue-on-an-azure-subscription

        MessagingFactory factory = MessagingFactory.CreateFromConnectionString(CloudConnectionString);

        QueueClient deadLetterClient = factory.CreateQueueClient(QueueClient.FormatDeadLetterPath(_QueueClient.Path), ReceiveMode.PeekLock);
        BrokeredMessage receivedDeadLetterMessage;

        List<string> lstDeadLetterQueue = new List<string>();

        // Ref: https://code.msdn.microsoft.com/Brokered-Messaging-Dead-22536dd8/sourcecode?fileId=123792&pathId=497121593
        // Log the dead-lettered messages that could not be processed:

        while ((receivedDeadLetterMessage = deadLetterClient.Receive(TimeSpan.FromSeconds(10))) != null)
        {
                lstDeadLetterQueue.Add(String.Format("DeadLettering Reason is \"{0}\" and Deadlettering error description is \"{1}\"",
                receivedDeadLetterMessage.Properties["DeadLetterReason"],
                receivedDeadLetterMessage.Properties["DeadLetterErrorDescription"]));
                var locktime = receivedDeadLetterMessage.LockedUntilUtc;
        }

        return lstDeadLetterQueue.Count;
    }

Problem with implementation

Because I am receiving each message in peek and block mode, the messages have a lock duration set. During this time i cannot receive or even see the messages again until this time period has timed out.

There must be an easier way of just getting the count without having to poll the queue?

I do not want to consume the messages either, i would just like the count of the total amount.


Solution

  • You can use the NamespaceManager's GetQueue() method which has a MessageCountDetails property, which in turn has a DeadLetterMessageCount property. Something like:

    var namespaceManager = Microsoft.ServiceBus.NamespaceManager.CreateFromConnectionString("<CONN_STRING>");
    var messageDetails = namespaceManager.GetQueue("<QUEUE_NAME>").MessageCountDetails;
    var deadLetterCount = messageDetails.DeadLetterMessageCount;