How can I get total number of devices and total number of messages send to azure IoT hub c#

azure iot hub view messages
azure iot hub message queue
azure iot hub duplicate messages
azure iot hub log analytics
iot hub message routing
azure iot hub register device c#
docs azure iot hub
azure iot hub pdf

we only have these two methods available for azure IoThub in c#.

Device device = await registryManager.GetDeviceAsync("deviceId");


device = await registryManager.GetDevicesAsync("max count");

but how to get all available device count or active device count and also a messages count using c#?

The number of devices can be retrieved by using a device query, e.g.:

SELECT COUNT() AS numberOfDevices FROM c

which returns something like this:

[ { "numberOfDevices": 123 } ]

To retrieve the number of messages you need to connect to the Event Hub-compatible endpoint, connecting to each underlying partition and looking at each Partition Info (Last Sequence Number and Sequence Number). There is some data retention involved though, so unless you add more logic to this, you will get a number representing the count of messages currently present in the hub, not the total since the creation, not the total left to process.

Update: here's the code showing a couple of methods to get the number of devices:

using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.Azure.Devices;
using Newtonsoft.Json;

namespace Test
    class Program
        static async Task Main()
            string connString = ";SharedAccessKeyName=_______;SharedAccessKey=_______";
            RegistryManager registry = RegistryManager.CreateFromConnectionString(connString);

            // Method 1: using Device Twin
            string queryString = "SELECT COUNT() AS numberOfDevices FROM devices";
            IQuery query = registry.CreateQuery(queryString, 1);
            string json = (await query.GetNextAsJsonAsync()).FirstOrDefault();
            Dictionary<string, long> data = JsonConvert.DeserializeObject<Dictionary<string, long>>(json);
            long count1 = data["numberOfDevices"];

            // Method 2: using Device Registry
            RegistryStatistics stats = await registry.GetRegistryStatisticsAsync();
            long count2 = stats.TotalDeviceCount;

Pricing—IoT Hub, can I get total number of devices and total number of messages send to azure IoT hub c# we only have these two methods available for azure IoThub in c#. Optionally, you can send cloud-to-device messages by using the Azure portal. To do this, browse to the overview page for your IoT Hub, select IoT Devices, select the simulated device, and select Message to Device. In the first CLI session, confirm that the simulated device received the message. After you view the message, close the second CLI

As of my knowledge,

There is no direct method to actually get the total number of devices. Alternatively what you could do is to create a List and whenever you add Devices using AddDeviceAsync you should push the object to the list.

Same with Total number of messages, you should create your own way to keep the value updated.

The following code should help.

static async Task startClient(string IoTHub, string IoTDevicePrefix, int deviceNumber, string commonKey, int maxMessages, int messageDelaySeconds)
    string connectionString = "HostName=" + IoTHub + ";DeviceId=" + IoTDevicePrefix + deviceNumber + ";SharedAccessKey=" + commonKey;
    DeviceClient device = DeviceClient.CreateFromConnectionString(connectionString, Microsoft.Azure.Devices.Client.TransportType.Mqtt);
    await device.OpenAsync();
    Random rnd = new Random();
    int mycounter = 1;
    Console.WriteLine("Device " + IoTDevicePrefix + deviceNumber + " started");

    while (mycounter <= maxMessages)
        Thread.Sleep((messageDelaySeconds * 1000) + rnd.Next(1, 100));
        string message = "{ \'loadTest\':\'True\', 'sequenceNumber': " + mycounter + ", \'SubmitTime\': \'" + DateTime.UtcNow + "\', \'randomValue\':" + rnd.Next(1, 4096 * 4096) + " }";
        Microsoft.Azure.Devices.Client.Message IoTMessage = new Microsoft.Azure.Devices.Client.Message(Encoding.UTF8.GetBytes(message));
        await device.SendEventAsync(IoTMessage);
    await device.CloseAsync();
    Console.WriteLine("Device " + IoTDevicePrefix + deviceNumber + " ended");

static void createDevices(int number)
    for (int i = 1; i <= number; i++)
        var registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString);
        Device mydevice = new Device(IoTDevicePrefix + i.ToString());
        mydevice.Authentication = new AuthenticationMechanism();
        mydevice.Authentication.SymmetricKey.PrimaryKey = commonKey;
        mydevice.Authentication.SymmetricKey.SecondaryKey = commonKey;
            Console.WriteLine("Adding device: " + IoTDevicePrefix + i.ToString());
        catch (Exception er)
            Console.WriteLine("  Error adding device: " + IoTDevicePrefix + i.ToString() + " error: " + er.InnerException.Message);


How to use Azure IoT Hub metrics to assess and monitor the overall health Count, Total, Number of device-to-cloud telemetry messages sent  I will have C# Driver which will get data out of a ClearScada instance, this driver should send that data to the azure iot hub. essentially I just need to figure the sending from C# to Azure iot. Questions: Where Can I see my messages.? Is my function correct or is there a flaw in my understanding.

Each IoT hub is provisioned with a certain number of units in a specific tier. IoT Plug and Play devices will send separate messages per interface, not the total number of connections), Higher of 100/sec or 12/sec/unit Hi @olivierbloch I went thru' the code at a higher level. It looks like you have used Storage Table in your app. My understanding is that the device sent messages are inserted to the Storage Tables, from where the message are retrieved as per the updated time stamp to display the message on the View(web page).

What is maximum message size for Cloud to Device Messaging for IoT hub? Azure IoT Hub overview. Connect, monitor, and control millions of IoT assets running on a broad set of operating systems and protocols to jumpstart your Internet of Things project with the IoT Hub. Enhance security of your IoT solutions by using per-device authentication to communicate with devices with the appropriate credentials. Securely

can handle 400,000 messages a day. The maximum message size for messages sent from a device to the cloud is 256 KB. I get a lot of asks for new routing endpoints in Azure IoT Hub, and one of the more common asks is to be able to route directly to Azure Functions. Having the power of serverless compute at your fingertips is very powerful and allows you to do all sorts of amazing things with your IoT data.

The IoT hub provides a secure channel for devices to communicate and send data The IoT hub provides total control over device access and can manage each MQTT, MQTT over WebSocket IoT hub also includes built-in message routing Additionally, the IoT hub can be combined with additional Azure services to  Well, an Azure IoT Hub contains an Event Hub and hence essentially is an Event Hub plus additional features. An important additional feature is that an Event Hub can only receive messages, whereas an IoT Hub additionally can also send messages to individual devices. Further, an Event Hub has access security on hub level, whereas an IoT Hub is

  • this is very much useful and not giving anywhere though it is there into registryManager unable to find it easy! thanks :)
  • but it does not contain device count , total message count etc
  • add to the url query string: metricnames=dailyMessageQuotaUsed,totalDeviceCount,connectedDeviceCount,...
  • list of IoT Hub metrics:…