快速入门:使用 C# 服务 SDK 将 TPM 设备注册到 IoT 中心设备预配服务Quickstart: Enroll TPM device to IoT Hub Device Provisioning Service using C# service SDK

本文介绍如何使用 C# 服务 SDK 和示例 C# .NET Core 应用程序,在 Azure IoT 中心设备预配服务中以编程方式为 TPM 设备创建单个注册。This article shows how to programmatically create an individual enrollment for a TPM device in the Azure IoT Hub Device Provisioning Service by using the C# Service SDK and a sample C# .NET Core application. 可以通过该单个注册项,选择性地将模拟的 TPM 设备注册到预配服务。You can optionally enroll a simulated TPM device to the provisioning service by using this individual enrollment entry. 本文使用 Windows 开发计算机,不过,这些步骤在 Windows 和 Linux 计算机上均适用。Although these steps work on both Windows and Linux computers, this article uses a Windows development computer.

准备开发环境Prepare the development environment

  1. 检查计算机上是否安装了 Visual Studio 2019Verify you have Visual Studio 2019 installed on your computer.

  2. 检查计算机上是否安装了 .NET Core SDKVerify you have the .NET Core SDK installed on your computer.

  3. 在继续操作之前,请先完成使用 Azure 门户设置 IoT 中心设备预配服务中的步骤。Complete the steps in Set up the IoT Hub Device Provisioning Service with the Azure portal before you continue.

  4. (可选)如需在本快速入门末尾注册模拟设备,请执行使用 C# 设备 SDK 创建和预配模拟的 TPM 设备中的过程,一直到获取设备的认可密钥那一步。(Optional) If you want to enroll a simulated device at the end of this quickstart, follow the procedure in Create and provision a simulated TPM device using C# device SDK up to the step where you get an endorsement key for the device. 保存认可密钥和注册 ID,并视需要记下设备 ID,因为稍后需要在本快速入门中用到。Save the endorsement key, registration ID, and, optionally, the device ID, because you need to use them later in this quickstart.

    备注

    请勿执行使用 Azure 门户创建单个注册的步骤。Don't follow the steps to create an individual enrollment by using the Azure portal.

获取适用于预配服务的连接字符串Get the connection string for your provisioning service

对于本快速入门中的示例,需要适用于预配服务的连接字符串。For the sample in this quickstart, you need the connection string for your provisioning service.

  1. 登录到 Azure 门户,选择“所有资源”,然后选择你的设备预配服务。 Sign in to the Azure portal, select All resources, and then your Device Provisioning Service.

  2. 选择“共享访问策略”,然后选择需要用来打开其属性的访问策略。 Choose Shared access policies, then select the access policy you want to use to open its properties. 在“访问策略”中,复制并保存主密钥连接字符串。 In Access Policy, copy and save the primary key connection string.

    从门户获取预配服务连接字符串

创建单个注册示例Create the individual enrollment sample

本部分介绍如何创建一个 .NET Core 控制台应用,以便向预配服务添加 TPM 设备的单个注册。This section shows how to create a .NET Core console app that adds an individual enrollment for a TPM device to your provisioning service. 进行一些修改后,还可以按这些步骤创建 Windows IoT Core 控制台应用,以便添加单个注册。With some modification, you can also follow these steps to create a Windows IoT Core console app to add the individual enrollment. 若要详细了解如何使用 IoT Core 进行开发,请参阅 Windows IoT Core 开发人员文档To learn more about developing with IoT Core, see Windows IoT Core developer documentation.

  1. 打开 Visual Studio 并选择“创建新项目” 。Open Visual Studio and select Create a new project. 在“创建新项目”中,为 C# 项目模板选择“控制台应用(.NET Core)”,然后选择“下一步”。 In Create a new project, choose the Console App (.NET Core) project template for C# and select Next.

  2. 将项目命名为“CreateTpmEnrollment”,然后按“创建” 。Name the project CreateTpmEnrollment, and press Create.

    配置 Visual C# Windows 经典桌面项目

  3. 在 Visual Studio 中打开该解决方案后,在“解决方案资源管理器”窗格中右键单击“CreateTpmEnrollment”项目 。When the solution opens in Visual Studio, in the Solution Explorer pane, right-click the CreateTpmEnrollment project. 选择“管理 NuGet 包”。 Select Manage NuGet Packages.

  4. 在“NuGet 包管理器”中选择“浏览”,搜索并选择“Microsoft.Azure.Devices.Provisioning.Service”,然后按“安装” 。In NuGet Package Manager, select Browse, search for and choose Microsoft.Azure.Devices.Provisioning.Service, and then press Install.

    “NuGet 包管理器”窗口

    此步骤会下载、安装 Azure IoT 预配服务客户端 SDK NuGet 包及其依赖项并添加对它的引用。This step downloads, installs, and adds a reference to the Azure IoT Provisioning Service Client SDK NuGet package and its dependencies.

  5. Program.cs 顶部的其他 using 语句之后添加以下 using 语句:Add the following using statements after the other using statements at the top of Program.cs:

    using System.Threading.Tasks;
    using Microsoft.Azure.Devices.Provisioning.Service;
    
  6. 将以下字段添加到 Program 类,并进行下列更改。Add the following fields to the Program class, making the changes listed below.

    private static string ProvisioningConnectionString = "{ProvisioningServiceConnectionString}";
    private const string RegistrationId = "sample-registrationid-csharp";
    private const string TpmEndorsementKey =
        "AToAAQALAAMAsgAgg3GXZ0SEs/gakMyNRqXXJP1S124GUgtk8qHaGzMUaaoABgCAAEMAEAgAAAAAAAEAxsj2gUS" +
        "cTk1UjuioeTlfGYZrrimExB+bScH75adUMRIi2UOMxG1kw4y+9RW/IVoMl4e620VxZad0ARX2gUqVjYO7KPVt3d" +
        "yKhZS3dkcvfBisBhP1XH9B33VqHG9SHnbnQXdBUaCgKAfxome8UmBKfe+naTsE5fkvjb/do3/dD6l4sGBwFCnKR" +
        "dln4XpM03zLpoHFao8zOwt8l/uP3qUIxmCYv9A7m69Ms+5/pCkTu/rK4mRDsfhZ0QLfbzVI6zQFOKF/rwsfBtFe" +
        "WlWtcuJMKlXdD8TXWElTzgh7JS4qhFzreL0c1mI0GCj+Aws0usZh7dLIVPnlgZcBhgy1SSDQMQ==";
    
    // Optional parameters
    private const string OptionalDeviceId = "myCSharpDevice";
    private const ProvisioningStatus OptionalProvisioningStatus = ProvisioningStatus.Enabled;
    
    • ProvisioningServiceConnectionString 占位符值替换为需要为其创建注册的预配服务的连接字符串。Replace the ProvisioningServiceConnectionString placeholder value with the connection string of the provisioning service that you want to create the enrollment for.

    • 可以选择更改注册 ID、认可密钥、设备 ID 和预配状态。You may optionally change the registration ID, endorsement key, device ID, and provisioning status.

    • 如果将此快速入门与使用 C# 设备 SDK 创建和预配模拟的 TPM 设备快速入门结合使用来预配模拟设备,请将认可密钥和注册 ID 替换为在该快速入门中记下的值。If you're using this quickstart together with the Create and provision a simulated TPM device using C# device SDK quickstart to provision a simulated device, replace the endorsement key and registration ID with the values that you noted in that quickstart. 可以将设备 ID 替换为在该快速入门中建议的值,可以使用自己的值,也可以使用此示例中的默认值。You can replace the device ID with the value suggested in that quickstart, use your own value, or use the default value in this sample.

  7. 将以下方法添加到 Program 类。Add the following method to the Program class. 此代码创建单个注册条目,然后调用 ProvisioningServiceClient 中的 CreateOrUpdateIndividualEnrollmentAsync 方法,将单个注册添加到预配服务。This code creates individual enrollment entry and then calls the CreateOrUpdateIndividualEnrollmentAsync method on the ProvisioningServiceClient to add the individual enrollment to the provisioning service.

    public static async Task RunSample()
    {
        Console.WriteLine("Starting sample...");
    
        using (ProvisioningServiceClient provisioningServiceClient =
                ProvisioningServiceClient.CreateFromConnectionString(ProvisioningConnectionString))
        {
            #region Create a new individualEnrollment config
            Console.WriteLine("\nCreating a new individualEnrollment...");
            Attestation attestation = new TpmAttestation(TpmEndorsementKey);
            IndividualEnrollment individualEnrollment =
                    new IndividualEnrollment(
                            RegistrationId,
                            attestation);
    
            // The following parameters are optional. Remove them if you don't need them.
            individualEnrollment.DeviceId = OptionalDeviceId;
            individualEnrollment.ProvisioningStatus = OptionalProvisioningStatus;
            #endregion
    
            #region Create the individualEnrollment
            Console.WriteLine("\nAdding new individualEnrollment...");
            IndividualEnrollment individualEnrollmentResult =
                await provisioningServiceClient.CreateOrUpdateIndividualEnrollmentAsync(individualEnrollment).ConfigureAwait(false);
            Console.WriteLine("\nIndividualEnrollment created with success.");
            Console.WriteLine(individualEnrollmentResult);
            #endregion
    
        }
    }
    
  8. 最后,将 Main 方法的主体替换为以下行:Finally, replace the body of the Main method with the following lines:

    RunSample().GetAwaiter().GetResult();
    Console.WriteLine("\nHit <Enter> to exit ...");
    Console.ReadLine();
    
  9. 生成解决方案。Build the solution.

运行单个注册示例Run the individual enrollment sample

在 Visual Studio 中运行此示例,为 TPM 设备创建单个注册。Run the sample in Visual Studio to create the individual enrollment for your TPM device.

系统将显示命令提示符窗口并开始显示确认消息。A Command Prompt window will appear and start showing confirmation messages. 成功创建后,命令提示符窗口会显示新的单个注册的属性。On successful creation, the Command Prompt window displays the properties of the new individual enrollment.

可以验证是否已创建单个注册。You can verify that the individual enrollment has been created. 转到设备预配服务的摘要,依次选择“管理注册”、“单个注册”。 Go to the Device Provisioning Service summary, and select Manage enrollments, then select Individual Enrollments. 此时会看到一个新的注册条目,对应于示例中使用的注册 ID。You should see a new enrollment entry that corresponds to the registration ID you used in the sample.

门户中的注册属性

选择该条目即可验证认可密钥以及该条目的其他属性。Select the entry to verify the endorsement key and other properties for the entry.

如果你一直在按使用 C# 设备 SDK 创建和预配模拟的 TPM 设备快速入门中的步骤操作,可以继续执行该快速入门中的其余步骤来注册模拟设备。If you've been following the steps in the Create and provision a simulated TPM device using C# device SDK quickstart, you can continue with the remaining steps in that quickstart to enroll your simulated device. 务必跳过使用 Azure 门户创建单个注册的步骤。Be sure to skip the steps to create an individual enrollment using the Azure portal.

清理资源Clean up resources

如果你打算学习 C# 服务示例,请勿清理本快速入门中创建的资源。If you plan to explore the C# service sample, don't clean up the resources created in this quickstart. 否则,请使用以下步骤删除本快速入门创建的所有资源。Otherwise, use the following steps to delete all resources created by this quickstart.

  1. 关闭计算机上的 C# 示例输出窗口。Close the C# sample output window on your computer.

  2. 在 Azure 门户中导航到你的设备预配服务,选择“管理注册”,然后选择“单个注册”选项卡。 选中通过本快速入门创建的注册项的“注册 ID”旁边的复选框,然后按窗格顶部的“删除”按钮 。Navigate to your Device Provisioning service in the Azure portal, select Manage enrollments, and then select the Individual Enrollments tab. Select the check box next to the Registration ID for the enrollment entry you created using this quickstart, and press the Delete button at the top of the pane.

  3. 如果已按照使用 C# 设备 SDK 创建和预配模拟的 TPM 设备中的步骤创建模拟的 TPM 设备,请执行以下步骤:If you followed the steps in Create and provision a simulated TPM device using C# device SDK to create a simulated TPM device, do the following steps:

    1. 关闭 TPM 模拟器窗口以及模拟设备的示例输出窗口。Close the TPM simulator window and the sample output window for the simulated device.

    2. 在 Azure 门户中,导航到预配了设备的 IoT 中心。In the Azure portal, navigate to the IoT Hub where your device was provisioned. 在“资源管理器”下的菜单中,选择“IoT 设备”,选中在本快速入门中注册的设备的“设备 ID”旁边的复选框,然后按窗格顶部的“删除”按钮 。In the menu under Explorers, select IoT devices, select the check box next to the DEVICE ID of the device you registered in this quickstart, and then press the Delete button at the top of the pane.

后续步骤Next steps

在本快速入门中,你以编程方式为 TPM 设备创建了单个注册条目。In this quickstart, you’ve programmatically created an individual enrollment entry for a TPM device. 此外,你已根据需要在计算机上创建了一个 TPM 模拟设备,并已使用 Azure IoT 中心设备预配服务将其预配到 IoT 中心。Optionally, you created a TPM simulated device on your computer and provisioned it to your IoT hub using the Azure IoT Hub Device Provisioning Service. 若要深入了解设备预配,请继续学习本教程有关如何在 Azure 门户中进行设备预配服务设置的内容。To learn about device provisioning in depth, continue to the tutorial for the Device Provisioning Service setup in the Azure portal.