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.
Assign role to Microsoft Entra (Azure AD) username.
Send and receive messages using .NET Client Library.
Sign in to Azure and run application.
Clean up resources.
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.
Click Cloud Shell button on the menu bar at the top right side of the Azure portal.
It will launch an interactive shell which can be used to run the steps outlined in this article. Select a Bash environment. To use code editor in cloud shell toolbar go to Settings menu and then select Go to Classic version.
Create resource group - Resource group is a logical container used to hold related resources. In it include the resources which you want to manage as a group. App configuration resource belongs to this resource group. Create it using az group create command.
az group create \
--name myResourceGroup1 \
--location eastus2
eastus2 is location code instead of it one can use their nearest region location.
Create variables - Here, several commands require unique names/values with same parameters. Hence, for easy to manage let's create some variables, assign values and reuse them in the command parameters. let command is used as below to create required variables.
let resourceGroup=myResourceGroup1 \
location=eastus2 \
storageAccountName=myStorageAccountName$RANDOM
Create storage account - Storage account contains all azure storage data objects, such as blobs, files, queues, and tables. It is an Azure Resource Manager resource. It provides unique namespace for Azure Storage data. Create it using az storage account create command. Using this storage account all the activities will be performed in below console application section. It will take few minutes to complete the operation process.
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 and Create Queue - In this section, let’s create DefaultAzureCredentialOptions object to configure DefaultAzureCredential credentials and then create a queue client. Locate // CREATE QUEUE CLIENT & QUEUE comment, then add following code directly beneath comment.
// 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 Messages and List Messages - First, send messages to queue and save receipt to us further. Second, peek messages from queue and display them on console. Locate // SEND & LIST MESSAGES comment, then add following code directly beneath comment.
// 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 and List Messages - First, update fifth message with saved receipt and send it. Second, peek messages from queue for updated message and display them on console. Locate // UPDATE MESSAGE & LIST MESSAGES comment, then add following code directly beneath comment.
// 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:
Navigate to resource group which is being created here and view its contents.
Delete resource group selection from the toolbar.
Choose resource group name and then follow next directions to delete resource group and all the resources it contains.
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.