Step 2: Write Your First Program

Write your first program

  1. In Solution Explorer, double-click Program.cs to open it in the Visual Studio editor. Add the following using statements at the top of the file to include the namespaces for the model you just created, as well as for the Service Bus:

    using System;
    using Microsoft.ServiceBus;
    using Microsoft.ServiceBus.Messaging;
    
  2. Identify your server, ports and service namespace name. You can do this by hard coding the values, asking the user for inputs, or reading from the configuration file. The following code hard-codes the values:

    static string ServerFQDN;
    static int HttpPort = 9355;
    static int TcpPort = 9354;
    static string ServiceNamespace = "ServiceBusDefaultNamespace";
    
  3. Build the Service Bus connection string:

    ServiceBusConnectionStringBuilder connBuilder = new ServiceBusConnectionStringBuilder();
    connBuilder.ManagementPort = HttpPort;
    connBuilder.RuntimePort = TcpPort;
    connBuilder.Endpoints.Add(new UriBuilder() { Scheme = "sb", Host = ServerFQDN, Path = ServiceNamespace }.Uri);
    connBuilder.StsEndpoints.Add(new UriBuilder() { Scheme = "https", Host = ServerFQDN, Port = HttpPort, Path = ServiceNamespace }.Uri);
    
  4. Create a NamespaceManager instance (for management operations) and a MessagingFactory instance (for sending and receiving messages):

    MessagingFactory messageFactory = MessagingFactory.CreateFromConnectionString(connBuilder.ToString());
    NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connBuilder.ToString());
    
  5. With the newly-created URI and token, create a new queue:

    const string QueueName = "ServiceBusQueueSample";
    
    if (namespaceManager == null)
    {
        Console.WriteLine("\nUnexpected Error: NamespaceManager is NULL");
        return;
    }
    
    if (namespaceManager.QueueExists(QueueName))
    {
        namespaceManager.DeleteQueue(QueueName);
    }
    namespaceManager.CreateQueue(QueueName);
    
  6. Create a queue client to send and receive messages to and from the queue:

    QueueClient myQueueClient = messageFactory.CreateQueueClient(QueueName);
    
  7. Create a simple brokered message and send it to the queue:

    BrokeredMessage sendMessage = new BrokeredMessage("Hello World !");
    myQueueClient.Send(sendMessage);
    
  8. Receive the message from the queue:

    BrokeredMessage receivedMessage = myQueueClient.Receive(TimeSpan.FromSeconds(5));
    
    if (receivedMessage != null)
    {
        Console.WriteLine(string.Format("Message received: Body = {0}", receivedMessage.GetBody<string>()));
        receivedMessage.Complete();
    }
    
  9. Close the connection to the Service Bus.

    if (messageFactory != null)                    
    {
        messageFactory.Close();
    }
    

The following is the complete Program.cs file as it should appear after following the previous steps:

namespace Microsoft.Samples.QueuesOnPrem
{
    using System;
    using Microsoft.ServiceBus;
    using Microsoft.ServiceBus.Messaging;

    public class Sender
    {
        static string ServerFQDN;
        static int HttpPort = 9355;
        static int TcpPort = 9354;
        static string ServiceNamespace = "ServiceBusDefaultNamespace";


        static void Main(string[] args)
        {
            ServerFQDN = System.Net.Dns.GetHostEntry(string.Empty).HostName;

            ServiceBusConnectionStringBuilder connBuilder = new ServiceBusConnectionStringBuilder();
            connBuilder.ManagementPort = HttpPort;
            connBuilder.RuntimePort = TcpPort;
            connBuilder.Endpoints.Add(new UriBuilder() { Scheme = "sb", Host = ServerFQDN, Path = ServiceNamespace }.Uri);
            connBuilder.StsEndpoints.Add(new UriBuilder() { Scheme = "https", Host = ServerFQDN, Port = HttpPort, Path = ServiceNamespace }.Uri);

            MessagingFactory messageFactory = MessagingFactory.CreateFromConnectionString(connBuilder.ToString());
            NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connBuilder.ToString());

            if (namespaceManager == null)
            {
                Console.WriteLine("\nUnexpected Error");
                return;
            }

            string QueueName = "ServiceBusQueueSample";
            if (namespaceManager.QueueExists(QueueName))
            {
                namespaceManager.DeleteQueue(QueueName);
            }
            namespaceManager.CreateQueue(QueueName);

            QueueClient myQueueClient = messageFactory.CreateQueueClient(QueueName);

            try
            {
                BrokeredMessage sendMessage = new BrokeredMessage("Hello World !");
                myQueueClient.Send(sendMessage);

                // Receive the message from the queue
                BrokeredMessage receivedMessage = myQueueClient.Receive(TimeSpan.FromSeconds(5));

                if (receivedMessage != null)
                {
                    Console.WriteLine(string.Format("Message received: {0}", receivedMessage.GetBody<string>()));
                    receivedMessage.Complete();
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Unexpected exception {0}", e.ToString());
                throw;
            }
            finally
            {                
                if (messageFactory != null)
                    messageFactory.Close();
            }
            Console.WriteLine("Press  ENTER to clean up and exit.");
            Console.ReadLine();
        }
    }
}

Build Date:

2013-10-18