Azure-iot-sdk-csharp: How do I bulk delete devices from a query?

Created on 14 Aug 2019  路  6Comments  路  Source: Azure/azure-iot-sdk-csharp

Description of the issue:

I want to execute RegistryManager.RemoveDevices2Async() in order to bulk delete some devices. This method takes an enumerable of Device objects as input.

In order to get existing devices I first run a query using RegistryManager.CreateQuery. This method returns Twin objects and not device objects.

How can I convert a result from a query to something I can use with RemoveDevices2Async?

I have tried the following:

  • From the resulting Twin objects, create a new device: new Device(twin.DeviceId). This resulted in an ETag error when trying to bulk delete (I tried both not setting Etag and copying Etag from twin).
  • Iterate the list of twin, and call RegistryManager.GetDeviceAsync. This works and I can delete the devices. However...iterating and doing one GetDeviceAsync call per device kind of defeats the purpose of a bulk operation.

So, how can I do something like "query -> get result -> bulk remove" in an efficient way?

All 6 comments

Hi @andrejohansson
I will be looking at this and will keep you posted on my findings.
Thanks.

Hello @andrejohansson ,

Your research is right, the query returns twin objects which can then be used to get device objects and pass to RemoveDevices2Async. More details on query language can be found here: https://docs.microsoft.com/en-us/azure/iot-hub/iot-hub-devguide-query-language#device-twin-queries

You can try the following for bulk remove:

IEnumerable twins = await query.GetNextAsTwinAsync().ConfigureAwait(false);
IEnumerable devicesToDelete = twins.Select(t => { return new Device(t.DeviceId); });
await _registryManager.RemoveDevices2Async(devicesToDelete, true, ct).ConfigureAwait(false);

I tested this with existing sample (https://github.com/Azure-Samples/azure-iot-samples-csharp/tree/master/iot-hub/Samples/service/RegistryManagerSample). Let us know if this works for you.

Thanks

We have not heard back on this. Please reopen the issue if there are any following questions. Thank you!

@andrejohansson, thank you for your contribution to our open-sourced project! Please help us improve by filling out this 2-minute customer satisfaction survey

Sorry for not responding. It seems to work for me!

@andrejohansson Thanks for letting us know.

Was this page helpful?
0 / 5 - 0 ratings