Get started with device management (.NET)

Back-end apps can use Azure IoT Hub primitives, such as device twin and direct methods, to remotely start and monitor device management actions on devices. This tutorial shows you how a back-end app and a device app can work together to initiate and monitor a remote device reboot using IoT Hub.

Note

The features described in this article are available only in the standard tier of IoT Hub. For more information about the basic and standard/free IoT Hub tiers, see Choose the right IoT Hub tier.

Use a direct method to initiate device management actions (such as reboot, factory reset, and firmware update) from a back-end app in the cloud. The device is responsible for:

  • Handling the method request sent from IoT Hub.

  • Initiating the corresponding device-specific action on the device.

  • Providing status updates through reported properties to IoT Hub.

You can use a back-end app in the cloud to run device twin queries to report on the progress of your device management actions.

This tutorial shows you how to:

  • Use the Azure portal to create an IoT hub and create a device identity in your IoT hub.

  • Create a simulated device app that contains a direct method that reboots that device. Direct methods are invoked from the cloud.

  • Create a .NET console app that calls the reboot direct method in the simulated device app through your IoT hub.

At the end of this tutorial, you have two .NET console apps:

  • SimulateManagedDevice. This app connects to your IoT hub with the device identity created earlier, receives a reboot direct method, simulates a physical reboot, and reports the time for the last reboot.

  • TriggerReboot. This app calls a direct method in the simulated device app, displays the response, and displays the updated reported properties.

Prerequisites

  • Visual Studio.

  • An active Azure account. If you don't have an account, you can create a free account in just a couple of minutes.

  • Make sure that port 8883 is open in your firewall. The device sample in this article uses MQTT protocol, which communicates over port 8883. This port may be blocked in some corporate and educational network environments. For more information and ways to work around this issue, see Connecting to IoT Hub (MQTT).

Create an IoT hub

This section describes how to create an IoT hub using the Azure portal.

  1. Sign in to the Azure portal.

  2. From the Azure homepage, select the + Create a resource button, and then enter IoT Hub in the Search the Marketplace field.

  3. Select IoT Hub from the search results, and then select Create.

  4. On the Basics tab, complete the fields as follows:

    • Subscription: Select the subscription to use for your hub.

    • Resource Group: Select a resource group or create a new one. To create a new one, select Create new and fill in the name you want to use. To use an existing resource group, select that resource group. For more information, see Manage Azure Resource Manager resource groups.

    • Region: Select the region in which you want your hub to be located. Select the location closest to you. Some features, such as IoT Hub device streams, are only available in specific regions. For these limited features, you must select one of the supported regions.

    • IoT Hub Name: Enter a name for your hub. This name must be globally unique, with a length between 3 and 50 alphanumeric characters. The name can also include the dash ('-') character.

    Important

    Because the IoT hub will be publicly discoverable as a DNS endpoint, be sure to avoid entering any sensitive or personally identifiable information when you name it.

    Create a hub in the Azure portal.

  5. Select Next: Networking to continue creating your hub.

    Choose the endpoints that devices can use to connect to your IoT Hub. You can select the default setting Public endpoint (all networks), or choose Public endpoint (selected IP ranges), or Private endpoint. Accept the default setting for this example.

    Choose the endpoints that can connect.

  6. Select Next: Management to continue creating your hub.

    Set the size and scale for a new hub using the Azure portal.

    You can accept the default settings here. If desired, you can modify any of the following fields:

    • Pricing and scale tier: Your selected tier. You can choose from several tiers, depending on how many features you want and how many messages you send through your solution per day. The free tier is intended for testing and evaluation. It allows 500 devices to be connected to the hub and up to 8,000 messages per day. Each Azure subscription can create one IoT hub in the free tier.

      If you are working through a Quickstart for IoT Hub device streams, select the free tier.

    • IoT Hub units: The number of messages allowed per unit per day depends on your hub's pricing tier. For example, if you want the hub to support ingress of 700,000 messages, you choose two S1 tier units. For details about the other tier options, see Choosing the right IoT Hub tier.

    • Microsoft Defender for IoT: Turn this on to add an extra layer of threat protection to IoT and your devices. This option is not available for hubs in the free tier. Learn more about security recommendations for IoT Hub in Defender for IoT.

    • Advanced Settings > Device-to-cloud partitions: This property relates the device-to-cloud messages to the number of simultaneous readers of the messages. Most hubs need only four partitions.

  7. Select Next: Tags to continue to the next screen.

    Tags are name/value pairs. You can assign the same tag to multiple resources and resource groups to categorize resources and consolidate billing. In this document, you won't be adding any tags. For more information, see Use tags to organize your Azure resources.

    Assign tags for the hub using the Azure portal.

  8. Select Next: Review + create to review your choices. You see something similar to this screen, but with the values you selected when creating the hub.

    Review information for creating the new hub.

  9. Select Create to start the deployment of your new hub. Your deployment will be in progress a few minutes while the hub is being created. Once the deployment is complete, select Go to resource to open the new hub.

Register a new device in the IoT hub

In this section, you create a device identity in the identity registry in your IoT hub. A device cannot connect to a hub unless it has an entry in the identity registry. For more information, see the IoT Hub developer guide.

  1. In your IoT hub navigation menu, open Devices, then select Add Device to add a device in your IoT hub.

    Screen capture that shows how to create a device identity in the portal

  2. In Create a device, provide a name for your new device, such as myDeviceId, and select Save. This action creates a device identity for your IoT hub. Leave Auto-generate keys checked so that the primary and secondary keys will be generated automatically.

    Screen capture that shows how to add a new device

    Important

    The device ID may be visible in the logs collected for customer support and troubleshooting, so make sure to avoid any sensitive information while naming it.

  3. After the device is created, open the device from the list in the Devices pane. Copy the Primary Connection String. This connection string is used by device code to communicate with the hub.

    By default, the keys and connection strings are masked as they are sensitive information. If you click the eye icon, they are revealed. It is not necessary to reveal them to copy them with the copy button.

    Screen capture that shows the device connection string

Note

The IoT Hub identity registry only stores device identities to enable secure access to the IoT hub. It stores device IDs and keys to use as security credentials, and an enabled/disabled flag that you can use to disable access for an individual device. If your application needs to store other device-specific metadata, it should use an application-specific store. For more information, see IoT Hub developer guide.

Get the IoT hub connection string

In this article, you create a backend service that invokes a direct method on a device. To invoke a direct method on a device through IoT Hub, your service needs the service connect permission. By default, every IoT Hub is created with a shared access policy named service that grants this permission.

To get the IoT Hub connection string for the service policy, follow these steps:

  1. In the Azure portal, select Resource groups. Select the resource group where your hub is located, and then select your hub from the list of resources.

  2. On the left-side pane of your IoT hub, select Shared access policies.

  3. From the list of policies, select the service policy.

  4. Under Shared access keys, select the copy icon for the Primary connection string and save the value.

Screenshot that shows how to retrieve the connection string

For more information about IoT Hub shared access policies and permissions, see Access control and permissions.

Trigger a remote reboot on the device using a direct method

In this section, you create a .NET console app, using C#, that initiates a remote reboot on a device using a direct method. The app uses device twin queries to discover the last reboot time for that device.

  1. In Visual Studio, select Create a new project.

  2. In Create a new project, find and select the Console App (.NET Framework) project template, and then select Next.

  3. In Configure your new project, name the project TriggerReboot, and select .NET Framework version 4.5.1 or later. Select Create.

    New Visual C# Windows Classic Desktop project

  4. In Solution Explorer, right-click the TriggerReboot project, and then select Manage NuGet Packages.

  5. Select Browse, then search for and select Microsoft.Azure.Devices. Select Install to install the Microsoft.Azure.Devices package.

    NuGet Package Manager window

    This step downloads, installs, and adds a reference to the Azure IoT service SDK NuGet package and its dependencies.

  6. Add the following using statements at the top of the Program.cs file:

    using Microsoft.Azure.Devices;
    using Microsoft.Azure.Devices.Shared;
    
  7. Add the following fields to the Program class. Replace the {iot hub connection string} placeholder value with the IoT Hub connection string you copied previously in Get the IoT hub connection string.

    static RegistryManager registryManager;
    static string connString = "{iot hub connection string}";
    static ServiceClient client;
    static string targetDevice = "myDeviceId";
    
  8. Add the following method to the Program class. This code gets the device twin for the rebooting device and outputs the reported properties.

    public static async Task QueryTwinRebootReported()
    {
        Twin twin = await registryManager.GetTwinAsync(targetDevice);
        Console.WriteLine(twin.Properties.Reported.ToJson());
    }
    
  9. Add the following method to the Program class. This code initiates the reboot on the device using a direct method.

    public static async Task StartReboot()
    {
        client = ServiceClient.CreateFromConnectionString(connString);
        CloudToDeviceMethod method = new CloudToDeviceMethod("reboot");
        method.ResponseTimeout = TimeSpan.FromSeconds(30);
    
        CloudToDeviceMethodResult result = await 
          client.InvokeDeviceMethodAsync(targetDevice, method);
    
        Console.WriteLine("Invoked firmware update on device.");
    }
    
  10. Finally, add the following lines to the Main method:

    registryManager = RegistryManager.CreateFromConnectionString(connString);
    StartReboot().Wait();
    QueryTwinRebootReported().Wait();
    Console.WriteLine("Press ENTER to exit.");
    Console.ReadLine();
    
  11. Select Build > Build Solution.

Note

This tutorial performs only a single query for the device's reported properties. In production code, we recommend polling to detect changes in the reported properties.

Create a simulated device app

In this section, you:

  • Create a .NET console app that responds to a direct method called by the cloud.

  • Trigger a simulated device reboot.

  • Use the reported properties to enable device twin queries to identify devices and when they were last rebooted.

To create the simulated device app, follow these steps:

  1. In Visual Studio, in the TriggerReboot solution you already created, select File > New > Project. In Create a new project, find and select the Console App (.NET Framework) project template, and then select Next.

  2. In Configure your new project, name the project SimulateManagedDevice, and for Solution, select Add to solution. Select Create.

    Name and add your project to the solution

  3. In Solution Explorer, right-click the new SimulateManagedDevice project, and then select Manage NuGet Packages.

  4. Select Browse, then search for and select Microsoft.Azure.Devices.Client. Select Install.

    NuGet Package Manager window Client app

    This step downloads, installs, and adds a reference to the Azure IoT device SDK NuGet package and its dependencies.

  5. Add the following using statements at the top of the Program.cs file:

    using Microsoft.Azure.Devices.Client;
    using Microsoft.Azure.Devices.Shared;
    
  6. Add the following fields to the Program class. Replace the {device connection string} placeholder value with the device connection string that you noted previously in Register a new device in the IoT hub.

    static string DeviceConnectionString = "{device connection string}";
    static DeviceClient Client = null;
    
  7. Add the following to implement the direct method on the device:

    static Task<MethodResponse> onReboot(MethodRequest methodRequest, object userContext)
    {
        // In a production device, you would trigger a reboot 
        //   scheduled to start after this method returns.
        // For this sample, we simulate the reboot by writing to the console
        //   and updating the reported properties.
        try
        {
            Console.WriteLine("Rebooting!");
    
            // Update device twin with reboot time. 
            TwinCollection reportedProperties, reboot, lastReboot;
            lastReboot = new TwinCollection();
            reboot = new TwinCollection();
            reportedProperties = new TwinCollection();
            lastReboot["lastReboot"] = DateTime.Now;
            reboot["reboot"] = lastReboot;
            reportedProperties["iothubDM"] = reboot;
            Client.UpdateReportedPropertiesAsync(reportedProperties).Wait();
        }
        catch (Exception ex)
        {
            Console.WriteLine();
            Console.WriteLine("Error in sample: {0}", ex.Message);
        }
    
        string result = @"{""result"":""Reboot started.""}";
        return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 200));
    }
    
  8. Finally, add the following code to the Main method to open the connection to your IoT hub and initialize the method listener:

    try
    {
        Console.WriteLine("Connecting to hub");
        Client = DeviceClient.CreateFromConnectionString(DeviceConnectionString, 
          TransportType.Mqtt);
    
        // setup callback for "reboot" method
        Client.SetMethodHandlerAsync("reboot", onReboot, null).Wait();
        Console.WriteLine("Waiting for reboot method\n Press enter to exit.");
        Console.ReadLine();
    
        Console.WriteLine("Exiting...");
    
        // as a good practice, remove the "reboot" handler
        Client.SetMethodHandlerAsync("reboot", null, null).Wait();
        Client.CloseAsync().Wait();
    }
    catch (Exception ex)
    {
        Console.WriteLine();
        Console.WriteLine("Error in sample: {0}", ex.Message);
    }
    
  9. In Solution Explorer, right-click your solution, and then select Set StartUp Projects.

  10. For Common Properties > Startup Project, Select Single startup project, and then select the SimulateManagedDevice project. Select OK to save your changes.

  11. Select Build > Build Solution.

Note

To keep things simple, this tutorial does not implement any retry policy. In production code, you should implement retry policies (such as an exponential backoff), as suggested in Transient fault handling.

Run the apps

You're now ready to run the apps.

  1. To run the .NET device app SimulateManagedDevice, in Solution Explorer, right-click the SimulateManagedDevice project, select Debug, and then select Start new instance. The app should start listening for method calls from your IoT hub.

  2. After that the device is connected and waiting for method invocations, right-click the TriggerReboot project, select Debug, and then select Start new instance.

    You should see "Rebooting!" written in the SimulatedManagedDevice console and the reported properties of the device, which include the last reboot time, written in the TriggerReboot console.

    Service and device app run

Customize and extend the device management actions

Your IoT solutions can expand the defined set of device management patterns or enable custom patterns by using the device twin and cloud-to-device method primitives. Other examples of device management actions include factory reset, firmware update, software update, power management, network and connectivity management, and data encryption.

Device maintenance windows

Typically, you configure devices to perform actions at a time that minimizes interruptions and downtime. Device maintenance windows are a commonly used pattern to define the time when a device should update its configuration. Your back-end solutions can use the desired properties of the device twin to define and activate a policy on your device that enables a maintenance window. When a device receives the maintenance window policy, it can use the reported property of the device twin to report the status of the policy. The back-end app can then use device twin queries to attest to compliance of devices and each policy.

Next steps

In this tutorial, you used a direct method to trigger a remote reboot on a device. You used the reported properties to report the last reboot time from the device, and queried the device twin to discover the last reboot time of the device from the cloud.

ToTo continue getting started with IoT Hub and device management patterns such as end-to-end image-based update in Device Update for Azure IoT Hub tutorial using the Raspberry Pi 3 B+ Reference Image.

To learn how to extend your IoT solution and schedule method calls on multiple devices, see Schedule and broadcast jobs.