azureservicebus 3. Send messages to the queue


Example

In order to send messages to the queue, we will write a C# console application using Visual Studio.

Create a console application

  1. Launch Visual Studio and create a new Console application.

Add the Service Bus NuGet package

  1. Right click on the newly created project and select Manage NuGet Packages.

  2. Click the Browse tab, then search for “Microsoft Azure Service Bus” and select the Microsoft Azure Service Bus item. Click Install to complete the installation, then close this dialog box.

    Select a NuGet package

Write some code to send a message to the queue

  1. Add the following using statement to the top of the Program.cs file.

    using Microsoft.ServiceBus.Messaging;
    
  2. Add the following code to the Main method, set the connectionString variable as the connection string that was obtained when creating the namespace, and set queueName as the queue name that used when creating the queue.

    var connectionString = "<Your connection string>";
    var queueName = "<Your queue name>";
    
    var client = QueueClient.CreateFromConnectionString(connectionString, queueName);
    var message = new BrokeredMessage("This is a test message!");
    client.Send(message);
    

    Here is what your Program.cs should look like.

    using System;
    using Microsoft.ServiceBus.Messaging;
    
    namespace GettingStartedWithQueues
    {
        class Program
        {
            static void Main(string[] args)
            {
                var connectionString = "<Your connection string>";
                var queueName = "<Your queue name>";
    
                var client = QueueClient.CreateFromConnectionString(connectionString, queueName);
                var message = new BrokeredMessage("This is a test message!");
    
                client.Send(message);
            }
        }
    }
    
  3. Run the program, and check the Azure classic portal. Notice that the Queue Length value should now be 1.

    Queue length