예제 #1
0
        public async static Task DeleteAllDevicesInHubAsync(IotHubServiceClient hubClient)
        {
            Console.WriteLine($"\nTrying to clean up all devices\n");

            try
            {
                AsyncPageable <TwinData> asyncPageableResponse = hubClient.Devices.GetTwinsAsync();
                List <TwinData>          deviceTwins           = new List <TwinData>();
                await foreach (TwinData twin in asyncPageableResponse)
                {
                    deviceTwins.Add(twin);
                }

                foreach (TwinData twin in deviceTwins)
                {
                    DeviceIdentity device = await hubClient.Devices.GetIdentityAsync(twin.DeviceId);

                    await hubClient.Devices.DeleteIdentityAsync(device);
                }

                SampleLogger.PrintSuccess($"Cleanup succeeded\n");
            }
            catch (Exception ex)
            {
                SampleLogger.PrintWarning($"Cleanup failed due to:\n{ex.Message}\n");
            }
        }
예제 #2
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();
        }
예제 #3
0
        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 }).ConfigureAwait(false);

                // 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 CleanupAsync(client, devices).ConfigureAwait(false);
            }
        }
        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).ConfigureAwait(false);

                // 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 CleanupAsync(client, deviceIdentity).ConfigureAwait(false);
            }
        }
        public async Task ConfigurationsClient_ConfigurationsLifecycle()
        {
            string testConfigurationId = $"configlifecycle{GetRandom()}";
            // Generate a random priority less than 100
            int testPriority                      = int.Parse(GetRandom());
            IotHubServiceClient client            = GetClient();
            TwinConfiguration   twinConfiguration = CreateTestConfig(testConfigurationId);
            TwinConfiguration   createdConfig;

            try
            {
                // Create a twin configuration
                Response <TwinConfiguration> createResponse =
                    await client.Configurations.CreateOrUpdateConfigurationAsync(twinConfiguration).ConfigureAwait(false);

                createdConfig = createResponse.Value;

                // Get twin configuration
                Response <TwinConfiguration> getResponse = await client.Configurations.GetConfigurationAsync(testConfigurationId).ConfigureAwait(false);

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

                // Update a configuration
                createdConfig.Priority = testPriority;
                Response <TwinConfiguration> updatedConfig = await client.Configurations.CreateOrUpdateConfigurationAsync(createdConfig, IfMatchPrecondition.UnconditionalIfMatch).ConfigureAwait(false);

                updatedConfig.Value.Priority.Should().Be(testPriority, "Priority should have been updated.");
            }
            finally
            {
                // Delete twin configuration
                await CleanupAsync(client, twinConfiguration).ConfigureAwait(false);
            }
        }
예제 #7
0
        public async Task QueryClient_GetAllModulesTwinsWithTag()
        {
            string testDeviceId = $"QueryDevice{GetRandom()}";
            string testModuleId = $"QueryModule{GetRandom()}";

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

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

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

                int tryCount   = 0;
                var twinsFound = new List <TwinData>();
                // A new device may not return immediately from a query, so give it some time and some retries to appear.
                while (tryCount < _maxTryCount && !twinsFound.Any())
                {
                    // Query for module twins with a specific tag.
                    AsyncPageable <TwinData> queryResponse = client.Query.QueryAsync($"SELECT * FROM devices.modules WHERE moduleId = '{testModuleId}'");
                    await foreach (TwinData item in queryResponse)
                    {
                        twinsFound.Add(item);
                    }

                    tryCount++;

                    // Adding a delay to account for query cache sync.
                    await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
                }

                twinsFound.Count.Should().Be(1);
                twinsFound.First().ModuleId.Should().Be(testModuleId);

                // Delete the device
                // Deleting the device happens in the finally block as cleanup.
            }
            finally
            {
                await CleanupAsync(client, device).ConfigureAwait(false);
            }
        }
        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
                })
                          .ConfigureAwait(false))
                         .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 CleanupAsync(client, device).ConfigureAwait(false);
            }
        }
        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).ConfigureAwait(false);
                }

                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 CleanupAsync(client, deviceIdentity).ConfigureAwait(false);
            }
        }
예제 #10
0
 private async Task CleanupAsync(IotHubServiceClient client, IEnumerable <DeviceIdentity> deviceIdentities)
 {
     // Delete all devices.
     if (deviceIdentities != null)
     {
         await client.Devices.DeleteIdentitiesAsync(deviceIdentities).ConfigureAwait(false);
     }
 }
        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 DeviceIdentity
                {
                    DeviceId = testDeviceId
                }).ConfigureAwait(false)).Value;

                // Create a module on that device
                module = (await client.Modules.CreateOrUpdateIdentityAsync(
                              new 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 CleanupAsync(client, device).ConfigureAwait(false);
            }
        }
        public async Task StatisticsClient_Service_SuccessfulResponse()
        {
            IotHubServiceClient client = GetClient();

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

            Assert.IsNotNull(stat.Value, "Statistics response should not be null");
            Assert.IsNotNull(stat.Value.ConnectedDeviceCount, "ConnectedDeviceCount 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
                })
                          .ConfigureAwait(false))
                         .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 CleanupAsync(client, device).ConfigureAwait(false);
            }
        }
예제 #14
0
        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).ConfigureAwait(false)).Value;
                deviceTwo = (await client.Devices.GetIdentityAsync(deviceTwo.DeviceId).ConfigureAwait(false)).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 CleanupAsync(client, listOfDevicesToUpdate).ConfigureAwait(false);
            }
        }
        public async Task StatisticsClient_Device_SuccessfulResponse()
        {
            IotHubServiceClient client = GetClient();

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

            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");
        }
예제 #16
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

            #region Snippet:IotHubServiceClientInitializeWithIotHubSasCredential

            // Create an IotHubSasCredential type to use sas tokens to authenticate against your IoT Hub instance.
            // The default lifespan of the sas token is 30 minutes, and it is set to be renewed when at 15% or less of its lifespan.
            var credential = new IotHubSasCredential(options.IotHubSharedAccessPolicy, options.IotHubSharedAccessKey);

            IotHubServiceClient hubClient = new IotHubServiceClient(options.Endpoint, credential);

            #endregion Snippet:IotHubServiceClientInitializeWithIotHubSasCredential

            // 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();

            var bulkModuledentityLifecycleSamples = new BulkModuleIdentityLifecycleSamples(hubClient);
            await bulkModuledentityLifecycleSamples.RunSampleAsync();

            var querySamples = new QueryTwinSamples(hubClient);
            await querySamples.RunSampleAsync();

            // Run samples that require the device sample to be running.
            if (options.IsDeviceSampleRunning == true)
            {
                // This sample requires the device sample to be running so that it can connect to the device.
                var methodInvocationSamples = new MethodInvocationSamples(hubClient);
                await methodInvocationSamples.RunSampleAsync();
            }
        }
 private async Task CleanupAsync(IotHubServiceClient client, IEnumerable <DeviceIdentity> devices)
 {
     try
     {
         if (devices != null && devices.Any())
         {
             await client.Devices.DeleteIdentitiesAsync(devices, BulkIfMatchPrecondition.Unconditional).ConfigureAwait(false);
         }
     }
     catch (Exception ex)
     {
         Assert.Fail($"Test clean up failed: {ex.Message}");
     }
 }
        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 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 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 CleanupAsync(client, device).ConfigureAwait(false);
            }
        }
        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);
            }
        }
예제 #20
0
        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 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 CleanupAsync(client, device).ConfigureAwait(false);
            }
        }
 private async Task CleanupAsync(IotHubServiceClient client, TwinConfiguration config)
 {
     // cleanup
     try
     {
         if (config != null)
         {
             await client.Configurations.DeleteConfigurationAsync(config, IfMatchPrecondition.UnconditionalIfMatch).ConfigureAwait(false);
         }
     }
     catch (Exception ex)
     {
         Assert.Fail($"Test clean up failed: {ex.Message}");
     }
 }
 private async Task CleanupAsync(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}");
     }
 }
예제 #23
0
        private async Task <Response <JobProperties> > WaitForJobCompletionAsync(IotHubServiceClient client, string jobId)
        {
            Response <JobProperties> response;

            // Wait for job to complete.
            do
            {
                response = await client.Jobs.GetImportExportJobAsync(jobId).ConfigureAwait(false);

                // We do not need to really wait when running on mocked values(Playback mode).
                // This will speed up testing in Playback mode and the PR pipeline.
                await Delay(5000);
            } while (!IsTerminalStatus(response.Value.Status));

            return(response);
        }
        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 CleanupAsync(client, deviceIdentity).ConfigureAwait(false);
            }
        }
        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).ConfigureAwait(false);

                // 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 CleanupAsync(client, deviceIdentity).ConfigureAwait(false);
            }
        }
예제 #26
0
        private async Task <Response <JobProperties> > WaitForJobCompletionAsync(IotHubServiceClient client, string jobId)
        {
            Response <JobProperties> response;

            // Wait for job to complete.
            do
            {
                response = await client.Jobs.GetImportExportJobAsync(jobId).ConfigureAwait(false);

                // We do not need to really wait when running on mocked values(Playback mode).
                // This will speed up testing in Playback mode and the PR pipeline.
                if (TestSettings.Instance.TestMode != Core.TestFramework.RecordedTestMode.Playback)
                {
                    await Task.Delay(TimeSpan.FromSeconds(5)).ConfigureAwait(false);
                }
            } while (!IsTerminalStatus(response.Value.Status));

            return(response);
        }
예제 #27
0
        public async Task Jobs_Export_Import_Lifecycle()
        {
            // setup
            string testDevicePrefix = $"jobDevice";
            IEnumerable <DeviceIdentity> deviceIdentities = null;

            IotHubServiceClient client = GetClient();

            try
            {
                //Create multiple devices.
                deviceIdentities = BuildMultipleDevices(testDevicePrefix, DEVICE_COUNT);
                await client.Devices.CreateIdentitiesAsync(deviceIdentities).ConfigureAwait(false);

                // Export all devices to blob storage.
                Response <JobProperties> response = await client.Jobs
                                                    .CreateExportDevicesJobAsync(outputBlobContainerUri : TestEnvironment.StorageSasToken, excludeKeys : false)
                                                    .ConfigureAwait(false);

                response.GetRawResponse().Status.Should().Be(200);

                // Wait for job completion and validate result.
                response = await WaitForJobCompletionAsync(client, response.Value.JobId).ConfigureAwait(false);

                response.Value.Status.Should().Be(JobPropertiesStatus.Completed);

                //Import all devices from storage to create and provision devices on the IoTHub.
                response = await client.Jobs
                           .CreateImportDevicesJobAsync(TestEnvironment.StorageSasToken, TestEnvironment.StorageSasToken)
                           .ConfigureAwait(false);

                response.GetRawResponse().Status.Should().Be(200);

                // Wait for job completion and validate result.
                response = await WaitForJobCompletionAsync(client, response.Value.JobId).ConfigureAwait(false);

                response.Value.Status.Should().Be(JobPropertiesStatus.Completed);
            }
            finally
            {
                await CleanupAsync(client, deviceIdentities).ConfigureAwait(false);
            }
        }
예제 #28
0
        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 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 CleanupAsync(client, device).ConfigureAwait(false);
            }
        }
예제 #29
0
        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 CleanupAsync(client, devices).ConfigureAwait(false);
            }
        }
        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).ConfigureAwait(false);

                // 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 CleanupAsync(client, deviceIdentities).ConfigureAwait(false);
            }
        }