Get started with IoT Hub module identity and module twin using the portal and .NET device
Note
Module identities and module twins are similar to Azure IoT Hub device identity and device twin, but provide finer granularity. While Azure IoT Hub device identity and device twin enable the back-end application to configure a device and provide visibility on the device's conditions, a module identity and module twin provide these capabilities for individual components of a device. On capable devices with multiple components, such as operating system based devices or firmware devices, module identities and module twins allow for isolated configuration and conditions for each component.
In this tutorial, you will learn:
How to create a module identity in the portal.
How to use a .NET device SDK to update the module twin from your device.
Note
For information about the Azure IoT SDKs that you can use to build both applications to run on devices and your solution back end, see Azure IoT SDKs.
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.
Create a hub
This section describes how to create an IoT hub using the Azure portal.
Sign in to the Azure portal.
From the Azure homepage, select the + Create a resource button, and then enter IoT Hub in the Search the Marketplace field.
Select IoT Hub from the search results, and then select Create.
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.
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.
Select Next: Management to continue creating your hub.
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.
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.
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.
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 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.
In your IoT hub navigation menu, open Devices, then select Add Device to add a device in your IoT hub.
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.
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.
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.
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.
Create a module identity in the portal
Within one device identity, you can create up to 20 module identities. To add an identity, follow these steps:
For the device you created in the previous section, choose Add Module Identity to create your first module identity.
Enter the name myFirstModule. Save your module identity.

Your new module identity appears at the bottom of the screen. Select it to see module identity details.

Save the Connect string - primary key. You use it in the next section to you set up your module on the device.
Update the module twin using .NET device SDK
You've successfully created the module identity in your IoT Hub. Let's try to communicate to the cloud from your simulated device. Once a module identity is created, a module twin is implicitly created in IoT Hub. In this section, you will create a .NET console app on your simulated device that updates the module twin reported properties.
Create a Visual Studio project
To create an app that updates the module twin reported properties, follow these steps:
In Visual Studio, select Create a new project, then choose Console App (.NET Framework), and select Next.
In Configure your new project, enter UpdateModuleTwinReportedProperties as the Project name. Select Create to continue.

Install the latest Azure IoT Hub .NET device SDK
Module identity and module twin is in public preview. It's only available in the IoT Hub pre-release device SDKs. To install it, follow these steps:
In Visual Studio, open Tools > NuGet Package Manager > Manage NuGet Packages for Solution.
Select Browse, and then select Include prerelease. Search for Microsoft.Azure.Devices.Client. Select the latest version and install.

Now you have access to all the module features.
Get your module connection string
You need the module connection string for your console app. Follow these steps:
Sign in to the Azure portal.
Navigate to your IoT hub and select IoT Devices. Open myFirstDevice and you see that myFirstModule was successfully created.
Select myFirstModule under Module Identities. In Module Identity Details, copy the Connection string (primary key).

Create UpdateModuleTwinReportedProperties console app
To create your app, follow these steps:
- Add the following
usingstatements at the top of the Program.cs file:
using Microsoft.Azure.Devices.Client;
using Microsoft.Azure.Devices.Shared;
using Newtonsoft.Json;
- Add the following fields to the Program class. Replace the placeholder value with the module connection string.
private const string ModuleConnectionString = "<Your module connection string>";
private static ModuleClient Client = null;
- Add the following method OnDesiredPropertyChanged to the Program class:
private static async Task OnDesiredPropertyChanged(TwinCollection desiredProperties, object userContext)
{
Console.WriteLine("desired property change:");
Console.WriteLine(JsonConvert.SerializeObject(desiredProperties));
Console.WriteLine("Sending current time as reported property");
TwinCollection reportedProperties = new TwinCollection
{
["DateTimeLastDesiredPropertyChangeReceived"] = DateTime.Now
};
await Client.UpdateReportedPropertiesAsync(reportedProperties).ConfigureAwait(false);
}
- Finally, replace the Main method with the following code:
static void Main(string[] args)
{
Microsoft.Azure.Devices.Client.TransportType transport = Microsoft.Azure.Devices.Client.TransportType.Amqp;
try
{
Client = ModuleClient.CreateFromConnectionString(ModuleConnectionString, transport);
Client.SetConnectionStatusChangesHandler(ConnectionStatusChangeHandler);
Client.SetDesiredPropertyUpdateCallbackAsync(OnDesiredPropertyChanged, null).Wait();
Console.WriteLine("Retrieving twin");
var twinTask = Client.GetTwinAsync();
twinTask.Wait();
var twin = twinTask.Result;
Console.WriteLine(JsonConvert.SerializeObject(twin));
Console.WriteLine("Sending app start time as reported property");
TwinCollection reportedProperties = new TwinCollection();
reportedProperties["DateTimeLastAppLaunch"] = DateTime.Now;
Client.UpdateReportedPropertiesAsync(reportedProperties);
}
catch (AggregateException ex)
{
Console.WriteLine("Error in sample: {0}", ex);
}
Console.WriteLine("Waiting for Events. Press enter to exit...");
Console.ReadKey();
Client.CloseAsync().Wait();
}
private static void ConnectionStatusChangeHandler(ConnectionStatus status, ConnectionStatusChangeReason reason)
{
Console.WriteLine($"Status {status} changed: {reason}");
}
You can build and run this app by using F5.
This code sample shows you how to retrieve the module twin and update reported properties with AMQP protocol. In public preview, we only support AMQP for module twin operations.
Next steps
To continue getting started with IoT Hub and to explore other IoT scenarios, see: