Using Azure Service Bus Queues with C#, Cloud Shell, PowerShell, and CLI

Hands-On Lab

 

Photo of Jason Calton

Jason Calton

Training Architect

Length

01:00:00

Difficulty

Intermediate

In this lab, you will gain experience using C#, the Azure Cloud Shell/PowerShell/CLI, and Visual Studio to connect to and use Azure Service Bus queues. You will use the Azure Cloud Shell to create a Service Bus namespace and queue. Then, you'll RDP into a Windows VM and update a pre-built Visual Studio solution with the appropriate C# code to connect to the queue, send messages to the queue, and subscribe to the queue to read messages. When you're finished, you will run the console application to see everything working. Finally, you will verify messages were sent and received from the queue using the Azure portal. Upon completion of the lab, you will have gained the experience required to work with Azure Service Bus queues using C#.

What are Hands-On Labs?

Hands-On Labs are scenario-based learning environments where learners can practice without consequences. Don't compromise a system or waste money on expensive downloads. Practice real-world skills without the real-world risk, no assembly required.

Using Azure Service Bus Queues with C#, Cloud Shell, PowerShell, and CLI

Introduction

In this lab, you will gain experience using C#, the Azure Cloud Shell/PowerShell/CLI, and Visual Studio to connect to and use Azure Service Bus queues.

You will use the Azure Cloud Shell to create a Service Bus namespace and queue. Then, you'll RDP into a Windows VM and update a pre-built Visual Studio solution with the appropriate C# code to connect to the queue, send messages to the queue, and subscribe to the queue to read messages. When you're finished, you will run the console application to see everything working. Finally, you will verify messages were sent and received from the queue using the Azure Portal.

Upon completion of the lab, you will have gained the experience required to work with Azure Service Bus queues using C#.

Log in to the Azure Portal

On the hands-on lab page, you will find the necessary information in the Credentials section. The credentials provided here will be different than those shown in the video.

  1. Copy the username by clicking the clipboard icon next to the username.
  2. Click the Open Azure Portal button.
  3. Paste the copied username into the Sign in window and click Next.
  4. Copy the password from the Credentials section of the hands-on lab page by clicking the clipboard icon next to the password.
  5. Paste the copied password into the Sign in window for the Azure Portal and click Sign in.
  6. Click Maybe later on the Welcome to Azure message to skip the guided tour.

Set up Cloud Shell, RDP into VM, Download Solution, and Set up Visual Studio

Set up Cloud Shell

It is easier to have the Azure Portal page and Cloud Shell open in separate tabs. The easiest way to accomplish this is to right-click on the current Azure Portal tab in your browser and choose the Duplicate Tab option. In the new tab, click on the Cloud Shell icon found at the top of the portal. When the Cloud Shell window opens, drag the window slider to the top of the screen.

Cloud Shell asks us if we would like to use Bash or PowerShell.

  1. For this exercise, click on the PowerShell option.
  2. Next, click Show Advanced Settings when Cloud Shell prompts for a storage account.
    • From here, our Subscription and Resource Group have been populated for us already.
    • Choose the South Central US option for our Cloud Shell region.
    • Select the Use existing radio button under Storage account to populate our existing account in the associated field.
    • Finally, name your File Share by typing in a name in the File Share field. This name can be anything you want or even random letters.
  3. Now that all of the Advanced Settings are filled in, click the Create Storage button to begin creating the storage. After the storage is created for Cloud Shell, the Cloud Shell terminal is ready for us to use!

The commands we are going to use are provided under the Objectives section of the hands-on lab page. Expand the first objective to show the first set of commands. Select all of the text in the code block and copy it to your clipboard by right-clicking and choosing Copy. Back in the Cloud Shell tab, click the {} icon in the PowerShell menu at the top of the page to open the editor. Paste the code we copied into the editor window.

There are a few blanks that will need to be filled in.

  1. First, cut or copy the az group list command and paste it into the first blank in the $resourcegroup line.

    $resourceGroup = az group list --query '[0].name' --output json
  2. Next, cut or copy the az servicebus namespace create command into the second blank:

    az servicebus namespace create --resource-group $resourceGroup --name $namespaceName --location southcentralus
  3. And finally, cut or copy the az servicebus queue create command into the third blank:

    az servicebus queue create --resource-group $resourceGroup --namespace-name $namespaceName --name myQueue
  4. The completely filled-out commands should look like this:

    # create a Service Bus namespace and queue
    $resourceGroup = az group list --query '[0].name' --output json
    $namespaceName  = "LALab" + (Get-Date).ticks
    
    az servicebus namespace create --resource-group $resourceGroup --name $namespaceName --location southcentralus
    az servicebus queue create --resource-group $resourceGroup --namespace-name $namespaceName --name myQueue
    #

Now that all of our commands are completely filled out, select all of the commands and copy them to your clipboard. Back in the Cloud Shell window, right-click and choose the Paste option to paste the commands into the terminal. The commands will begin executing and the command output will be presented in the terminal window.

We can verify this process completed successfully in the Azure Portal.

  1. Start by clicking All resources in the navigation bar on the left of the screen.
  2. Our Service Bus has been created and we can click on its name to show more information about it.
  3. Next, click on Queues under the Entities section to show the queue that was created and named myqueue.

All of the necessary steps for setting up our Cloud Shell and creating our namespace and queue are done! Now that that's complete, we can use RDP to connect to our virtual machine.

RDP into VM

To use RDP to connect to your VM, click the All resources button to get back to the resource list. Click on the name of our VM (lab-VM) to bring up more information about your VM.

  1. From this page, click on Connect to bring up the connection window.

  2. Click on the Download RDP File button to download a file to use to connect to this VM.

  3. Choose the Save File option and open your browser's Downloads folder.

  4. Choose the icon to View the downloaded item in a folder.

  5. Next, right-click the file and choose Edit.

  6. In the Display tab, choose the resolution that works best for you. In this lab, the instructor chose to use 1024 by 768 for this setting.

  7. Next, under the Local Resources tab, change the Keyboard configuration to the On the remote computer option. This allows you to use keyboard shortcuts like Ctrl+C and Ctrl+V to copy and paste in and out of the VM.

  8. Click on the Connect button to start connecting to your VM.

  9. A User Account Control (UAC) window will pop up. Click Connect to continue.

  10. Next, a Windows Security window will prompt you for your username and password. The username and password are provided on the hands-on lab page under the second task in the Objectives section.

    UserName : "azureuser"
    Password : "LA!2018!Lab"
  11. Copy and paste the username and password from the hands-on lab page into the password prompt and then click OK.

  12. A certificate error window will be displayed. Click on Yes to continue. The connection may take a few minutes, but when it is complete, your VM window will be displayed.

The VM will finish setting up and logging in. Once it is ready, we need to download the C# project used to send and receive messages to our queue. Thankfully, this can be completed with a few handy PowerShell commands provided on the hands-on lab page under the second task in the Objectives section (the same section we copied the username and password to connect to our VM).

Add-Type -Path "C:Program Files (x86)Reference AssembliesMicrosoftFramework.NETFrameworkv4.5System.IO.Compression.FileSystem.dll"

$url = "https://github.com/linuxacademy/content-azure-labs/blob/master/zips/azure-service-bus-queues.zip?raw=true"
$zipfile = "C:UsersazureuserDesktopazure-service-bus-queues.zip"
$folder = "C:UsersazureuserDesktop"

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Invoke-WebRequest -UseBasicParsing -OutFile $zipfile $url

[System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $folder)

Remove-Item -Path $zipfile
#

Copy all of the commands in the code block. In our VM, open PowerShell by clicking the Windows button in the bottom-left, type in PowerShell, and click PowerShell in the search results. Once the PowerShell window is open, right-click in the PowerShell window to paste in the commands that were copied from the hands-on lab page. You will notice the necessary .zip file appears on the Desktop of your VM. The commands we entered in our PowerShell window will extract this file and then remove the original .zip file. We can close the PowerShell window once the commands have completed. Now we are ready to set up Visual Studio!

Set up Visual Studio

Open the folder that was extracted to the Desktop of your VM. Double-click on the azure-service-bus-queues file to open this in Visual Studio. In the How do you want to open this file? window, click OK to use Microsoft Visual Studio Version Selector. Visual Studio will start to load, which may take a moment.

The first dialogue window that pops up asks us to sign in. Click the Sign in button and use the same credentials we used to sign in to the Azure Portal. For reference, this is provided at the top of the hands-on lab page under the Credentials section. Copy and paste the username and password into the sign-in window and click Sign in.

The next dialogue window allows you to configure a theme you may want to use. You don't have to change any settings here, but you can if you would like. When you are ready, click the Start Visual Studio button. Visual Studio will begin to load, which may take a few minutes.

Note: A dialogue window may ask us to check for an updated license. Click the Check for updated license link to update your license. Click the Close button to close this window.

We are now ready to use Visual Studio!

Update Visual Studio Solution, Run Console App, and Verify Queue Message Count in Azure Portal

Update Visual Studio Solution

Start by expanding the Dependencies and then the NuGet tabs, found under azure-service-bus-queues in the Solution Explorer on the right in Visual Studio. We are able to verify we have the Service Bus SDK, shown as Microsoft.Azure.ServiceBus, listed under NuGet. Next, click Program.cs in the Solution Explorer to open our console application. As we are reviewing the code, we notice the code has a few blanks that will need to be filled in.

  1. The ServiceBusConnectionString line has a blank that needs to be filled in. This information can be found in the Azure Portal.
    • In the Azure Portal, click All Resources next to Home at the top of the page.
    • Click on the name of your Service Bus namespace in the list of resources.
    • Under Settings in the menu on the left of this page, click Shared access policies.
    • Next, click on the RootManageSharedAccessKey policy.
    • The information we are looking for is found here in the Primary Connection String field. Copy this string to your clipboard.
    • Back in Visual Studio, paste the connection string we copied into the blank next to ServiceBusConnectionString.
  2. Further down in the code, under the static async Task SendMessagesAsync(int numberOfMessagesToSend) section, there is another blank that needs to be filled in.
    • The line await.queueClient.__________(message); has a blank that needs to be filled in.
    • The commented code just before this line contains the options we have to pick from. We are looking for the option that sends a message immediately.
    • Cut or copy the SendAsync option and paste it in to replace the blank in the line.
    • The line should now look like await.queueClient.SendAsync(message);.
  3. Another blank that needs to be filled in is found in the static void RegisterOnMessageHandlerAndReceiveMessages() section.
    • The line queueClient.__________(ProcessMessageAsync, messageHandlerOptions); has a blank that can be filled in with the options listed directly above it.
    • Cut or copy the RegisterMessageHandler option and paste it in to replace the blank in the line.
    • The line should now look like queueClient.RegisterMessageHandler(ProcessMessageAsync, messageHandlerOptions);.
  4. The last blank we need to fill in is found in the static async Task ProcessMessagesAsync(Message message, CancellationToken token) section.
    • Just as before, the line await queueClient.__________(message.SystemProperties.LockToken); has a blank that can be filled in with the options listed directly above it.
    • Cut or copy the CompleteAsync option and paste it in to replace the blank in the line.
    • The line should now look like await queueClient.CompleteAsync(message.SystemProperties.LockToken);.

Now that all of the blanks have been filled in, let's save our changes by clicking the Save icon in the bar at the top of Visual Studio (or by using the Ctrl+S keyboard shortcut). We are now ready to run our console application!

Run Console App

It's time to run our console application and watch it work! Click the play icon in the bar at the top of the page. This will execute our code and display its progress in a new window. Our console application first displays that it is sending 10 messages. It then pauses for us to manually verify the queue message count in the Azure Portal.

Verify Queue Message Count in Azure Portal

Back in the Azure Portal, we should still be in our Service Bus namespace window. Click on Queues in the menu on the left of this page, found under Entities in the list. Next, click on myqueue to display more information on the queue. The Active message count section will display 10 messages, verifying that the 10 messages sent by our console application have definitely been sent to the queue. Perfect! We can now go back to our console application in Visual Studio and let it continue running.

In Visual Studio running on our VM, press any key to continue running the console application. The remainder of the code will begin executing and display messages verifying that messages were received from the queue. We can verify that the messages were removed from the queue in the Azure Portal. In the Azure Portal, we can't refresh the queue page, so we need to navigate to that page again. Click on All resources at the top of the page, click the Service Bus namespace name in the resource list, click Queues in the menu on the left under Entities, and click on myqueue in the list of queues. Here, we can see the Active message count now displays 0 messages, verifying that our console application has received and cleared those messages from the queue.

Summary

You have used the Azure Cloud Shell to create a Service Bus namespace and queue. Then, you used RDP to connect to a Windows VM and updated a pre-built Visual Studio solution with the appropriate C# code to connect to the queue, send messages to the queue, and subscribe to the queue to read messages. You ran the console application to see everything working. Finally, you verified messages were sent and received from the queue using the Azure Portal. Great job!