Skip to content

Quickstart .NET

Chaoyi Yuan edited this page Dec 6, 2018 · 4 revisions

Create and control an IoT device connected to an IoT hub (.NET)

IoT Hub is an Azure service that enables you to ingest high volumes of telemetry from your IoT devices into the cloud and manage your devices from the cloud. In this quickstart, you will use Visual Studio IoT Hub Toolkit to create a simulated device connected to your IoT hub and control it with a direct method. You can use direct methods to remotely change the behavior of a device connected to your IoT hub.


  1. Install the Visual Studio Code extension Azure Account and sign in. If you don’t have an Azure subscription, create a free account before you begin.

  2. Install the Visual Studio Code extension Azure IoT Hub Toolkit.

The quickstart also uses a pre-written .NET applications as a simulated device application that responds to direct methods called from a back-end application. To receive the direct method calls, this application connects to a device-specific endpoint on your IoT hub. For other supported programming languages, you can refer to IoT Hub Documentations.

  1. The application is written using C#. You need the .NET Core SDK 2.1.0 or greater on your development machine. You can download the .NET Core SDK for multiple platforms from .NET.

You can verify the current version of C# on your development machine using the following command:

dotnet --version

Create an IoT hub

The first step is to create an IoT hub in your subscription from VS Code. The IoT hub enables you to ingest high volumes of telemetry into the cloud from many devices. The hub then enables one or more back-end services running in the cloud to read and process that telemetry.

  1. Click ... > Create IoT Hub at AZURE IOT HUB DEVICES tab, or type Azure IoT Hub: Create IoT Hub in Command Palette.

create hub

  1. Choose your subscription, resource group, and the closest deploy location to you.
  2. For Pricing and scale tier, select the F1 - Free tier if it's still available on your subscription.
  3. Enter the name of your IoT Hub.
  4. Wait a few minutes until the IoT Hub is created. you can see that your devices status become No device in ....

create hub res

Register a device

A device must be registered with your IoT hub before it can connect. You will also need to make a note of its connection string.

  1. Click ... > Create Device at AZURE IOT HUB DEVICES tab, or type Azure IoT Hub: Create Device in Command Palette.
  2. Enter device ID as MyDevice and press Enter.
  3. Wait a few seconds until the new device is created.
  4. Right-click your device and select Copy Device Connection String, the connection string of the selected device will be copy to your clipboard, which looks like Hostname=...=. You will use this Device Connection String later in the quickstart.

create device

Send simulated telemetry and listen for direct method calls

The simulated device application connects to a device-specific endpoint on your IoT hub, sends simulated telemetry, and listens for direct method calls from your hub. In this quickstart, the direct method call from the hub tells the device to change the interval at which it sends telemetry. The simulated device sends an acknowledgement back to your hub after it executes the direct method.

  1. In VS Code, open an empty folder, create a new .Net project and add package reference.

    dotnet new console
    dotnet add package Microsoft.Azure.Devices.Client --version 1.17.0
  2. Open the generated Program.cs, and replace the file content with following code:

    // Copyright (c) Microsoft. All rights reserved.
    // Licensed under the MIT license. See LICENSE file in the project root for full license information.
    // This application uses the Azure IoT Hub device SDK for .NET
    // For samples see:
    using System;
    using Microsoft.Azure.Devices.Client;
    using Newtonsoft.Json;
    using System.Text;
    using System.Threading.Tasks;
    namespace simulated_device
        class SimulatedDevice
            private static DeviceClient s_deviceClient;
            // The device connection string to authenticate the device with your IoT hub.
            // Using the Azure CLI:
            // az iot hub device-identity show-connection-string --hub-name {YourIoTHubName} --device-id MyDevice --output table
            private readonly static string s_connectionString = "{Your device connection string here}";
            private static int s_telemetryInterval = 1; // Seconds
            // Handle the direct method call
            private static Task<MethodResponse> SetTelemetryInterval(MethodRequest methodRequest, object userContext)
                var data = Encoding.UTF8.GetString(methodRequest.Data);
                // Check the payload is a single integer value
                if (Int32.TryParse(data.Replace("\"",""), out s_telemetryInterval))
                    Console.ForegroundColor = ConsoleColor.Green;
                    Console.WriteLine("Telemetry interval set to {0} seconds", data);
                    // Acknowlege the direct method call with a 200 success message
                    string result = "{\"result\":\"Executed direct method: " + methodRequest.Name + "\"}";
                    return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 200));
                    // Acknowlege the direct method call with a 400 error message
                    string result = "{\"result\":\"Invalid parameter\"}";
                    return Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(result), 400));
            // Async method to send simulated telemetry
            private static async void SendDeviceToCloudMessagesAsync()
                // Initial telemetry values
                double minTemperature = 20;
                double minHumidity = 60;
                Random rand = new Random();
                while (true)
                    double currentTemperature = minTemperature + rand.NextDouble() * 15;
                    double currentHumidity = minHumidity + rand.NextDouble() * 20;
                    // Create JSON message
                    var telemetryDataPoint = new
                        temperature = currentTemperature,
                        humidity = currentHumidity
                    var messageString = JsonConvert.SerializeObject(telemetryDataPoint);
                    var message = new Message(Encoding.ASCII.GetBytes(messageString));
                    // Add a custom application property to the message.
                    // An IoT hub can filter on these properties without access to the message body.
                    message.Properties.Add("temperatureAlert", (currentTemperature > 30) ? "true" : "false");
                    // Send the tlemetry message
                    await s_deviceClient.SendEventAsync(message);
                    Console.WriteLine("{0} > Sending message: {1}", DateTime.Now, messageString);
                    await Task.Delay(s_telemetryInterval * 1000);
            private static void Main(string[] args)
                Console.WriteLine("IoT Hub Quickstarts - Simulated device. Ctrl-C to exit.\n");
                // Connect to the IoT hub using the MQTT protocol
                s_deviceClient = DeviceClient.CreateFromConnectionString(s_connectionString, TransportType.Mqtt);
                // Create a handler for the direct method call
                s_deviceClient.SetMethodHandlerAsync("SetTelemetryInterval", SetTelemetryInterval, null).Wait();
  3. Replace the value of the s_connectionString variable in Program.cs with the Device Connection String you made a note of previously. Then save your changes to Program.cs file.

  4. In the terminal window, cd FOLDER_PATH and run the following commands to install the required packages for simulated device application:

    dotnet restore
  5. In the terminal window, run the following command to build and run the simulated device application:

    dotnet run

    The following screenshot shows the output as the simulated device application sends telemetry to your IoT hub:

    Run the simulated device

Monitor IoT Hub D2C message in VS Code

While the device sending telemetry to your IoT hub, it is also possible to monitor those message in VS Code.

  1. Right-click your device and select Start Monitoring D2C Message.

start monitor

  1. The monitored messages will be shown in OUTPUT > Azure IoT Hub Toolkit view.
  2. To stop monitoring, right-click the OUTPUT view and select Stop Monitoring D2C Message.

stop monitor

Invoke the direct method

The VS Code IoT Hub Toolkit extension can also connects to the service-side endpoint on your IoT Hub and makes direct method calls to a device through it.

  1. Right-click your device and select Invoke Direct Method.


  1. Enter the method name SetTelemetryInterval.
  2. Enter the payload 10 as the number of seconds between each telemetry sent.
  3. Results will be shown in OUTPUT > Azure IoT Hub Toolkit view, if success, you will see that the D2C message interval have changed.

invoke res

set interval

Clone this wiki locally
You can’t perform that action at this time.