skip to Main Content

I have an Azure Storage Queue and want to create a service to view the contents of for admin-purposes. I know I can view the queue using Storage Explorer, but I want to be able to view the messages (and their contents) in a C# application.

From what I can see, the API allows me to get the write to and pop from the head of the queue, but I need to see all messages without removing them.

2

Answers


  1. What you need to use is PeekMessagesAsync, with that you can peek the first X messages in the queue. Example:

    // Create a QueueClient.
    var queueClient = new QueueClient("your-storage-account", "your-queue-name");
    
    // Peek at the first 32 messages in the queue.
    var messages = await queueClient.PeekMessagesAsync(32);
    

    Next you can do whatever you want with it.

    Login or Signup to reply.
  2. try using the following code:

    public static class DryRunIterator
    {
        public static async IAsyncEnumerable<ServiceBusReceivedMessage> GetMessages(string connectionString, string queueName, int prefetchCount)
        {
            await using var serviceBusClient = new ServiceBusClient(connectionString);
    
            await using var deadLetterReceiver = serviceBusClient.CreateReceiver(queueName, new ServiceBusReceiverOptions() { PrefetchCount = prefetchCount, ReceiveMode = ServiceBusReceiveMode.PeekLock });
            long? lastReceivedSequenceNumber = null;
    
            while (true)
            {
                var messages = await deadLetterReceiver.PeekMessagesAsync(prefetchCount, lastReceivedSequenceNumber + 1);
    
                if (messages.Count == 0)
                    break;
    
                foreach (var message in messages)
                {
                    yield return message;
    
                    lastReceivedSequenceNumber = message.SequenceNumber;
                }
            }
    
            await deadLetterReceiver.CloseAsync();
        }
    }
    

    it uses Azure.Messaging.ServiceBus.

    Hope this helps.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search