/// <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> /// 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> /// 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> /// 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 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> /// 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> /// 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); }
/// <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> /// 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> /// 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> /// 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> /// 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> /// 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> /// 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}"); } }