步骤 2:编写第一个程序

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

编写第一个程序

  1. 在“解决方案资源管理器”中,双击 Program.cs 以在 Visual Studio 编辑器中打开它。在该文件的顶部添加以下 using 语句以包含你刚创建的模型的命名空间以及 Service Bus 的命名空间:

    using System;
    using Microsoft.ServiceBus;
    using Microsoft.ServiceBus.Messaging;
    
    
  2. 标识你的服务器、端口和服务命名空间名称。你可以通过对值进硬编码、要求用户输入,或者从配置文件读取,来完成此操作。以下代码对值进行硬编码:

    static string ServerFQDN;
    static int HttpPort = 9355;
    static int TcpPort = 9354;
    static string ServiceNamespace = "ServiceBusDefaultNamespace";
    
  3. 构建 Service Bus 连接字符串:

    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. 创建一个 NamespaceManager 实例(用于管理操作)和一个 MessagingFactory 实例(用于发送和接收消息):

    MessagingFactory messageFactory = MessagingFactory.CreateFromConnectionString(connBuilder.ToString());
    NamespaceManager namespaceManager = NamespaceManager.CreateFromConnectionString(connBuilder.ToString());
    
  5. 使用新创建的 URI 和令牌创建新队列:

    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. 创建用于将消息发送到队列和从队列接收消息的队列客户端:

    QueueClient myQueueClient = messageFactory.CreateQueueClient(QueueName);
    
  7. 创建简单中转消息并将其发送到队列:

    BrokeredMessage sendMessage = new BrokeredMessage("Hello World !");
    myQueueClient.Send(sendMessage);
    
  8. 从队列接收消息:

    BrokeredMessage receivedMessage = myQueueClient.Receive(TimeSpan.FromSeconds(5));
    
    if (receivedMessage != null)
    {
        Console.WriteLine(string.Format("Message received: Body = {0}", receivedMessage.GetBody<string>()));
        receivedMessage.Complete();
    }
    
  9. 关闭与 Service Bus 的连接。

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

以下是完整的 Program.cs 文件,该文件应在执行前面的步骤后出现:

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();
        }
    }
}


生成日期:

2013-09-12

社区附加资源

显示: