Jon Th
Jon Th

Reputation: 377

Azure IoT Hub RegistryManager update many twins - only if properties exist

How can I make sure that RegistryManager.UpdateTwins2Async() only updates properties to the device twins and never adds them if they don't exist? To explain...

I'm developing an Azure IoT web application in .NET Core 3.1. I need to update multiple device device twins in the IoT Hub with a patch. So far, I'm doing this

var updateTask = await mRegistryManager.UpdateTwins2Async(finalTwinList);

But now we have a new version of IoT devices that contain extra properties and therefore I only want to update properties in devices that HAVE those properties (i.e. only the devices with the new version).

I know that the UpdateTwins2Async() method changes the properties if they are found in a device but I'm pretty sure that it ADDS them if they don't exist. It would be very bad if those new properties were added to the older devices.

So how can I make sure that UpdateTwins2Async() only updates properties and never adds them?

Upvotes: 1

Views: 293

Answers (1)

Matthijs van der Veer
Matthijs van der Veer

Reputation: 4085

I'm going to post this as an answer, but it might not fit your solution. If you want to make sure that you're only doing this for the correct devices, you could first retrieve them using a query and then check your finalTwinList again.

var list = new List<Twin>();
var sql = "SELECT * FROM devices WHERE is_defined(properties.desired.yourtaghere)";
var query = registryManager.CreateQuery(sql, 100);
while (query.HasMoreResults)
{
    var page = await query.GetNextAsTwinAsync();
    foreach (var twin in page)
    {
        list.Add(twin);
    }
}

// now check your finalTwinList, any device ID that's not also in your newly created list can go!

If you're only updated a handful of devices at a time and have a few thousand devices in your hub, that query is overkill. You could change it to be more specific:

SELECT * FROM devices
  WHERE deviceId IN ['entries', 'from', 'your', 'list']
  AND is_defined(properties.desired.yourtaghere)

Upvotes: 1

Related Questions