/// <summary> /// Creates a new module identity. /// </summary> /// <param name="deviceId">Unique identifier of the device.</param> /// <param name="moduleId">Unique identifier of the new module.</param> public async Task <ModuleIdentity> CreateModuleIdentityAsync(string deviceId, string moduleId) { SampleLogger.PrintHeader("CREATE MODULE IDENTITY"); // Construct the module identity object. var moduleIdentity = new ModuleIdentity { DeviceId = deviceId, ModuleId = moduleId }; try { Console.WriteLine($"Creating a new module with Id: '{moduleId}'"); #region Snippet:IotHubCreateModuleIdentity // Call APIs to create the module identity. Response <ModuleIdentity> response = await IoTHubServiceClient.Modules.CreateOrUpdateIdentityAsync(moduleIdentity); SampleLogger.PrintSuccess($"Successfully created a new module identity: DeviceId: '{deviceId}', ModuleId: '{response.Value.ModuleId}', ETag: '{response.Value.Etag}'"); #endregion Snippet:IotHubCreateModuleIdentity return(response.Value); } catch (Exception ex) { // Try to cleanup before exiting with fatal error. await CleanupHelper.DeleteAllDevicesInHubAsync(IoTHubServiceClient); SampleLogger.FatalError($"Failed to create module identity due to:\n{ex}"); throw; } }
/// <summary> /// Update a twin configuration. /// </summary> /// <param name="twinConfiguration">Twin Configuration to to be updated.</param> public async Task <TwinConfiguration> UpdateConfigurationAsync(TwinConfiguration twinConfiguration) { SampleLogger.PrintHeader("UPDATE A CONFIGURATION"); try { #region Snippet:IotHubUpdateConfiguration twinConfiguration.Priority = Random.Next(MaxRandomValue); Console.WriteLine($"Updating twin configuration with Id: '{twinConfiguration.Id}''s priority to: '{twinConfiguration.Priority}'"); Response <TwinConfiguration> response = await IoTHubServiceClient.Configurations .CreateOrUpdateConfigurationAsync(twinConfiguration, IfMatchPrecondition.UnconditionalIfMatch) .ConfigureAwait(false); TwinConfiguration updatedConfiguration = response.Value; SampleLogger.PrintSuccess($"Successfully updated twin configuration: Id: '{updatedConfiguration.Id}', Priority: '{updatedConfiguration.Priority}', ETag: '{updatedConfiguration.Etag}'"); #endregion Snippet:IotHubUpdateConfiguration return(updatedConfiguration); } catch (Exception ex) { // Try to cleanup before exiting with fatal error. await DeleteConfigurationAsync(twinConfiguration); SampleLogger.FatalError($"Failed to update a twin configuration due to:\n{ex}"); throw; } }
/// <summary> /// Update a module identity. /// </summary> /// <param name="deviceId">Unique identifier of the device the module belongs to.</param> /// <param name="moduleId">Unique identifier of the module to be updated.</param> public async Task <ModuleIdentity> UpdateModuleIdentityAsync(string deviceId, string moduleId) { SampleLogger.PrintHeader("UPDATE A MODULE"); try { #region Snippet:IotHubUpdateModuleIdentity Response <ModuleIdentity> getResponse = await IoTHubServiceClient.Modules.GetIdentityAsync(deviceId, moduleId); ModuleIdentity moduleIdentity = getResponse.Value; Console.WriteLine($"Current module identity: DeviceId: '{moduleIdentity.DeviceId}', ModuleId: '{moduleIdentity.ModuleId}', ManagedBy: '{moduleIdentity.ManagedBy ?? "N/A"}', ETag: '{moduleIdentity.Etag}'"); Console.WriteLine($"Updating module identity with Id: '{moduleIdentity.ModuleId}'. Setting 'ManagedBy' property to: '{Environment.UserName}'"); moduleIdentity.ManagedBy = Environment.UserName; Response <ModuleIdentity> response = await IoTHubServiceClient.Modules.CreateOrUpdateIdentityAsync(moduleIdentity); ModuleIdentity updatedModule = response.Value; SampleLogger.PrintSuccess($"Successfully updated module identity: DeviceId: '{updatedModule.DeviceId}', ModuleId: '{updatedModule.ModuleId}', ManagedBy: '{updatedModule.ManagedBy}', ETag: '{updatedModule.Etag}'"); #endregion Snippet:IotHubUpdateModuleIdentity return(updatedModule); } catch (Exception ex) { // Try to cleanup before exiting with fatal error. await CleanupHelper.DeleteAllDevicesInHubAsync(IoTHubServiceClient); SampleLogger.FatalError($"Failed to update a module identity due to:\n{ex}"); throw; } }
/// <summary> /// Get device twin. /// </summary> /// <param name="deviceId">Unique identifier of the device to be updated.</param> public async Task <TwinData> GetDeviceTwinAsync(string deviceId) { SampleLogger.PrintHeader("GET A DEVICE TWIN"); try { Console.WriteLine($"Getting device twin with Id: '{deviceId}'"); #region Snippet:IotHubGetDeviceTwin Response <TwinData> response = await IoTHubServiceClient.Devices.GetTwinAsync(deviceId); SampleLogger.PrintSuccess($"\t- Device Twin: DeviceId: '{response.Value.DeviceId}', Status: '{response.Value.Status}', ETag: '{response.Value.Etag}'"); #endregion Snippet:IotHubGetDeviceTwin return(response.Value); } catch (Exception ex) { // Try to cleanup before exiting with fatal error. await CleanupHelper.DeleteAllDevicesInHubAsync(IoTHubServiceClient); SampleLogger.FatalError($"Failed to get a device twin due to:\n{ex}"); throw; } }
/// <summary> /// Creates a new device identity. /// </summary> /// <param name="deviceId">Unique identifier of the device.</param> public async Task <DeviceIdentity> CreateDeviceIdentityAsync(string deviceId) { SampleLogger.PrintHeader("CREATE DEVICE IDENTITY"); // Construct the device identity object. var deviceIdentity = new DeviceIdentity { DeviceId = deviceId }; try { Console.WriteLine($"Creating a new device with Id '{deviceId}'"); Response <DeviceIdentity> response = await IoTHubServiceClient.Devices.CreateOrUpdateIdentityAsync(deviceIdentity); SampleLogger.PrintSuccess($"Successfully create a new device identity with Id: '{response.Value.DeviceId}', ETag: '{response.Value.Etag}'"); return(response.Value); } catch (Exception ex) { // Try to cleanup before exiting with fatal error. await CleanupHelper.DeleteAllDevicesInHubAsync(IoTHubServiceClient); SampleLogger.FatalError($"Failed to create device identity due to:\n{ex}"); throw; } }
/// <summary> /// Invokes a method on the device. /// </summary> /// <param name="deviceId">Unique identifier of the device to be updated.</param> public async Task InvokeMethodOnDeviceAsync(string deviceId) { SampleLogger.PrintHeader("INVOKE REBOOT METHOD ON A DEVICE"); try { #region Snippet:IotInvokeMethodOnDevice var request = new CloudToDeviceMethodRequest { MethodName = "reboot", }; CloudToDeviceMethodResponse response = (await IoTHubServiceClient.Devices .InvokeMethodAsync(deviceId, request) .ConfigureAwait(false)) .Value; SampleLogger.PrintSuccess($"\t- Method 'REBOOT' invoked on device {deviceId}"); SampleLogger.PrintHeader($"Status of method invocation is: {response.Status}"); #endregion Snippet:IotInvokeMethodOnDevice } catch (Exception ex) { // Try to cleanup before exiting with fatal error. await CleanupHelper.DeleteAllDevicesInHubAsync(IoTHubServiceClient); SampleLogger.FatalError($"Failed to invoke method on device due to:\n{ex.Message}"); throw; } }
/// <summary> /// Starts an export job to store devices in IoTHub to storage. /// </summary> private async Task <Response <JobProperties> > CreateExportJobAsync() { try { #region Snippet:IotHubExportJob SampleLogger.PrintHeader("START EXPORT JOB"); //Import all devices from storage to create and provision devices on the IoTHub. Response <JobProperties> response = await IoTHubServiceClient.Jobs .CreateExportDevicesJobAsync(outputBlobContainerUri : ContainerSasUri, excludeKeys : false); SampleLogger.PrintSuccess($"Successfully started export job {response.Value.JobId}."); return(response); #endregion Snippet:IotHubExportJob } catch (Exception ex) { // Try to cleanup before exiting with fatal error. await CleanupHelper.DeleteAllDevicesInHubAsync(IoTHubServiceClient); SampleLogger.FatalError($"Failed to start export job due to:\n{ex}"); throw; } }
/// <summary> /// Creates a new twin configuration. /// </summary> /// <param name="twinConfiguration">Twin Configuration to create.</param> public async Task <TwinConfiguration> CreateConfigurationAsync(TwinConfiguration twinConfiguration) { SampleLogger.PrintHeader("CREATE TWIN CONFIGURATION"); TwinConfiguration createdConfig; try { // Create a twin configuration #region Snippet:IotHubCreateConfiguration Response <TwinConfiguration> createResponse = await IoTHubServiceClient.Configurations .CreateOrUpdateConfigurationAsync(twinConfiguration) .ConfigureAwait(false); createdConfig = createResponse.Value; Console.WriteLine($"Successfully created a new configuration with Id: '{createdConfig.Id}', ETag: '{createdConfig.Etag}'"); #endregion Snippet:IotHubCreateConfiguration return(createdConfig); } catch (Exception ex) { // Try to cleanup before exiting with fatal error. await DeleteConfigurationAsync(twinConfiguration); SampleLogger.FatalError($"Failed to create twin configuration due to:\n{ex}"); throw; } }
/// <summary> /// Deletes a device identity. /// </summary> /// <param name="deviceId">Unique identifier of the device.</param> public async Task DeleteDeviceIdentityAsync(string deviceId) { SampleLogger.PrintHeader("DELETE DEVICE IDENTITY"); try { // Get the device identity first. Response <DeviceIdentity> getResponse = await IoTHubServiceClient.Devices.GetIdentityAsync(deviceId); DeviceIdentity deviceIdentity = getResponse.Value; Console.WriteLine($"Deleting device identity with Id: '{deviceIdentity.DeviceId}'"); Response response = await IoTHubServiceClient.Devices.DeleteIdentityAsync(deviceIdentity); SampleLogger.PrintSuccess($"Successfully deleted device identity with Id: '{deviceIdentity.DeviceId}'"); } catch (Exception ex) { // Try to cleanup before exiting with fatal error. await CleanupHelper.DeleteAllDevicesInHubAsync(IoTHubServiceClient); SampleLogger.FatalError($"Failed to device identity due to:\n{ex}"); } }
/// <summary> /// Update a device identity. /// </summary> /// <param name="deviceId">Unique identifier of the device to be updated.</param> public async Task <DeviceIdentity> UpdateDeviceIdentityAsync(string deviceId) { SampleLogger.PrintHeader("UPDATE A DEVICE"); try { #region Snippet:IotHubUpdateDeviceIdentity Response <DeviceIdentity> getResponse = await IoTHubServiceClient.Devices.GetIdentityAsync(deviceId); DeviceIdentity deviceIdentity = getResponse.Value; Console.WriteLine($"Current device identity: DeviceId: '{deviceIdentity.DeviceId}', Status: '{deviceIdentity.Status}', ETag: '{deviceIdentity.Etag}'"); Console.WriteLine($"Updating device identity with Id: '{deviceIdentity.DeviceId}'. Disabling device so it cannot connect to IoT Hub."); deviceIdentity.Status = DeviceStatus.Disabled; Response <DeviceIdentity> response = await IoTHubServiceClient.Devices.CreateOrUpdateIdentityAsync(deviceIdentity); DeviceIdentity updatedDevice = response.Value; SampleLogger.PrintSuccess($"Successfully updated device identity: DeviceId: '{updatedDevice.DeviceId}', DeviceId: '{updatedDevice.DeviceId}', Status: '{updatedDevice.Status}', ETag: '{updatedDevice.Etag}'"); #endregion Snippet:IotHubUpdateDeviceIdentity return(updatedDevice); } catch (Exception ex) { // Try to cleanup before exiting with fatal error. await CleanupHelper.DeleteAllDevicesInHubAsync(IoTHubServiceClient); SampleLogger.FatalError($"Failed to update a device identity due to:\n{ex}"); throw; } }
/// <summary> /// Get a device identity. /// </summary> /// <param name="deviceId">Unique identifier of the device the device belongs to.</param> /// <param name="deviceId">Unique identifier of the device to get.</param> public async Task <DeviceIdentity> GetDeviceIdentityAsync(string deviceId) { SampleLogger.PrintHeader("GET A DEVICE"); try { Console.WriteLine($"Getting device identity with Id: '{deviceId}'\n"); #region Snippet:IotHubGetDeviceIdentity Response <DeviceIdentity> response = await IoTHubServiceClient.Devices.GetIdentityAsync(deviceId); DeviceIdentity deviceIdentity = response.Value; SampleLogger.PrintSuccess($"\t- Device Id: '{deviceIdentity.DeviceId}', ETag: '{deviceIdentity.Etag}'"); #endregion Snippet:IotHubGetDeviceIdentity return(deviceIdentity); } catch (Exception ex) { // Try to cleanup before exiting with fatal error. await CleanupHelper.DeleteAllDevicesInHubAsync(IoTHubServiceClient); SampleLogger.FatalError($"Failed to get a device identity due to:\n{ex}"); throw; } }
/// <summary> /// List all module identities within a device. /// </summary> /// <param name="deviceId">Unique identifier of the device to query.</param> public async Task <IReadOnlyList <ModuleIdentity> > ListAllModulesAsync(string deviceId) { SampleLogger.PrintHeader("LIST ALL MODULES"); try { Console.WriteLine($"Listing all modules in device with Id: '{deviceId}'\n"); #region Snippet:IotHubGetModuleIdentities Response <IReadOnlyList <ModuleIdentity> > response = await IoTHubServiceClient.Modules.GetIdentitiesAsync(deviceId); foreach (ModuleIdentity moduleIdentity in response.Value) { SampleLogger.PrintSuccess($"\t- Device Id: '{moduleIdentity.DeviceId}', Module Id: '{moduleIdentity.ModuleId}', ETag: '{moduleIdentity.Etag}'"); } #endregion Snippet:IotHubGetModuleIdentities return(response.Value); } catch (Exception ex) { // Try to cleanup before exiting with fatal error. await CleanupHelper.DeleteAllDevicesInHubAsync(IoTHubServiceClient); SampleLogger.FatalError($"Failed to list module identities due to:\n{ex}"); throw; } }
/// <summary> /// Deletes a module identity. /// </summary> /// <param name="deviceId">Unique identifier of the device the module belongs to.</param> /// <param name="moduleId">Unique identifier of the module to be updated.</param> public async Task DeleteModuleIdentityAsync(string deviceId, string moduleId) { SampleLogger.PrintHeader("DELETE MODULE IDENTITY"); try { // Get the module identity first. Response <ModuleIdentity> getResponse = await IoTHubServiceClient.Modules.GetIdentityAsync(deviceId, moduleId); ModuleIdentity moduleIdentity = getResponse.Value; Console.WriteLine($"Deleting module identity: DeviceId: '{moduleIdentity.DeviceId}', ModuleId: '{moduleIdentity.ModuleId}', ETag: '{moduleIdentity.Etag}'"); // We use UnconditionalIfMatch to force delete the Module Identity (disregard the IfMatch ETag). Response response = await IoTHubServiceClient.Modules.DeleteIdentityAsync(moduleIdentity); SampleLogger.PrintSuccess($"Successfully deleted module identity: DeviceId: '{deviceId}', ModuleId: '{moduleId}'"); } catch (Exception ex) { // Try to cleanup before exiting with fatal error. await CleanupHelper.DeleteAllDevicesInHubAsync(IoTHubServiceClient); SampleLogger.FatalError($"Failed to delete module identity due to:\n{ex}"); } }
/// <summary> /// Get a twin configuration. /// </summary> /// <param name="twinConfiguration">Twin Configuration</param> public async Task <TwinConfiguration> GetConfigurationAsync(TwinConfiguration twinConfiguration) { SampleLogger.PrintHeader("GET A CONFIGURATION"); try { Console.WriteLine($"Getting twin configuration with Id: '{twinConfiguration.Id}'\n"); #region Snippet:IotHubGetConfiguration Response <TwinConfiguration> getResponse = await IoTHubServiceClient.Configurations .GetConfigurationAsync(twinConfiguration.Id) .ConfigureAwait(false); TwinConfiguration responseConfiguration = getResponse.Value; SampleLogger.PrintSuccess($"Configuration Id: '{responseConfiguration.Id}', ETag: '{responseConfiguration.Etag}'"); #endregion Snippet:IotHubGetConfiguration return(responseConfiguration); } catch (Exception ex) { // Try to cleanup before exiting with fatal error. await DeleteConfigurationAsync(twinConfiguration); SampleLogger.FatalError($"Failed to get a twin configuration due to:\n{ex}"); throw; } }
/// <summary> /// Gets the status of an import or export job. /// </summary> private async Task <Response <JobProperties> > WaitForJobCompletionAsync(string jobId) { Response <JobProperties> response; try { // Wait for job to complete. do { #region Snippet:GetImportExportJob SampleLogger.PrintHeader("GET IMPORT/EXPORT JOB STATUS"); response = await IoTHubServiceClient.Jobs.GetImportExportJobAsync(jobId); await Task.Delay(TimeSpan.FromSeconds(5)); SampleLogger.PrintSuccess($"Job status is - {response.Value.Status}."); #endregion Snippet:GetImportExportJob } while (!IsTerminalStatus(response.Value.Status)); } catch (Exception ex) { // Try to cleanup before exiting with fatal error. await CleanupHelper.DeleteAllDevicesInHubAsync(IoTHubServiceClient); SampleLogger.FatalError($"Failed to get status of import export job due to:\n{ex}"); throw; } return(response); }
public async static Task DeleteAllDevicesInHubAsync(IotHubServiceClient hubClient) { Console.WriteLine($"\nTrying to clean up all devices\n"); try { AsyncPageable <TwinData> asyncPageableResponse = hubClient.Devices.GetTwinsAsync(); List <TwinData> deviceTwins = new List <TwinData>(); await foreach (TwinData twin in asyncPageableResponse) { deviceTwins.Add(twin); } foreach (TwinData twin in deviceTwins) { DeviceIdentity device = await hubClient.Devices.GetIdentityAsync(twin.DeviceId); await hubClient.Devices.DeleteIdentityAsync(device); } SampleLogger.PrintSuccess($"Cleanup succeeded\n"); } catch (Exception ex) { SampleLogger.PrintWarning($"Cleanup failed due to:\n{ex.Message}\n"); } }
/// <summary> /// Update multiple module twin desired properties. /// </summary> /// <param name="moduleTwins">Collection of module twins to be updated.</param> public async Task UpdateModuleTwinsAsync(IEnumerable <TwinData> moduleTwins) { SampleLogger.PrintHeader("UPDATE MODULE TWINS"); string userPropName = "user"; try { Console.WriteLine($"Setting a new desired property {userPropName} to: '{Environment.UserName}' for each twin"); #region Snippet:IotHubUpdateModuleTwins foreach (TwinData twin in moduleTwins) { twin.Properties.Desired.Add(new KeyValuePair <string, object>(userPropName, Environment.UserName)); } Response <BulkRegistryOperationResponse> response = await IoTHubServiceClient.Modules.UpdateTwinsAsync(moduleTwins); var bulkResponse = response.Value; if (bulkResponse.IsSuccessful ?? true) { SampleLogger.PrintSuccess("Successfully updated the module twins"); } else { SampleLogger.PrintWarning("Failed to update the module twins"); foreach (var bulkOperationError in bulkResponse.Errors) { SampleLogger.PrintWarning($"Module id that failed: {bulkOperationError.ModuleId}, for device {bulkOperationError.DeviceId}, error code: {bulkOperationError.ErrorCode}"); } } #endregion Snippet:IotHubUpdateModuleTwins } catch (Exception ex) { // Try to cleanup before exiting with fatal error. await CleanupHelper.DeleteAllDevicesInHubAsync(IoTHubServiceClient); SampleLogger.FatalError($"Failed to update a module identity due to:\n{ex}"); throw; } }
/// <summary> /// Update a device twin desired properties. /// </summary> /// <param name="deviceId">Unique identifier of the device to be updated.</param> public async Task <TwinData> UpdateDeviceTwinAsync(string deviceId) { SampleLogger.PrintHeader("UPDATE A DEVICE TWIN"); string userPropName = "user"; try { // Get the device #region Snippet:IotHubUpdateDeviceTwin Response <TwinData> getResponse = await IoTHubServiceClient.Devices.GetTwinAsync(deviceId); TwinData deviceTwin = getResponse.Value; Console.WriteLine($"Updating device twin: DeviceId: '{deviceTwin.DeviceId}', ETag: '{deviceTwin.Etag}'"); Console.WriteLine($"Setting a new desired property {userPropName} to: '{Environment.UserName}'"); deviceTwin.Properties.Desired.Add(new KeyValuePair <string, object>(userPropName, Environment.UserName)); Response <TwinData> response = await IoTHubServiceClient.Devices.UpdateTwinAsync(deviceTwin); TwinData updatedTwin = response.Value; var userPropValue = (string)updatedTwin.Properties.Desired .Where(p => p.Key == userPropName) .First() .Value; SampleLogger.PrintSuccess($"Successfully updated device twin: DeviceId: '{updatedTwin.DeviceId}', desired property: ['{userPropName}': '{userPropValue}'], ETag: '{updatedTwin.Etag}',"); #endregion Snippet:IotHubUpdateDeviceTwin return(updatedTwin); } catch (Exception ex) { // Try to cleanup before exiting with fatal error. await CleanupHelper.DeleteAllDevicesInHubAsync(IoTHubServiceClient); SampleLogger.FatalError($"Failed to update a device identity due to:\n{ex}"); throw; } }
/// <summary> /// Update multiple device identity. /// </summary> /// <param name="deviceIdentities">Collection of device identities to be updated.</param> public async Task UpdateDeviceIdentitiesAsync(IEnumerable <DeviceIdentity> deviceIdentities) { SampleLogger.PrintHeader("UPDATE DEVICE IDENTITIES"); try { Console.WriteLine($"Disabling multiple devices so they cannot connect to IoT Hub."); #region Snippet:IotHubUpdateDeviceIdentities foreach (var identity in deviceIdentities) { identity.Status = DeviceStatus.Disabled; } Response <BulkRegistryOperationResponse> response = await IoTHubServiceClient.Devices.UpdateIdentitiesAsync(deviceIdentities, BulkIfMatchPrecondition.IfMatch); var bulkResponse = response.Value; if (bulkResponse.IsSuccessful ?? true) { SampleLogger.PrintSuccess("Successfully disabled the device identities"); } else { SampleLogger.PrintWarning("Failed to disable the device identities"); foreach (var bulkOperationError in bulkResponse.Errors) { SampleLogger.PrintWarning($"Device id that failed: {bulkOperationError.DeviceId}, error code: {bulkOperationError.ErrorCode}"); } } #endregion Snippet:IotHubUpdateDeviceIdentities } catch (Exception ex) { // Try to cleanup before exiting with fatal error. await CleanupHelper.DeleteAllDevicesInHubAsync(IoTHubServiceClient); SampleLogger.FatalError($"Failed to update a device identity due to:\n{ex}"); throw; } }
/// <summary> /// Gets service statistics on the IoT Hub. /// </summary> public async Task GetServiceStatisticsAsync() { SampleLogger.PrintHeader("GET SERVICE STATISTICS"); try { #region Snippet:IotHubGetServiceStatistics Response <Models.ServiceStatistics> statistics = await IoTHubServiceClient.Statistics.GetServiceStatisticsAsync(); Console.WriteLine($"Total connected device count: {statistics.Value.ConnectedDeviceCount}"); #endregion Snippet:IotHubGetServiceStatistics } catch (Exception ex) { SampleLogger.FatalError($"Failed to get service statistics due to:\n{ex}"); throw; } }
/// <summary> /// Create multiple device identities. /// </summary> /// <param name="deviceIdentities">Collection of device identities to be created.</param> public async Task CreateDeviceIdentitiesAsync(IEnumerable <DeviceIdentity> deviceIdentities) { SampleLogger.PrintHeader("CREATE DEVICE IDENTITIES"); try { Console.WriteLine($"Creating {BulkCount} new devices"); #region Snippet:IotHubCreateDeviceIdentities Response <BulkRegistryOperationResponse> response = await IoTHubServiceClient.Devices.CreateIdentitiesAsync(deviceIdentities); var bulkResponse = response.Value; if (bulkResponse.IsSuccessful ?? true) { SampleLogger.PrintSuccess("Successfully created new device identities"); } else { SampleLogger.PrintWarning("Failed to create new device identities"); foreach (var bulkOperationError in bulkResponse.Errors) { SampleLogger.PrintWarning($"Device id that failed: {bulkOperationError.DeviceId}, error code: {bulkOperationError.ErrorCode}"); } } #endregion Snippet:IotHubCreateDeviceIdentities } catch (Exception ex) { // Try to cleanup before exiting with fatal error. await CleanupHelper.DeleteAllDevicesInHubAsync(IoTHubServiceClient); SampleLogger.FatalError($"Failed to create device identity due to:\n{ex}"); throw; } }
/// <summary> /// Delete multiple module identities. /// </summary> /// <param name="moduleIdentities">Collection of module identities to be deleted.</param> public async Task DeleteModuleIdentitiesAsync(IEnumerable <ModuleIdentity> moduleIdentities) { SampleLogger.PrintHeader("DELETE MODULE IDENTITIES"); try { Console.WriteLine($"Deleting bulk module identities"); #region Snippet:IotHubDeleteModuleIdentities Response <BulkRegistryOperationResponse> response = await IoTHubServiceClient.Modules.DeleteIdentitiesAsync(moduleIdentities); var bulkResponse = response.Value; if (bulkResponse.IsSuccessful ?? true) { SampleLogger.PrintSuccess("Successfully deleted the module identities"); } else { SampleLogger.PrintWarning("Failed to delete the module identities"); foreach (var bulkOperationError in bulkResponse.Errors) { SampleLogger.PrintWarning($"Module id that failed: {bulkOperationError.ModuleId}, for device {bulkOperationError.DeviceId}, error code: {bulkOperationError.ErrorCode}"); } } #endregion Snippet:IotHubDeleteModuleIdentities } catch (Exception ex) { // Try to cleanup before exiting with fatal error. await CleanupHelper.DeleteAllDevicesInHubAsync(IoTHubServiceClient); SampleLogger.FatalError($"Failed to delete module identity due to:\n{ex}"); } }
/// <summary> /// Deletes a twin configuration. /// </summary> /// <param name="twinConfiguration">Twin Configuration to delete.</param> public async Task DeleteConfigurationAsync(TwinConfiguration twinConfiguration) { SampleLogger.PrintHeader("DELETE A CONFIGURATION"); try { Console.WriteLine($"Deleting twin configuration with Id: '{twinConfiguration.Id}'"); #region Snippet:IotHubDeleteConfiguration Response response = await IoTHubServiceClient.Configurations .DeleteConfigurationAsync(twinConfiguration, IfMatchPrecondition.UnconditionalIfMatch) .ConfigureAwait(false); SampleLogger.PrintSuccess($"Successfully deleted twin configuration with Id: '{twinConfiguration.Id}'"); #endregion Snippet:IotHubDeleteConfiguration } catch (Exception ex) { SampleLogger.FatalError($"Failed to delete twin configuration due to:\n{ex}"); } }