ksk
ksk

Reputation: 57

Simple way to get data from IoT Hub in C#

I try use code from MS tutorial https://learn.microsoft.com/en-us/azure/iot-hub/iot-hub-csharp-csharp-getstarted and this

internal class Program
{
private static string connectionString = "HostName=...=";
private static string d2cEndpoint = "messages/events";
private static EventHubClient eventHubClient;

private static void Main(string[] args)
{
    Console.WriteLine("Receive messages\n");
    eventHubClient = EventHubClient.
       CreateFromConnectionString(
          connectionString, d2cEndpoint);

    var d2cPartitions = eventHubClient.
            GetRuntimeInformation().PartitionIds;

    foreach (string partition in d2cPartitions)
    {
        ReceiveMessagesFromDeviceAsync(partition);
    }
    Console.ReadLine();
}

private async static Task ReceiveMessagesFromDeviceAsync(
                                      string partition)
{
    var eventHubReceiver = eventHubClient.
          GetDefaultConsumerGroup().
            CreateReceiver(partition, DateTime.UtcNow);
    while (true)
    {
        EventData eventData = await eventHubReceiver.
                                            ReceiveAsync();
        if (eventData == null) continue;

        string data = Encoding.UTF8.GetString(
                                  eventData.GetBytes());
        Console.WriteLine(string.Format(
          "Message received. Partition: {0} Data: '{1}'",
          partition, data));
    }
}
} 

to get data from IoT Hub, but still something was wrong. It is possible to get this data in easy way?

Upvotes: 1

Views: 2787

Answers (1)

Roman Kiss
Roman Kiss

Reputation: 8235

Using the VS2017 version >=15.3.1 you can create an Azure Functions project for EventHubTrigger function without any single line code. The following template code snippet shows this function:

using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.WebJobs.ServiceBus;

namespace FunctionApp4
{
public static class Function1
{
    [FunctionName("Function1")]
    public static void Run([EventHubTrigger("myEventHubName", Connection = "myIoTHub")]string myEventHubMessage, TraceWriter log)
    {
        log.Info($"C# Event Hub trigger function processed a message: {myEventHubMessage}");
    }
}

}

and the local.settings.json file:

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "DefaultEndpointsProtocol=https;AccountName=...;AccountKey=...",
    "AzureWebJobsDashboard": "DefaultEndpointsProtocol=https;AccountName=...;AccountKey=...",
    "myIoTHub": "Endpoint=sb://....servicebus.windows.net/;SharedAccessKeyName=iothubowner;SharedAccessKey=..."
  }
}

The following screen snippet shows a console output of the local azure function: Function1

Upvotes: 1

Related Questions