Search code examples
c#azure-functionsazure-iot-hubazure-iot-edgeazure-sdk-.net

GetNextAsTwinAsync() randomly fails after being deployed in Azure function app


I'm trying to update tags of device twin through C# SDK in Azure. While executing locally GetNextAsTwinAsync() works perfectly, but after function is deployed on Az fucntion app, the function returns null. I tried debugging the query and it returns true,also I couldn't find any alternative function for the same. My code is

string fetchQuery = $"SELECT * FROM devices WHERE deviceId = '{device.Id}'";
                var query = _registry.CreateQuery(fetchQuery, 1);
                var page = await query.GetNextAsTwinAsync();
                var twin = page.FirstOrDefault();
                if (twin != null)
                {
                    var patch =
                            @"{
                                tags: {
                                    tenantId: " +
                                    tenantId +
                                    @",
                                    __type__: 'iiotedge',
                                    os: 'linux'
                                }
                            }";

                        _telemetryClient.TrackTrace("updating twin" + $"{patch}");

                        var UpdateTwinStatus = await _registry.UpdateTwinAsync(twin.DeviceId, patch, twin.ETag)

I want to update device twin tags for a device based on deviceId


Solution

  • I have referred this MSDOC for IoT Hub query and Function .

    Before updating :

    enter image description here

    enter image description here

      var connectionString = "your connection string";                      var registryManager = RegistryManager.CreateFromConnectionString(connectionString);
      var query = registryManager.CreateQuery("SELECT * FROM devices", 100); 
      while (query.HasMoreResults) 
                  { 
      var twins = await query.GetNextAsTwinAsync();
               foreach (var twin in twins) 
                  {
                    twin.Tags = new TwinCollection();
                    twin.Tags["location"] = "Building A";
                    twin.Tags["temperature"] = "72F";
                    await registryManager.UpdateTwinAsync(twin.DeviceId, twin, twin.ETag);
                    log.LogInformation($"Tags updated for device {twin.DeviceId}");
                    log.LogInformation($"Tags: {twin.Tags}");
                    } 
                    }
                     await registryManager.CloseAsync();
                     return  new OkResult();
    

    After Updating :

    enter image description here

    Output :

    enter image description here

    In Azure:

    enter image description here