Create an IoT hub using Azure Resource Manager template (.NET)

Introduction

You can use Azure Resource Manager to create and manage Azure IoT hubs programmatically. This tutorial shows you how to use an Azure Resource Manager template to create an IoT hub from a C# program.

Note

Azure has two different deployment models for creating and working with resources: Azure Resource Manager and classic. This article covers using the Azure Resource Manager deployment model.

To complete this tutorial, you need the following:

  • Visual Studio 2015 or Visual Studio 2017.
  • An active Azure account.
    If you don't have an account, you can create a free account in just a couple of minutes.
  • An Azure Storage account where you can store your Azure Resource Manager template files.
  • Azure PowerShell 1.0 or later.

Prepare to authenticate Azure Resource Manager requests

You must authenticate all the operations that you perform on resources using the Azure Resource Manager with Azure Active Directory (AD). The easiest way to configure this is to use PowerShell or Azure CLI.

Install the Azure PowerShell cmdlets before you continue.

The following steps show how to set up password authentication for an AD application using PowerShell. You can run these commands in a standard PowerShell session.

  1. Log in to your Azure subscription using the following command:

    Login-AzureRmAccount
    
  2. If you have multiple Azure subscriptions, signing in to Azure grants you access to all the Azure subscriptions associated with your credentials. Use the following command to list the Azure subscriptions available for you to use:

    Get-AzureRMSubscription
    

    Use the following command to select subscription that you want to use to run the commands to manage your IoT hub. You can use either the subscription name or ID from the output of the previous command:

    Select-AzureRMSubscription `
        -SubscriptionName "{your subscription name}"
    
  3. Make a note of your TenantId and SubscriptionId. You need them later.

  4. Create a new Azure Active Directory application using the following command, replacing the place holders:

    • {Display name}: a display name for your application such as MySampleApp
    • {Home page URL}: the URL of the home page of your app such as http://mysampleapp/home. This URL does not need to point to a real application.
    • {Application identifier}: A unique identifier such as http://mysampleapp. This URL does not need to point to a real application.
    • {Password}: A password that you use to authenticate with your app.

      New-AzureRmADApplication -DisplayName {Display name} -HomePage {Home page URL} -IdentifierUris {Application identifier} -Password {Password}
      
  5. Make a note of the ApplicationId of the application you created. You need this later.
  6. Create a new service principal using the following command, replacing {MyApplicationId} with the ApplicationId from the previous step:

    New-AzureRmADServicePrincipal -ApplicationId {MyApplicationId}
    
  7. Set up a role assignment using the following command, replacing {MyApplicationId} with your ApplicationId.

    New-AzureRmRoleAssignment -RoleDefinitionName Owner -ServicePrincipalName {MyApplicationId}
    

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:

  • TenantId
  • SubscriptionId
  • ApplicationId
  • Password

Prepare your Visual Studio project

  1. In Visual Studio, create a Visual C# Windows Classic Desktop project using the Console App (.NET Framework) project template. Name the project CreateIoTHub.
  2. In Solution Explorer, right-click on your project and then click Manage NuGet Packages.
  3. In 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. In 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. 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. In Program.cs, add the following static variables replacing the placeholder values. You made a note of ApplicationId, SubscriptionId, TenantId, and Password earlier in this tutorial. Your Azure Storage account name is the name of the Azure Storage account where you store your Azure Resource Manager template files. Resource group name is the name of the resource group you use when you create the IoT Hub, it can be a pre-existing resource group or a new one. Deployment 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.windows.net";
    static string rgName = "{Resource group name}";
    static string deploymentName = "{Deployment name}";
    

Obtain an Azure Resource Manager token

Azure Active Directory must authenticate all the tasks that you perform on resources using the Azure Resource Manager. The example shown here uses password authentication, for other approaches see Authenticating Azure Resource Manager requests.

  1. 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. 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;
    }
    

Submit an Azure Resource Manager template to create an IoT hub

Use a JSON template and parameter file to create an IoT hub in your resource group. 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. Add a JSON file called template.json to your project.
  2. Replace the contents of template.json with the following resource definition to add a standard IoT hub to the East US region. 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": "East US",
        "sku": {
          "name": "S1",
          "tier": "Standard",
          "capacity": 1
        },
        "properties": {
          "location": "East US"
        }
      }
      ],
      "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. Add a JSON file called parameters.json to your project.
  4. Replace the contents of parameters.json with the following parameter information that sets a name for the new IoT hub such as {your initials}mynewiothub. 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" }
      }
    }
    
    Important

    The IoT hub will be publicly discoverable as a DNS endpoint, so make sure to avoid any sensitive information while naming it.

  5. In Server Explorer, connect to your Azure subscription, and in your Azure Storage account create a container called templates. In the Properties panel, set the Public Read Access permissions for the templates container to Blob.
  6. In Server Explorer, right-click on the templates container and then click View Blob Container. 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. 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. Add the following method to Program.cs:

    static void CreateIoTHub(ResourceManagementClient client)
    {
    
    }
    
  8. 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. 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

You can now complete the application by calling the CreateIoTHub method before you build and run it.

  1. 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. You can verify that your application added the new IoT hub by visiting the Azure portal and viewing your list of resources, or by using the Get-AzureRmResource PowerShell cmdlet.
Note

This example application adds an S1 Standard IoT Hub for which you are billed. You can delete the IoT hub through the Azure portal or by using the Remove-AzureRmResource PowerShell cmdlet when you are finished.

Next steps

Now you have deployed an IoT hub using an Azure Resource Manager template with a C# program, you may want to explore further:

To learn more about developing for IoT Hub, see the following articles:

To further explore the capabilities of IoT Hub, see: