|
| 1 | +--- |
| 2 | +title: Get started with Azure IoT Hub device twins (.NET/.NET) | Microsoft Docs |
| 3 | +description: How to use Azure IoT Hub device twins to add tags and then use an IoT Hub query. You use the Azure IoT device SDK for .NET to implement the simulated device app and the Azure IoT service SDK for .NET to implement a service app that adds the tags and runs the IoT Hub query. |
| 4 | +author: kgremban |
| 5 | + |
| 6 | +ms.service: iot-hub |
| 7 | +services: iot-hub |
| 8 | +ms.devlang: csharp |
| 9 | +ms.topic: conceptual |
| 10 | +ms.date: 02/17/2023 |
| 11 | +ms.author: kgremban |
| 12 | +ms.custom: "mqtt, devx-track-csharp" |
| 13 | +--- |
| 14 | + |
| 15 | +# Get started with device twins (.NET) |
| 16 | + |
| 17 | +[!INCLUDE [iot-hub-selector-twin-get-started](../../includes/iot-hub-selector-twin-get-started.md)] |
| 18 | + |
| 19 | +This article shows you how to: |
| 20 | + |
| 21 | +* Use a simulated device to report its connectivity channel as a reported property on the device twin. |
| 22 | + |
| 23 | +* Query devices using filters on the tags and properties previously created. |
| 24 | + |
| 25 | +In this article, you create two .NET console apps: |
| 26 | + |
| 27 | +* **AddTagsAndQuery**: a back-end app that adds tags and queries device twins. |
| 28 | + |
| 29 | +* **ReportConnectivity**: a simulated device app that connects to your IoT hub and reports its connectivity condition. |
| 30 | + |
| 31 | +> [!NOTE] |
| 32 | +> See [Azure IoT SDKs](iot-hub-devguide-sdks.md) for more information about the SDK tools available to build both device and back-end apps. |
| 33 | +
|
| 34 | +## Prerequisites |
| 35 | + |
| 36 | +* Visual Studio. |
| 37 | + |
| 38 | +* An IoT Hub. Create one with the [CLI](iot-hub-create-using-cli.md) or the [Azure portal](iot-hub-create-through-portal.md). |
| 39 | + |
| 40 | +* A registered device. Register one in the [Azure portal](iot-hub-create-through-portal.md#register-a-new-device-in-the-iot-hub). |
| 41 | + |
| 42 | +* 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)](iot-hub-mqtt-support.md#connecting-to-iot-hub). |
| 43 | + |
| 44 | +## Get the IoT hub connection string |
| 45 | + |
| 46 | +[!INCLUDE [iot-hub-howto-twin-shared-access-policy-text](../../includes/iot-hub-howto-twin-shared-access-policy-text.md)] |
| 47 | + |
| 48 | +[!INCLUDE [iot-hub-include-find-custom-connection-string](../../includes/iot-hub-include-find-custom-connection-string.md)] |
| 49 | + |
| 50 | +## Create a device app that updates reported properties |
| 51 | + |
| 52 | +In this section, you create a .NET console app that connects to your hub as **myDeviceId**, and then updates its reported properties to confirm that it's connected using a cellular network. |
| 53 | + |
| 54 | +1. Open Visual Studio and select **Create new project**. |
| 55 | + |
| 56 | +1. Choose **Console App (.NET Framework)**, then select **Next**. |
| 57 | + |
| 58 | +1. In **Configure your new project**, name the project **ReportConnectivity**, then select **Next**. |
| 59 | + |
| 60 | +1. In Solution Explorer, right-click the **ReportConnectivity** project, and then select **Manage NuGet Packages**. |
| 61 | + |
| 62 | +1. Keep the default .NET Framework, then select **Create** to create the project. |
| 63 | + |
| 64 | +1. Select **Browse** and search for and choose **Microsoft.Azure.Devices.Client**. Select **Install**. |
| 65 | + |
| 66 | + This step downloads, installs, and adds a reference to the [Azure IoT device SDK](https://www.nuget.org/packages/Microsoft.Azure.Devices.Client/) NuGet package and its dependencies. |
| 67 | + |
| 68 | +1. Add the following `using` statements at the top of the **Program.cs** file: |
| 69 | + |
| 70 | + ```csharp |
| 71 | + using Microsoft.Azure.Devices.Client; |
| 72 | + using Microsoft.Azure.Devices.Shared; |
| 73 | + using Newtonsoft.Json; |
| 74 | + ``` |
| 75 | + |
| 76 | +1. Add the following fields to the **Program** class. Replace `{device connection string}` with the device connection string you saw when you registered a device in the IoT Hub: |
| 77 | + |
| 78 | + ```csharp |
| 79 | + static string DeviceConnectionString = "HostName=<yourIotHubName>.azure-devices.net;DeviceId=<yourIotDeviceName>;SharedAccessKey=<yourIotDeviceAccessKey>"; |
| 80 | + static DeviceClient Client = null; |
| 81 | + ``` |
| 82 | + |
| 83 | +1. Add the following method to the **Program** class: |
| 84 | + |
| 85 | + ```csharp |
| 86 | + public static async void InitClient() |
| 87 | + { |
| 88 | + try |
| 89 | + { |
| 90 | + Console.WriteLine("Connecting to hub"); |
| 91 | + Client = DeviceClient.CreateFromConnectionString(DeviceConnectionString, |
| 92 | + TransportType.Mqtt); |
| 93 | + Console.WriteLine("Retrieving twin"); |
| 94 | + await Client.GetTwinAsync(); |
| 95 | + } |
| 96 | + catch (Exception ex) |
| 97 | + { |
| 98 | + Console.WriteLine(); |
| 99 | + Console.WriteLine("Error in sample: {0}", ex.Message); |
| 100 | + } |
| 101 | + } |
| 102 | + ``` |
| 103 | + |
| 104 | + The **Client** object exposes all the methods you require to interact with device twins from the device. The code shown above initializes the **Client** object, and then retrieves the device twin for **myDeviceId**. |
| 105 | + |
| 106 | +1. Add the following method to the **Program** class: |
| 107 | + |
| 108 | + ```csharp |
| 109 | + public static async void ReportConnectivity() |
| 110 | + { |
| 111 | + try |
| 112 | + { |
| 113 | + Console.WriteLine("Sending connectivity data as reported property"); |
| 114 | + |
| 115 | + TwinCollection reportedProperties, connectivity; |
| 116 | + reportedProperties = new TwinCollection(); |
| 117 | + connectivity = new TwinCollection(); |
| 118 | + connectivity["type"] = "cellular"; |
| 119 | + reportedProperties["connectivity"] = connectivity; |
| 120 | + await Client.UpdateReportedPropertiesAsync(reportedProperties); |
| 121 | + } |
| 122 | + catch (Exception ex) |
| 123 | + { |
| 124 | + Console.WriteLine(); |
| 125 | + Console.WriteLine("Error in sample: {0}", ex.Message); |
| 126 | + } |
| 127 | + } |
| 128 | + ``` |
| 129 | + |
| 130 | + The code above updates the reported property of **myDeviceId** with the connectivity information. |
| 131 | + |
| 132 | +1. Finally, add the following lines to the **Main** method: |
| 133 | + |
| 134 | + ```csharp |
| 135 | + try |
| 136 | + { |
| 137 | + InitClient(); |
| 138 | + ReportConnectivity(); |
| 139 | + } |
| 140 | + catch (Exception ex) |
| 141 | + { |
| 142 | + Console.WriteLine(); |
| 143 | + Console.WriteLine("Error in sample: {0}", ex.Message); |
| 144 | + } |
| 145 | + Console.WriteLine("Press Enter to exit."); |
| 146 | + Console.ReadLine(); |
| 147 | + ``` |
| 148 | + |
| 149 | +1. In Solution Explorer, right-click on your solution, and select **Set StartUp Projects**. |
| 150 | + |
| 151 | +1. In **Common Properties** > **Startup Project**, select **Multiple startup projects**. For **ReportConnectivity**, select **Start** as the **Action**. Select **OK** to save your changes. |
| 152 | + |
| 153 | +1. Run this app by right-clicking the **ReportConnectivity** project and selecting **Debug**, then **Start new instance**. You should see the app getting the twin information, and then sending connectivity as a ***reported property***. |
| 154 | + |
| 155 | +  |
| 156 | + |
| 157 | + After the device reported its connectivity information, it should appear in both queries. |
| 158 | + |
| 159 | +1. Right-click the **AddTagsAndQuery** project and select **Debug** > **Start new instance** to run the queries again. This time, **myDeviceId** should appear in both query results. |
| 160 | + |
| 161 | +  |
| 162 | + |
| 163 | +## Create a service app that updates desired properties and queries twins |
| 164 | + |
| 165 | +In this section, you create a .NET console app, using C#, that adds location metadata to the device twin associated with **myDeviceId**. The app queries IoT hub for devices located in the US and then queries devices that report a cellular network connection. |
| 166 | + |
| 167 | +1. In Visual Studio, select **File > New > Project**. In **Create a new project**, select **Console App (.NET Framework)**, and then select **Next**. |
| 168 | + |
| 169 | +1. In **Configure your new project**, name the project **AddTagsAndQuery**, the select **Next**. |
| 170 | + |
| 171 | + :::image type="content" source="./media/iot-hub-csharp-csharp-twin-getstarted/config-addtagsandquery-app.png" alt-text="Screenshot of how to create a new Visual Studio project." lightbox="./media/iot-hub-csharp-csharp-twin-getstarted/config-addtagsandquery-app.png"::: |
| 172 | + |
| 173 | +1. Accept the default version of the .NET Framework, then select **Create** to create the project. |
| 174 | + |
| 175 | +1. In Solution Explorer, right-click the **AddTagsAndQuery** project, and then select **Manage NuGet Packages**. |
| 176 | + |
| 177 | +1. Select **Browse** and search for and select **Microsoft.Azure.Devices**. Select **Install**. |
| 178 | + |
| 179 | +  |
| 180 | + |
| 181 | + This step downloads, installs, and adds a reference to the [Azure IoT service SDK](https://www.nuget.org/packages/Microsoft.Azure.Devices/) NuGet package and its dependencies. |
| 182 | + |
| 183 | +1. Add the following `using` statements at the top of the **Program.cs** file: |
| 184 | + |
| 185 | + ```csharp |
| 186 | + using Microsoft.Azure.Devices; |
| 187 | + ``` |
| 188 | + |
| 189 | +1. Add the following fields to the **Program** class. Replace `{iot hub connection string}` with the IoT Hub connection string that you copied in [Get the IoT hub connection string](#get-the-iot-hub-connection-string). |
| 190 | + |
| 191 | + ```csharp |
| 192 | + static RegistryManager registryManager; |
| 193 | + static string connectionString = "{iot hub connection string}"; |
| 194 | + ``` |
| 195 | + |
| 196 | +1. Add the following method to the **Program** class: |
| 197 | + |
| 198 | + ```csharp |
| 199 | + public static async Task AddTagsAndQuery() |
| 200 | + { |
| 201 | + var twin = await registryManager.GetTwinAsync("myDeviceId"); |
| 202 | + var patch = |
| 203 | + @"{ |
| 204 | + tags: { |
| 205 | + location: { |
| 206 | + region: 'US', |
| 207 | + plant: 'Redmond43' |
| 208 | + } |
| 209 | + } |
| 210 | + }"; |
| 211 | + await registryManager.UpdateTwinAsync(twin.DeviceId, patch, twin.ETag); |
| 212 | + |
| 213 | + var query = registryManager.CreateQuery( |
| 214 | + "SELECT * FROM devices WHERE tags.location.plant = 'Redmond43'", 100); |
| 215 | + var twinsInRedmond43 = await query.GetNextAsTwinAsync(); |
| 216 | + Console.WriteLine("Devices in Redmond43: {0}", |
| 217 | + string.Join(", ", twinsInRedmond43.Select(t => t.DeviceId))); |
| 218 | + |
| 219 | + query = registryManager.CreateQuery("SELECT * FROM devices WHERE tags.location.plant = 'Redmond43' AND properties.reported.connectivity.type = 'cellular'", 100); |
| 220 | + var twinsInRedmond43UsingCellular = await query.GetNextAsTwinAsync(); |
| 221 | + Console.WriteLine("Devices in Redmond43 using cellular network: {0}", |
| 222 | + string.Join(", ", twinsInRedmond43UsingCellular.Select(t => t.DeviceId))); |
| 223 | + } |
| 224 | + ``` |
| 225 | + |
| 226 | + The **RegistryManager** class exposes all the methods required to interact with device twins from the service. The previous code first initializes the **registryManager** object, then retrieves the device twin for **myDeviceId**, and finally updates its tags with the desired location information. |
| 227 | + |
| 228 | + After updating, it executes two queries: the first selects only the device twins of devices located in the **Redmond43** plant, and the second refines the query to select only the devices that are also connected through cellular network. |
| 229 | + |
| 230 | + The previous code, when it creates the **query** object, specifies a maximum number of returned documents. The **query** object contains a **HasMoreResults** boolean property that you can use to invoke the **GetNextAsTwinAsync** methods multiple times to retrieve all results. A method called **GetNextAsJson** is available for results that are not device twins, for example, results of aggregation queries. |
| 231 | + |
| 232 | +1. Finally, add the following lines to the **Main** method: |
| 233 | + |
| 234 | + ```csharp |
| 235 | + registryManager = RegistryManager.CreateFromConnectionString(connectionString); |
| 236 | + AddTagsAndQuery().Wait(); |
| 237 | + Console.WriteLine("Press Enter to exit."); |
| 238 | + Console.ReadLine(); |
| 239 | + ``` |
| 240 | + |
| 241 | +1. Run this application by right-clicking on the **AddTagsAndQuery** project and selecting **Debug**, followed by **Start new instance**. You should see one device in the results for the query asking for all devices located in **Redmond43** and none for the query that restricts the results to devices that use a cellular network. |
| 242 | + |
| 243 | +  |
| 244 | + |
| 245 | +In this article, you: |
| 246 | + |
| 247 | +* Added device metadata as tags from a back-end app |
| 248 | +* Reported device connectivity information in the device twin |
| 249 | +* Queried the device twin information, using SQL-like IoT Hub query language |
| 250 | + |
| 251 | +## Next steps |
| 252 | + |
| 253 | +To learn how to: |
| 254 | + |
| 255 | +* Send telemetry from devices, see [Quickstart: Send telemetry from an IoT Plug and Play device to Azure IoT Hub](../iot-develop/quickstart-send-telemetry-iot-hub.md?pivots=programming-language-csharp). |
| 256 | + |
| 257 | +* Configure devices using device twin's desired properties, see [Tutorial: Configure your devices from a back-end service](tutorial-device-twins.md). |
| 258 | + |
| 259 | +* Control devices interactively, such as turning on a fan from a user-controlled app, see [Quickstart: Control a device connected to an IoT hub](./quickstart-control-device.md?pivots=programming-language-csharp). |
0 commit comments