For purposes of our integration checking, I want to count the number of messages on an Azure queue. The method looks like this:
internal void VerifyMessagesOnQueue(string queueNameKey, int expectedNumberOfMessages)
{
var azureStorageConnectionKey = ConfigurationManager.AppSettings["AzureStorageConnectionKey"];
var storageAccount = CloudStorageAccount.Parse(azureStorageConnectionKey);
var queueClient = storageAccount.CreateCloudQueueClient();
var queue = queueClient.GetQueueReference(ConfigurationManager.AppSettings[queueNameKey]);
var messages = queue.PeekMessages(int.MaxValue);
messages.Count().Should().Be(expectedNumberOfMessages);
}
Right now I'm using var messages = queue.PeekMessages(int.MaxValue);
to try to get all the messages on a queue. It returns an HTML repsonse 400. I have tried var messages = queue.PeekMessages(expectedNumberOfMessages);
, but when expectedNumberOfMessages
is 0, I also get an HTML response 400.
How can I reliably check the number of messages on an Azure queue without disrupting it (this is why I was using .PeekMessage
)?
I want to count the number of messages on an Azure queue
I suggest you could try the following code to achieve your goal. I have created a console project to test.
StorageConnectionString in App.config:
<appSettings>
<add key="StorageConnectionString" value="DefaultEndpointsProtocol=https;AccountName=×××;AccountKey=×××" />
</appSettings>
Code in Program.cs:
static void Main(string[] args)
{
string Queue_Name = "myqueue";
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
Microsoft.Azure.CloudConfigurationManager.GetSetting("StorageConnectionString"));
CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
CloudQueue queue = queueClient.GetQueueReference(Queue_Name);
queue.FetchAttributes();
var count=queue.ApproximateMessageCount;
Console.WriteLine("message number in queue:"+count);
}
The Result about queue count: