This article describes how to use the SDK for C# to create a topic, create a queue, create a subscription, publish a message, receive and delete the message, delete the topic, and delete the queue.

Step 1: Prepare the environment

  1. Download the latest version of the SDK for C#, decompress the package, and then add the folder to Visual Studio as a solution.
  2. The solution contains four projects. Right-click the AliyunSDK_MNS project and select Rebuild. The Aliyun.MNS.dll file is generated in the bin directory of the project.
    Note Specify the Aliyun.MNS.dll file as the reference of the other three projects.
  3. Specify the SyncTopicOperations.cs file in the AliyunSDK_MNS_Sample project.
    1. Set the AliyunSDK_MNS_Sample project as the startup project and the SyncTopicOperations file as the startup object.
    2. Open the SyncTopicOperations.cs file and specify the following information:
      • AccessKey ID and AccessKey secret
        • The AccessKey pair that is used to call the API operations of Alibaba Cloud.
        • If you are using an Alibaba Cloud account, go to the AccessKey Management page of the Alibaba Cloud Management Console to create and view your AccessKey pair.
        • If you are a Resource Access Management (RAM) user, log on to the RAM console to view your AccessKey pair.
      • Endpoint
        • The endpoint that is used to access Message Service (MNS). To view the endpoints of MNS, log on to the MNS console. For more information, see View the endpoints of a topic.
        • The endpoints of MNS vary based on regions.

Step 2: Create a topic

If no topic is available, you must create a topic. The default name of the new topic is TestCSharpTopic. You can also specify another topic name.

// 1.Generate a request to create a topic. You can also specify other parameters of the topic. 
var createTopicRequest = new CreateTopicRequest
{
    TopicName = _topicName
};

Topic topic = null;
try
{
    topic = client.CreateTopic(createTopicRequest);
    Console.WriteLine("Create topic successfully, topic name: {0}", topic.TopicName);
}
catch (MNSException me)
{
    // 2.The topic may fail to be created if a network error occurs or the topic name already exists. You can call the CatchException or Catch TopicAlreadyExistException operation to identify and resolve the failure. 
    Console.WriteLine("CreateTopic Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("Create topic failed, exception info: " + ex.Message);
    return;
}          

Step 3: Create a queue

If no queue is available, you must create a queue. The default name of the new queue is myqueue. You can also specify another queue name.

// 1.You can specify the parameters of the queue based on your needs. For more information about the parameters of a queue, see Queue. 
var createQueueRequest = new CreateQueueRequest
{
    QueueName = _queueName,
    Attributes =
    {
        // You must specify the VisibilityTimeout parameter. Default value: 30. 
        VisibilityTimeout = 30,
        MaximumMessageSize = 40960,
        MessageRetentionPeriod = 345600,
        // The PollingWaitSeconds parameter specifies the timeout period of a long polling request. 
        PollingWaitSeconds = 30
    }
};

try
{
    // 2.Create a queue. If you do not need to specify the parameters of a queue, you can use the client.CreateQueue(_ queueName) method to create a queue. 
    var queue = client.CreateQueue(createQueueRequest);
    Console.WriteLine("Create queue successfully, queue name: {0}", queue.QueueName);
}
catch (MNSException me)
{
    // 3.The queue may fail to be created if a network error occurs or the queue name already exists. You can call the CatchException operation to identify and resolve the failure. 
    Console.WriteLine("CreateQueue Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("Create queue failed, exception info: " + ex.Message);
}           

Step 4: Create a subscription

You can use the following sample code to create a subscription to the topic:

string region = "";
string accountId = "";
string queueName = "TestQueue";
try
{
    // 1.You can specify the parameters of the subscription. The second parameter specifies the endpoint that is used to receive messages. 
    SubscribeResponse res = topic.Subscribe(_subscriptionName, "acs:mns:" + region +":" + accountId +":queues/" + queueName);
    // 2.The subscription is created. 
    Console.WriteLine("Subscribe succeed");
}
catch (MNSException me)
{
    // 3.The subscription may fail to be created if a network error occurs or the subscription name already exists. You can call the CatchException operation to identify and resolve the failure. 
    Console.WriteLine("Subscribe Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("Subscribe failed, exception info: " + ex.Message);
}                       

Step 5: Publish a message

You can use the following sample code to publish a message to the topic:

try
{
    var response = topic.PublishMessage("message here </asdas\">");
    // 1.The message is published. 
    Console.WriteLine("PublishMessage succeed! " + response.MessageId);
}
catch (MNSException me)
{
    // 2.The message may fail to be published if a network error occurs. You can call the CatchException operation to identify and resolve the failure. 
    Console.WriteLine("PublishMessage Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("PublishMessage failed, exception info: " + ex.Message);
}           

Step 6: Receive and delete the message from the queue

After the message is pushed from a topic to a queue, you can receive and delete the message from the queue.

try
{
    // 1.Call the receiveMessage() function. 
    // We recommend that you set the WaitSeconds parameter to 30 when you call the receiveMessage() function. 
    // If you set the WaitSeconds parameter to a non-zero value, a request of receiving messages is an HTTP long polling request. The long-polling request holds until a message is available in the queue. The maximum value of the WaitSeconds parameter is 30. 
    var receiveMessageResponse = nativeQueue.ReceiveMessage(30);
    // 2.Retrieve the value of the ReceiptHandle parameter. The receipt handle of the message has a validity period and can be used to modify or delete the message. For more information, see QueueMessage. 
    _receiptHandle = message.ReceiptHandle;
}
catch (MNSException me)
{
    // 3.A message may fail to be received if an error occurs. You can call the CatchException operation to identify and resolve the failure. 
    Console.WriteLine("ReceiveMessage Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("ReceiveMessage failed, exception info: " + ex.Message);
}

// Specify your own logic to process messages based on your needs. 
// The VisibilityTimeout parameter specifies the period when a message remains in the Inactive state in the queue after the message has been consumed by a client. After the specified period, the message changes to the Active state again and can be consumed by other clients. This prevents message loss against unexpected exits. 

// 4.After a message is consumed, you can delete the message from the queue. 
try
{
    // 5.Call the deleteMessage() function. 
    var deleteMessageResponse = nativeQueue.DeleteMessage(_receiptHandle);
}
catch (MNSException me)
{
    // 6.If an error occurs, you can call the CatchException operation to identify and resolve the failure. 
    // If the receipt handle expires, the MessageNotExist error is returned. This error indicates that you cannot use the receipt handle to find the corresponding message. 
    // To make sure that you can consume the message before the receipt handle expires, you must set the VisibilityTimeout parameter to an appropriate value. You can call the changeMessageVisibility() function to modify the value of the VisibilityTimeout parameter. 
    Console.WriteLine("DeleteMessage Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("Delete message failed, exception info: " + ex.Message);
}            

Step 7: Delete the topic

You can use the following sample code to delete the topic:

try
{
    client.DeleteTopic(_topicName);
    Console.WriteLine("Delete topic succeed");
}
catch (Exception ex)
{
    Console.WriteLine("Delete topic failed, exception info: " + ex.Message);
}            

Step 8: Delete the queue

You can use the following sample code to delete the queue:

try 
{
    var deleteQueueResponse = client.DeleteQueue(deleteQueueRequest);
} 
catch (MNSException me)
{
    Console.WriteLine("DeleteQueue Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("Delete queue failed, exception info: " + ex.Message);
}