Sending messages to the queue

In this section, we will create a console application that will actually send messages to the queue. To create this application, follow these steps:

  1. Create a new console application and name it FlixOne.BookStore.MessageSender using Visual Studio's new project (C#) template:
  1. Add the NuGet package Microsoft Azure Service Bus by right-clicking on the project.
  1. Write the code to send the message to the queue, and your Program.cs file will contain the following MainAsync() method:
 private static async Task MainAsync()
{
const int numberOfMessagesToSend = 10;
_client = new QueueClient(ConnectionString, QueueName);
WriteLine("Starting...");
await SendMessagesAsync(numberOfMessagesToSend);
WriteLine("Ending...");
WriteLine("Press any key...");
ReadKey();
await _client.CloseAsync();
}

In the preceding code, we are creating our queue client by providing ConnectionString and QueueName that we have already set in our Azure portal. It calls the SendMessagesAsync() method that accepts a parameter containing the count of the number of messages needed to be sent.

  1. Create a SendMessagesAsync() method and add the following code:
private static async Task SendMessagesAsync(int numberOfMessagesToSend)
{
try
{
for (var index = 0; index < numberOfMessagesToSend; index++)
{
var customMessage = $"#{index}:
A message from FlixOne.BookStore.MessageSender.";
var message = new
Message(Encoding.UTF8.GetBytes(customMessage));
WriteLine($"Sending message: {customMessage}");
await _client.SendAsync(message);
}
}
catch (Exception exception)
{
WriteLine($"Weird! It's exception with message:
{exception.Message}");
}
}
  1. Run the program and wait for a while. You will get the following:
  1. Go to the Azure portal and then go to the created queue to check whether it displays a message. The below image is showing overview of flixonequeue where we can see Active Message Count etc.