Search code examples
c#azure-iot-hubazure-iot-sdk

Exception in reading list of Azure IoT devices in C# azure function


I'm fetching list of Azure IoT devices using IoT hub sql query in C# function.

 var query = _registry.CreateQuery("SELECT deviceId,tags.SiteId FROM devices", 100);

I'm getting below error in function while debugging

System.Private.CoreLib: Exception while executing function: shared_iot_eventhub_reader_function. Microsoft.Azure.Devices: result type is Raw.

Same query works in Azure portal. What changes do I need to make in query to give me list of Azure IoT devices

enter image description here

I want to fetch a List of Azure IoT devices in my Azure IoT Hub


Solution

  • using Azure Function I was able to get the reading list of Azure IoT devices with Twin objects.

    I have referred this MSDOC for IoT Hub query ,Function and for your comments @Dai

      
                var connectionString = "your connection string";
                var registryManager = RegistryManager.CreateFromConnectionString(connectionString);
    
                var query = registryManager.CreateQuery("SELECT * FROM devices", 100);
                while (query.HasMoreResults)
                {
                    var page = await query.GetNextAsTwinAsync();
                    foreach (var twin in page)
                    {
                  
                        log.LogInformation($"Device Id: {twin.DeviceId}");
                        log.LogInformation($"ModuleId :{twin.ModuleId}");
                        log.LogInformation($"Tags:{twin.Tags}");
                        log.LogInformation($"CloudToDeviceMessageCount :{twin.CloudToDeviceMessageCount}");
                        log.LogInformation($"StatusUpdatedTime :{twin.StatusUpdatedTime.ToString()}");
                        log.LogInformation($"twin.Properties:{twin.Properties.ToString()}");
                        log.LogInformation($"LastActivity :{ twin.LastActivityTime.ToString()}");
                        log.LogInformation($"Version: {twin.Version.ToString()}");
                    }
                }
    
                await registryManager.CloseAsync();
    
                return new OkResult();
            
    
    

    Output :

    enter image description here