使用 Azure 资源管理器模板创建 IoT 中心 (.NET)Create an IoT hub using Azure Resource Manager template (.NET)

可以使用 Azure 资源管理器以编程方式创建和管理 Azure IoT 中心。You can use Azure Resource Manager to create and manage Azure IoT hubs programmatically. 本教程介绍如何使用 Azure 资源管理器模板通过 C# 程序创建 IoT 中心。This tutorial shows you how to use an Azure Resource Manager template to create an IoT hub from a C# program.

备注

Azure 提供了用于创建和使用资源的两个不同部署模型:Azure 资源管理器模型和经典模型Azure has two different deployment models for creating and working with resources: Azure Resource Manager and classic. 本文介绍了如何使用 Azure 资源管理器部署模型。This article covers using the Azure Resource Manager deployment model.

备注

本文进行了更新,以便使用新的 Azure PowerShell Az 模块。This article has been updated to use the new Azure PowerShell Az module. 你仍然可以使用 AzureRM 模块,至少在 2020 年 12 月之前,它将继续接收 bug 修补程序。You can still use the AzureRM module, which will continue to receive bug fixes until at least December 2020. 若要详细了解新的 Az 模块和 AzureRM 兼容性,请参阅新 Azure Powershell Az 模块简介To learn more about the new Az module and AzureRM compatibility, see Introducing the new Azure PowerShell Az module. 有关 Az 模块安装说明,请参阅安装 Azure PowerShellFor Az module installation instructions, see Install Azure PowerShell.

要完成本教程,需要以下各项:To complete this tutorial, you need the following:

  • Visual Studio。Visual Studio.
  • 有效的 Azure 帐户。An active Azure account.
    如果没有帐户,只需花费几分钟就能创建一个帐户If you don't have an account, you can create a account in just a couple of minutes.
  • 可以存储 Azure 资源管理器模板文件的 Azure 存储帐户An Azure Storage account where you can store your Azure Resource Manager template files.
  • Azure PowerShell 1.0 或更高版本。Azure PowerShell 1.0 or later.

准备对 Azure Resource Manager 请求进行身份验证Prepare to authenticate Azure Resource Manager requests

必须使用 Azure Resource Manager 配合 Azure Active Directory (AD) 来验证所有针对资源执行的操作。You must authenticate all the operations that you perform on resources using the Azure Resource Manager with Azure Active Directory (AD). 最简单的配置方式是使用 PowerShell 或 Azure CLI。The easiest way to configure this is to use PowerShell or Azure CLI.

在继续之前,请安装 Azure PowerShell cmdletInstall the Azure PowerShell cmdlets before you continue.

以下步骤说明如何使用 PowerShell 设置 AD 应用程序的密码身份验证。The following steps show how to set up password authentication for an AD application using PowerShell. 可以在标准 PowerShell 会话中运行这些命令。You can run these commands in a standard PowerShell session.

  1. 使用以下命令登录到 Azure 订阅:Sign in to your Azure subscription using the following command:

    Connect-AzureRmAccount -Environment AzureChinaCloud
    
  2. 如果有多个 Azure 订阅,则访问 Azure 即有权访问与凭据关联的所有 Azure 订阅。If you have multiple Azure subscriptions, signing in to Azure grants you access to all the Azure subscriptions associated with your credentials. 使用以下命令,列出可供使用的 Azure 订阅:Use the following command to list the Azure subscriptions available for you to use:

    Get-AzureRMSubscription
    

    使用以下命令,选择想要用于运行命令以管理 IoT 中心的订阅。Use the following command to select subscription that you want to use to run the commands to manage your IoT hub. 可使用上一命令输出中的订阅名称或 ID:You can use either the subscription name or ID from the output of the previous command:

    Select-AzureRMSubscription `
        -SubscriptionName "{your subscription name}"
    
  3. 记下 TenantIdSubscriptionIdMake a note of your TenantId and SubscriptionId. 稍后会需要它们。You need them later.

  4. 使用以下命令并替换占位符,以创建新的 Azure Active Directory 应用程序:Create a new Azure Active Directory application using the following command, replacing the place holders:

    • {Display name}:应用程序的显示名称,例如 MySampleApp{Display name}: a display name for your application such as MySampleApp

    • {Home page URL}: 应用主页的 URL,例如 http://mysampleapp/home。{Home page URL}: the URL of the home page of your app such as http://mysampleapp/home. 此 URL 不需要指向实际的应用程序。This URL does not need to point to a real application.

    • {Application identifier}: 唯一的标识符,例如 http://mysampleapp{Application identifier}: A unique identifier such as http://mysampleapp. 此 URL 不需要指向实际的应用程序。This URL does not need to point to a real application.

    • {Password}: 用于向应用进行身份验证的密码。{Password}: A password that you use to authenticate with your app.

      $SecurePassword=ConvertTo-SecureString {password} �asplaintext �force
      New-AzureRmADApplication -DisplayName {Display name} -HomePage {Home page URL} -IdentifierUris {Application identifier} -Password $SecurePassword
      
  5. 请记下创建的应用程序的 ApplicationIdMake a note of the ApplicationId of the application you created. 稍后会需要它。You need this later.

  6. 使用以下命令(将 {MyApplicationId} 替换为上一步骤中的 ApplicationId)创建新的服务主体:Create a new service principal using the following command, replacing {MyApplicationId} with the ApplicationId from the previous step:

    New-AzureRmADServicePrincipal -ApplicationId {MyApplicationId}
    
  7. 使用以下命令(将 {MyApplicationId} 替换为 ApplicationId)设置角色分配。Set up a role assignment using the following command, replacing {MyApplicationId} with your ApplicationId.

    New-AzureRmRoleAssignment -RoleDefinitionName Owner -ServicePrincipalName {MyApplicationId}
    

现在,已创建可从自定义 C# 应用程序进行身份验证的 Azure AD 应用程序。You have now finished creating the Azure AD application that enables you to authenticate from your custom C# application. 在本教程的后续内容中,需要用到以下值:You need the following values later in this tutorial:

  • TenantIdTenantId
  • SubscriptionIdSubscriptionId
  • ApplicationIdApplicationId
  • 密码Password

准备 Visual Studio 项目Prepare your Visual Studio project

  1. 在 Visual Studio 中,使用“控制台应用(.NET Framework)” 项目模板创建 Visual C# Windows 经典桌面项目。In Visual Studio, create a Visual C# Windows Classic Desktop project using the Console App (.NET Framework) project template. 将项目命名为 CreateIoTHubName the project CreateIoTHub.

  2. 在解决方案资源管理器中右键单击项目,然后单击“管理 NuGet 包”。In Solution Explorer, right-click on your project and then click Manage NuGet Packages.

  3. 在 NuGet 包管理器中,选中“包括预发行版”,并在“浏览”页上搜索 Microsoft.Azure.Management.ResourceManagerIn NuGet Package Manager, check Include prerelease, and on the Browse page search for Microsoft.Azure.Management.ResourceManager. 选择该包,单击“安装” ,在“审阅更改” 中单击“确定” ,并单击“我接受” 以接受许可证。Select the package, click Install, in Review Changes click OK, then click I Accept to accept the licenses.

  4. 在 NuGet 包管理器中,搜索 Microsoft.IdentityModel.Clients.ActiveDirectoryIn NuGet Package Manager, search for Microsoft.IdentityModel.Clients.ActiveDirectory. 单击“安装”,在“审阅更改”中单击“确定”,并单击“我接受”以接受许可证。Click Install, in Review Changes click OK, then click I Accept to accept the license.

  5. 在 Program.cs 中,将现有 using 语句替换为以下代码:In Program.cs, replace the existing using statements with the following code:

    using System;
    using Microsoft.Azure.Management.ResourceManager;
    using Microsoft.Azure.Management.ResourceManager.Models;
    using Microsoft.IdentityModel.Clients.ActiveDirectory;
    using Microsoft.Rest;
    
  6. 在 Program.cs 中,将占位符值替换为以下静态变量。In Program.cs, add the following static variables replacing the placeholder values. 在本教程前面的介绍中,已记下 ApplicationIdSubscriptionIdTenantIdPasswordYou made a note of ApplicationId, SubscriptionId, TenantId, and Password earlier in this tutorial. Your Azure Storage account name 是要在其中存储 Azure 资源管理器模板文件的 Azure 存储帐户的名称。Your Azure Storage account name is the name of the Azure Storage account where you store your Azure Resource Manager template files. 资源组名称 是创建 IoT 中心时要使用的资源组名称。Resource group name is the name of the resource group you use when you create the IoT hub. 名称可以是现有的资源组或新资源组。The name can be a pre-existing or new resource group. 部署名称是部署的名称,例如 Deployment_01Deployment name is a name for the deployment, such as Deployment_01.

    static string applicationId = "{Your ApplicationId}";
    static string subscriptionId = "{Your SubscriptionId}";
    static string tenantId = "{Your TenantId}";
    static string password = "{Your application Password}";
    static string storageAddress = "https://{Your storage account name}.blob.core.chinacloudapi.cn";
    static string rgName = "{Resource group name}";
    static string deploymentName = "{Deployment name}";
    

获取 Azure 资源管理器令牌Obtain an Azure Resource Manager token

Azure Active Directory 必须使用 Azure Resource Manager 来验证所有针对资源执行的任务。Azure Active Directory must authenticate all the tasks that you perform on resources using the Azure Resource Manager. 此处显示的示例使用密码身份验证。有关其他方法,请参阅对 Azure 资源管理器请求进行身份验证The example shown here uses password authentication, for other approaches see Authenticating Azure Resource Manager requests.

  1. 将以下代码添加到 Program.cs 中的 Main 方法,以使用应用程序 ID 和密码从 Azure AD 中检索令牌。Add the following code to the Main method in Program.cs to retrieve a token from Azure AD using the application id and password.

    var authContext = new AuthenticationContext(string.Format  
      ("https://login.microsoftonline.com/{0}", tenantId));
    var credential = new ClientCredential(applicationId, password);
    AuthenticationResult token = authContext.AcquireTokenAsync
      ("https://management.core.windows.net/", credential).Result;
    
    if (token == null)
    {
      Console.WriteLine("Failed to obtain the token");
      return;
    }
    
  2. 创建一个 ResourceManagementClient 对象,该对象通过在 Main 方法的末尾添加以下代码来使用令牌:Create a ResourceManagementClient object that uses the token by adding the following code to the end of the Main method:

    var creds = new TokenCredentials(token.AccessToken);
    var client = new ResourceManagementClient(creds);
    client.SubscriptionId = subscriptionId;
    
  3. 创建或获取对你使用的资源组的引用:Create, or obtain a reference to, the resource group you are using:

    var rgResponse = client.ResourceGroups.CreateOrUpdate(rgName,
        new ResourceGroup("East US"));
    if (rgResponse.Properties.ProvisioningState != "Succeeded")
    {
      Console.WriteLine("Problem creating resource group");
      return;
    }
    

提交模板以创建 IoT 中心Submit a template to create an IoT hub

使用 JSON 模板和参数文件在资源组中创建 IoT 中心。Use a JSON template and parameter file to create an IoT hub in your resource group. 还可以使用 Azure 资源管理器模板更改现有 IoT 中心。You can also use an Azure Resource Manager template to make changes to an existing IoT hub.

  1. 在解决方案资源管理器中右键单击项目,单击“添加”,然后单击“新建项”。In Solution Explorer, right-click on your project, click Add, and then click New Item. 将名为 template.json 的 JSON 文件添加到项目。Add a JSON file called template.json to your project.

  2. 若要在中国东部 区域中添加一个标准 IoT 中心,请将“template.json” 的内容替换为以下资源定义。To add a standard IoT hub to the China East region, replace the contents of template.json with the following resource definition. 有关支持 IoT 中心的区域的最新列表,请参阅 Azure 状态For the current list of regions that support IoT Hub see Azure Status:

    {
      "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentTemplate.json#",
      "contentVersion": "1.0.0.0",
      "parameters": {
        "hubName": {
          "type": "string"
        }
      },
      "resources": [
      {
        "apiVersion": "2016-02-03",
        "type": "Microsoft.Devices/IotHubs",
        "name": "[parameters('hubName')]",
        "location": "China East",
        "sku": {
          "name": "S1",
          "tier": "Standard",
          "capacity": 1
        },
        "properties": {
          "location": "China East"
        }
      }
      ],
      "outputs": {
        "hubKeys": {
          "value": "[listKeys(resourceId('Microsoft.Devices/IotHubs', parameters('hubName')), '2016-02-03')]",
          "type": "object"
        }
      }
    }
    
  3. 在解决方案资源管理器中右键单击项目,单击“添加”,然后单击“新建项”。In Solution Explorer, right-click on your project, click Add, and then click New Item. 将名为 parameters.json 的 JSON 文件添加到项目。Add a JSON file called parameters.json to your project.

  4. parameters.json 的内容替换为以下参数信息,以便将新 IoT 中心的名称设置为 {your initials}mynewiothubReplace the contents of parameters.json with the following parameter information that sets a name for the new IoT hub such as {your initials}mynewiothub. IoT 中心名称必须全局唯一,因此,应包含姓名或姓名首字母缩写:The IoT hub name must be globally unique so it should include your name or initials:

    {
      "$schema": "https://schema.management.azure.com/schemas/2015-01-01/deploymentParameters.json#",
      "contentVersion": "1.0.0.0",
      "parameters": {
        "hubName": { "value": "mynewiothub" }
      }
    }
    

    重要

    IoT 中心将公开为 DNS 终结点,因此,命名时请务必避免包含任何敏感信息。The IoT hub will be publicly discoverable as a DNS endpoint, so make sure to avoid any sensitive information while naming it.

  5. 服务器资源管理器中,连接到 Azure 订阅,并在 Azure 存储帐户中创建名为 templates 的容器。In Server Explorer, connect to your Azure subscription, and in your Azure Storage account create a container called templates. 在“属性”面板中,将 templates 容器的“公共读取访问权限”权限设置为“Blob”。In the Properties panel, set the Public Read Access permissions for the templates container to Blob.

  6. 在“服务器资源管理器”中,右键单击 templates 容器,并单击“查看 Blob 容器”。In Server Explorer, right-click on the templates container and then click View Blob Container. 单击“上传 Blob”按钮,选择“parameters.json”和“templates.json”这两个文件,然后单击“打开”,将 JSON 文件上传到 templates 容器。Click the Upload Blob button, select the two files, parameters.json and templates.json, and then click Open to upload the JSON files to the templates container. 包含 JSON 数据的 Blob 的 URL 如下:The URLs of the blobs containing the JSON data are:

    https://{Your storage account name}.blob.core.windows.net/templates/parameters.json
    https://{Your storage account name}.blob.core.windows.net/templates/template.json
    
  7. 将以下方法添加到 Program.cs:Add the following method to Program.cs:

    static void CreateIoTHub(ResourceManagementClient client)
    {
    
    }
    
  8. 将以下代码添加到 CreateIoTHub 方法以将模板和参数文件提交到 Azure 资源管理器:Add the following code to the CreateIoTHub method to submit the template and parameter files to the Azure Resource Manager:

    var createResponse = client.Deployments.CreateOrUpdate(
        rgName,
        deploymentName,
        new Deployment()
        {
          Properties = new DeploymentProperties
          {
            Mode = DeploymentMode.Incremental,
            TemplateLink = new TemplateLink
            {
              Uri = storageAddress + "/templates/template.json"
            },
            ParametersLink = new ParametersLink
            {
              Uri = storageAddress + "/templates/parameters.json"
            }
          }
        });
    
  9. 将以下代码添加到 CreateIoTHub 方法以显示新 IoT 中心的状态和密钥:Add the following code to the CreateIoTHub method that displays the status and the keys for the new IoT hub:

    string state = createResponse.Properties.ProvisioningState;
    Console.WriteLine("Deployment state: {0}", state);
    
    if (state != "Succeeded")
    {
      Console.WriteLine("Failed to create iothub");
    }
    Console.WriteLine(createResponse.Properties.Outputs);
    

完成并运行应用程序Complete and run the application

现在,可以调用 CreateIoTHub 方法来完成应用程序,然后生成并运行该应用程序。You can now complete the application by calling the CreateIoTHub method before you build and run it.

  1. 将以下代码添加到 Main 方法末尾:Add the following code to the end of the Main method:

    CreateIoTHub(client);
    Console.ReadLine();
    
  2. 单击“生成”,并单击“生成解决方案”。Click Build and then Build Solution. 更正所有错误。Correct any errors.

  3. 单击“调试”,并单击“开始调试”以运行应用程序。Click Debug and then Start Debugging to run the application. 运行部署可能需要几分钟时间。It may take several minutes for the deployment to run.

  4. 若要验证应用程序是否添加了新的 IoT 中心,请访问 Azure 门户并查看资源列表。To verify your application added the new IoT hub, visit the Azure portal and view your list of resources. 另外,也可以使用 Get-AzResource PowerShell cmdlet。Alternatively, use the Get-AzResource PowerShell cmdlet.

备注

本示例应用程序将添加用于对你计费的 S1 标准 IoT 中心。This example application adds an S1 Standard IoT Hub for which you are billed. 在完成任务后,可以通过 Azure 门户 或者使用 Remove-AzResource PowerShell cmdlet 删除该 IoT 中心。You can delete the IoT hub through the Azure portal or by using the Remove-AzResource PowerShell cmdlet when you are finished.

后续步骤Next steps

现在,已经使用包含 C# 程序的 Azure 资源管理器模板部署了 IoT 中心,你可能想要进一步探究:Now you have deployed an IoT hub using an Azure Resource Manager template with a C# program, you may want to explore further:

若要详细了解如何开发 IoT 中心,请参阅以下文章:To learn more about developing for IoT Hub, see the following articles:

若要进一步探索 IoT 中心的功能,请参阅:To further explore the capabilities of IoT Hub, see: