.NET SDK guide

Updated at:

IoT Platform provides a server-side .NET SDK that you can use to call cloud APIs. This guide covers SDK installation, configuration, and usage examples.

Install the SDK

  1. Install the .NET development environment.

    The Alibaba Cloud .NET SDK supports the following development environments:

    • .NET Framework 4.5 or later.

    • .NET Standard 2.0 or later.

    • C# 4.0 or later.

    • Visual Studio 2010 or later.

  2. Install the core SDK library for OpenAPI.

    • Install the library using the .NET command-line interface (CLI).

      By default, this command installs the latest version. To install a specific version, append --version version_number.

      dotnet add package AlibabaCloud.OpenApiClient 
    • Alternatively, add the dependency to the .csproj file and then run a command to install it.

      1. Add the dependency.

        <PackageReference Include="AlibabaCloud.OpenApiClient" Version="0.0.13" />
      2. Run the following command to install the package.

        dotnet build
  3. Install the IoT .NET SDK using the NuGet package manager. For more information, see the NuGet package.

    • To install using Visual Studio:

      1. In Visual Studio Solution Explorer, right-click your project and select Manage NuGet Packages.

      2. On the NuGet Package Manager panel, click Browse.

      3. In the search box, enter AlibabaCloud.SDK. Select AlibabaCloud.SDK.Iot20180120, published by aliyun-openapi-sdk. For more information, see AlibabaCloud.SDK.Iot20180120.

      4. Click Install.

    • Other installation methods:

      • Install using the dotnet CLI. For version information, see IoT Platform SDK Center.

        # Install the latest version
        dotnet add package AlibabaCloud.SDK.Iot20180120
        
        # Install a specific SDK version, for example, 3.0.9
        dotnet add package AlibabaCloud.SDK.Iot20180120 --version 3.0.9
      • Install using the package manager.

        # Install the latest version
        Install-Package AlibabaCloud.SDK.Iot20180120
        
        # Install a specific SDK version, for example, 3.0.9
        Install-Package AlibabaCloud.SDK.Iot20180120 -Version 3.0.9

    For the .NET SDK source code, see alibabacloud-csharp-sdk.

Initialize the SDK

  1. Create a config object of the AlibabaCloud.OpenApiClient.Models.Config class to store SDK initialization information, including your AccessKey ID, AccessKey secret, and region ID.

  2. Create a client instance of the AlibabaCloud.SDK.Iot20180120.Client class and initialize it using the AlibabaCloud.SDK.Iot20180120.Client(config) constructor.

    The Request and Response parameters for subsequent API calls are available in AlibabaCloud.SDK.Iot20180120.Models.

The following code provides an example of how to initialize the SDK for the China (Shanghai) region. In your actual scenario, replace the endpoint with the one for the region where your IoT Platform service is located.

AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config();
// Your AccessKey ID.
config.AccessKeyId = Environment.GetEnvironmentVariable("ACCESS_KEY_ID");
// Your AccessKey secret.
config.AccessKeySecret = Environment.GetEnvironmentVariable("ACCESS_KEY_SECRET");
// Your region ID.
config.RegionId = "cn-shanghai";
AlibabaCloud.SDK.Iot20180120.Client client = new AlibabaCloud.SDK.Iot20180120.Client(config);

Parameter

Description

AccessKeyId

The AccessKey ID for your Alibaba Cloud account.

Create or view your AccessKey on the AccessKey Management page in the Alibaba Cloud console.

AccessKeySecret

The AccessKey secret for your Alibaba Cloud account.

RegionId

The region ID of your IoT Platform service. This is used to construct the service endpoint in the format: iot.${RegionId}.aliyuncs.com.

You can view the current service region in the upper-left corner of the IoT Platform console.

For more information about how to specify a region ID, see Regions and zones.

For information about HTTP request configuration, proxy configuration, timeouts, and retry mechanisms, see V2.0 .NET SDK (Recommended).

Make a call

The IoT Platform cloud SDK encapsulates two classes for each API: ${API name}+"Request" and ${API name}+"Response". These classes contain the API request and response.

Call steps

  1. Initialize the SDK client. For more information, see SDK initialization.

  2. Create a request instance of the ${API_Name}+"Request" class for the API call.

  3. Set the required request parameters on the request instance in the request.${parameter_name} format.

  4. Call the ${API_Name}(request) method of the client instance to send the request. The method returns a response instance of the ${API_Name}+"Response" class, which contains the body and headers from the server.

  5. Retrieve the return parameter values from the body member of the response instance in the response.body.${return_parameter_name} format.

    For example, use response.body.RequestId to retrieve the unique identifier that Alibaba Cloud generates for the API request. RequestId is a common return parameter, along with Success, ErrorMessage, and Code.

  6. You can use the catch() method to handle exceptions.

For more information about IoT Platform cloud APIs, see API list. For descriptions of the request parameters in the request and the response parameters in the response, see the documentation for the specific API.

This topic uses the Pub API as an example to show how to publish a message to a topic. For information about request parameters, see Pub.

Important

In the following code, iotInstanceId is the instance ID. For more information about instances, see Instance overview.

For information about how to purchase an instance, see Purchase an Enterprise instance.

For information about how to obtain an instance ID, see IoT Platform instance-related FAQ.

AlibabaCloud.SDK.Iot20180120.Models.PubRequest request = new AlibabaCloud.SDK.Iot20180120.Models.PubRequest
{
    // The ID of the IoT Platform instance.
    IotInstanceId = "${iotInstanceId}",
    // The ProductKey of the product.
    ProductKey = "${productKey}",
    // The message body to send, which is a Base64-encoded string of "Hello World."
    MessageContent = Convert.ToBase64String(Encoding.Default.GetBytes("Hello World.")),
    // The custom topic of the device that receives the message.
    TopicFullName = "/${productKey}/${deviceName}/user/get",
    // The method to send the message. QoS 0 and QoS 1 are supported.
    Qos = 0,
};
// Obtain the response object for the corresponding request from the client object.
try
{
    AlibabaCloud.SDK.Iot20180120.Models.PubResponse response = client.Pub(request);
    Console.WriteLine("publish message result: " + response.Body.Success);
    Console.WriteLine(response.Body.Code);
    Console.WriteLine(response.Body.ErrorMessage);
}
catch (TeaException error)
{
    Console.WriteLine(error.Code);
    Console.WriteLine(error.Message);
}
catch (Exception _error)
{
    Console.WriteLine(_error.Message);
    Console.WriteLine(_error.StackTrace);
}

Complete code example

Note

In your actual scenario, replace the parameter values based on the parameter descriptions provided earlier in this topic.

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

using Tea;
using Tea.Utils;

namespace AlibabaCloud.SDK.Sample
{
    public class Sample
    {
        /**
         * Initialize the client using an AccessKey ID and an AccessKey secret.
         * @param accessKeyId 
         * @param accessKeySecret
         * @param regionId
         * @return Client
         * @throws Exception
         */
        public static AlibabaCloud.SDK.Iot20180120.Client CreateClient()
        {
            AlibabaCloud.OpenApiClient.Models.Config config = new AlibabaCloud.OpenApiClient.Models.Config();
            // Your AccessKey ID.
            config.AccessKeyId = Environment.GetEnvironmentVariable("ACCESS_KEY_ID");
            // Your AccessKey secret.
            config.AccessKeySecret = Environment.GetEnvironmentVariable("ACCESS_KEY_SECRET");
            // Your region ID.
            config.RegionId = "cn-shanghai";
            return new AlibabaCloud.SDK.Iot20180120.Client(config);
        }


        public static void Main(string[] args)
        {
            try
            {
                AlibabaCloud.SDK.Iot20180120.Client client = CreateClient();
                AlibabaCloud.SDK.Iot20180120.Models.PubRequest request = new AlibabaCloud.SDK.Iot20180120.Models.PubRequest
                {
                    // The ID of the IoT Platform instance.
                    IotInstanceId = "${iotInstanceId}",
                    // The ProductKey of the product.
                    ProductKey = "${productKey}",
                    // The message body to send, which is a Base64-encoded string of "Hello World."
                    MessageContent = Convert.ToBase64String(Encoding.Default.GetBytes("Hello World.")),
                    // The custom topic of the device that receives the message.
                    TopicFullName = "/${productKey}/${deviceName}/user/get",
                    // The method to send the message. QoS 0 and QoS 1 are supported.
                    Qos = 0,
                };
                AlibabaCloud.SDK.Iot20180120.Models.PubResponse response = client.Pub(request);
                Console.WriteLine("publish message result: " + response.Body.Success);
                Console.WriteLine(response.Body.Code);
                Console.WriteLine(response.Body.ErrorMessage);
            }
            catch (TeaException error)
            {
                Console.WriteLine(error.Code);
                Console.WriteLine(error.Message);
            }
            catch (Exception _error)
            {
                Console.WriteLine(_error.Message);
                Console.WriteLine(_error.StackTrace);
            }
        }
    }
}

Appendix: Sample code

You can go to the IoT Platform Cloud SDK Example Center to view or download sample code for API calls. The sample code includes examples for SDKs in languages such as Java, Python, PHP, Node.js, Go, C++, and .NET.

The Alibaba Cloud OpenAPI Developer Portal provides an online API debugging tool. On the API debugging page, you can quickly search for and test API calls. The system automatically generates sample SDK code for different languages based on the parameters that you enter. The sample code is displayed on the SDK Example tab on the right side of the page. On the Call Result tab, you can view the request URL and the response in JSON format.