skip to Main Content

I am sending telemetry(data) from simulator device to Azure IoT Hub and receiving that telemetry into this code.

 namespace CentralSystem
{
  internal class Program
  {
    static readonly string connectionString = "IoT Hub Connection string here";
    static readonly string iotHubD2cEndpoint = "messages/events";
    static EventHubClient eventHubClient;

    public static Dictionary<string, string> values = new Dictionary<string, string>();

    private static async Task ReceiveMessagesFromDeviceAsync(string partition, CancellationToken ct)   
    {
        var eventHubReceiver = eventHubClient.GetDefaultConsumerGroup().CreateReceiver(partition, DateTime.UtcNow);
        while (true)
        {
            if (ct.IsCancellationRequested) break;

            EventData eventData = await eventHubReceiver.ReceiveAsync();
            if (eventData == null) continue;

            string data = Encoding.UTF8.GetString(eventData.GetBytes());
            values = JsonConvert.DeserializeObject<Dictionary<string, string>>(data);  
            foreach (var kv in values)                                                 
            {                                                                          
                Console.WriteLine(kv.Key + " : " + kv.Value);                          
            }                                                                          
            Console.WriteLine();
        }
    }

This above code run perfectly but I need to access "data" variable outside the function means access it globally. Because I need to put all values in "data" variable to dictionary. so that I have declared dictionary as globally.

Please tell me that how to figure out this thing?

2

Answers


  1. if I understood correctly.
    Isn’t it stored in your "values" dictionary?

    If you need only values:
    Create List of strings above the function (like your values):

    List<string> listOfValues = new List<string>()
    

    and do this like a dictionary but only for Values:

    listOfValues.Add(Value)
    

    After the function, do what you want with it

    Login or Signup to reply.
  2. Looking at the code you have provided you are already storing all values of the "data" variable in the dictionary "values" which is globally declared. You can directly use "values" to proceed further and access the data inside it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search