/// <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>
        /// 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>
        /// 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;
            }
        }
Exemple #4
0
        /// <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>
        /// 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
            {
                #region Snippet:IotHubDeleteModuleIdentity

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

                #endregion Snippet:IotHubDeleteModuleIdentity
            }
            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 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>
        /// Get module twin.
        /// </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 <TwinData> GetModuleTwinAsync(string deviceId, string moduleId)
        {
            SampleLogger.PrintHeader("GET A MODULE TWIN");

            try
            {
                Console.WriteLine($"Getting module twin with Id: '{moduleId}'");

                #region Snippet:IotHubGetModuleTwin

                Response <TwinData> response = await IoTHubServiceClient.Modules.GetTwinAsync(deviceId, moduleId);

                SampleLogger.PrintSuccess($"\t- Module Twin: DeviceId: '{response.Value.DeviceId}', ModuleId: '{response.Value.ModuleId}', Status: '{response.Value.Status}', ETag: '{response.Value.Etag}'");

                #endregion Snippet:IotHubGetModuleTwin

                return(response.Value);
            }
            catch (Exception ex)
            {
                // Try to cleanup before exiting with fatal error.
                await CleanupHelper.DeleteAllDevicesInHubAsync(IoTHubServiceClient);

                SampleLogger.FatalError($"Failed to get a module twin due to:\n{ex}");
                throw;
            }
        }
        /// <summary>
        /// Get 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 get.</param>
        public async Task <ModuleIdentity> GetModuleIdentityAsync(string deviceId, string moduleId)
        {
            SampleLogger.PrintHeader("GET A MODULE");

            try
            {
                Console.WriteLine($"Getting module identity with Id: '{moduleId}'\n");

                #region Snippet:IotHubGetModuleIdentity

                Response <ModuleIdentity> response = await IoTHubServiceClient.Modules.GetIdentityAsync(deviceId, moduleId);

                ModuleIdentity moduleIdentity = response.Value;

                SampleLogger.PrintSuccess($"\t- Device Id: '{moduleIdentity.DeviceId}', Module Id: '{moduleIdentity.ModuleId}', ETag: '{moduleIdentity.Etag}'");

                #endregion Snippet:IotHubGetModuleIdentity

                return(moduleIdentity);
            }
            catch (Exception ex)
            {
                // Try to cleanup before exiting with fatal error.
                await CleanupHelper.DeleteAllDevicesInHubAsync(IoTHubServiceClient);

                SampleLogger.FatalError($"Failed to get a module identity 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;
            }
        }
Exemple #10
0
        /// <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;
            }
        }
Exemple #11
0
        /// <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);
        }
Exemple #12
0
        /// <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 module twin desired properties.
        /// </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 <TwinData> UpdateModuleTwinAsync(string deviceId, string moduleId)
        {
            SampleLogger.PrintHeader("UPDATE A MODULE TWIN");

            string userPropName = "user";

            try
            {
                // Get the device module

                #region Snippet:IotHubUpdateModuleTwin

                Response <TwinData> getResponse = await IoTHubServiceClient.Modules.GetTwinAsync(deviceId, moduleId);

                TwinData moduleTwin = getResponse.Value;

                Console.WriteLine($"Updating module twin: DeviceId: '{moduleTwin.DeviceId}', ModuleId: '{moduleTwin.ModuleId}', ETag: '{moduleTwin.Etag}'");
                Console.WriteLine($"Setting a new desired property {userPropName} to: '{Environment.UserName}'");

                moduleTwin.Properties.Desired.Add(new KeyValuePair <string, object>(userPropName, Environment.UserName));

                Response <TwinData> response = await IoTHubServiceClient.Modules.UpdateTwinAsync(moduleTwin);

                TwinData updatedTwin = response.Value;

                var userPropValue = (string)updatedTwin.Properties.Desired
                                    .Where(p => p.Key == userPropName)
                                    .First()
                                    .Value;

                SampleLogger.PrintSuccess($"Successfully updated module twin: DeviceId: '{updatedTwin.DeviceId}', ModuleId: '{updatedTwin.ModuleId}', desired property: [{userPropName}: '{userPropValue}'], ETag: '{updatedTwin.Etag}',");

                #endregion Snippet:IotHubUpdateModuleTwin

                return(updatedTwin);
            }
            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 multiple module identities.
        /// </summary>
        /// <param name="moduleIdentities">Collection of module identities to be updated.</param>
        public async Task UpdateModuleIdentitiesAsync(IEnumerable <ModuleIdentity> moduleIdentities)
        {
            SampleLogger.PrintHeader("UPDATE MODULE IDENTITIES");

            try
            {
                Console.WriteLine($"Disconnect multiple modules so they cannot connect to IoT Hub.");

                #region Snippet:IotHubUpdateModuleIdentities

                foreach (var identity in moduleIdentities)
                {
                    identity.ConnectionState = ModuleConnectionState.Disconnected;
                }

                Response <BulkRegistryOperationResponse> response = await IoTHubServiceClient.Modules.UpdateIdentitiesAsync(moduleIdentities, BulkIfMatchPrecondition.IfMatch);

                var bulkResponse = response.Value;

                if (bulkResponse.IsSuccessful ?? true)
                {
                    SampleLogger.PrintSuccess("Successfully disconnected the module identities");
                }
                else
                {
                    SampleLogger.PrintWarning("Failed to disconnect 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:IotHubUpdateModuleIdentities
            }
            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>
        /// Create multiple module identities.
        /// </summary>
        /// <param name="moduleIdentities">Collection of modules identities to be created.</param>
        public async Task CreateModuleIdentitiesAsync(IEnumerable <ModuleIdentity> moduleIdentities)
        {
            SampleLogger.PrintHeader("CREATE MODULE IDENTITIES");

            try
            {
                Console.WriteLine($"Creating {BulkCount} new modules");

                #region Snippet:IotHubCreateModuleIdentities

                Response <BulkRegistryOperationResponse> response = await IoTHubServiceClient.Modules.CreateIdentitiesAsync(moduleIdentities);

                var bulkResponse = response.Value;

                if (bulkResponse.IsSuccessful ?? true)
                {
                    SampleLogger.PrintSuccess("Successfully created new module identities");
                }
                else
                {
                    SampleLogger.PrintWarning("Failed to create new 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:IotHubCreateModuleIdentities
            }
            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>
        /// Delete multiple device identities.
        /// </summary>
        /// <param name="deviceIdentities">Collection of device identities to be deleted.</param>
        public async Task DeleteDeviceIdentitiesAsync(IEnumerable <DeviceIdentity> deviceIdentities)
        {
            SampleLogger.PrintHeader("DELETE DEVICE IDENTITIES");

            try
            {
                #region Snippet:IotHubDeleteDeviceIdentities

                Console.WriteLine($"Deleting bulk device identities");

                Response <BulkRegistryOperationResponse> response = await IoTHubServiceClient.Devices.DeleteIdentitiesAsync(deviceIdentities);

                var bulkResponse = response.Value;

                if (bulkResponse.IsSuccessful ?? true)
                {
                    SampleLogger.PrintSuccess("Successfully deleted the device identities");
                }
                else
                {
                    SampleLogger.PrintWarning("Failed to delete the device identities");

                    foreach (var bulkOperationError in bulkResponse.Errors)
                    {
                        SampleLogger.PrintWarning($"Device id that failed: {bulkOperationError.DeviceId}, error code: {bulkOperationError.ErrorCode}");
                    }
                }

                #endregion Snippet:IotHubDeleteDeviceIdentities
            }
            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}");
            }
        }