Create an IoT hub using the resource provider REST API (.NET)

You can use the IoT Hub resource provider REST API to create and manage Azure IoT hubs programmatically. This tutorial shows you how to use the IoT Hub resource provider REST API 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.
  • 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 CreateIoTHubREST.

  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 System.Net.Http;
    using System.Net.Http.Headers;
    using System.Text;
    using Microsoft.Azure.Management.ResourceManager;
    using Microsoft.Azure.Management.ResourceManager.Models;
    using Microsoft.IdentityModel.Clients.ActiveDirectory;
    using Newtonsoft.Json;
    using Microsoft.Rest;
    using System.Linq;
    using System.Threading;
    
  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. Resource group name is the name of the resource group you use when you create the IoT hub. You can use a pre-existing or a new resource group. IoT Hub name is the name of the IoT Hub you create, such as MyIoTHub. The name of your IoT hub must be globally unique. 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 rgName = "{Resource group name}";
    static string iotHubName = "{IoT Hub name including your initials}";
    
    Important

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

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

Use the resource provider REST API to create an IoT hub

Use the IoT Hub resource provider REST API to create an IoT hub in your resource group. You can also use the resource provider REST API to make changes to an existing IoT hub.

  1. Add the following method to Program.cs:

    static void CreateIoTHub(string token)
    {
    
    }
    
  2. Add the following code to the CreateIoTHub method. This code creates an HttpClient object with the authentication token in the headers:

    HttpClient client = new HttpClient();
    client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", token);
    
  3. Add the following code to the CreateIoTHub method. This code describes the IoT hub to create and generates a JSON representation. For the current list of locations that support IoT Hub see Azure Status:

    var description = new
    {
      name = iotHubName,
      location = "East US",
      sku = new
      {
        name = "S1",
        tier = "Standard",
        capacity = 1
      }
    };
    
    var json = JsonConvert.SerializeObject(description, Formatting.Indented);
    
  4. Add the following code to the CreateIoTHub method. This code submits the REST request to Azure. The code then checks the response and retrieves the URL you can use to monitor the state of the deployment task:

    var content = new StringContent(JsonConvert.SerializeObject(description), Encoding.UTF8, "application/json");
    var requestUri = string.Format("https://management.azure.com/subscriptions/{0}/resourcegroups/{1}/providers/Microsoft.devices/IotHubs/{2}?api-version=2016-02-03", subscriptionId, rgName, iotHubName);
    var result = client.PutAsync(requestUri, content).Result;
    
    if (!result.IsSuccessStatusCode)
    {
      Console.WriteLine("Failed {0}", result.Content.ReadAsStringAsync().Result);
      return;
    }
    
    var asyncStatusUri = result.Headers.GetValues("Azure-AsyncOperation").First();
    
  5. Add the following code to the end of the CreateIoTHub method. This code uses the asyncStatusUri address retrieved in the previous step to wait for the deployment to complete:

    string body;
    do
    {
      Thread.Sleep(10000);
      HttpResponseMessage deploymentstatus = client.GetAsync(asyncStatusUri).Result;
      body = deploymentstatus.Content.ReadAsStringAsync().Result;
    } while (body == "{\"status\":\"Running\"}");
    
  6. Add the following code to the end of the CreateIoTHub method. This code retrieves the keys of the IoT hub you created and prints them to the console:

    var listKeysUri = string.Format("https://management.azure.com/subscriptions/{0}/resourceGroups/{1}/providers/Microsoft.Devices/IotHubs/{2}/IoTHubKeys/listkeys?api-version=2016-02-03", subscriptionId, rgName, iotHubName);
    var keysresults = client.PostAsync(listKeysUri, null).Result;
    
    Console.WriteLine("Keys: {0}", keysresults.Content.ReadAsStringAsync().Result);
    

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(token.AccessToken);
    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. To verify that your application added the new IoT hub, visit the Azure portal and view your list of resources. Alternatively, use the Get-AzureRmResource PowerShell cmdlet.

Note

This example application adds an S1 Standard IoT Hub for which you are billed. When you are finished, 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 the resource provider REST API, 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: