public async Task DeviceClient_TokenConnectionDoubleRelease_Ok() { TestDevice testDevice = await TestDevice.GetTestDeviceAsync(DevicePrefix).ConfigureAwait(false); string deviceConnectionString = testDevice.ConnectionString; var config = new Configuration.IoTHub.DeviceConnectionStringParser(deviceConnectionString); string iotHub = config.IoTHub; string deviceId = config.DeviceID; string key = config.SharedAccessKey; SharedAccessSignatureBuilder builder = new SharedAccessSignatureBuilder() { Key = key, TimeToLive = new TimeSpan(0, 10, 0), Target = $"{iotHub}/devices/{WebUtility.UrlEncode(deviceId)}", }; DeviceAuthenticationWithToken auth = new DeviceAuthenticationWithToken(deviceId, builder.ToSignature()); using (DeviceClient deviceClient = DeviceClient.Create(iotHub, auth, Client.TransportType.Amqp_Tcp_Only)) { _log.WriteLine($"Created {nameof(DeviceClient)} ID={TestLogging.IdOf(deviceClient)}"); Console.WriteLine("DeviceClient OpenAsync."); await deviceClient.OpenAsync().ConfigureAwait(false); Console.WriteLine("DeviceClient SendEventAsync."); await deviceClient.SendEventAsync(new Client.Message(Encoding.UTF8.GetBytes("TestMessage"))).ConfigureAwait(false); Console.WriteLine("DeviceClient CloseAsync."); await deviceClient.CloseAsync().ConfigureAwait(false); // First release } // Second release }
public async Task DeviceClient_Not_Exist_AMQP() { TestDevice testDevice = await TestDevice.GetTestDeviceAsync(DevicePrefix).ConfigureAwait(false); var config = new Configuration.IoTHub.DeviceConnectionStringParser(testDevice.ConnectionString); using (DeviceClient deviceClient = DeviceClient.CreateFromConnectionString($"HostName={config.IoTHub};DeviceId=device_id_not_exist;SharedAccessKey={config.SharedAccessKey}", Client.TransportType.Amqp_Tcp_Only)) { await deviceClient.OpenAsync().ConfigureAwait(false); } }
public async Task DeviceClient_Bad_Credentials_AMQP() { TestDevice testDevice = await TestDevice.GetTestDeviceAsync(DevicePrefix).ConfigureAwait(false); var config = new Configuration.IoTHub.DeviceConnectionStringParser(testDevice.ConnectionString); string invalidKey = Convert.ToBase64String(Encoding.UTF8.GetBytes("invalid_key")); using (DeviceClient deviceClient = DeviceClient.CreateFromConnectionString($"HostName={config.IoTHub};DeviceId={config.DeviceID};SharedAccessKey={invalidKey}", Client.TransportType.Amqp_Tcp_Only)) { await deviceClient.OpenAsync().ConfigureAwait(false); } }
public async Task DeviceClient_TokenConnectionDoubleRelease_Ok() { string deviceConnectionString = null; try { deviceConnectionString = Configuration.IoTHub.DeviceConnectionString; } catch (InvalidOperationException) { /* Invalid configuration. */ } if (string.IsNullOrEmpty(deviceConnectionString)) { Console.WriteLine("Device configuration not found. Test inconclusive."); return; } var config = new Configuration.IoTHub.DeviceConnectionStringParser(deviceConnectionString); string iotHub = config.IoTHub; string deviceId = config.DeviceID; string key = config.SharedAccessKey; SharedAccessSignatureBuilder builder = new SharedAccessSignatureBuilder() { Key = "Lfc0z9UTENYRt0vEoFQjXeUkQV3ifk5f3qFN5N7vFlY=", TimeToLive = new TimeSpan(0, 10, 0), Target = $"{iotHub}/devices/{WebUtility.UrlEncode(deviceId)}", }; DeviceAuthenticationWithToken auth = new DeviceAuthenticationWithToken(deviceId, builder.ToSignature()); using (DeviceClient iotClient = DeviceClient.Create(iotHub, auth, Client.TransportType.Amqp_Tcp_Only)) { Console.WriteLine("DeviceClient OpenAsync."); await iotClient.OpenAsync(); Console.WriteLine("DeviceClient SendEventAsync."); await iotClient.SendEventAsync(new Client.Message(Encoding.UTF8.GetBytes("TestMessage"))); Console.WriteLine("DeviceClient CloseAsync."); await iotClient.CloseAsync(); // First release } // Second release }
private async Task DeviceClient_Gives_ConnectionStatus_DeviceDisabled_Base( Client.TransportType protocol, Func <RegistryManager, string, Task> registryManagerOperation) { TestDevice testDevice = await TestDevice.GetTestDeviceAsync(DevicePrefix + $"_{Guid.NewGuid()}").ConfigureAwait(false); string deviceConnectionString = testDevice.ConnectionString; var config = new Configuration.IoTHub.DeviceConnectionStringParser(deviceConnectionString); string deviceId = config.DeviceID; ConnectionStatus? status = null; ConnectionStatusChangeReason?statusChangeReason = null; int deviceDisabledReceivedCount = 0; using (DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, protocol)) { ConnectionStatusChangesHandler statusChangeHandler = (s, r) => { if (r == ConnectionStatusChangeReason.Device_Disabled) { status = s; statusChangeReason = r; deviceDisabledReceivedCount++; } }; deviceClient.SetConnectionStatusChangesHandler(statusChangeHandler); _log.WriteLine($"{nameof(DeviceClient_Gives_ConnectionStatus_DeviceDisabled_Base)}: Created {nameof(DeviceClient)} with device Id={testDevice.Id}"); await deviceClient.OpenAsync().ConfigureAwait(false); // Receiving the module twin should succeed right now. _log.WriteLine($"{nameof(DeviceClient_Gives_ConnectionStatus_DeviceDisabled_Base)}: DeviceClient GetTwinAsync."); var twin = await deviceClient.GetTwinAsync().ConfigureAwait(false); Assert.IsNotNull(twin); // Delete/disable the device in IoT Hub. This should trigger the ConnectionStatusChangesHandler. using (RegistryManager registryManager = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString)) { await registryManagerOperation(registryManager, deviceId).ConfigureAwait(false); } _log.WriteLine($"{nameof(DeviceClient_Gives_ConnectionStatus_DeviceDisabled_Base)}: Completed RegistryManager operation."); // Artificial sleep waiting for the connection status change handler to get triggered. int sleepCount = 50; for (int i = 0; i < sleepCount; i++) { await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false); if (deviceDisabledReceivedCount == 1) { break; } } _log.WriteLine($"{nameof(DeviceClient_Gives_ConnectionStatus_DeviceDisabled_Base)}: Asserting connection status change."); Assert.AreEqual(1, deviceDisabledReceivedCount); Assert.AreEqual(ConnectionStatus.Disconnected, status); Assert.AreEqual(ConnectionStatusChangeReason.Device_Disabled, statusChangeReason); } }
async Task DeviceClient_Gives_ConnectionStatus_DeviceDisabled_Base( Client.TransportType protocol, Func <RegistryManager, string, Task> registryManagerOperation) { TestDevice testDevice = await TestDevice.GetTestDeviceAsync(DevicePrefix + $"_{Guid.NewGuid()}").ConfigureAwait(false); string deviceConnectionString = testDevice.ConnectionString; var config = new Configuration.IoTHub.DeviceConnectionStringParser(deviceConnectionString); string deviceId = config.DeviceID; ConnectionStatus? status = null; ConnectionStatusChangeReason?statusChangeReason = null; int deviceDisabledReceivedCount = 0; using (DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, protocol)) { ConnectionStatusChangesHandler statusChangeHandler = (s, r) => { if (r == ConnectionStatusChangeReason.Device_Disabled) { status = s; statusChangeReason = r; deviceDisabledReceivedCount++; } }; deviceClient.SetConnectionStatusChangesHandler(statusChangeHandler); _log.WriteLine($"Created {nameof(DeviceClient)} ID={TestLogging.IdOf(deviceClient)}"); Console.WriteLine("DeviceClient OpenAsync."); await deviceClient.OpenAsync().ConfigureAwait(false); // Receiving the module twin should succeed right now. Console.WriteLine("ModuleClient GetTwinAsync."); var twin = await deviceClient.GetTwinAsync().ConfigureAwait(false); Assert.IsNotNull(twin); // Delete the device in IoT Hub. This should trigger the ConnectionStatusChangesHandler. using (RegistryManager registryManager = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString)) { await registryManagerOperation(registryManager, deviceId).ConfigureAwait(false); } // Periodically keep retrieving the device twin to keep connection alive. // The ConnectionStatusChangesHandler should be triggered when the connection is closed from IoT hub with an // exception thrown. int twinRetrievals = 50; for (int i = 0; i < twinRetrievals; i++) { try { await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false); if (deviceDisabledReceivedCount == 1) { // Call an API on the client again to trigger the ConnectionStatusChangesHandler once again with the // Device_Disabled status. // This currently does not work due to some issues with IoT hub allowing new connections even when the // device is deleted/disabled. Once that problem is investigated and fixed, we can re-enable this call // and test for multiple invocations of the ConnectionStatusChangeHandler. // await deviceClient.GetTwinAsync().ConfigureAwait(false); break; } } catch (Exception ex) { _log.WriteLine($"Exception occurred while retrieving module twin: {ex}"); } } Assert.AreEqual(1, deviceDisabledReceivedCount); Assert.AreEqual(ConnectionStatus.Disconnected, status); Assert.AreEqual(ConnectionStatusChangeReason.Device_Disabled, statusChangeReason); } }