Get started with Azure queue storage and Visual Studio Connected Services (ASP.NET)

Tip

Try the Microsoft Azure Storage Explorer

Microsoft Azure Storage Explorer is a free, standalone app from Microsoft that enables you to work visually with Azure Storage data on Windows, macOS, and Linux.

Overview

Azure queue storage provides cloud messaging between application components. In designing applications for scale, application components are often decoupled, so that they can scale independently. Queue storage delivers asynchronous messaging for communication between application components, whether they are running in the cloud, on the desktop, on an on-premises server, or on a mobile device. Queue storage also supports managing asynchronous tasks and building process work flows.

This tutorial shows how to write ASP.NET code for some common scenarios using Azure queue storage entities. These scenarios include common tasks such as creating an Azure queue, and adding, modifying, reading, and removing queue messages.

Prerequisites

What is Queue Storage?

Azure Queue storage is a service for storing large numbers of messages that can be accessed from anywhere in the world via authenticated calls using HTTP or HTTPS. A single queue message can be up to 64 KB in size, and a queue can contain millions of messages, up to the total capacity limit of a storage account.

Common uses of Queue storage include:

  • Creating a backlog of work to process asynchronously
  • Passing messages from an Azure web role to an Azure worker role

Queue Service Concepts

The Queue service contains the following components:

Queue1

  • URL format: Queues are addressable using the following URL format:
    http://<storage account>.queue.core.windows.net/<queue>

    The following URL addresses a queue in the diagram:

    http://myaccount.queue.core.windows.net/images-to-download

  • Storage Account: All access to Azure Storage is done through a storage account. See Azure Storage Scalability and Performance Targets for details about storage account capacity.

  • Queue: A queue contains a set of messages. All messages must be in a queue. Note that the queue name must be all lowercase. For information on naming queues, see Naming Queues and Metadata.
  • Message: A message, in any format, of up to 64 KB. The maximum time that a message can remain in the queue is 7 days.

Create an Azure storage account

The easiest way to create your first Azure storage account is by using the Azure Portal. To learn more, see Create a storage account.

You can also create an Azure storage account by using Azure PowerShell, Azure CLI, or the Storage Resource Provider Client Library for .NET.

Set up the development environment

This section walks you setting up your development environment, including creating an ASP.NET MVC app, adding a Connected Services connection, adding a controller, and specifying the required namespace directives.

Create an ASP.NET MVC app project

  1. Open Visual Studio.

  2. Select File->New->Project from the main menu

  3. On the New Project dialog, specify the options as highlighted in the following figure:

    Create ASP.NET project

  4. Select OK.

  5. On the New ASP.NET Project dialog, specify the options as highlighted in the following figure:

    Specify MVC

  6. Select OK.

Use Connected Services to connect to an Azure storage account

  1. In the Solution Explorer, right-click the project, and from the context menu, select Add->Connected Service.

  2. On the Add Connected Service dialog, select Azure Storage, and then select Configure.

    Connected Service dialog

  3. On the Azure Storage dialog, select the desired Azure storage account with which you want to work, and select Add.

Create an MVC controller

  1. In the Solution Explorer, right-click Controllers, and, from the context menu, select Add->Controller.

    Add a controller to an ASP.NET MVC app

  2. On the Add Scaffold dialog, select MVC 5 Controller - Empty, and select Add.

    Specify MVC controller type

  3. On the Add Controller dialog, name the controller QueuesController, and select Add.

    Name the MVC controller

  4. Add the following using directives to the QueuesController.cs file:

    using Microsoft.Azure;
    using Microsoft.WindowsAzure.Storage;
    using Microsoft.WindowsAzure.Storage.Auth;
    using Microsoft.WindowsAzure.Storage.Queue;
    

    Create a queue

The following steps illustrate how to create a queue:

Note

This section assumes you have completed the steps Set up the development environment.

  1. Open the QueuesController.cs file.

  2. Add a method called CreateQueue that returns an ActionResult.

    public ActionResult CreateQueue()
    {
        // The code in this section goes here.
    
        return View();
    }
    
  3. Within the CreateQueue method, get a CloudStorageAccount object that represents your storage account information. Use the following code to get the storage connection string and storage account information from the Azure service configuration: (Change <storage-account-name> to the name of the Azure storage account you're accessing.)

    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
       CloudConfigurationManager.GetSetting("<storage-account-name>_AzureStorageConnectionString"));
    
  4. Get a CloudQueueClient object represents a queue service client.

    CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
    
  5. Get a CloudQueue object that represents a reference to the desired queue name. The CloudQueueClient.GetQueueReference method does not make a request against queue storage. The reference is returned whether or not the queue exists.

    CloudQueue queue = queueClient.GetQueueReference("test-queue");
    
  6. Call the CloudQueue.CreateIfNotExists method to create the queue if it does not yet exist. The CloudQueue.CreateIfNotExists method returns true if the queue does not exist, and is successfully created. Otherwise, false is returned.

    ViewBag.Success = queue.CreateIfNotExists();
    
  7. Update the ViewBag with the name of the queue.

    ViewBag.QueueName = queue.Name;
    
  8. In the Solution Explorer, expand the Views folder, right-click Queues, and from the context menu, select Add->View.

  9. On the Add View dialog, enter CreateQueue for the view name, and select Add.

  10. Open CreateQueue.cshtml, and modify it so that it looks like the following code snippet:

    @{
        ViewBag.Title = "Create Queue";
    }
    
    <h2>Create Queue results</h2>
    
    Creation of @ViewBag.QueueName @(ViewBag.Success == true ? "succeeded" : "failed")
    
  11. In the Solution Explorer, expand the Views->Shared folder, and open _Layout.cshtml.

  12. After the last Html.ActionLink, add the following Html.ActionLink:

    <li>@Html.ActionLink("Create queue", "CreateQueue", "Queues")</li>
    
  13. Run the application, and select Create queue to see results similar to the following screen shot:

    Create queue

    As mentioned previously, the CloudQueue.CreateIfNotExists method returns true only when the queue doesn't exist and is created. Therefore, if you run the app when the queue exists, the method returns false. To run the app multiple times, you must delete the queue before running the app again. Deleting the queue can be done via the CloudQueue.Delete method. You can also delete the queue using the Azure portal or the Microsoft Azure Storage Explorer.

Add a message to a queue

Once you've created a queue, you can add messages to that queue. This section walks you through adding a message to a queue test-queue.

Note

This section assumes you have completed the steps Set up the development environment.

  1. Open the QueuesController.cs file.

  2. Add a method called AddMessage that returns an ActionResult.

    public ActionResult AddMessage()
    {
        // The code in this section goes here.
    
        return View();
    }
    
  3. Within the AddMessage method, get a CloudStorageAccount object that represents your storage account information. Use the following code to get the storage connection string and storage account information from the Azure service configuration: (Change <storage-account-name> to the name of the Azure storage account you're accessing.)

    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
       CloudConfigurationManager.GetSetting("<storage-account-name>_AzureStorageConnectionString"));
    
  4. Get a CloudQueueClient object represents a queue service client.

    CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
    
  5. Get a CloudQueueContainer object that represents a reference to the queue.

    CloudQueue queue = queueClient.GetQueueReference("test-queue");
    
  6. Create the CloudQueueMessage object representing the message you want to add to the queue. A CloudQueueMessage object can be created from either a string (in UTF-8 format) or a byte array.

    CloudQueueMessage message = new CloudQueueMessage("Hello, Azure Queue Storage");
    
  7. Call the CloudQueue.AddMessage method to add the messaged to the queue.

    queue.AddMessage(message);
    
  8. Create and set a couple of ViewBag properties for display in the view.

    ViewBag.QueueName = queue.Name;
    ViewBag.Message = message.AsString;
    
  9. In the Solution Explorer, expand the Views folder, right-click Queues, and from the context menu, select Add->View.

  10. On the Add View dialog, enter AddMessage for the view name, and select Add.

  11. Open AddMessage.cshtml, and modify it so that it looks like the following code snippet:

    @{
        ViewBag.Title = "Add Message";
    }
    
    <h2>Add Message results</h2>
    
    The message '@ViewBag.Message' was added to the queue '@ViewBag.QueueName'.
    
  12. In the Solution Explorer, expand the Views->Shared folder, and open _Layout.cshtml.

  13. After the last Html.ActionLink, add the following Html.ActionLink:

    <li>@Html.ActionLink("Add message", "AddMessage", "Queues")</li>
    
  14. Run the application, and select Add message to see results similar to the following screen shot:

    Add  message

The two sections - Read a message from a queue without removing it and Read and remove a message from a queue - illustrate how to read messages from a queue.

Read a message from a queue without removing it

This section illustrates how to peek at a queued message (read the first message without removing it).

Note

This section assumes you have completed the steps Set up the development environment.

  1. Open the QueuesController.cs file.

  2. Add a method called PeekMessage that returns an ActionResult.

    public ActionResult PeekMessage()
    {
        // The code in this section goes here.
    
        return View();
    }
    
  3. Within the PeekMessage method, get a CloudStorageAccount object that represents your storage account information. Use the following code to get the storage connection string and storage account information from the Azure service configuration: (Change <storage-account-name> to the name of the Azure storage account you're accessing.)

    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
       CloudConfigurationManager.GetSetting("<storage-account-name>_AzureStorageConnectionString"));
    
  4. Get a CloudQueueClient object represents a queue service client.

    CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
    
  5. Get a CloudQueueContainer object that represents a reference to the queue.

    CloudQueue queue = queueClient.GetQueueReference("test-queue");
    
  6. Call the CloudQueue.PeekMessage method to read the first message in the queue without removing it from the queue.

    CloudQueueMessage message = queue.PeekMessage();
    
  7. Update the ViewBag with two values: the queue name and the message that was read. The CloudQueueMessage object exposes two properties for getting the object's value: CloudQueueMessage.AsBytes and CloudQueueMessage.AsString. AsString (used in this example) returns a string, while AsBytes returns a byte array.

    ViewBag.QueueName = queue.Name; 
    ViewBag.Message = (message != null ? message.AsString : "");
    
  8. In the Solution Explorer, expand the Views folder, right-click Queues, and from the context menu, select Add->View.

  9. On the Add View dialog, enter PeekMessage for the view name, and select Add.

  10. Open PeekMessage.cshtml, and modify it so that it looks like the following code snippet:

    @{
        ViewBag.Title = "PeekMessage";
    }
    
    <h2>Peek Message results</h2>
    
    <table border="1">
        <tr><th>Queue</th><th>Peeked Message</th></tr>
        <tr><td>@ViewBag.QueueName</td><td>@ViewBag.Message</td></tr>
    </table>    
    
  11. In the Solution Explorer, expand the Views->Shared folder, and open _Layout.cshtml.

  12. After the last Html.ActionLink, add the following Html.ActionLink:

    <li>@Html.ActionLink("Peek message", "PeekMessage", "Queues")</li>
    
  13. Run the application, and select Peek message to see results similar to the following screen shot:

    Peek message

Read and remove a message from a queue

In this section, you learn how to read and remove a message from a queue.

Note

This section assumes you have completed the steps Set up the development environment.

  1. Open the QueuesController.cs file.

  2. Add a method called ReadMessage that returns an ActionResult.

    public ActionResult ReadMessage()
    {
        // The code in this section goes here.
    
        return View();
    }
    
  3. Within the ReadMessage method, get a CloudStorageAccount object that represents your storage account information. Use the following code to get the storage connection string and storage account information from the Azure service configuration: (Change <storage-account-name> to the name of the Azure storage account you're accessing.)

    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
       CloudConfigurationManager.GetSetting("<storage-account-name>_AzureStorageConnectionString"));
    
  4. Get a CloudQueueClient object represents a queue service client.

    CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
    
  5. Get a CloudQueueContainer object that represents a reference to the queue.

    CloudQueue queue = queueClient.GetQueueReference("test-queue");
    
  6. Call the CloudQueue.GetMessage method to read the first message in the queue. The CloudQueue.GetMessage method makes the message invisible for 30 seconds (by default) to any other code reading messages so that no other code can modify or delete the message while your processing it. To change the amount of time the message is invisible, modify the visibilityTimeout parameter being passed to the CloudQueue.GetMessage method.

    // This message will be invisible to other code for 30 seconds.
    CloudQueueMessage message = queue.GetMessage();     
    
  7. Call the CloudQueueMessage.Delete method to delete the message from the queue.

    queue.DeleteMessage(message);
    
  8. Update the ViewBag with the message deleted, and the name of the queue.

    ViewBag.QueueName = queue.Name;
    ViewBag.Message = message.AsString;
    
  9. In the Solution Explorer, expand the Views folder, right-click Queues, and from the context menu, select Add->View.

  10. On the Add View dialog, enter ReadMessage for the view name, and select Add.

  11. Open ReadMessage.cshtml, and modify it so that it looks like the following code snippet:

    @{
        ViewBag.Title = "ReadMessage";
    }
    
    <h2>Read Message results</h2>
    
    <table border="1">
        <tr><th>Queue</th><th>Read (and Deleted) Message</th></tr>
        <tr><td>@ViewBag.QueueName</td><td>@ViewBag.Message</td></tr>
    </table>
    
  12. In the Solution Explorer, expand the Views->Shared folder, and open _Layout.cshtml.

  13. After the last Html.ActionLink, add the following Html.ActionLink:

    <li>@Html.ActionLink("Read/Delete message", "ReadMessage", "Queues")</li>
    
  14. Run the application, and select Read/Delete message to see results similar to the following screen shot:

    Read and delete message

Get the queue length

This section illustrates how to get the queue length (number of messages).

Note

This section assumes you have completed the steps Set up the development environment.

  1. Open the QueuesController.cs file.

  2. Add a method called GetQueueLength that returns an ActionResult.

    public ActionResult GetQueueLength()
    {
        // The code in this section goes here.
    
        return View();
    }
    
  3. Within the ReadMessage method, get a CloudStorageAccount object that represents your storage account information. Use the following code to get the storage connection string and storage account information from the Azure service configuration: (Change <storage-account-name> to the name of the Azure storage account you're accessing.)

    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
       CloudConfigurationManager.GetSetting("<storage-account-name>_AzureStorageConnectionString"));
    
  4. Get a CloudQueueClient object represents a queue service client.

    CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
    
  5. Get a CloudQueueContainer object that represents a reference to the queue.

    CloudQueue queue = queueClient.GetQueueReference("test-queue");
    
  6. Call the CloudQueue.FetchAttributes method to retrieve the queue's attributes (including its length).

    queue.FetchAttributes();
    
  7. Access the CloudQueue.ApproximateMessageCount property to get the queue's length.

    int? nMessages = queue.ApproximateMessageCount;
    
  8. Update the ViewBag with the name of the queue, and its length.

    ViewBag.QueueName = queue.Name;
    ViewBag.Length = nMessages;
    
  9. In the Solution Explorer, expand the Views folder, right-click Queues, and from the context menu, select Add->View.

  10. On the Add View dialog, enter GetQueueLength for the view name, and select Add.

  11. Open GetQueueLengthMessage.cshtml, and modify it so that it looks like the following code snippet:

    @{
        ViewBag.Title = "GetQueueLength";
    }
    
    <h2>Get Queue Length results</h2>
    
    The queue '@ViewBag.QueueName' has a length of (number of messages): @ViewBag.Length
    
  12. In the Solution Explorer, expand the Views->Shared folder, and open _Layout.cshtml.

  13. After the last Html.ActionLink, add the following Html.ActionLink:

    <li>@Html.ActionLink("Get queue length", "GetQueueLength", "Queues")</li>
    
  14. Run the application, and select Get queue length to see results similar to the following screen shot:

    Get queue length

Delete a queue

This section illustrates how to delete a queue.

Note

This section assumes you have completed the steps Set up the development environment.

  1. Open the QueuesController.cs file.

  2. Add a method called DeleteQueue that returns an ActionResult.

    public ActionResult DeleteQueue()
    {
        // The code in this section goes here.
    
        return View();
    }
    
  3. Within the DeleteQueue method, get a CloudStorageAccount object that represents your storage account information. Use the following code to get the storage connection string and storage account information from the Azure service configuration: (Change <storage-account-name> to the name of the Azure storage account you're accessing.)

    CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
       CloudConfigurationManager.GetSetting("<storage-account-name>_AzureStorageConnectionString"));
    
  4. Get a CloudQueueClient object represents a queue service client.

    CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient();
    
  5. Get a CloudQueueContainer object that represents a reference to the queue.

    CloudQueue queue = queueClient.GetQueueReference("test-queue");
    
  6. Call the CloudQueue.Delete method to delete the queue represented by the CloudQueue object.

    queue.Delete();
    
  7. Update the ViewBag with the name of the queue, and its length.

    ViewBag.QueueName = queue.Name;
    
  8. In the Solution Explorer, expand the Views folder, right-click Queues, and from the context menu, select Add->View.

  9. On the Add View dialog, enter DeleteQueue for the view name, and select Add.

  10. Open DeleteQueue.cshtml, and modify it so that it looks like the following code snippet:

    @{
        ViewBag.Title = "DeleteQueue";
    }
    
    <h2>Delete Queue results</h2>
    
    @ViewBag.QueueName deleted.
    
  11. In the Solution Explorer, expand the Views->Shared folder, and open _Layout.cshtml.

  12. After the last Html.ActionLink, add the following Html.ActionLink:

    <li>@Html.ActionLink("Delete queue", "DeleteQueue", "Queues")</li>
    
  13. Run the application, and select Get queue length to see results similar to the following screen shot:

    Delete queue

Next steps

View more feature guides to learn about additional options for storing data in Azure.