Esempio n. 1
0
        /// <summary>
        /// Main entry point to the sample.
        /// </summary>
        public static async Task Main(string[] args)
        {
            // Parse and validate parameters

            CommandLineOptions options = null;
            ParserResult <CommandLineOptions> result = Parser.Default.ParseArguments <CommandLineOptions>(args)
                                                       .WithParsed(parsedOptions =>
            {
                options = parsedOptions;
            })
                                                       .WithNotParsed(errors =>
            {
                Environment.Exit(1);
            });

            // Instantiate the client
            IoTHubServiceClient hubClient = new IoTHubServiceClient(options.IotHubConnectionString);

            // Run the samples
            var deviceIdentityLifecycleSamples = new DeviceIdentityLifecycleSamples(hubClient);
            await deviceIdentityLifecycleSamples.RunSampleAsync();

            var moduleIdentityLifecycleSamples = new ModuleIdentityLifecycleSamples(hubClient);
            await moduleIdentityLifecycleSamples.RunSampleAsync();

            var bulkDeviceIdentityLifecycleSamples = new BulkDeviceIdentityLifecycleSamples(hubClient);
            await bulkDeviceIdentityLifecycleSamples.RunSampleAsync();
        }
        public async Task DevicesClient_BulkCreation_DeviceWithTwin()
        {
            string testDevicePrefix  = $"bulkDeviceWithTwin";
            string userPropertyName  = "user";
            string userPropertyValue = "userA";

            IoTHubServiceClient client = GetClient();

            IDictionary <string, object> desiredProperties = new Dictionary <string, object>
            {
                { userPropertyName, userPropertyValue }
            };

            // We will build multiple devices and all of them with the same desired properties for convenience.
            IDictionary <DeviceIdentity, TwinData> devicesAndTwins = BuildDevicesAndTwins(testDevicePrefix, BULK_DEVICE_COUNT, desiredProperties);

            try
            {
                // Create all devices with twins
                Response <BulkRegistryOperationResponse> createResponse = await client.Devices.CreateIdentitiesWithTwinAsync(devicesAndTwins).ConfigureAwait(false);

                // TODO: (azabbasi) Once the issue with the error parsing is resolved, include the error message in the message of the assert statement.
                Assert.IsTrue(createResponse.Value.IsSuccessful, "Bulk device creation ended with errors");

                // Verify that the desired properties were set
                // For quicker test run, we will only verify the first device on the list.
                Response <TwinData> getResponse = await client.Devices.GetTwinAsync(devicesAndTwins.Keys.First().DeviceId).ConfigureAwait(false);

                getResponse.Value.Properties.Desired[userPropertyName].Should().Be(userPropertyValue);
            }
            finally
            {
                await Cleanup(client, devicesAndTwins.Keys);
            }
        }
        public async Task ModulesClient_BulkCreation_SingleDevice()
        {
            string testDevicePrefix = $"bulkDevice";
            string testModulePrefix = $"bulkModule";

            string deviceId       = $"{testDevicePrefix}{GetRandom()}";
            var    deviceIdentity = new DeviceIdentity()
            {
                DeviceId = deviceId
            };

            IList <ModuleIdentity> moduleIdentities = BuildMultipleModules(deviceId, testModulePrefix, BULK_MODULE_COUNT);

            IoTHubServiceClient client = GetClient();

            try
            {
                // Create single device to house these bulk modules
                await client.Devices.CreateOrUpdateIdentityAsync(deviceIdentity);

                // Create modules in bulk on that device
                Response <BulkRegistryOperationResponse> createResponse = await client.Modules.CreateIdentitiesAsync(moduleIdentities).ConfigureAwait(false);

                Assert.IsTrue(createResponse.Value.IsSuccessful, "Bulk module creation ended with errors");
            }
            finally
            {
                await Cleanup(client, deviceIdentity);
            }
        }
        public async Task DevicesClient_BulkCreation_OneAlreadyExists()
        {
            string testDevicePrefix   = $"bulkDevice";
            string existingDeviceName = $"{testDevicePrefix}{GetRandom()}";

            IoTHubServiceClient    client  = GetClient();
            IList <DeviceIdentity> devices = BuildMultipleDevices(testDevicePrefix, BULK_DEVICE_COUNT - 1);

            try
            {
                // We first create a single device.
                Response <DeviceIdentity> response = await client.Devices.CreateOrUpdateIdentityAsync(new DeviceIdentity { DeviceId = existingDeviceName });

                // Add the existing device to the list of devices to be bulk created.
                devices.Add(response.Value);

                // Create all devices
                Response <BulkRegistryOperationResponse> createResponse = await client.Devices.CreateIdentitiesAsync(devices).ConfigureAwait(false);

                // TODO: (azabbasi) Once the issue with the error parsing is resolved, include the error message in the message of the assert statement.
                Assert.IsTrue(createResponse.Value.IsSuccessful, "Bulk device creation failed with errors");
            }
            finally
            {
                await Cleanup(client, devices);
            }
        }
        public async Task ModulesClient_Query_GetTwins()
        {
            string testDevicePrefix = $"bulkDevice";
            string testModulePrefix = $"bulkModule";

            IoTHubServiceClient client = GetClient();

            string         deviceId       = $"{testDevicePrefix}{GetRandom()}";
            DeviceIdentity deviceIdentity = new DeviceIdentity()
            {
                DeviceId = deviceId
            };

            IList <ModuleIdentity> moduleIdentities = BuildMultipleModules(deviceId, testModulePrefix, BULK_MODULE_COUNT);

            try
            {
                // Create the device to house all these modules
                await client.Devices.CreateOrUpdateIdentityAsync(deviceIdentity).ConfigureAwait(false);

                // Create the modules in bulk so they can be queried later
                Response <BulkRegistryOperationResponse> createResponse = await client.Modules.CreateIdentitiesAsync(moduleIdentities).ConfigureAwait(false);

                Assert.IsTrue(createResponse.Value.IsSuccessful, "Bulk module creation ended with errors");

                // We will retry the operation since it can take some time for the query to match what was recently created.
                int            matchesFound = 0;
                DateTimeOffset startTime    = DateTime.UtcNow;

                while (DateTime.UtcNow - startTime < _queryMaxWaitTime)
                {
                    matchesFound = 0;
                    AsyncPageable <TwinData> twins = client.Modules.GetTwinsAsync();

                    // We will verify we have twins for all recently created devices.
                    await foreach (TwinData twin in twins)
                    {
                        if (moduleIdentities.Any(d => d.DeviceId.Equals(twin.DeviceId, StringComparison.OrdinalIgnoreCase)))
                        {
                            matchesFound++;
                        }
                    }

                    if (matchesFound == BULK_MODULE_COUNT)
                    {
                        break;
                    }

                    await Task.Delay(_queryRetryInterval);
                }

                matchesFound.Should().Be(BULK_MODULE_COUNT, "Timed out waiting for all the bulk created modules to be query-able." +
                                         " Number of matching modules must be equal to the number of recently created modules.");
            }
            finally
            {
                await Cleanup(client, deviceIdentity);
            }
        }
        public async Task ModulesClient_UpdateDevice_EtagDoesNotMatch()
        {
            string testDeviceId = $"UpdateWithETag{GetRandom()}";
            string testModuleId = $"UpdateWithETag{GetRandom()}";

            DeviceIdentity      device = null;
            ModuleIdentity      module = null;
            IoTHubServiceClient client = GetClient();

            try
            {
                // Create a device
                device = (await client.Devices.CreateOrUpdateIdentityAsync(
                              new Models.DeviceIdentity
                {
                    DeviceId = testDeviceId
                }).ConfigureAwait(false)).Value;

                // Create a module on that device
                module = (await client.Modules.CreateOrUpdateIdentityAsync(
                              new Models.ModuleIdentity
                {
                    DeviceId = testDeviceId,
                    ModuleId = testModuleId
                }).ConfigureAwait(false)).Value;

                // Update the module to get a new ETag value.
                string managedByValue = "SomeChangedValue";
                module.ManagedBy = managedByValue;

                ModuleIdentity updatedModule = (await client.Modules.CreateOrUpdateIdentityAsync(module).ConfigureAwait(false)).Value;

                Assert.AreNotEqual(updatedModule.Etag, module.Etag, "ETag should have been updated.");

                // Perform another update using the old device object to verify precondition fails.
                string anotherManagedByValue = "SomeOtherChangedValue";
                module.ManagedBy = anotherManagedByValue;
                try
                {
                    await client.Modules.CreateOrUpdateIdentityAsync(module, IfMatchPrecondition.IfMatch).ConfigureAwait(false);

                    Assert.Fail($"Update call with outdated ETag should fail with 412 (PreconditionFailed)");
                }
                // We will catch the exception and verify status is 412 (PreconditionfFailed)
                catch (RequestFailedException ex)
                {
                    Assert.AreEqual(412, ex.Status, $"Expected the update to fail with http status code 412 (PreconditionFailed)");
                }

                // Perform the same update and ignore the ETag value by providing UnconditionalIfMatch precondition
                ModuleIdentity forcefullyUpdatedModule = (await client.Modules.CreateOrUpdateIdentityAsync(module, IfMatchPrecondition.UnconditionalIfMatch).ConfigureAwait(false)).Value;
                forcefullyUpdatedModule.ManagedBy.Should().Be(anotherManagedByValue);
            }
            finally
            {
                await Cleanup(client, device);
            }
        }
Esempio n. 7
0
        public async Task StatisticsClient_Service_SuccessfulResponse()
        {
            IoTHubServiceClient client = GetClient();

            Response <ServiceStatistics> stat = await client.Statistics.GetServiceStatisticsAsync();

            Assert.IsNotNull(stat.Value, "Statistics response should not be null");
            Assert.IsNotNull(stat.Value.ConnectedDeviceCount, "ConnectedDeviceCount should not be null");
        }
        public async Task ModulesClient_IdentityLifecycle()
        {
            string testDeviceId = $"IdentityLifecycleDevice{GetRandom()}";
            string testModuleId = $"IdentityLifecycleModule{GetRandom()}";

            DeviceIdentity      device = null;
            ModuleIdentity      module = null;
            IoTHubServiceClient client = GetClient();

            try
            {
                // Create a device to house the module
                device = (await client.Devices.CreateOrUpdateIdentityAsync(
                              new DeviceIdentity
                {
                    DeviceId = testDeviceId
                })).Value;

                // Create a module on the device
                Response <ModuleIdentity> createResponse = await client.Modules.CreateOrUpdateIdentityAsync(
                    new ModuleIdentity
                {
                    DeviceId = testDeviceId,
                    ModuleId = testModuleId
                }).ConfigureAwait(false);

                module = createResponse.Value;

                module.DeviceId.Should().Be(testDeviceId);
                module.ModuleId.Should().Be(testModuleId);

                // Get device
                // Get the device and compare ETag values (should remain unchanged);
                Response <ModuleIdentity> getResponse = await client.Modules.GetIdentityAsync(testDeviceId, testModuleId).ConfigureAwait(false);

                getResponse.Value.Etag.Should().BeEquivalentTo(module.Etag, "ETag value should not have changed.");

                module = getResponse.Value;

                // Update a module
                string managedByValue = "SomeChangedValue";
                module.ManagedBy = managedByValue;

                // TODO: (azabbasi) We should leave the IfMatchPrecondition to be the default value once we know more about the fix.
                Response <ModuleIdentity> updateResponse = await client.Modules.CreateOrUpdateIdentityAsync(module, IfMatchPrecondition.UnconditionalIfMatch).ConfigureAwait(false);

                updateResponse.Value.ManagedBy.Should().Be(managedByValue, "Module should have changed its managedBy value");

                // Delete the device
                // Deleting the device happens in the finally block as cleanup.
            }
            finally
            {
                await Cleanup(client, device);
            }
        }
        public async Task DevicesClient_BulkUpdate()
        {
            string testDevicePrefix = $"bulkDeviceUpdate";

            IoTHubServiceClient    client = GetClient();
            IList <DeviceIdentity> listOfDevicesToUpdate = null;

            try
            {
                // Create two devices
                Response <DeviceIdentity> deviceOneCreateResponse = await client.Devices.CreateOrUpdateIdentityAsync(
                    new DeviceIdentity
                {
                    DeviceId = $"{testDevicePrefix}{GetRandom()}",
                    Status   = DeviceStatus.Enabled,
                }).ConfigureAwait(false);

                Response <DeviceIdentity> deviceTwoCreateResponse = await client.Devices.CreateOrUpdateIdentityAsync(
                    new DeviceIdentity
                {
                    DeviceId = $"{testDevicePrefix}{GetRandom()}",
                    Status   = DeviceStatus.Enabled,
                }).ConfigureAwait(false);

                DeviceIdentity deviceOne = deviceOneCreateResponse.Value;
                DeviceIdentity deviceTwo = deviceTwoCreateResponse.Value;

                listOfDevicesToUpdate = new List <DeviceIdentity> {
                    deviceOne, deviceTwo
                };

                // Update device status to disabled.
                deviceOne.Status = DeviceStatus.Disabled;
                deviceTwo.Status = DeviceStatus.Disabled;

                // Make the API call to disable devices.
                Response <BulkRegistryOperationResponse> updateResponse =
                    await client.Devices.UpdateIdentitiesAsync(listOfDevicesToUpdate, BulkIfMatchPrecondition.Unconditional)
                    .ConfigureAwait(false);

                // TODO: (azabbasi) Once the issue with the error parsing is resolved, include the error message in the message of the assert statement.
                Assert.IsTrue(updateResponse.Value.IsSuccessful, "Bulk device update ended with errors");

                // Verify the devices status is updated.
                deviceOne = (await client.Devices.GetIdentityAsync(deviceOne.DeviceId)).Value;
                deviceTwo = (await client.Devices.GetIdentityAsync(deviceTwo.DeviceId)).Value;

                deviceOne.Status.Should().Be(DeviceStatus.Disabled, "Device should have been disabled");
                deviceTwo.Status.Should().Be(DeviceStatus.Disabled, "Device should have been disabled");
            }
            finally
            {
                await Cleanup(client, listOfDevicesToUpdate);
            }
        }
Esempio n. 10
0
        public async Task StatisticsClient_Device_SuccessfulResponse()
        {
            IoTHubServiceClient client = GetClient();

            Response <DevicesStatistics> stat = await client.Statistics.GetDevicesStatisticsAsync();

            Assert.IsNotNull(stat.Value, "Statistics response should not be null");
            Assert.IsNotNull(stat.Value.TotalDeviceCount, "TotalDeviceCount should not be null");
            Assert.IsNotNull(stat.Value.EnabledDeviceCount, "EnabledDeviceCount should not be null");
            Assert.IsNotNull(stat.Value.DisabledDeviceCount, "DisabledDeviceCount should not be null");
        }
        public async Task ModulesClient_GetModulesOnDevice()
        {
            int    moduleCount  = 5;
            string testDeviceId = $"IdentityLifecycleDevice{GetRandom()}";

            string[] testModuleIds = new string[moduleCount];
            for (int i = 0; i < moduleCount; i++)
            {
                testModuleIds[i] = $"IdentityLifecycleModule{i}-{GetRandom()}";
            }

            DeviceIdentity      device = null;
            IoTHubServiceClient client = GetClient();

            try
            {
                // Create a device to house the modules
                device = (await client.Devices.CreateOrUpdateIdentityAsync(
                              new DeviceIdentity
                {
                    DeviceId = testDeviceId
                })).Value;

                // Create the modules on the device
                for (int i = 0; i < moduleCount; i++)
                {
                    Response <ModuleIdentity> createResponse = await client.Modules.CreateOrUpdateIdentityAsync(
                        new ModuleIdentity
                    {
                        DeviceId = testDeviceId,
                        ModuleId = testModuleIds[i]
                    }).ConfigureAwait(false);
                }

                // List the modules on the test device
                IReadOnlyList <ModuleIdentity> modulesOnDevice = (await client.Modules.GetIdentitiesAsync(testDeviceId).ConfigureAwait(false)).Value;

                IEnumerable <string> moduleIdsOnDevice = modulesOnDevice
                                                         .ToList()
                                                         .Select(module => module.ModuleId);

                Assert.AreEqual(moduleCount, modulesOnDevice.Count);
                for (int i = 0; i < moduleCount; i++)
                {
                    Assert.IsTrue(moduleIdsOnDevice.Contains(testModuleIds[i]));
                }
            }
            finally
            {
                await Cleanup(client, device);
            }
        }
        public async Task ModulesClient_DeviceTwinLifecycle()
        {
            string testDeviceId = $"TwinLifecycleDevice{GetRandom()}";
            string testModuleId = $"TwinLifecycleModule{GetRandom()}";

            DeviceIdentity device = null;
            ModuleIdentity module = null;

            IoTHubServiceClient client = GetClient();

            try
            {
                // Create a device
                device = (await client.Devices.CreateOrUpdateIdentityAsync(
                              new Models.DeviceIdentity
                {
                    DeviceId = testDeviceId
                }).ConfigureAwait(false)).Value;

                // Create a module on that device. Note that this implicitly creates the module twin
                module = (await client.Modules.CreateOrUpdateIdentityAsync(
                              new Models.ModuleIdentity
                {
                    DeviceId = testDeviceId,
                    ModuleId = testModuleId
                }).ConfigureAwait(false)).Value;

                // Get the module twin
                TwinData moduleTwin = (await client.Modules.GetTwinAsync(testDeviceId, testModuleId).ConfigureAwait(false)).Value;

                moduleTwin.ModuleId.Should().BeEquivalentTo(testModuleId, "ModuleId on the Twin should match that of the module identity.");

                // Update device twin
                string propName  = "username";
                string propValue = "userA";
                moduleTwin.Properties.Desired.Add(new KeyValuePair <string, object>(propName, propValue));

                // TODO: (azabbasi) We should leave the IfMatchPrecondition to be the default value once we know more about the fix.
                Response <TwinData> updateResponse = await client.Modules.UpdateTwinAsync(moduleTwin, IfMatchPrecondition.UnconditionalIfMatch).ConfigureAwait(false);

                updateResponse.Value.Properties.Desired.Where(p => p.Key == propName).First().Value.Should().Be(propValue, "Desired property value is incorrect.");

                // Delete the module
                // Deleting the module happens in the finally block as cleanup.
            }
            finally
            {
                await Cleanup(client, device);
            }
        }
 private async Task Cleanup(IoTHubServiceClient client, IEnumerable <DeviceIdentity> devices)
 {
     try
     {
         if (devices != null && devices.Any())
         {
             await client.Devices.DeleteIdentitiesAsync(devices, BulkIfMatchPrecondition.Unconditional);
         }
     }
     catch (Exception ex)
     {
         Assert.Fail($"Test clean up failed: {ex.Message}");
     }
 }
        public async Task DevicesClient_UpdateDevice_EtagDoesNotMatch()
        {
            string testDeviceId = $"UpdateWithETag{GetRandom()}";

            DeviceIdentity      device = null;
            IoTHubServiceClient client = GetClient();

            try
            {
                // Create a device
                Response <DeviceIdentity> createResponse = await client.Devices.CreateOrUpdateIdentityAsync(
                    new Models.DeviceIdentity
                {
                    DeviceId = testDeviceId
                }).ConfigureAwait(false);

                // Store the device object to later update it with invalid ETag
                device = createResponse.Value;

                // Update the device to get a new ETag value.
                device.Status = DeviceStatus.Disabled;
                Response <DeviceIdentity> getResponse = await client.Devices.CreateOrUpdateIdentityAsync(device).ConfigureAwait(false);

                DeviceIdentity updatedDevice = getResponse.Value;

                Assert.AreNotEqual(updatedDevice.Etag, device.Etag, "ETag should have been updated.");

                // Perform another update using the old device object to verify precondition fails.
                device.Status = DeviceStatus.Enabled;
                try
                {
                    Response <DeviceIdentity> updateResponse = await client.Devices.CreateOrUpdateIdentityAsync(device).ConfigureAwait(false);

                    Assert.Fail($"Update call with outdated ETag should fail with 412 (PreconditionFailed)");
                }
                // We will catch the exception and verify status is 412 (PreconditionfFailed)
                catch (RequestFailedException ex)
                {
                    Assert.AreEqual(412, ex.Status, $"Expected the update to fail with http status code 412 (PreconditionFailed)");
                }

                // Perform the same update and ignore the ETag value by providing UnconditionalIfMatch precondition
                await client.Devices.CreateOrUpdateIdentityAsync(device, IfMatchPrecondition.UnconditionalIfMatch).ConfigureAwait(false);
            }
            finally
            {
                await Cleanup(client, device);
            }
        }
Esempio n. 15
0
        public async Task DevicesClient_Query_GetTwins()
        {
            string testDeviceprefix = $"bulkDevice";

            IEnumerable <DeviceIdentity> devices = BuildMultipleDevices(testDeviceprefix, BULK_DEVICE_COUNT);

            IoTHubServiceClient client = GetClient();

            try
            {
                // Create all devices
                Response <BulkRegistryOperationResponse> createResponse = await client.Devices.CreateIdentitiesAsync(devices).ConfigureAwait(false);

                Assert.IsTrue(createResponse.Value.IsSuccessful, "Bulk device creation ended with errors");

                // We will retry the operation since it can take some time for the query to match what was recently created.
                int            matchesFound = 0;
                DateTimeOffset startTime    = DateTime.UtcNow;

                while (DateTime.UtcNow - startTime < _queryMaxWaitTime)
                {
                    matchesFound = 0;
                    AsyncPageable <TwinData> twins = client.Devices.GetTwinsAsync();

                    // We will verify we have twins for all recently created devices.
                    await foreach (TwinData twin in twins)
                    {
                        if (devices.Any(d => d.DeviceId.Equals(twin.DeviceId, StringComparison.OrdinalIgnoreCase)))
                        {
                            matchesFound++;
                        }
                    }

                    if (matchesFound == BULK_DEVICE_COUNT)
                    {
                        break;
                    }

                    await Task.Delay(_queryRetryInterval);
                }

                matchesFound.Should().Be(BULK_DEVICE_COUNT, "Timed out waiting for all the bulk created devices to be query-able." +
                                         " Number of matching devices must be equal to the number of recently created devices.");
            }
            finally
            {
                await Cleanup(client, devices);
            }
        }
 private async Task Cleanup(IoTHubServiceClient client, DeviceIdentity device)
 {
     // cleanup
     try
     {
         if (device != null)
         {
             await client.Devices.DeleteIdentityAsync(device, IfMatchPrecondition.UnconditionalIfMatch).ConfigureAwait(false);
         }
     }
     catch (Exception ex)
     {
         Assert.Fail($"Test clean up failed: {ex.Message}");
     }
 }
        public async Task ModulesClient_BulkCreation_ModuleWithTwin()
        {
            string testDevicePrefix  = $"bulkDeviceWithTwin";
            string testModulePrefix  = $"bulkModuleWithTwin";
            string userPropertyName  = "user";
            string userPropertyValue = "userA";

            IoTHubServiceClient client = GetClient();

            string         deviceId       = $"{testDevicePrefix}{GetRandom()}";
            DeviceIdentity deviceIdentity = new DeviceIdentity()
            {
                DeviceId = deviceId
            };

            IDictionary <string, object> desiredProperties = new Dictionary <string, object>
            {
                { userPropertyName, userPropertyValue }
            };

            // We will build a single device with multiple modules, and each module will have the same initial twin.
            IDictionary <ModuleIdentity, TwinData> modulesAndTwins = BuildModulesAndTwins(deviceId, testModulePrefix, BULK_MODULE_COUNT, desiredProperties);

            try
            {
                // Create device to house the modules
                await client.Devices.CreateOrUpdateIdentityAsync(deviceIdentity).ConfigureAwait(false);

                // Create the modules with an initial twin in bulk
                Response <BulkRegistryOperationResponse> createResponse = await client.Modules.CreateIdentitiesWithTwinAsync(modulesAndTwins).ConfigureAwait(false);

                // TODO: (azabbasi) Once the issue with the error parsing is resolved, include the error message in the message of the assert statement.
                Assert.IsTrue(createResponse.Value.IsSuccessful, "Bulk module creation ended with errors");

                // Verify that the desired properties were set
                // For quicker test run, we will only verify the first device on the list.
                Response <TwinData> getResponse = await client.Modules.GetTwinAsync(modulesAndTwins.Keys.First().DeviceId, modulesAndTwins.Keys.First().ModuleId).ConfigureAwait(false);

                getResponse.Value.Properties.Desired[userPropertyName].Should().Be(userPropertyValue);
            }
            finally
            {
                await Cleanup(client, deviceIdentity);
            }
        }
        public async Task ModulesClient_BulkCreation_OneAlreadyExists()
        {
            string testDevicePrefix = $"bulkDeviceCreate";
            string testModulePrefix = $"bulkModuleCreate";

            IoTHubServiceClient client = GetClient();

            string deviceId       = $"{testDevicePrefix}{GetRandom()}";
            var    deviceIdentity = new DeviceIdentity()
            {
                DeviceId = deviceId
            };

            IList <ModuleIdentity> modules = BuildMultipleModules(deviceId, testModulePrefix, BULK_MODULE_COUNT - 1);

            try
            {
                // We first create a single device to house these bulk modules.
                await client.Devices.CreateOrUpdateIdentityAsync(deviceIdentity);

                // Create a single module on that device that will be used to cause a conflict later
                await client.Modules.CreateOrUpdateIdentityAsync(
                    new ModuleIdentity()
                {
                    DeviceId = deviceId,
                    ModuleId = modules.ElementAt(0).ModuleId     //Use the same module id as the first module in the bulk list
                }).ConfigureAwait(false);

                // Create all devices
                Response <BulkRegistryOperationResponse> createResponse = await client.Modules.CreateIdentitiesAsync(modules).ConfigureAwait(false);

                // TODO: (azabbasi) Once the issue with the error parsing is resolved, include the error message in the message of the assert statement.
                Assert.IsTrue(createResponse.Value.IsSuccessful, "Bulk device creation failed with errors");
                createResponse.Value.Errors.Count.Should().Be(1);

                // Since there is exactly one error, it is safe to just look at the first one here
                var error = createResponse.Value.Errors.First();
                error.ModuleId.Should().Be(modules.ElementAt(0).ModuleId, "Error should have been tied to the moduleId that was already created");
            }
            finally
            {
                await Cleanup(client, deviceIdentity);
            }
        }
        public async Task DevicesClient_IdentityLifecycle()
        {
            string testDeviceId = $"IdentityLifecycleDevice{GetRandom()}";

            DeviceIdentity      device = null;
            IoTHubServiceClient client = GetClient();

            try
            {
                // Create a device
                Response <DeviceIdentity> createResponse = await client.Devices.CreateOrUpdateIdentityAsync(
                    new Models.DeviceIdentity
                {
                    DeviceId = testDeviceId
                }).ConfigureAwait(false);

                device = createResponse.Value;

                // Get device
                // Get the device and compare ETag values (should remain unchanged);
                Response <DeviceIdentity> getResponse = await client.Devices.GetIdentityAsync(testDeviceId).ConfigureAwait(false);

                getResponse.Value.Etag.Should().BeEquivalentTo(device.Etag, "ETag value should not have changed.");

                device = getResponse.Value;

                // Update a device
                device.Status = DeviceStatus.Disabled;

                // TODO: (azabbasi) We should leave the IfMatchPrecondition to be the default value once we know more about the fix.
                Response <DeviceIdentity> updateResponse = await client.Devices.CreateOrUpdateIdentityAsync(device, IfMatchPrecondition.UnconditionalIfMatch).ConfigureAwait(false);

                updateResponse.Value.Status.Should().Be(DeviceStatus.Disabled, "Device should have been disabled");

                // Delete the device
                // Deleting the device happens in the finally block as cleanup.
            }
            finally
            {
                await Cleanup(client, device);
            }
        }
        public async Task DevicesClient_BulkCreation()
        {
            string testDevicePrefix = $"bulkDevice";

            IEnumerable <DeviceIdentity> devices = BuildMultipleDevices(testDevicePrefix, BULK_DEVICE_COUNT);

            IoTHubServiceClient client = GetClient();

            try
            {
                // Create all devices
                Response <BulkRegistryOperationResponse> createResponse = await client.Devices.CreateIdentitiesAsync(devices).ConfigureAwait(false);

                Assert.IsTrue(createResponse.Value.IsSuccessful, "Bulk device creation ended with errors");
            }
            finally
            {
                await Cleanup(client, devices);
            }
        }
        public async Task ModulesClient_BulkCreation_MultipleDevices()
        {
            string testDevicePrefix = $"bulkDevice";
            string testModulePrefix = $"bulkModule";

            List <DeviceIdentity> deviceIdentities = new List <DeviceIdentity>();
            List <ModuleIdentity> moduleIdentities = new List <ModuleIdentity>();

            for (int moduleIndex = 0; moduleIndex < BULK_MODULE_COUNT; moduleIndex++)
            {
                string deviceId = $"{testDevicePrefix}{GetRandom()}";
                deviceIdentities.Add(new DeviceIdentity()
                {
                    DeviceId = deviceId
                });

                moduleIdentities.Add(new ModuleIdentity()
                {
                    DeviceId = deviceId,
                    ModuleId = $"{testModulePrefix}{GetRandom()}"
                });
            }

            IoTHubServiceClient client = GetClient();

            try
            {
                // Create devices to house these bulk modules
                await client.Devices.CreateIdentitiesAsync(deviceIdentities);

                // Create modules in bulk on those devices
                Response <BulkRegistryOperationResponse> createResponse = await client.Modules.CreateIdentitiesAsync(moduleIdentities).ConfigureAwait(false);

                Assert.IsTrue(createResponse.Value.IsSuccessful, "Bulk module creation ended with errors");
            }
            finally
            {
                await Cleanup(client, deviceIdentities);
            }
        }
Esempio n. 22
0
 public ModuleIdentityLifecycleSamples(IoTHubServiceClient client)
 {
     IoTHubServiceClient = client;
 }
        public async Task ModulesClient_BulkUpdate()
        {
            string testDevicePrefix = $"bulkDeviceUpdate";
            string testModulePrefix = $"bulkModuleUpdate";

            IoTHubServiceClient client = GetClient();

            string deviceId       = $"{testDevicePrefix}{GetRandom()}";
            var    deviceIdentity = new DeviceIdentity()
            {
                DeviceId = deviceId
            };

            IList <ModuleIdentity> listOfModulesToUpdate = new List <ModuleIdentity>();

            try
            {
                // Create the device to house two modules
                await client.Devices.CreateOrUpdateIdentityAsync(deviceIdentity);

                AuthenticationMechanismType initialAuthenticationType = AuthenticationMechanismType.Sas;
                AuthenticationMechanismType updatedAuthenticationType = AuthenticationMechanismType.SelfSigned;

                for (int moduleIndex = 0; moduleIndex < BULK_MODULE_COUNT; moduleIndex++)
                {
                    // Create modules on that device
                    ModuleIdentity createdModule = (await client.Modules.CreateOrUpdateIdentityAsync(
                                                        new ModuleIdentity
                    {
                        DeviceId = deviceId,
                        ModuleId = $"{testModulePrefix}{GetRandom()}",
                        Authentication = new AuthenticationMechanism()
                        {
                            Type = initialAuthenticationType
                        },
                    }).ConfigureAwait(false)).Value;

                    // Update the authentication field so that we can test updating this identity later
                    createdModule.Authentication = new AuthenticationMechanism()
                    {
                        Type = AuthenticationMechanismType.SelfSigned
                    };

                    listOfModulesToUpdate.Add(createdModule);
                }

                // Make the API call to update the modules.
                Response <BulkRegistryOperationResponse> updateResponse =
                    await client.Modules.UpdateIdentitiesAsync(listOfModulesToUpdate, BulkIfMatchPrecondition.Unconditional)
                    .ConfigureAwait(false);

                // TODO: (azabbasi) Once the issue with the error parsing is resolved, include the error message in the message of the assert statement.
                Assert.IsTrue(updateResponse.Value.IsSuccessful, "Bulk module update ended with errors");

                // Verify that each module successfully updated its authentication field
                foreach (ModuleIdentity module in listOfModulesToUpdate)
                {
                    var updatedModule = (await client.Modules.GetIdentityAsync(module.DeviceId, module.ModuleId)).Value;
                    updatedModule.Authentication.Type.Should().Be(updatedAuthenticationType, "Module should have been updated");
                }
            }
            finally
            {
                await Cleanup(client, deviceIdentity);
            }
        }
 public BulkDeviceIdentityLifecycleSamples(IoTHubServiceClient client)
 {
     IoTHubServiceClient = client;
 }
        public async Task DevicesClient_InvokeMethodOnDevice()
        {
            if (!this.IsAsync)
            {
                // TODO: Tim: The device client doesn't appear to open a connection to iothub or start
                // listening for method invocations when this test is run in Sync mode. Not sure why though.
                // calls to track 1 library don't throw, but seem to silently fail
                return;
            }

            string testDeviceId = $"InvokeMethodDevice{GetRandom()}";

            DeviceIdentity      device        = null;
            DeviceClient        deviceClient  = null;
            IoTHubServiceClient serviceClient = GetClient();

            try
            {
                // Create a device to invoke the method on
                device = (await serviceClient.Devices.CreateOrUpdateIdentityAsync(
                              new DeviceIdentity
                {
                    DeviceId = testDeviceId
                })).Value;

                // Method expectations
                string expectedMethodName     = "someMethodToInvoke";
                int    expectedStatus         = 222;
                object expectedRequestPayload = null;

                // Create module client instance to receive the method invocation
                string moduleClientConnectionString = $"HostName={GetHostName()};DeviceId={testDeviceId};SharedAccessKey={device.Authentication.SymmetricKey.PrimaryKey}";
                deviceClient = DeviceClient.CreateFromConnectionString(moduleClientConnectionString, TransportType.Mqtt_Tcp_Only);

                // These two methods are part of our track 1 device client. When the test fixture runs when isAsync = true,
                // these methods work. When isAsync = false, these methods silently don't work.
                await deviceClient.OpenAsync();

                await deviceClient.SetMethodHandlerAsync(
                    expectedMethodName,
                    (methodRequest, userContext) =>
                {
                    return(Task.FromResult(new MethodResponse(expectedStatus)));
                },
                    null).ConfigureAwait(false);

                // Invoke the method on the module
                CloudToDeviceMethodRequest methodRequest = new CloudToDeviceMethodRequest()
                {
                    MethodName = expectedMethodName,
                    Payload    = expectedRequestPayload,
                    ConnectTimeoutInSeconds  = 5,
                    ResponseTimeoutInSeconds = 5
                };

                var methodResponse = (await serviceClient.Devices.InvokeMethodAsync(testDeviceId, methodRequest).ConfigureAwait(false)).Value;

                Assert.AreEqual(expectedStatus, methodResponse.Status);
            }
            finally
            {
                if (deviceClient != null)
                {
                    await deviceClient.CloseAsync().ConfigureAwait(false);
                }

                await Cleanup(serviceClient, device);
            }
        }
        public async Task ModulesClient_UpdateModuleTwin_EtagDoesNotMatch()
        {
            string testDeviceId = $"TwinLifecycleDevice{GetRandom()}";
            string testModuleId = $"TwinLifecycleModule{GetRandom()}";

            DeviceIdentity device = null;
            ModuleIdentity module = null;

            IoTHubServiceClient client = GetClient();

            try
            {
                // Create a device
                device = (await client.Devices.CreateOrUpdateIdentityAsync(
                              new Models.DeviceIdentity
                {
                    DeviceId = testDeviceId
                }).ConfigureAwait(false)).Value;

                // Create a module on that device. Note that this implicitly creates the module twin
                module = (await client.Modules.CreateOrUpdateIdentityAsync(
                              new Models.ModuleIdentity
                {
                    DeviceId = testDeviceId,
                    ModuleId = testModuleId
                }).ConfigureAwait(false)).Value;

                // Get the module twin
                TwinData moduleTwin = (await client.Modules.GetTwinAsync(testDeviceId, testModuleId).ConfigureAwait(false)).Value;

                moduleTwin.ModuleId.Should().BeEquivalentTo(testModuleId, "ModuleId on the Twin should match that of the module identity.");

                // Update device twin
                string propName  = "username";
                string propValue = "userA";
                moduleTwin.Properties.Desired.Add(new KeyValuePair <string, object>(propName, propValue));

                // TODO: (azabbasi) We should leave the IfMatchPrecondition to be the default value once we know more about the fix.
                Response <TwinData> updateResponse = await client.Modules.UpdateTwinAsync(moduleTwin, IfMatchPrecondition.UnconditionalIfMatch).ConfigureAwait(false);

                updateResponse.Value.Properties.Desired.Where(p => p.Key == propName).First().Value.Should().Be(propValue, "Desired property value is incorrect.");

                // Perform another update using the old device object to verify precondition fails.
                try
                {
                    // Try to update the twin with the previously up-to-date twin
                    await client.Modules.UpdateTwinAsync(moduleTwin, IfMatchPrecondition.IfMatch).ConfigureAwait(false);

                    Assert.Fail($"Update call with outdated ETag should fail with 412 (PreconditionFailed)");
                }
                // We will catch the exception and verify status is 412 (PreconditionfFailed)
                catch (RequestFailedException ex)
                {
                    Assert.AreEqual(412, ex.Status, $"Expected the update to fail with http status code 412 (PreconditionFailed)");
                }

                // Delete the module
                // Deleting the module happens in the finally block as cleanup.
            }
            finally
            {
                await Cleanup(client, device);
            }
        }