Create Real-Time IoT Solution On Azure

We learned to create IoT Edge Devices and simulate telemetry data to IoT Hub in my previous blog. We will attempt to build a real-time end-to-end IoT solution on Azure in this article. We would use IoT Edge to simulate Telemetry data to the IoT Hub. The
Azure Stream Analytics job would process the Telemetry, data and store it in Cosmos DB. To display the processed data, we would create an MVC Web application. The data flow in IoT Solution would be as below:

So let’s Begin.


  • Add IoT Extension to Azure CLI
az extension add --name azure-iot

Create Cloud Resources

A resource group to manage all the resources you use in this quickstart.

az group create --name IoTEdgeResources --location westus2

Create an IoT Edge Device

A Windows virtual machine to act as your IoT Edge device. You can create this virtual machine using the following command, replacing {password} with a secure password:

az vm create --resource-group IoTEdgeResources --name EdgeVM --image MicrosoftWindowsDesktop:Windows-10:rs5-pro:latest --admin-username azureuser --admin-password {password} --size Standard_DS1_v2 

Create an IoT Hub

The below code creates a free F1 hub in the resource group IoTEdgeResources. Replace {hub_name} with a unique name for your IoT hub.

az iot hub create --resource-group IoTEdgeResources --name {hub_name} --sku F1 --partition-count 2

Register IoT Edge Device to IoT Hub

  • In the Azure cloud shell, enter the following command to create a device named myEdgeDevice in your hub.
az iot hub device-identity create --device-id EdgeVM --hub-name {hub_name} --edge-enabled
  • Retrieve the connection string for your device, which links your physical device with its identity in IoT Hub.
az iot hub device-identity show-connection-string --device-id myEdgeDevice --hub-name {hub_name}
  • Copy the value of the connectionString key from the JSON output and save it. This value is the device connection string.

Install and Start IoT Edge Runtime

Use PowerShell to download and install the IoT Edge runtime. Use the device connection string that you retrieved from IoT Hub to configure your device.

  • In the virtual machine, run PowerShell as an administrator.
  • Use an AMD64 session of PowerShell to install IoT Edge, not PowerShell (x86). If you’re not sure which session type you’re using, run the following command
(Get-Process -Id $PID).StartInfo.EnvironmentVariables["PROCESSOR_ARCHITECTURE"]
  • The Deploy-IoTEdge command checks that your Windows machine is on a supported version, turns on the containers feature, downloads the Moby runtime, and then downloads the IoT Edge runtime.
. {Invoke-WebRequest -useb} | Invoke-Expression; Deploy-IoTEdge -ContainerOs Windows
  • Your machine may restart automatically. If you are prompted by the Deploy-IoTEdge command to reboot, do so now.
  • Run PowerShell as an administrator again.
  • The Initialize-IoTEdge command configures the IoT Edge runtime on your machine. The command defaults to manual provisioning with Windows containers.
. {Invoke-WebRequest -useb} | Invoke-Expression; Initialize-IoTEdge -ContainerOs Windows

When prompted for a DeviceConnectionString, provide the string that you copied in the previous section. Don’t include quotes around the connection string.

Simulate Telemetry Data to IoT Hub


Create Azure Cosmos DB Account

  • Search for Azure Cosmos DB
  • Click Add
  • Provide Details and Click on Review + Create

Create Input in Stream Analytics

  • Go to Resource
  • Click on Inputs > Add stream Input > IoT Hub
  • Provide Details and Click on Save

Create Output in Stream Analytics

  • Create Output in Stream Analytics
  • Go to Resource
  • Click on Outputs > Add stream Output > Azure CosmosDB
  • Provide Details and Click on Save
  • Click on Query
  • Type Below sample query and Click on Save Query
SELECT MachineName,ServerName,Process,LastStatus,Status,Time
INTO [CosmosOutput]

Create a MVC Web Application

  • Open Visual Studio 2019 on your computer.
  • On the File menu, select New, and then choose Project.
  • In the New Project dialog, select Templates / Visual C# / Web/ ASP.NET Web Application (.NET Framework),
  • Name your project, and then select MVC and then click OK.
  • In the Solution Explorer, right click on your new web application, and then click Manage NuGet Packages
  • In the NuGet tab, click Browse, and search Azure DocumentDB and click Install.

Connect to an Azure Cosmos DB account

  • Create ServerDetails entity class in Models folder,
public class ServerDetails
    public string MachineName { get; set; }
    public string ServerName { get; set; }
    public string Process { get; set; }
    public int  LastStatus { get; set; }
    public string Status { get; set; }
    public DateTime Time { get; set; }
  • In HomeController class add ServerDetails Action 
public ActionResult ServerDetails()
    return View();
  • Then, we need to add a View to the employee action. Right Click on View > Add View
  • Add these references in HomeController.cs,
using System.Net;  
using Microsoft.Azure.Documents;  
using Microsoft.Azure.Documents.Client;
  • Add these two constants in constructor 
string EndpointUrl;  
    private string PrimaryKey;  
    private DocumentClient client;  
    public HomeController(){  
        EndpointUrl = "<your endpoint URL>";  
        PrimaryKey = "<your primary key>"; }  

Get Azure Cosmos DB URI and Primary Key

  • Go to your Azure Cosmos DB account, and then click Keys.
  • Copy URI and Endpoint
  • Replace the values in Placeholder
public HomeController()  
    EndpointUrl = "<>";  
    PrimaryKey = "<xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx>”  
  • Create a new instance of the DocumentClient.
public  HomeController()  
        EndpointUrl = "https://";  
        PrimaryKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";  
        client = new DocumentClient(new Uri(EndpointUrl), PrimaryKey);  

Query Azure Cosmos DB

  • Add below code to HomeController.cs
public ActionResult ServerDetails()
 FeedOptions queryOptions = new FeedOptions { EnableCrossPartitionQuery = true , MaxItemCount = -1 };
IQueryable<ServerDetails> serverQuery = this.client.CreateDocumentQuery<ServerDetails>(
                    UriFactory.CreateDocumentCollectionUri("DemoDB", "DemoContainer"), queryOptions)
                    .Where(f => f.Status == "Disconnect");
            return View(serverQuery);

In this article, we learnt to implement a real-time end-to-end IoT Solution. You may add addition components as needed for various business use cases.

Categories: Azure, Azure IoT

Tags: , , , , ,

Leave a Reply