Quantcast
Channel: Brian Pedersen's Sitecore and .NET Blog
Viewing all articles
Browse latest Browse all 285

Read from Azure Queue with .NET Core

$
0
0

The documentation around Azure Queues and .NET Core is a little fuzzy, as the approach have changed slightly over the last updates. Previously you had a shared Storage Account NuGet Package that gave access to Queues, Blob Storage and Table storage. Now you use seperate NuGet packages, and the one for queues are:

The reading and writing to the queue have changed slightly also, so this is a simple but complete example on how to send and receive messages using Azure.Storage.Queues:

using Azure.Storage.Queues;
using Azure.Storage.Queues.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MyCode
{
  public class QueueRepository 
  {
    private int _batchCount;
    private QueueClient _client;

    /// <summary>
    /// Create a new instance of QueueRepository
    /// </summary>
    /// <param name="connectionString">Connectionstring to Azure Storage Account</param>
    /// <param name="queueName">Name of queue</param>
    /// <param name="batchCount">Number of messages to get from queue per call</param>
    public QueueRepository(string connectionString, string queueName, int batchCount)
    {
      _client = new QueueClient(connectionstring, queueName);
      _batchCount = batchCount;
    }

    /// <summary>
    /// Add a new message to the queue
    /// </summary>
    /// <param name="messageText">Contents of the message</param>
    public async Task Send(string messageText)
    {
	  // If you do not base64 encode the message before adding it, you
	  // cannot read the message using Visual Studio Cloud Explorer
      await _client.SendMessageAsync(Base64Encode(messageText));
    }

    /// <summary>
    /// Read a maximum of _batchCount messages from the queue. Once they are
	/// read, they are immediately deleted from the queue. This approach is
	/// not the default approach, and will negate the auto-retry machanism 
	/// built into the queue system. But it makes the queue easier to understand
    /// </summary>
    public async Task<IEnumerable<QueueMessage>> Receive()
    {
      int maxCount = _batchCount;
      int maxBatchCount = 32;
      List<QueueMessage> receivedMessages = new List<QueueMessage>();
      do
      {
        if (maxCount < 32)
          maxBatchCount = maxCount;
        QueueMessage[] messages = await _client.ReceiveMessagesAsync(maxBatchCount, TimeSpan.FromSeconds(30));
        receivedMessages.AddRange(messages);
        await DeleteMessageFromQueue(messages);

        if (messages.Count() < maxBatchCount)
          return receivedMessages;

        maxCount -= messages.Count();
      } while (maxCount > 0);

      return receivedMessages;
    }

    private async Task DeleteMessageFromQueue(QueueMessage[] messages)
    {
      foreach (QueueMessage message in messages)
      {
        await _client.DeleteMessageAsync(message.MessageId, message.PopReceipt);
      }
    }

    private static string Base64Encode(string plainText)
    {
      var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
      return System.Convert.ToBase64String(plainTextBytes);
    }
  }
}

EXPLANATION:

The constructor takes the azure storage account connection string and the queue name as parameters, along with a batchcount. The batchcount is how many messages are received from the queue per read.

The Send method will base64 encode the message before adding it to the queue. If you do not do this, you cannot read the message using Visual Studio Cloud Explorer.

The Receive method will read batchcount messages from the queue. Messages are deleted immediately after reading. If you do not do this, you will have to manually delete the message before 30 seconds, or the message will appear in the queue again. Delete the code that deletes from the queue if you wish that functionality.

Also, please note that messages that you receive are also base64 encoded. To decode the message you can use this QueueMessage Extension Method. The extension method will also convert a JSON queue message into an object.

MORE TO READ:


Viewing all articles
Browse latest Browse all 285

Trending Articles