Azure – A Simple way to read IoT Hub from ASP.Net

The ability to read data hosted in Azure IoT Hub is a common scenario.  This data can be used for monitoring and reporting in many different scenarios.

This article demonstrates a simple method to access the data in the IoT Hub without adding extra services to Azure and reduce the cost.

The first step is to have an IoT Hub in the portal with 2 values:

– IoT connection string
– Device ID

The connection string must be configured as seen here:

create-iot-hub5

Second is the code to create the device ID (this code doesn’t run in an IoT device, but it does run in ASP.Net):

private static async Task AddDeviceAsync()
{
string deviceId = “myFirstDevice”;
Device device;
try
{
device = await registryManager.AddDeviceAsync(new Device(deviceId));
}
catch (DeviceAlreadyExistsException)
{
device = await registryManager.GetDeviceAsync(deviceId);
}
Console.WriteLine(“Generated device key: {0}”, device.Authentication.SymmetricKey.PrimaryKey);
}

Once this is complete,  it is time to compile the ASP.Net code which is the exciting piece of this exercise.

First a call has to be made to Microsoft.Azure.Devices.Common and the Microsoft.ServiceBus.Messaging library:

using Microsoft.Azure.Devices.Common;
using Microsoft.ServiceBus.Messaging;

Next create public variables in the ASP.Net as read only but this is a personal preference:

static EventHubClient eventHubClient = null;
static EventHubReceiver eventHubReceiver = null;

readonly string IoTConnectionString = “”;
readonly string deviceID = “”;

Now create 2 methods that are critically important to access the IoT Hub.

The first one is to set both hubs, the client and the receiver with the following method:

private void SetHubs()
{
eventHubClient = EventHubClient.CreateFromConnectionString(connectionString, “messages/events”);

int eventHubPartitionsCount = eventHubClient.GetRuntimeInformation().PartitionCount;
string partition = EventHubPartitionKeyResolver.ResolveToPartition(device, eventHubPartitionsCount);
eventHubReceiver = eventHubClient.GetConsumerGroup(“$Default”).CreateReceiver(partition, DateTime.Now.AddHours(-4));
}

Second is retrieving the data from it:

private async void GetData()
{
var events = await eventHubReceiver.ReceiveAsync(int.MaxValue);

var eventData = await eventHubReceiver.ReceiveAsync(TimeSpan.FromSeconds(1));

if (eventData != null)
{

var data = Encoding.UTF8.GetString(eventData.GetBytes());

if (eventData.Properties.Count > 0)
{
var value= eventData.Properties[“”].ToString();
}
}
}

This step is optional,  if the goal is to have data available when the website launches call both method at the Page_Load and call access the IoT Hub and set the Hubs:

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetHubs();
}
}

This code can run in ASP.Net either MVC or WebForms.  The good news is that we are using the service bus library without adding a service bus or other services like storage to Azure, you can do that after, remember the data in the IoT Hub expires after a limited time frame, this won’t be forever.

Happy codding!!!!

2 Comments

  1. Gforse November 6, 2016 Reply
  2. Jey January 17, 2017 Reply

Leave a Reply