All Products
Search
Document Center

IoT Platform:Use IoT Platform SDK for .NET

Last Updated:Oct 22, 2023

IoT Platform provides an SDK for .NET. This topic describes how to install and configure IoT Platform SDK for .NET. This topic also provides sample code on how to use the SDK to call API operations of IoT Platform.

Install the SDK

  1. Install a .NET development environment.

    IoT Platform SDK for .NET supports the following development environments:

    • .NET Framework 4.5 and later

    • .NET Standard 2.0 and later

    • C# 4.0 and later

    • Visual Studio 2010 and later

  2. Install Alibaba Cloud SDK for .NET.

    • Use .NET CLI to install the SDK.

      You can run the following command to install the latest version of the SDK. If you want to install a specific version of the SDK, add --versionVersion number to the command.

      dotnet add package AlibabaCloud.OpenApiClient 
    • Configure the .csproj file to add a dependency. Then, run a command to install the SDK.

      1. Add the following dependency:

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

        dotnet build
  3. Use NuGet to install the SDK. For more information, visit NuGet Packages.

    • Use Visual Studio to install the SDK.

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

      2. In the NuGet Package Manager panel, click the Browse tab.

      3. On the Browse tab, enter AlibabaCloud.SDK in the search box and select the AlibabaCloud.SDK.Iot20180120 entry whose Authors column displays aliyun-openapi-sdk from the result list. For more information about the SDK, visit AlibabaCloud.SDK.Iot20180120.

      4. Click Install.

    • Other installation methods

      • Use the dotnet CLI to install the SDK. For information about other versions, visit IoT Platform SDK Sample Center.

        # Install the latest version of the SDK.
        dotnet add package AlibabaCloud.SDK.Iot20180120
        
        # Specify the SDK version that you want to install. In this example, the SDK of version 3.0.9 is installed.
        dotnet add package AlibabaCloud.SDK.Iot20180120 --version 3.0.9
      • Use an installation package to install the SDK.

        # Install the latest version of the SDK.
        Install-Package AlibabaCloud.SDK.Iot20180120
        
        # Specify the SDK version that you want to install. In this example, the SDK of version 3.0.9 is installed.
        Install-Package AlibabaCloud.SDK.Iot20180120 -Version 3.0.9

    For information about the source code of the SDK for .NET, visit alibabacloud-csharp-sdk.

Initialize the SDK

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

  2. Create a client instance of the AlibabaCloud.SDK.Iot20180120 class. Call the AlibabaCloud.SDK.Iot20180120.Client(config) method to load the SDK initialization information. After the information is loaded, the SDK is initialized.

    The Request and Response parameters are obtained from AlibabaCloud.SDK.Iot20180120.Models for subsequent API calls.

For example, if you want to use the SDK in the China (Shanghai) region, you can use the following code to initialize the SDK. In the production environment, you must select the region where IoT Platform is activated.

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");
// The region ID. 
config.RegionId = "cn-shanghai";
AlibabaCloud.SDK.Iot20180120.Client client = new AlibabaCloud.SDK.Iot20180120.Client(config);

Parameter

Description

AccessKeyId

The AccessKey ID of your Alibaba Cloud account.

You can go to the AccessKey Pair page in the Alibaba Cloud Management Console to create or view your AccessKey pairs.

AccessKeySecret

The AccessKey secret of your Alibaba Cloud account.

RegionId

The ID of the region where your IoT Platform instance resides. The region ID is used in the endpoint for service access. The endpoint is in the iot.${RegionId}.aliyuncs.com format.

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

For more information about the formats of region IDs, see Supported regions.

Initiate a request

The SDK encapsulates two classes for each API operation. The class whose name is in the ${API name}+"Request" format indicates the request, and the class whose name is in the ${API name}+"Response" format indicates the response.

Procedure

  1. Initialize the SDK. For more information, see the Initialize the SDK section of this topic.

  2. Create an API request by generating a request instance of the ${API operation name}+"Request" class.

  3. Call the request.${Request parameter} method of the request instance to specify the request parameters.

  4. Create a response instance of the ${API operation name}+"Response" class to obtain the response. Call the ${API operation name}(request) method of the client instance to obtain the response to the API request. The response includes the body and headers returned by the server.

  5. Call the response.body.${Response parameter} method to obtain the values of response parameters.

    For example, you can call the response.body.RequestId method to obtain the unique identifier generated by Alibaba Cloud for an API request. RequestId is a common response parameter. Common response parameters also include Success, ErrorMessage, and Code.

  6. Call the catch() method to handle exceptions.

For more information about the API operations of IoT Platform, see List of operations by function. For more information about the request parameters and response parameters of each API operation, see the API reference.

The following example shows how to call the Pub operation to publish a message to a topic. For more information about request parameters, see Pub.

Important

In the following sample code, ${iotInstanceId} specifies the ID of an instance. You can view the ID of the instance on the Overview page in the IoT Platform console.

  • If your instance has an ID, you must specify the ID for this parameter. Otherwise, the call fails.

  • If no Overview page or ID is generated for your instance, you do not need to configure this parameter. You must delete the request code that is related to the IotInstanceId parameter or specify an empty string ("") for the parameter. Otherwise, the call fails.

For more information about IoT Platform instances, see Overview. For more information about how to purchase an instance, see Purchase Enterprise Edition instances. For more information, see FAQ about IoT Platform instances.

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 content of the message that you want to send. Encode "hello world" in Base64 as a string. 
    MessageContent = Convert.ToBase64String(Encoding.Default.GetBytes("Hello World.")),
    // The custom topic that is used to publish the message. 
    TopicFullName = "/${productKey}/${deviceName}/user/get",
    // The message sending mode. IoT Platform SDK supports QoS 0 and QoS 1. 
    Qos = 0,
};
// Obtain a response by using the client instance. 
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);
}

Sample code

Note

You can replace the values of the preceding parameters with actual values based on your business scenario.

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
    {
        /**
         * Use your AccessKey ID and AccessKey secret to initialize the client. 
         * @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");
            // The 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("${accessKey}", "${accessKeySecret}");
                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 content of the message that you want to send. Encode "hello world" in Base64 as a string. 
                    MessageContent = Convert.ToBase64String(Encoding.Default.GetBytes("Hello World.")),
                    // The custom topic that is used to publish the message. 
                    TopicFullName = "/${productKey}/${deviceName}/user/get",
                    // The message sending mode. IoT Platform SDK supports QoS 0 and QoS 1. 
                    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 view or download the sample code of API operations in IoT Platform SDK Sample Center. Sample code of SDKs for Java, Python, PHP, Node.js, Go, C++, and .NET is provided.

Alibaba Cloud OpenAPI Explorer provides online debugging tools for API operations. On the API Debugging page, you can search for API operations, call API operations, and generate sample code for API operations of different SDKs. On the right side of the page, you can view the sample code of an SDK on the Sample Code tab. On the Debugging Result tab, you can view the actual request URL and response in the JSON format.