private async Task ReceiveSingleMessage(Client.TransportType transport) { Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager); ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(hubConnectionString); var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport); try { await deviceClient.OpenAsync(); if (transport == Client.TransportType.Mqtt_Tcp_Only || transport == Client.TransportType.Mqtt_WebSocket_Only) { // Dummy ReceiveAsync to ensure mqtt subscription registration before SendAsync() is called on service client. await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(2)); } string payload, messageId, p1Value; await serviceClient.OpenAsync(); await serviceClient.SendAsync(deviceInfo.Item1, ComposeC2DTestMessage(out payload, out messageId, out p1Value)); await VerifyReceivedC2DMessage(transport, deviceClient, payload, p1Value); } finally { await deviceClient.CloseAsync(); await serviceClient.CloseAsync(); await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager); } }
private async Task Twin_ClientHandlesRejectionInvalidPropertyName(Client.TransportType transport) { var propName1 = "$" + Guid.NewGuid().ToString(); var propName2 = Guid.NewGuid().ToString(); Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager); using (var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport)) { var exceptionThrown = false; try { await deviceClient.UpdateReportedPropertiesAsync(new TwinCollection { [propName1] = 123, [propName2] = "abcd" }).ConfigureAwait(false); } catch (Exception) { exceptionThrown = true; } if (!exceptionThrown) { throw new AssertFailedException("Exception was expected, but not thrown."); } var serviceTwin = await registryManager.GetTwinAsync(deviceInfo.Item1).ConfigureAwait(false); Assert.IsFalse(serviceTwin.Properties.Reported.Contains(propName1)); } await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager).ConfigureAwait(false); }
private async Task sendMethodAndRespondWithObseletedSetMethodHandler(Client.TransportType transport) { Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager); var assertResult = new TaskCompletionSource <Tuple <bool, bool> >(); var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport); // TODO: #193 // DeviceClient.SetMethodHandler(string, MethodCallback, object)' is obsolete: 'Please use SetMethodHandlerAsync. #pragma warning disable CS0618 deviceClient?.SetMethodHandler(MethodName, (request, context) => { assertResult.TrySetResult(new Tuple <bool, bool>(request.Name.Equals(MethodName), request.DataAsJson.Equals(ServiceRequestJson))); return(Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(DeviceResponseJson), 200))); }, null); #pragma warning restore CS0618 // sleep to ensure async tasks started in SetMethodHandler has completed Thread.Sleep(5000); await ServiceSendMethodAndVerifyResponse(deviceInfo.Item1, MethodName, DeviceResponseJson, ServiceRequestJson, assertResult); await deviceClient.CloseAsync(); await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager); }
private async Task Twin_ServiceDoesNotCreateNullPropertyInCollection(Client.TransportType transport) { var propName1 = Guid.NewGuid().ToString(); var propName2 = Guid.NewGuid().ToString(); var propEmptyValue = "{}"; Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager); using (var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport)) { await deviceClient.UpdateReportedPropertiesAsync(new TwinCollection { [propName1] = null }); var serviceTwin = await registryManager.GetTwinAsync(deviceInfo.Item1); Assert.IsFalse(serviceTwin.Properties.Reported.Contains(propName1)); await deviceClient.UpdateReportedPropertiesAsync(new TwinCollection { [propName1] = new TwinCollection { [propName2] = null } }); serviceTwin = await registryManager.GetTwinAsync(deviceInfo.Item1); Assert.IsTrue(serviceTwin.Properties.Reported.Contains(propName1)); String value1 = serviceTwin.Properties.Reported[propName1].ToString(); // TODO: #243 // If service team fixed the Issue #243 the following Assert.AreNotEqual should fail // and need to be changed to Assert.AreEqual Assert.AreNotEqual(value1, propEmptyValue); await deviceClient.UpdateReportedPropertiesAsync(new TwinCollection { [propName1] = new TwinCollection { [propName2] = null } }); serviceTwin = await registryManager.GetTwinAsync(deviceInfo.Item1); Assert.IsTrue(serviceTwin.Properties.Reported.Contains(propName1)); String value2 = serviceTwin.Properties.Reported[propName1].ToString(); Assert.AreEqual(value2, propEmptyValue); } await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager); }
//// This function create a device with x509 cert and send a message to the iothub on the transport specified. //// It then verifies the message is received at the eventHubClient. internal async Task SendSingleMessageX509(Client.TransportType transport) { // TODO: Update Jenkins Config string endpoint = Configuration.IoTHub.EventHubString; if (endpoint.IsNullOrWhiteSpace()) { return; } Tuple <string, string> deviceInfo = TestUtil.CreateDeviceWithX509(DevicePrefix, hostName, registryManager); EventHubClient eventHubClient; PartitionReceiver eventHubReceiver = await CreateEventHubReceiver(deviceInfo.Item1).ConfigureAwait(false); X509Certificate2 cert = Configuration.IoTHub.GetCertificateWithPrivateKey(); var auth = new DeviceAuthenticationWithX509Certificate(deviceInfo.Item1, cert); var deviceClient = DeviceClient.Create(deviceInfo.Item2, auth, transport); try { await deviceClient.OpenAsync().ConfigureAwait(false); string payload; string p1Value; Client.Message testMessage = ComposeD2CTestMessage(out payload, out p1Value); await deviceClient.SendEventAsync(testMessage).ConfigureAwait(false); bool isReceived = false; Stopwatch sw = new Stopwatch(); sw.Start(); while (!isReceived && sw.Elapsed.Minutes < 1) { var events = await eventHubReceiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(5)).ConfigureAwait(false); isReceived = VerifyTestMessage(events, deviceInfo.Item1, payload, p1Value); } sw.Stop(); Assert.IsTrue(isReceived, "Message is not received."); } finally { await deviceClient.CloseAsync().ConfigureAwait(false); await eventHubReceiver.CloseAsync().ConfigureAwait(false); await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager).ConfigureAwait(false); } }
private async Task ReceiveMessageRecovery(Client.TransportType transport, string faultType, string reason, int delayInSec) { await sequentialTestSemaphore.WaitAsync(); Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager); ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(hubConnectionString); var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport); try { await deviceClient.OpenAsync(); if (transport == Client.TransportType.Mqtt_Tcp_Only || transport == Client.TransportType.Mqtt_WebSocket_Only) { // Dummy ReceiveAsync to ensure mqtt subscription registration before SendAsync() is called on service client. await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(2)); } string payload, messageId, p1Value; await serviceClient.OpenAsync(); await serviceClient.SendAsync(deviceInfo.Item1, ComposeC2DTestMessage(out payload, out messageId, out p1Value)); await VerifyReceivedC2DMessage(transport, deviceClient, payload, p1Value); // send error command await deviceClient.SendEventAsync( TestUtil.ComposeErrorInjectionProperties(faultType, reason, delayInSec)); await Task.Delay(1000); await serviceClient.SendAsync(deviceInfo.Item1, ComposeC2DTestMessage(out payload, out messageId, out p1Value)); await VerifyReceivedC2DMessage(transport, deviceClient, payload, p1Value); } finally { await deviceClient.CloseAsync(); await serviceClient.CloseAsync(); await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager); sequentialTestSemaphore.Release(1); } }
private async Task sendMethodAndRespondWithSetMethodHandler(Client.TransportType transport) { Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager); var assertResult = new TaskCompletionSource <Tuple <bool, bool> >(); var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport); await(deviceClient?.SetMethodHandlerAsync(MethodName, (request, context) => { assertResult.TrySetResult(new Tuple <bool, bool>(request.Name.Equals(MethodName), request.DataAsJson.Equals(ServiceRequestJson))); return(Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(DeviceResponseJson), 200))); }, null)).ConfigureAwait(false); await ServiceSendMethodAndVerifyResponse(deviceInfo.Item1, MethodName, DeviceResponseJson, ServiceRequestJson, assertResult).ConfigureAwait(false); await deviceClient.CloseAsync().ConfigureAwait(false); await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager).ConfigureAwait(false); }
internal async Task SendSingleMessage(Client.TransportType transport) { // TODO: Update Jenkins Config if (Configuration.IoTHub.EventHubString.IsNullOrWhiteSpace()) { return; } Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager); PartitionReceiver eventHubReceiver = await CreateEventHubReceiver(deviceInfo.Item1); var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport); try { await deviceClient.OpenAsync(); string payload; string p1Value; Client.Message testMessage = ComposeD2CTestMessage(out payload, out p1Value); await deviceClient.SendEventAsync(testMessage); bool isReceived = false; Stopwatch sw = new Stopwatch(); sw.Start(); while (!isReceived && sw.Elapsed.Minutes < 1) { var events = await eventHubReceiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(30)); isReceived = VerifyTestMessage(events, deviceInfo.Item1, payload, p1Value); } sw.Stop(); Assert.IsTrue(isReceived, "Message is not received."); } finally { await deviceClient.CloseAsync(); await eventHubReceiver.CloseAsync(); await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager); } }
private async Task Twin_ServiceSetsDesiredPropertyAndDeviceReceivesItOnNextGet(Client.TransportType transport) { var propName = Guid.NewGuid().ToString(); var propValue = Guid.NewGuid().ToString(); Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager); var twinPatch = new Twin(); twinPatch.Properties.Desired[propName] = propValue; await registryManager.UpdateTwinAsync(deviceInfo.Item1, twinPatch, "*").ConfigureAwait(false); var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport); var deviceTwin = await deviceClient.GetTwinAsync().ConfigureAwait(false); Assert.AreEqual <string>(deviceTwin.Properties.Desired[propName].ToString(), propValue); await deviceClient.CloseAsync().ConfigureAwait(false); await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager).ConfigureAwait(false); }
private async Task _Twin_ServiceSetsDesiredPropertyAndDeviceReceivesEvent_WithObseleteCallbackSetter(Client.TransportType transport) { var tcs = new TaskCompletionSource <bool>(); var propName = Guid.NewGuid().ToString(); var propValue = Guid.NewGuid().ToString(); Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager); var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport); // TODO: #193 // DeviceClient.SetDesiredPropertyUpdateCallback(DesiredPropertyUpdateCallback, object)' is obsolete: 'Please use SetDesiredPropertyUpdateCallbackAsync. #pragma warning disable CS0618 await deviceClient.SetDesiredPropertyUpdateCallback((patch, context) => { return(Task.Run(() => { try { Assert.AreEqual(patch[propName].ToString(), propValue); } catch (Exception e) { tcs.SetException(e); } finally { tcs.SetResult(true); } })); }, null); #pragma warning restore CS0618 var twinPatch = new Twin(); twinPatch.Properties.Desired[propName] = propValue; await registryManager.UpdateTwinAsync(deviceInfo.Item1, twinPatch, "*"); await tcs.Task; await deviceClient.CloseAsync(); await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager); }
async Task uploadFileDisconnectTransport(Client.TransportType transport, string filename, string faultType, string reason, int delayInSec, int durationInSec = 0, int retryDurationInMilliSec = 24000) { Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager); DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport); deviceClient.OperationTimeoutInMilliseconds = (uint)retryDurationInMilliSec; Task fileuploadTask; Task <FileNotification> verifyTask; using (FileStream fileStreamSource = new FileStream(filename, FileMode.Open, FileAccess.Read)) { verifyTask = VerifyFileNotification(deviceInfo); fileuploadTask = deviceClient.UploadToBlobAsync(filename, fileStreamSource); try { await deviceClient.SendEventAsync(TestUtil.ComposeErrorInjectionProperties(faultType, reason, delayInSec, durationInSec)).ConfigureAwait(false); } catch (Exception) { // catch and ignore exceptions resulted from error injection and continue to // check result of the file upload status } await Task.WhenAll(fileuploadTask, verifyTask).ConfigureAwait(false); } FileNotification fileNotification = await verifyTask.ConfigureAwait(false); Assert.IsNotNull(fileNotification, "FileNotification is not received."); Assert.AreEqual(deviceInfo.Item1 + "/" + filename, fileNotification.BlobName, "Uploaded file name mismatch in notifications"); Assert.AreEqual(new FileInfo(filename).Length, fileNotification.BlobSizeInBytes, "Uploaded file size mismatch in notifications"); Assert.IsFalse(string.IsNullOrEmpty(fileNotification.BlobUri), "File notification blob uri is null or empty"); await deviceClient.CloseAsync().ConfigureAwait(false); await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager).ConfigureAwait(false); }
private async Task Twin_DeviceSetsReportedPropertyAndGetsItBack(Client.TransportType transport) { var propName = Guid.NewGuid().ToString(); var propValue = Guid.NewGuid().ToString(); Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager); var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport); TwinCollection props = new TwinCollection(); props[propName] = propValue; await deviceClient.UpdateReportedPropertiesAsync(props).ConfigureAwait(false); var deviceTwin = await deviceClient.GetTwinAsync().ConfigureAwait(false); Assert.AreEqual <String>(deviceTwin.Properties.Reported[propName].ToString(), propValue); await deviceClient.CloseAsync().ConfigureAwait(false); await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager).ConfigureAwait(false); }
private async Task Twin_DeviceSetsReportedPropertyAndServiceReceivesIt(Client.TransportType transport) { var propName = Guid.NewGuid().ToString(); var propValue = Guid.NewGuid().ToString(); Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager); var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport); var patch = new TwinCollection(); patch[propName] = propValue; await deviceClient.UpdateReportedPropertiesAsync(patch).ConfigureAwait(false); await deviceClient.CloseAsync().ConfigureAwait(false); var serviceTwin = await registryManager.GetTwinAsync(deviceInfo.Item1).ConfigureAwait(false); Assert.AreEqual <string>(serviceTwin.Properties.Reported[propName].ToString(), propValue); TestContext.WriteLine("verified " + serviceTwin.Properties.Reported[propName].ToString() + "=" + propValue); await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager).ConfigureAwait(false); }
private async Task Twin_ServiceSetsDesiredPropertyAndDeviceReceivesEvent(Client.TransportType transport) { var tcs = new TaskCompletionSource <bool>(); var propName = Guid.NewGuid().ToString(); var propValue = Guid.NewGuid().ToString(); Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager); var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport); await deviceClient.OpenAsync().ConfigureAwait(false); await deviceClient.SetDesiredPropertyUpdateCallbackAsync((patch, context) => { return(Task.Run(() => { try { Assert.AreEqual(patch[propName].ToString(), propValue); } catch (Exception e) { tcs.SetException(e); } finally { tcs.SetResult(true); } })); }, null).ConfigureAwait(false); var twinPatch = new Twin(); twinPatch.Properties.Desired[propName] = propValue; await registryManager.UpdateTwinAsync(deviceInfo.Item1, twinPatch, "*").ConfigureAwait(false); await tcs.Task.ConfigureAwait(false); await deviceClient.CloseAsync().ConfigureAwait(false); await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager).ConfigureAwait(false); }
private async Task Twin_DeviceReportedPropertiesRecovery(Client.TransportType transport, string faultType, string reason, int delayInSec) { var propName = Guid.NewGuid().ToString(); var propValue1 = Guid.NewGuid().ToString(); Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager); var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport); TwinCollection props = new TwinCollection(); props[propName] = propValue1; await deviceClient.UpdateReportedPropertiesAsync(props).ConfigureAwait(false); var deviceTwin = await deviceClient.GetTwinAsync().ConfigureAwait(false); Assert.AreEqual <String>(deviceTwin.Properties.Reported[propName].ToString(), propValue1); // send error command await deviceClient.SendEventAsync(TestUtil.ComposeErrorInjectionProperties(faultType, reason, delayInSec)).ConfigureAwait(false); deviceTwin = await deviceClient.GetTwinAsync().ConfigureAwait(false); Assert.AreEqual <String>(deviceTwin.Properties.Reported[propName].ToString(), propValue1); var propValue2 = Guid.NewGuid().ToString(); props[propName] = propValue2; await deviceClient.UpdateReportedPropertiesAsync(props).ConfigureAwait(false); deviceTwin = await deviceClient.GetTwinAsync().ConfigureAwait(false); Assert.AreEqual <String>(deviceTwin.Properties.Reported[propName].ToString(), propValue2); await deviceClient.CloseAsync().ConfigureAwait(false); await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager).ConfigureAwait(false); }
async Task uploadFile(Client.TransportType transport, string filename, bool x509auth = false) { DeviceClient deviceClient; Tuple <string, string> deviceInfo; if (x509auth) { deviceInfo = TestUtil.CreateDeviceWithX509(DevicePrefix, hostName, registryManager); X509Certificate2 cert = Configuration.IoTHub.GetCertificateWithPrivateKey(); var auth = new DeviceAuthenticationWithX509Certificate(deviceInfo.Item1, cert); deviceClient = DeviceClient.Create(deviceInfo.Item2, auth, transport); } else { deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager); deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport); } using (FileStream fileStreamSource = new FileStream(filename, FileMode.Open, FileAccess.Read)) { await deviceClient.UploadToBlobAsync(filename, fileStreamSource).ConfigureAwait(false); } FileNotification fileNotification = await VerifyFileNotification(deviceInfo).ConfigureAwait(false); Assert.IsNotNull(fileNotification, "FileNotification is not received."); Assert.AreEqual(deviceInfo.Item1 + "/" + filename, fileNotification.BlobName, "Uploaded file name mismatch in notifications"); Assert.AreEqual(new FileInfo(filename).Length, fileNotification.BlobSizeInBytes, "Uploaded file size mismatch in notifications"); Assert.IsFalse(string.IsNullOrEmpty(fileNotification.BlobUri), "File notification blob uri is null or empty"); await deviceClient.CloseAsync().ConfigureAwait(false); await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager).ConfigureAwait(false); }
private async Task SendMessageRecovery(Client.TransportType transport, string faultType, string reason, int delayInSec, int durationInSec = 0, int retryDurationInMilliSec = 240000) { await sequentialTestSemaphore.WaitAsync(); Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager); var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport); EventHubClient eventHubClient; EventHubReceiver eventHubReceiver = CreateEventHubReceiver(deviceInfo.Item1, out eventHubClient); try { deviceClient.OperationTimeoutInMilliseconds = (uint)retryDurationInMilliSec; ConnectionStatus? lastConnectionStatus = null; ConnectionStatusChangeReason?lastConnectionStatusChangeReason = null; int setConnectionStatusChangesHandlerCount = 0; deviceClient.SetConnectionStatusChangesHandler((status, statusChangeReason) => { lastConnectionStatus = status; lastConnectionStatusChangeReason = statusChangeReason; setConnectionStatusChangesHandlerCount++; }); await deviceClient.OpenAsync(); if (transport != Client.TransportType.Http1) { Assert.AreEqual(1, setConnectionStatusChangesHandlerCount); Assert.AreEqual(ConnectionStatus.Connected, lastConnectionStatus); Assert.AreEqual(ConnectionStatusChangeReason.Connection_Ok, lastConnectionStatusChangeReason); } string payload, p1Value; Client.Message testMessage = ComposeD2CTestMessage(out payload, out p1Value); await deviceClient.SendEventAsync(testMessage); bool isReceived = false; Stopwatch sw = new Stopwatch(); sw.Start(); while (!isReceived && sw.Elapsed.Minutes < 1) { var events = await eventHubReceiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(5)); isReceived = VerifyTestMessage(events, deviceInfo.Item1, payload, p1Value); } sw.Stop(); // send error command and clear eventHubReceiver of the fault injection message await deviceClient.SendEventAsync(TestUtil.ComposeErrorInjectionProperties(faultType, reason, delayInSec, durationInSec)); await eventHubReceiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(5)); Thread.Sleep(1000); testMessage = ComposeD2CTestMessage(out payload, out p1Value); await deviceClient.SendEventAsync(testMessage); sw.Reset(); sw.Start(); while (!isReceived && sw.Elapsed.Minutes < 1) { var events = await eventHubReceiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(5)); isReceived = VerifyTestMessage(events, deviceInfo.Item1, payload, p1Value); } sw.Stop(); await deviceClient.CloseAsync(); if (transport != Client.TransportType.Http1) { Assert.AreEqual(2, setConnectionStatusChangesHandlerCount); Assert.AreEqual(ConnectionStatus.Disabled, lastConnectionStatus); Assert.AreEqual(ConnectionStatusChangeReason.Client_Close, lastConnectionStatusChangeReason); } } finally { await deviceClient.CloseAsync(); await eventHubReceiver.CloseAsync(); await eventHubClient.CloseAsync(); await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager); sequentialTestSemaphore.Release(1); } }
private async Task SendMethodAndRespondRecovery(Client.TransportType transport, string faultType, string reason, int delayInSec) { Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager); var assertResult = new TaskCompletionSource <Tuple <bool, bool> >(); DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport); ConnectionStatus? lastConnectionStatus = null; ConnectionStatusChangeReason?lastConnectionStatusChangeReason = null; int setConnectionStatusChangesHandlerCount = 0; var tcsConnected = new TaskCompletionSource <bool>(); var tcsDisconnected = new TaskCompletionSource <bool>(); deviceClient.SetConnectionStatusChangesHandler((status, statusChangeReason) => { Debug.WriteLine("Connection Changed to {0} because {1}", status, statusChangeReason); if (status == ConnectionStatus.Disconnected_Retrying) { tcsDisconnected.TrySetResult(true); Assert.AreEqual(ConnectionStatusChangeReason.No_Network, statusChangeReason); } else if (status == ConnectionStatus.Connected) { tcsConnected.TrySetResult(true); } lastConnectionStatus = status; lastConnectionStatusChangeReason = statusChangeReason; setConnectionStatusChangesHandlerCount++; }); await deviceClient.SetMethodHandlerAsync(MethodName, (request, context) => { assertResult.TrySetResult(new Tuple <bool, bool>(request.Name.Equals(MethodName), request.DataAsJson.Equals(ServiceRequestJson))); return(Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(DeviceResponseJson), 200))); }, null).ConfigureAwait(false); // assert on successfuly connection await Task.WhenAny( Task.Run(async() => { await Task.Delay(1000).ConfigureAwait(false); }), tcsConnected.Task).ConfigureAwait(false); Assert.IsTrue(tcsConnected.Task.IsCompleted, "Initial connection failed"); if (transport != Client.TransportType.Http1) { Assert.AreEqual(1, setConnectionStatusChangesHandlerCount); Assert.AreEqual(ConnectionStatus.Connected, lastConnectionStatus); Assert.AreEqual(ConnectionStatusChangeReason.Connection_Ok, lastConnectionStatusChangeReason); } // check on normal operation await ServiceSendMethodAndVerifyResponse(deviceInfo.Item1, MethodName, DeviceResponseJson, ServiceRequestJson, assertResult).ConfigureAwait(false); // reset ConnectionStatusChangesHandler data setConnectionStatusChangesHandlerCount = 0; tcsConnected = new TaskCompletionSource <bool>(); tcsDisconnected = new TaskCompletionSource <bool>(); // send error command await deviceClient.SendEventAsync(TestUtil.ComposeErrorInjectionProperties(faultType, reason, delayInSec)).ConfigureAwait(false); // wait for disconnection await Task.WhenAny( Task.Run(async() => { await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false); }), tcsDisconnected.Task).ConfigureAwait(false); Assert.IsTrue(tcsDisconnected.Task.IsCompleted, "Error injection did not interrupt the device"); // allow max 3 minutes for connection recovery await Task.WhenAny( Task.Run(async() => { ////////////////////////change it to 30 await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false); return(Task.FromResult(true)); }), tcsConnected.Task).ConfigureAwait(false); Assert.IsTrue(tcsConnected.Task.IsCompleted, "Recovery connection failed"); assertResult = new TaskCompletionSource <Tuple <bool, bool> >(); await ServiceSendMethodAndVerifyResponse(deviceInfo.Item1, MethodName, DeviceResponseJson, ServiceRequestJson, assertResult).ConfigureAwait(false); setConnectionStatusChangesHandlerCount = 0; //remove and CloseAsync await deviceClient.SetMethodHandlerAsync(MethodName, null, null).ConfigureAwait(false); if (transport != Client.TransportType.Http1) { Assert.AreEqual(1, setConnectionStatusChangesHandlerCount); Assert.AreEqual(ConnectionStatus.Disabled, lastConnectionStatus); Assert.AreEqual(ConnectionStatusChangeReason.Client_Close, lastConnectionStatusChangeReason); } await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager).ConfigureAwait(false); }
private async Task Twin_DeviceDesiredPropertyUpdateRecovery(Client.TransportType transport, string faultType, string reason, int delayInSec) { var tcs = new TaskCompletionSource <bool>(); var propName = Guid.NewGuid().ToString(); var propValue = Guid.NewGuid().ToString(); Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager); var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport); ConnectionStatus? lastConnectionStatus = null; ConnectionStatusChangeReason?lastConnectionStatusChangeReason = null; int setConnectionStatusChangesHandlerCount = 0; var tcsConnected = new TaskCompletionSource <bool>(); var tcsDisconnected = new TaskCompletionSource <bool>(); deviceClient.SetConnectionStatusChangesHandler((status, statusChangeReason) => { if (status == ConnectionStatus.Disconnected_Retrying) { tcsDisconnected.TrySetResult(true); Assert.AreEqual(ConnectionStatusChangeReason.No_Network, statusChangeReason); } else if (status == ConnectionStatus.Connected) { tcsConnected.TrySetResult(true); } lastConnectionStatus = status; lastConnectionStatusChangeReason = statusChangeReason; setConnectionStatusChangesHandlerCount++; }); await deviceClient.SetDesiredPropertyUpdateCallbackAsync((patch, context) => { return(Task.Run(() => { try { Assert.AreEqual(patch[propName].ToString(), propValue); } catch (Exception e) { tcs.SetException(e); } finally { tcs.SetResult(true); } })); }, null).ConfigureAwait(false); // assert on successfuly connection await Task.WhenAny( Task.Run(async() => { await Task.Delay(1000).ConfigureAwait(false); }), tcsConnected.Task).ConfigureAwait(false); Assert.IsTrue(tcsConnected.Task.IsCompleted, "Initial connection failed"); if (transport != Client.TransportType.Http1) { Assert.AreEqual(1, setConnectionStatusChangesHandlerCount); Assert.AreEqual(ConnectionStatus.Connected, lastConnectionStatus); Assert.AreEqual(ConnectionStatusChangeReason.Connection_Ok, lastConnectionStatusChangeReason); } var twinPatch = new Twin(); twinPatch.Properties.Desired[propName] = propValue; await registryManager.UpdateTwinAsync(deviceInfo.Item1, twinPatch, "*").ConfigureAwait(false); await tcs.Task.ConfigureAwait(false); // send error command await deviceClient.SendEventAsync(TestUtil.ComposeErrorInjectionProperties(faultType, reason, delayInSec)).ConfigureAwait(false); // reset ConnectionStatusChangesHandler data setConnectionStatusChangesHandlerCount = 0; tcsConnected = new TaskCompletionSource <bool>(); tcsDisconnected = new TaskCompletionSource <bool>(); // wait for disconnection await Task.WhenAny( Task.Run(async() => { await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false); }), tcsDisconnected.Task).ConfigureAwait(false); Assert.IsTrue(tcsDisconnected.Task.IsCompleted, "Error injection did not interrupt the device"); // allow max 30s for connection recovery await Task.WhenAny( Task.Run(async() => { await Task.Delay(TimeSpan.FromSeconds(10)).ConfigureAwait(false); return(Task.FromResult(true)); }), tcsConnected.Task).ConfigureAwait(false); Assert.IsTrue(tcsConnected.Task.IsCompleted, "Recovery connection failed"); tcs = new TaskCompletionSource <bool>(); twinPatch = new Twin(); twinPatch.Properties.Desired[propName] = propValue; await registryManager.UpdateTwinAsync(deviceInfo.Item1, twinPatch, "*").ConfigureAwait(false); await tcs.Task.ConfigureAwait(false); await deviceClient.CloseAsync().ConfigureAwait(false); await TestUtil.RemoveDeviceAsync(deviceInfo.Item1, registryManager).ConfigureAwait(false); }