In this article, let’s create Azure Queue Storage resources using Azure CLI. Assign “Storage Queue Data Contributor” role to Microsoft Entra (Azure AD) user name allows user account permission to create queues, send and receive messages using Azure RBAC. Build a .NET console application using Azure.Storage.Queues SDK to create and and delete queue as well as to send and receive messages. Sign in to Azure and run the application to verify the result. After this exercise, you will be able to send and receive messages from Azure Queue Storage using .NET Client Library.

Following tasks are performed in this article:

Create Azure Queue Storage Resources

First basic task is to create and make ready Azure Queue Storage resources to Azure using Azure CLI. Azure CLI (Azure Cloud Shell) is used to create the required resources. Azure CLI is the free Bash shell which can be run directly within the Azure portal. That is preinstalled and configured within the account. Perform the below steps one by one to achieve this.

Use Azure CLI (Azure Cloud Shell)

It is a free Bash shell which can be run directly within the Azure portal. It is preinstalled and configured within an account.

az group create \ 
     --name myResourceGroup1 \ 
     --location eastus2 
let resourceGroup=myResourceGroup1 \
     location=eastus2 \
     storageAccountName=myStorageAccountName$RANDOM
az storage account create \
     --resource-group $resourceGroup \
     --name $storageAccountName 
     --location $location 
     --sku Standard_LRS

Assign role to Microsoft Entra (Azure AD) user

Let’s assign Microsoft Entra user to “Storage Queue Data Contributor” role which gives user account permission to create queues, send and receive messages using Azure RBAC. It is important to assign roles to Microsoft Entra (Azure AD) user name. Roles will define what access and permissions a user has within an organization’s Microsoft cloud environment. Roles determine what resources and actions a user can perform. “Storage Queue Data Contributor” role is to be assigned to Microsoft Entra user which allows application to send and receive messages. One by one perform below steps in Azure CLI.

Retrieve userPrincipalName

First, retrieve userPrincipalName from account as mentioned in following command. It retrieves the information about currently authenticated user including their UPN and represents that who the role will be assigned to.

userPrincipal=$(az rest 
     --method GET 
     --url https://graph.microsoft.com/v1.0/me \
     --headers 'Content-Type=application/json' \
     --query userPrincipalName 
     --output tsv)

Retrieve resource ID

Second, get the resource ID of storage account using below command. This will be used in next step to set scope for role assignment. Resource ID sets scope for role assignment to specific namespace.

resourceID=$(az storage account show \
     --resource-group $resourceGroup \
     --name $storageAccountName\ 
     --query id \
     --output tsv)

Create and assign “Storage Queue Data Contributor” role

Finally, create and assign “Storage Queue Data Contributor” role using az role assignment create command. Command execution will create and assign “Storage Queue Data Contributor” role which gives permission to create queues, send and receive messages using Azure RBAC. This will give permissions to manage next routines. userPrincipal and resourceID variables are created in first and second steps which are used in this command to receive actual value at command execution time.

az role assignment create \
     --assignee $userPrincipal\
     --role "Storage Queue Data Contributor" \
     --scope $resourceID

Now, required basic resources are deployed and ready to use in console application.

Send and Receive Messages using .NET Client Library

Let’s set-up the .NET console application to send and receive the messages using .NET Client Library. Perform the following steps one by one in to Cloud Shell to achieve this.

.NET Project Setup

Set up one console application to send and receive message using .NET Client Library.

mkdir queuestorage1
cd queuestorage1
dotnet new console
dotnet add package Azure.Identity
dotnet add package Azure.Storage.Queues

Starter Code

Add the below starter code into the project and replace template code in Program.cs file by using editor in Cloud Shell.

code Program.cs
using System;
using System.Threading.Tasks;
using Azure;
using Azure.Identity;
using Azure.Storage.Queues;
using Azure.Storage.Queues.Models;

//Replace MY_STORAGE_ACCOUNT_NAME with actual storage account name
string storageAccountName = "<MY_STORAGE_ACCOUNT_NAME>";

// Create unique queue name
string queueName = "myQueue-" + Guid.NewGuid().ToString();

// CREATE QUEUE CLIENT & QUEUE

// SEND & LIST MESSAGES

// UPDATE MESSAGE & LIST MESSAGES

// DELETE MESSAGES & DELETE QUEUE

Complete Code

Add following code one by one at mentioned commented section to complete the application. Let’s update the code for commented lines for specific operations one by one as described to create and delete queue, send and receive messages, update and delete messages, etc.

// CREATE QUEUE CLIENT & QUEUE

// Create DefaultAzureCredentialOptions object to configure DefaultAzureCredential credentials
DefaultAzureCredentialOptions objDefaultAzureCredentialOptions = new()
{
     ExcludeEnvironmentCredential = true,
     ExcludeManagedIdentityCredential = true
};

// Create queue client 
QueueClient objQueueClient = new QueueClient(
     new Uri($"https://{storageAccountName}.queue.core.windows.net/{queueName}"),
     new DefaultAzureCredential(objDefaultAzureCredentialOptions));

// Create queue
await objQueueClient.CreateAsync();

Console.WriteLine($"Queue with name {queueName} has been created successfully!");
Console.WriteLine("Press any key to add messages in queue!");
Console.ReadKey();
// SEND & LIST MESSAGES

// Send messages to queue
await objQueueClient.SendMessageAsync("Message - 1");
await objQueueClient.SendMessageAsync("Message - 2");
await objQueueClient.SendMessageAsync("Message - 3");
await objQueueClient.SendMessageAsync("Message - 4");

// Send message & save receipt to us further
SendReceipt objSendReceipt = await objQueueClient.SendMessageAsync("Message - 5");

Console.WriteLine("Messages have been added in queue successfully!");
Console.WriteLine("Press any key to peek messages from queue!");
Console.ReadKey();

// Peek & view messages from queue
foreach (var message in (await objQueueClient.PeekMessagesAsync(maxMessages: 10)).Value)
{
     Console.WriteLine($"Peeking message: {message.MessageText}");
}

Console.WriteLine("Press any key to update message in queue!");
Console.ReadKey();
// UPDATE MESSAGE & LIST MESSAGES

// Update fifth message with saved receipt
await objQueueClient.UpdateMessageAsync(objSendReceipt.MessageId, objSendReceipt.PopReceipt, "Message - 5 updated");

Console.WriteLine("Message fifth has been updated successfully!");
Console.WriteLine("Press any key to peek messages from queue for updated message!");
Console.ReadKey();

// Peek & view messages from queue for updated message
foreach (var message in (await objQueueClient.PeekMessagesAsync(maxMessages: 10)).Value)
{
     Console.WriteLine($"Peeking message: {message.MessageText}");
}

Console.WriteLine("Press any key to delete messages from queue!");
Console.ReadKey();
// DELETE MESSAGES & DELETE QUEUE

// Delete messages from queue
foreach (var message in (await objQueueClient.ReceiveMessagesAsync(maxMessages: 10)).Value)
{
     Console.WriteLine($"Deleting message: {message.MessageText}");
     await objQueueClient.DeleteMessageAsync(message.MessageId, message.PopReceipt);
}

Console.WriteLine("Messages have been deleted from queue successfully!");
Console.WriteLine("Press any key to delete queue!");
Console.ReadKey();

// Delete queue
await objQueueClient.DeleteAsync();

Console.WriteLine("Queue has been deleted successfully!");
Console.WriteLine("Press any key to Exit!");
Console.ReadKey();

Sign in to Azure and run application

Now application is ready to run. One by one execute the following commands in Azure CLI to run an application and perform the mentioned steps to verify the result outcomes.

az login
dotnet run
Queue with name myQueue-0c7dbd4c-d8bc-548f-a165-82765926851e has been created successfully!
Press any key to add messages in queue!
Messages have been added in queue successfully!
Press any key to peek messages from queue!
Peeking message: Message - 1
Peeking message: Message - 2
Peeking message: Message - 3
Peeking message: Message - 4
Peeking message: Message - 5
Press any key to update message in queue!
Message fifth has been updated successfully!
Press any key to peek messages from queue for updated message!
Peeking message: Message - 1
Peeking message: Message - 2
Peeking message: Message - 3
Peeking message: Message - 4
Peeking message: Message - 5 updated
Press any key to delete messages from queue!
Deleting message: Message - 1
Deleting message: Message - 2
Deleting message: Message - 3
Deleting message: Message - 4
Deleting message: Message - 5
Messages have been deleted from queue successfully!
Press any key to delete queue!
Queue has been deleted successfully!
Press any key to Exit!

Clean up resources

Once finished the exercise it's recommended to delete cloud resources are being created to avoid the unnecessary resource usage and any future costs. Deleting a resource group will delete all resources contained within it. Perform following steps one by one into Azure Portal to achieve this:

One can also clean up resources using Azure CLI as following:

Delete role assignment - az role assignment delete command is used to remove role assignments.

az role assignment delete\
     --role "Storage Queue Data Contributor" \
     --scope $resourceID

Delete storage account - az storage account delete command is used to delete an existing storage. It removes all the associated resources under it.

az storage account delete \
     --name $storageAccountName \
     --resource-group $resourceGroup

Delete resource group - az group delete command is used to remove resource group.

az group delete \
     --name myResourceGroup1

Summary

Here, a complete process flow is described to send and receive messages from Azure Queue Storage using .NET Client Library. Azure Queue Storage resource is created using Azure CLI and assigned “Storage Queue Data Contributor” role to Microsoft Entra (Azure AD) user name. A .NET console application is developed using Azure.Storage.Queues SDK to send and receive messages through Queue Storage. Finally, resources are cleaned up. A complete code of Program.cs file is attached with this article.