Search code examples
c#azureazure-storageazure-storage-queuesazure-storage-emulator

Retrieve number of messages in CloudQueue based on condition


I'm using Azure Storage Emulator. I have a CloudQueue and some messages. I want to retrieve the number of messages where Dequeue Count is greater than 3 for example.

I can do a loop for all the messages and increment a counter when a message has a Dequeue Count > 3 but I would like to find an optimized alternative.

How can I apply filters after fetching the queue ?

CloudStorageAccount storageAccount = CloudStorageAccount.Parse(ConfigurationManager.AppSettings["StorageConnection"];
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
CloudQueue queue = queueClient.GetQueueReference("testQueue");
queue.CreateIfNotExists();

queue.FetchAttributes();

Solution

  • I can do a loop for all the messages and increment a counter when a message has a Dequeue Count > 3 but I would like to find an optimized alternative.

    AFAIK, that's the only way as Azure Storage Queues do not provide any server-side filtering mechanism based on message attributes. You will need to fetch the messages and apply filtering on the client side only.

    Here's the sample code that peeks at top 32 messages from the queue and examines DequeueCount property of the message:

            var account = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
            var queueClient = account.CreateCloudQueueClient();
            var queue = queueClient.GetQueueReference("myqueue");
            queue.CreateIfNotExists();
            var messages = queue.PeekMessages(32).ToList();
            for (var i=0; i<messages.Count; i++)
            {
                var message = messages[0];
                if (message.DequeueCount > 3)
                {
                    Console.WriteLine("Message has been dequeued more than 3 times. Do something!");
                }
            }