Step 2: Write Your First Program

注:本页面内容可能不完全适用中国大陆地区运营的 Windows Azure服务。如要了解不同地区 Windows Azure 服务的差异, 请参考本网站.

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 Service Bus:

    using System;
    using Microsoft.ServiceBus;
    using Microsoft.ServiceBus.Messaging;
    

    Obtain a Service Bus connection string from standard input (alternatively, you can read it from a configuration file):

    string connectionString;
    Console.WriteLine("Enter Service Bus Connection string:\n");
    connectionString = Console.ReadLine();
    

    Create a NamespaceManager instance (for management operations) and a MessagingFactory instance (for sending and receiving messages):

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

    using Microsoft.ServiceBus;
    using Microsoft.ServiceBus.Messaging;
    
  3. 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);
    
  4. Create a queue client to send and receive messages to and from the queue:

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

    BrokeredMessage sendMessage = new BrokeredMessage("Hello World !");
    myQueueClient.Send(sendMessage);
    
  6. 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();
    }
    
  7. Close the connection to 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();
        }
    }
}