Lab 3: Create a .NET Core project to read messages from a Service Bus queue

Task 1: Create a .NET project

  1. From the lab computer, start Visual Studio Code.

  2. In Visual Studio Code, in the File menu, select Open Folder.

  3. In the Open Folder window, browse to $HOME\training-az204\Labs\10\Starter\MessageReader, and then select Select Folder.

  4. In the Visual Studio Code window, activate the shortcut menu, and then select Open in Integrated Terminal.

  5. At the terminal prompt, run the following command to create a new .NET project named MessageReader in the current folder:

    dotnet new console --framework net6.0 --name MessageReader --output .
    
  6. Run the following command to import version 7.8.1 of the Azure.Messaging.ServiceBus package from NuGet:

    dotnet add package Azure.Messaging.ServiceBus --version 7.8.1
    
  7. At the terminal prompt, run the following command to build the .NET Core console application:

    dotnet build
    
  8. Select Kill Terminal (the Recycle Bin icon) to close the terminal pane and any associated processes.

Task 2: Read messages from an Azure Service Bus queue

  1. In the Explorer pane of the Visual Studio Code window, open the Program.cs file.

  2. On the code editor tab for the Program.cs file, delete all the code in the existing file.

  3. Add the same code which was included in the Program.cs file to allow for interaction with Azure Service Bus queues, but set the namespace to MessageReader:

    using System;
    using System.Threading.Tasks;
    using Azure.Messaging.ServiceBus;  
    namespace MessageReader
    {
       public class Program
       {
          private const string serviceBusConnectionString = "";
          static string queueName = "messagequeue";
          static ServiceBusClient client = default!;
       }
    }
    
  4. As before, update the serviceBusConnectionString string constant by setting its value to Primary Connection String of the Service Bus namespace you recorded earlier in this lab.

  5. Enter the following code to create a ServiceBusProcessor that will be used to process messages from the queue:

    static ServiceBusProcessor processor = default!;
    
  6. Enter the following code to create a static async MessageHandler task that displays the body of messages in the queue as they are being processed and deletes them after the processing completes:

    static async Task MessageHandler(ProcessMessageEventArgs args)
    {
        string body = args.Message.Body.ToString();
        Console.WriteLine($"Received: {body}");
        await args.CompleteMessageAsync(args.Message);
    }
    
  7. Enter the following code to create a static async ErrorHandler task that manages any exceptions encountered during message processing:

    static Task ErrorHandler(ProcessErrorEventArgs args)
    {
        Console.WriteLine(args.Exception.ToString());
        return Task.CompletedTask;
    }
    
  8. Enter the following code to create an asynchronous Main method:

    static async Task Main(string[] args)
    {
    }
    
  9. Review the Program.cs file, which should now include the following code. The <serviceBus-connection-string> placeholder represents the connection string to the target Azure Service Bus namespace:

    using System;
    using System.Threading.Tasks;
    using Azure.Messaging.ServiceBus;
    namespace MessageReader
    {
        class Program
        {
            static string serviceBusConnectionString = "<serviceBus-connection-string>`";
            static string queueName = "messagequeue";
            static ServiceBusClient client;
            static ServiceBusProcessor processor;
            static async Task MessageHandler(ProcessMessageEventArgs args)
            {
                string body = args.Message.Body.ToString();
                Console.WriteLine($"Received: {body}");
                await args.CompleteMessageAsync(args.Message);
            }
            static Task ErrorHandler(ProcessErrorEventArgs args)
            {
                Console.WriteLine(args.Exception.ToString());
                return Task.CompletedTask;
            }
            static async Task Main()
            {
            }
        }
    }
    
  10. In the Main method, add the following code to initialize client of type ServiceBusClient that will provide connectivity to the Service Bus namespace and processor that will be responsible for processing of messages:

    client = new ServiceBusClient(serviceBusConnectionString);
    processor = client.CreateProcessor(queueName, new ServiceBusProcessorOptions());
    

    Note: As mentioned earlier, the Service Bus client is safe to cache and use as a singleton for the lifetime of the application. This is considered one of the best practices when publishing and reading messages on a regular basis.

  11. In the Main method, add the following lines of code to create a try block, which first implements a message and error processing handler, initiates message processing, and stops processing following a user input:

    try
    {
        processor.ProcessMessageAsync += MessageHandler;
        processor.ProcessErrorAsync += ErrorHandler;
        await processor.StartProcessingAsync();
        Console.WriteLine("Wait for a minute and then press any key to end the processing");
        Console.ReadKey();
        Console.WriteLine("\nStopping the receiver...");
        await processor.StopProcessingAsync();
        Console.WriteLine("Stopped receiving messages");
    }
    
  12. In the Main method, add the following lines of code to create a finally block that asynchronously disposes of the processor and client objects, releasing any network and unmanaged resources:

    finally
    {
        await processor.DisposeAsync();
        await client.DisposeAsync();
    }
    
  13. Review the Main method, which should now consist of the following code:

    static async Task Main()
    {
        client = new ServiceBusClient(serviceBusConnectionString);
        processor = client.CreateProcessor(queueName, new ServiceBusProcessorOptions());
        try
        {
            processor.ProcessMessageAsync += MessageHandler;
            processor.ProcessErrorAsync += ErrorHandler;
    
            await processor.StartProcessingAsync();
            Console.WriteLine("Wait for a minute and then press any key to end the processing");
            Console.ReadKey();
    
            Console.WriteLine("\nStopping the receiver...");
            await processor.StopProcessingAsync();
            Console.WriteLine("Stopped receiving messages");
        }
        finally
        {
            await processor.DisposeAsync();
            await client.DisposeAsync();
        }
    }
    
  14. Save the Program.cs file.

  15. In the Visual Studio Code window, activate the shortcut menu, and then select Open in Integrated Terminal.

  16. At the terminal prompt, run the following command to launch the .NET Core console app:

    dotnet run
    

    Note: If you encounter any errors, review the Program.cs file in the $HOME\training-az204\Labs\10\Solution\MessageReader folder.

  17. Verify that the console message displayed at the terminal prompt states that each of the three messages in the queue has been received.

  18. At the terminal prompt, press any key to stop the receiver and terminate the app execution.

  19. Select Kill Terminal (the Recycle Bin icon) to close the terminal pane and any associated processes.

  20. Switch back to the Microsoft Edge browser displaying the Service Bus queue messagequeue in the Azure portal.

  21. On the Service Bus Explorer (preview) blade, select Peek from start, and note that the number of active messages in the queue has changed to 0.

Review

In this exercise, you read and deleted messages from the Azure Service Bus queue by using the .NET library.

results matching ""

    No results matching ""