This topic describes how to use the C# SDK to create a queue, send a message, receive and delete the message, and delete the queue.

Step 1: Prepare the environment

  1. Download the latest version of the C# SDK, decompress the package, and add the folder to Visual Studio as a solution.
  2. The solution contains four projects, in which AliyunSDK_MNS is the project where the SDK is located. Right-click the project name and select Rebuild. You can view the generated Aliyun.MNS.dll file in the bin directory of the project.

    Add references to other projects so that the projects can reference the Aliyun.MNS.dll file.

  3. To view sample code that you can use to manage queues, open the SyncTopicSample.cs file in the AliyunSDK_MNS_Sample project.
    1. Set AliyunSDK_MNS_Sample as the startup project and SyncTopicSample as the startup object.
    2. Open the SyncTopicSample.cs file and configure the AccessKey ID, AccessKey secret, and endpoint in the beginning rows of the file.
      • AccessKey ID and AccessKey secret
        • The AccessKey pair that is used to access the Alibaba Cloud API.
        • If you are using an Alibaba Cloud account, go to the Security Management page of the Alibaba Cloud console to create and view AccessKey pairs.
        • If you are a RAM user, log on to Alibaba Cloud RAM console to view AccessKey pairs.
      • Endpoint
        • The endpoint that is used to access MNS. Log on to the MNS console, and click Get Endpoint in the upper-right corner to view endpoints.
        • The endpoint of MNS changes based on regions.

Step 2: 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 a queue name.

// 1. You can specify the parameters of the queue based on your needs. 
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 time-out period of a long polling request.
        PollingWaitSeconds = 30
    }
};

try
{
    // 2. Create a custom queue
    // 2.1 If you do not need to specify the parameters of a queue, you can use the client.CreateQueue(_ queueName) method to create a custom queue.
    var queue = client.CreateQueue(createQueueRequest);
    Console.WriteLine("Create queue successfully, queue name: {0}", queue.QueueName);
}
catch (MNSException me)
{
    // 3. If an error occurs when you create a queue, troubleshoot the problem based on the returned error code.
    // 3.1 You can also specify code to determine whether a network error has occurred or the topic already exists.
    Console.WriteLine("CreateQueue Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("Create queue failed, exception info: " + ex.Message);
}           

Step 3: Send a message

After creating a queue, you can send messages to the queue.

try
{
    // 1. Retrieve a queue.
    var nativeQueue = client.GetNativeQueue(_queueName);
    // 2. Generate a request to send a message. You can specify the parameters of the message based on your needs.
    var sendMessageRequest = new SendMessageRequest("Alibaba<MessageBody>Cloud");
    // 3. Send a message without specifying parameters
    // 3.1 If you do not need to specify the parameters of a message, you can use the nativeQueue.SendMessage ("MessageBody") method.
    var sendMessageResponse = nativeQueue.SendMessage(sendMessageRequest);
    Console.WriteLine("Send message succeed“);
}
catch (MNSException me)
{
    // 3. If an error occurs when you create a queue, troubleshoot the problem based on the returned error code.
    // 3.1 You can also specify code to determine whether a network error has occurred or the topic already exists.
    Console.WriteLine("SendMessage Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("Send message failed, exception info: " + ex.Message);
}            

Step 4: Receive and delete the message

If messages exist in a queue, you can receive messages.

NextVisibleTime is an important parameter.

try
{
    // 1. Call the receiveMessage() function.
    // 1.1 We recommend that you set the WaitSeconds parameter to 30 when calling the receiveMessage() function.
    // 1.2 If you set the WaitSeconds parameter to a non-zero value, a request of receiving messages is an HTTP long polling request. The server does not close the connection until it has a message to send. 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 a message has a validity period and can be used to modify or delete the message. 
}
catch (MNSException me)
{
    // 3. A message may fail to be received if an error occurs. You can query the cause and solve the problem.
    Console.WriteLine("ReceiveMessage Failed! ErrorCode: " + me.ErrorCode);
}
catch (Exception ex)
{
    Console.WriteLine("ReceiveMessage failed, exception info: " + ex.Message);
}

//Specify your own logic for processing messages based on your business needs.
//The VisibilityTimeout parameter specifies the period when a message remains inactive in the queue after being consumed by a client. After the specified period, the message becomes active again and can be consumed by other clients. The message will not be lost if the program crashes or is stuck.

// 4. After receiving the message, 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 query the cause and solve the problem.
    // 6.1 If a receipt handle expires, the following error code is returned: MessageNotExist. This error code indicates that you cannot use the receipt handle to find the corresponding message.
    // 6.2 To ensure that you can manage a message in a timely manner before the current 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 5: 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);
}