Beispiel #1
0
        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();

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
        private async Task sendMethodAndRespondWithObseletedSetMethodHandler(Client.TransportType transport)
        {
            string deviceResponseJson = "{\"name\":\"e2e_test\"}";
            string serviceRequestJson = "{\"a\":123}";
            string methodName         = "MethodE2ETest";

            Tuple <string, string> deviceInfo = TestUtil.CreateDevice("E2E_Method_CSharp_", hostName, registryManager);
            var assertResult = new TaskCompletionSource <Tuple <bool, bool> >();
            var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport);

            deviceClient?.SetMethodHandler(methodName,
                                           (request, context) =>
            {
                assertResult.SetResult(new Tuple <bool, bool>(request.Name.Equals(methodName), request.DataAsJson.Equals(serviceRequestJson)));
                return(Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(deviceResponseJson), 200)));
            },
                                           null);

            // sleep to ensure async tasks started in SetMethodHandler has completed
            Thread.Sleep(5000);

            await ServiceSendMethodAndVerifyResponse(deviceInfo.Item1, methodName, deviceResponseJson, serviceRequestJson, assertResult);

            await deviceClient.CloseAsync();

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
Beispiel #3
0
        async Task sendMethodAndRespond(Client.TransportType transport)
        {
            Tuple <string, string> deviceInfo = TestUtil.CreateDevice("E2E_Method_CSharp_", hostName, registryManager);
            string deviceResponseJson         = "{\"name\":\"e2e_test\"}";
            string serviceRequestJson         = "{\"a\":123}";
            string methodName = "MethodE2ETest";

            var assertResult = new TaskCompletionSource <Tuple <bool, bool> >();
            var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport);
            await deviceClient.SetMethodHandlerAsync(methodName,
                                                     (request, context) =>
            {
                assertResult.SetResult(new Tuple <bool, bool>(request.Name.Equals(methodName), request.DataAsJson.Equals(serviceRequestJson)));
                return(Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(deviceResponseJson), 200)));
            },
                                                     null);

            ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(hubConnectionString);
            Task <CloudToDeviceMethodResult> directResponseFuture = serviceClient.InvokeDeviceMethodAsync(
                deviceInfo.Item1,
                new CloudToDeviceMethod(methodName, TimeSpan.FromMinutes(5)).SetPayloadJson(serviceRequestJson)
                );

            Assert.IsTrue(assertResult.Task.Result.Item1, "Method name is not matching with the send data");
            Assert.IsTrue(assertResult.Task.Result.Item2, "Json data is not matching with the send data");
            CloudToDeviceMethodResult response = await directResponseFuture;

            Assert.AreEqual(200, response.Status);
            Assert.AreEqual(deviceResponseJson, response.GetPayloadAsJson());

            await deviceClient.CloseAsync();

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
Beispiel #4
0
        // This function create a device with x509 cert and connect to the iothub on the transport specified.
        // Then a message is send from the service client.
        // It then verifies the message is received on the device.
        private async Task ReceiveSingleMessageX509(Client.TransportType transport)
        {
            Tuple <string, string> deviceInfo    = TestUtil.CreateDeviceWithX509(DevicePrefix, hostName, registryManager);
            ServiceClient          serviceClient = ServiceClient.CreateFromConnectionString(hubConnectionString);

            string certBase64 = Environment.GetEnvironmentVariable("IOTHUB_X509_PFX_CERTIFICATE");

            Byte[] buff = Convert.FromBase64String(certBase64);

            var cert = new X509Certificate2(buff);

            var auth         = new DeviceAuthenticationWithX509Certificate(deviceInfo.Item1, cert);
            var deviceClient = DeviceClient.Create(deviceInfo.Item2, auth, transport);
            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);

            await deviceClient.CloseAsync();

            await serviceClient.CloseAsync();

            TestUtil.RemoveDevice(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.
        private async Task SendSingleMessageX509(Client.TransportType transport)
        {
            Tuple <string, string> deviceInfo = TestUtil.CreateDeviceWithX509(DevicePrefix, hostName, registryManager);

            EventHubClient   eventHubClient;
            EventHubReceiver eventHubReceiver = CreateEventHubReceiver(deviceInfo.Item1, out eventHubClient);

            string certBase64 = Environment.GetEnvironmentVariable("IOTHUB_X509_PFX_CERTIFICATE");

            Byte[] buff = Convert.FromBase64String(certBase64);

            var cert = new X509Certificate2(buff);

            var auth         = new DeviceAuthenticationWithX509Certificate(deviceInfo.Item1, cert);
            var deviceClient = DeviceClient.Create(deviceInfo.Item2, auth, transport);
            await deviceClient.OpenAsync();

            string payload;
            string p1Value;

            Client.Message testMessage = ComposeD2CTestMessage(out payload, out p1Value);
            await deviceClient.SendEventAsync(testMessage);

            var events = await eventHubReceiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(5));

            VerifyTestMessage(events, deviceInfo.Item1, payload, p1Value);

            await deviceClient.CloseAsync();

            await eventHubClient.CloseAsync();

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
Beispiel #6
0
        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);
            await deviceClient.SetMethodHandlerAsync(MethodName,
                                                     (request, context) =>
            {
                assertResult.SetResult(new Tuple <bool, bool>(request.Name.Equals(MethodName), request.DataAsJson.Equals(ServiceRequestJson)));
                return(Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(DeviceResponseJson), 200)));
            },
                                                     null);

            await ServiceSendMethodAndVerifyResponse(deviceInfo.Item1, MethodName, DeviceResponseJson, ServiceRequestJson, assertResult);

            // send error command
            await deviceClient.SendEventAsync(TestUtil.ComposeErrorInjectionProperties(faultType, reason, delayInSec));

            // allow time for connection recovery
            await Task.Delay(TimeSpan.FromSeconds(3));

            assertResult = new TaskCompletionSource <Tuple <bool, bool> >();
            await ServiceSendMethodAndVerifyResponse(deviceInfo.Item1, MethodName, DeviceResponseJson, ServiceRequestJson, assertResult);

            await deviceClient.CloseAsync();

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
Beispiel #7
0
        private async Task SendSingleMessage(Client.TransportType transport)
        {
            Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager);

            EventHubClient   eventHubClient;
            EventHubReceiver eventHubReceiver = CreateEventHubReceiver(deviceInfo.Item1, out eventHubClient);

            var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport);
            await deviceClient.OpenAsync();

            string payload;
            string p1Value;

            Client.Message testMessage = ComposeD2CTestMessage(out payload, out p1Value);
            await deviceClient.SendEventAsync(testMessage);

            var events = await eventHubReceiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(5));

            VerifyTestMessage(events, deviceInfo.Item1, payload, p1Value);

            await deviceClient.CloseAsync();

            await eventHubClient.CloseAsync();

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
Beispiel #8
0
        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);

            EventHubClient   eventHubClient;
            EventHubReceiver eventHubReceiver = CreateEventHubReceiver(deviceInfo.Item1, out eventHubClient);

            var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport);

            deviceClient.OperationTimeoutInMilliseconds = (uint)retryDurationInMilliSec;
            await deviceClient.OpenAsync();

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

            await eventHubClient.CloseAsync();

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);

            sequentialTestSemaphore.Release(1);
        }
Beispiel #9
0
        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);
            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);

            await deviceClient.CloseAsync();

            await serviceClient.CloseAsync();

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
        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);

            var deviceTwin = await deviceClient.GetTwinAsync();
            Assert.AreEqual<String>(deviceTwin.Properties.Reported[propName].ToString(), propValue1);

            // send error command
            await deviceClient.SendEventAsync(TestUtil.ComposeErrorInjectionProperties(faultType, reason, delayInSec));
            Thread.Sleep(1000);

            deviceTwin = await deviceClient.GetTwinAsync();
            Assert.AreEqual<String>(deviceTwin.Properties.Reported[propName].ToString(), propValue1);

            var propValue2 = Guid.NewGuid().ToString();
            props[propName] = propValue2;
            await deviceClient.UpdateReportedPropertiesAsync(props);

            deviceTwin = await deviceClient.GetTwinAsync();
            Assert.AreEqual<String>(deviceTwin.Properties.Reported[propName].ToString(), propValue2);

            await deviceClient.CloseAsync();
            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
        private async Task SendMethodAndRespondRecovery(Client.TransportType transport, string faultType, string reason, int delayInSec)
        {
            Tuple <string, string> deviceInfo = TestUtil.CreateDevice("E2E_Method_CSharp_", hostName, registryManager);
            string deviceResponseJson         = "{\"name\":\"e2e_test\"}";
            string serviceRequestJson         = "{\"a\":123}";
            string methodName = "MethodE2ETest";

            var          assertResult = new TaskCompletionSource <Tuple <bool, bool> >();
            DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport);
            await deviceClient.SetMethodHandlerAsync(methodName,
                                                     (request, context) =>
            {
                assertResult.SetResult(new Tuple <bool, bool>(request.Name.Equals(methodName), request.DataAsJson.Equals(serviceRequestJson)));
                return(Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(deviceResponseJson), 200)));
            },
                                                     null);

            await ServiceSendMethodAndVerifyResponse(deviceInfo.Item1, methodName, deviceResponseJson, serviceRequestJson, assertResult);

            // send error command
            await deviceClient.SendEventAsync(TestUtil.ComposeErrorInjectionProperties(faultType, reason, delayInSec));

            Debug.WriteLine("Drop command sent from device client.");

            // allow time for connection recovery
            await Task.Delay(TimeSpan.FromSeconds(3));

            assertResult = new TaskCompletionSource <Tuple <bool, bool> >();
            await ServiceSendMethodAndVerifyResponse(deviceInfo.Item1, methodName, deviceResponseJson, serviceRequestJson, assertResult);

            await deviceClient.CloseAsync();

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
Beispiel #12
0
        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);

                string certBase64 = Environment.GetEnvironmentVariable("IOTHUB_X509_PFX_CERTIFICATE");
                Byte[] buff       = Convert.FromBase64String(certBase64);
                var    cert       = new X509Certificate2(buff);

                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);
            }

            ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(hubConnectionString);
            FileNotificationReceiver <FileNotification> fileNotificationReceiver = serviceClient.GetFileNotificationReceiver();

            FileNotification fileNotification;

            while (true)
            {
                // Receive the file notification from queue
                fileNotification = await fileNotificationReceiver.ReceiveAsync(TimeSpan.FromSeconds(20));

                Assert.IsNotNull(fileNotification);
                await fileNotificationReceiver.CompleteAsync(fileNotification);

                if (deviceInfo.Item1 == fileNotification.DeviceId)
                {
                    break;
                }
            }

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

            await serviceClient.CloseAsync();

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
Beispiel #13
0
        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);
            await deviceClient.OpenAsync();

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

            var twinPatch = new Twin();

            twinPatch.Properties.Desired[propName] = propValue;
            await registryManager.UpdateTwinAsync(deviceInfo.Item1, twinPatch, "*");

            await tcs.Task;

            // send error command
            await deviceClient.SendEventAsync(TestUtil.ComposeErrorInjectionProperties(faultType, reason, delayInSec));

            await Task.Delay(TimeSpan.FromSeconds(3));

            tcs       = new TaskCompletionSource <bool>();
            twinPatch = new Twin();
            twinPatch.Properties.Desired[propName] = propValue;
            await registryManager.UpdateTwinAsync(deviceInfo.Item1, twinPatch, "*");

            await tcs.Task;

            await deviceClient.CloseAsync();

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
Beispiel #14
0
        // 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.
        private async Task SendSingleMessageX509(Client.TransportType transport)
        {
            Tuple <string, string> deviceInfo = TestUtil.CreateDeviceWithX509(DevicePrefix, hostName, registryManager);

            EventHubClient   eventHubClient;
            EventHubReceiver eventHubReceiver = CreateEventHubReceiver(deviceInfo.Item1, out eventHubClient);

            string certBase64 = Environment.GetEnvironmentVariable("IOTHUB_X509_PFX_CERTIFICATE");

            Byte[] buff = Convert.FromBase64String(certBase64);

            var cert = new X509Certificate2(buff);

            var auth         = new DeviceAuthenticationWithX509Certificate(deviceInfo.Item1, cert);
            var deviceClient = DeviceClient.Create(deviceInfo.Item2, auth, 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(5));

                    isReceived = VerifyTestMessage(events, deviceInfo.Item1, payload, p1Value);
                }
                sw.Stop();

                Assert.IsTrue(isReceived, "Message is not received.");
            }
            finally
            {
                await deviceClient.CloseAsync();

                await eventHubReceiver.CloseAsync();

                await eventHubClient.CloseAsync();

                TestUtil.RemoveDevice(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, "*");
            
            var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport);
            var deviceTwin = await deviceClient.GetTwinAsync();
            Assert.AreEqual<string>(deviceTwin.Properties.Desired[propName].ToString(), propValue);
            await deviceClient.CloseAsync();
            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
Beispiel #16
0
        async Task sendSingleMessage(Client.TransportType transport)
        {
            Tuple <string, string> deviceInfo     = TestUtil.CreateDevice("E2E_Message_CSharp_", hostName, registryManager);
            EventHubClient         eventHubClient = EventHubClient.CreateFromConnectionString(hubConnectionString, "messages/events");
            var    eventHubPartitionsCount        = eventHubClient.GetRuntimeInformation().PartitionCount;
            string partition         = EventHubPartitionKeyResolver.ResolveToPartition(deviceInfo.Item1, eventHubPartitionsCount);
            string consumerGroupName = Environment.GetEnvironmentVariable("IOTHUB_EVENTHUB_CONSUMER_GROUP");

            if (consumerGroupName == null)
            {
                consumerGroupName = "$Default";
            }
            EventHubReceiver eventHubReceiver = eventHubClient.GetConsumerGroup(consumerGroupName).CreateReceiver(partition, DateTime.Now);

            var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport);
            await deviceClient.OpenAsync();

            string dataBuffer    = Guid.NewGuid().ToString();
            string propertyName  = "property1";
            string propertyValue = Guid.NewGuid().ToString();

            Client.Message eventMessage = new Client.Message(Encoding.UTF8.GetBytes(dataBuffer));
            eventMessage.Properties[propertyName] = propertyValue;
            await deviceClient.SendEventAsync(eventMessage);

            var events = await eventHubReceiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(5));

            foreach (var eventData in events)
            {
                var data = Encoding.UTF8.GetString(eventData.GetBytes());
                Assert.AreEqual(data, dataBuffer);

                var connectionDeviceId = eventData.SystemProperties["iothub-connection-device-id"].ToString();
                Assert.AreEqual(connectionDeviceId.ToUpper(), deviceInfo.Item1.ToUpper());

                Assert.AreEqual(eventData.Properties.Count, 1);
                var property = eventData.Properties.Single();
                Assert.AreEqual(property.Key, propertyName);
                Assert.AreEqual(property.Value, propertyValue);
            }

            await deviceClient.CloseAsync();

            await eventHubClient.CloseAsync();

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
        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();

                TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
                sequentialTestSemaphore.Release(1);
            }
        }
        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);

            var deviceTwin = await deviceClient.GetTwinAsync();
            Assert.AreEqual<String>(deviceTwin.Properties.Reported[propName].ToString(), propValue);

            await deviceClient.CloseAsync();
            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
        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);
            await deviceClient.CloseAsync();

            var serviceTwin = await registryManager.GetTwinAsync(deviceInfo.Item1);
            Assert.AreEqual<string>(serviceTwin.Properties.Reported[propName].ToString(), propValue);

            TestContext.WriteLine("verified " + serviceTwin.Properties.Reported[propName].ToString() + "=" + propValue);
            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
Beispiel #20
0
        private async Task SendMessageRecovery(Client.TransportType transport,
                                               string faultType, string reason, int delayInSec, int durationInSec = 0)
        {
            await sequentialTestSemaphore.WaitAsync();

            Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager);

            EventHubClient   eventHubClient;
            EventHubReceiver eventHubReceiver = CreateEventHubReceiver(deviceInfo.Item1, out eventHubClient);

            var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport);
            await deviceClient.OpenAsync();

            string payload, p1Value;

            Client.Message testMessage = ComposeD2CTestMessage(out payload, out p1Value);
            await deviceClient.SendEventAsync(testMessage);

            var events = await eventHubReceiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(5));

            VerifyTestMessage(events, deviceInfo.Item1, payload, p1Value);

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

            events = await eventHubReceiver.ReceiveAsync(int.MaxValue, TimeSpan.FromSeconds(5));

            VerifyTestMessage(events, deviceInfo.Item1, payload, p1Value);

            await deviceClient.CloseAsync();

            await eventHubClient.CloseAsync();

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);

            sequentialTestSemaphore.Release(1);
        }
        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();

            TestUtil.RemoveDevice(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));
                }
                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);
            }

            FileNotification fileNotification = await verifyTask;

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

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
Beispiel #23
0
        private async Task SendMethodAndRespond(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.SetResult(new Tuple <bool, bool>(request.Name.Equals(MethodName), request.DataAsJson.Equals(ServiceRequestJson)));
                return(Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(DeviceResponseJson), 200)));
            },
                                                     null);

            await ServiceSendMethodAndVerifyResponse(deviceInfo.Item1, MethodName, DeviceResponseJson, ServiceRequestJson, assertResult);

            await deviceClient.CloseAsync();

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
        private async Task SendSingleMessage(Client.TransportType transport)
        {
            Tuple <string, string> deviceInfo = TestUtil.CreateDevice(DevicePrefix, hostName, registryManager);
            EventHubClient         eventHubClient;
            EventHubReceiver       eventHubReceiver = CreateEventHubReceiver(deviceInfo.Item1, out eventHubClient);
            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(5));

                    isReceived = VerifyTestMessage(events, deviceInfo.Item1, payload, p1Value);
                }
                sw.Stop();

                Assert.IsTrue(isReceived, "Message is not received.");
            }
            finally
            {
                await deviceClient.CloseAsync();

                await eventHubReceiver.CloseAsync();

                await eventHubClient.CloseAsync();

                TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
            }
        }
Beispiel #25
0
        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("E2E_Twin_CSharp_", hostName, registryManager);
            var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport);
            await deviceClient.OpenAsync();

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

            var twinPatch = new Twin();

            twinPatch.Properties.Desired[propName] = propValue;
            await registryManager.UpdateTwinAsync(deviceInfo.Item1, twinPatch, "*");

            await tcs.Task;
            await deviceClient.CloseAsync();

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
        async Task uploadFile(Client.TransportType transport, string filename)
        {
            Tuple <string, string> deviceInfo = TestUtil.CreateDevice("E2E_FileUpload_CSharp_", hostName, registryManager);
            var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport);

            using (FileStream fileStreamSource = new FileStream(filename, FileMode.Open, FileAccess.Read))
            {
                await deviceClient.UploadToBlobAsync(filename, fileStreamSource);
            }

            ServiceClient serviceClient = ServiceClient.CreateFromConnectionString(hubConnectionString);
            FileNotificationReceiver <FileNotification> fileNotificationReceiver = serviceClient.GetFileNotificationReceiver();

            FileNotification fileNotification;

            while (true)
            {
                // Receive the file notification from queue
                fileNotification = await fileNotificationReceiver.ReceiveAsync(TimeSpan.FromSeconds(20));

                Assert.IsNotNull(fileNotification);
                await fileNotificationReceiver.CompleteAsync(fileNotification);

                if (deviceInfo.Item1 == fileNotification.DeviceId)
                {
                    break;
                }
            }

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

            await serviceClient.CloseAsync();

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
        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);
            }

            FileNotification fileNotification = await VerifyFileNotification(deviceInfo);

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

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
Beispiel #28
0
        async Task receiveSingleMessage(Client.TransportType transport)
        {
            Tuple <string, string> deviceInfo    = TestUtil.CreateDevice("E2E_Message_CSharp_", hostName, registryManager);
            ServiceClient          serviceClient = ServiceClient.CreateFromConnectionString(hubConnectionString);
            string dataBuffer     = Guid.NewGuid().ToString();
            var    serviceMessage = new Message(Encoding.ASCII.GetBytes(dataBuffer));

            serviceMessage.MessageId = Guid.NewGuid().ToString();

            string propertyName  = "property1";
            string propertyValue = Guid.NewGuid().ToString();

            serviceMessage.Properties[propertyName] = propertyValue;

            var deviceClient = DeviceClient.CreateFromConnectionString(deviceInfo.Item2, transport);
            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));
            }

            await serviceClient.OpenAsync();

            await serviceClient.SendAsync(deviceInfo.Item1, serviceMessage);

            var wait = true;

            Stopwatch sw = new Stopwatch();

            sw.Start();
            while (wait)
            {
                Client.Message receivedMessage;

                if (transport == Client.TransportType.Http1)
                {
                    // Long-polling is not supported in http
                    receivedMessage = await deviceClient.ReceiveAsync();
                }
                else
                {
                    receivedMessage = await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(1));
                }

                if (receivedMessage != null)
                {
                    string messageData = Encoding.ASCII.GetString(receivedMessage.GetBytes());
                    Assert.AreEqual(messageData, dataBuffer);

                    Assert.AreEqual(receivedMessage.Properties.Count, 1);
                    var prop = receivedMessage.Properties.Single();
                    Assert.AreEqual(prop.Key, propertyName);
                    Assert.AreEqual(prop.Value, propertyValue);

                    await deviceClient.CompleteAsync(receivedMessage);

                    wait = false;
                }

                if (sw.Elapsed.TotalSeconds > 5)
                {
                    throw new TimeoutException("Test is running longer than expected.");
                }
            }
            sw.Stop();

            await deviceClient.CloseAsync();

            await serviceClient.CloseAsync();

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
Beispiel #29
0
        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;

            bool assertStatusChange = false;

            deviceClient.SetConnectionStatusChangesHandler((status, statusChangeReason) =>
            {
                if (assertStatusChange)
                {
                    if (setConnectionStatusChangesHandlerCount == 0)
                    {
                        Assert.AreEqual(ConnectionStatus.Disconnected_Retrying, status);
                        Assert.AreEqual(ConnectionStatusChangeReason.No_Network, statusChangeReason);
                    }
                    else
                    {
                        Assert.AreEqual(ConnectionStatus.Connected, status);
                        Assert.AreEqual(ConnectionStatusChangeReason.Connection_Ok, statusChangeReason);
                    }
                }

                lastConnectionStatus             = status;
                lastConnectionStatusChangeReason = statusChangeReason;
                setConnectionStatusChangesHandlerCount++;
            });

            await deviceClient.SetMethodHandlerAsync(MethodName,
                                                     (request, context) =>
            {
                assertResult.SetResult(new Tuple <bool, bool>(request.Name.Equals(MethodName), request.DataAsJson.Equals(ServiceRequestJson)));
                return(Task.FromResult(new MethodResponse(Encoding.UTF8.GetBytes(DeviceResponseJson), 200)));
            },
                                                     null);

            if (transport != Client.TransportType.Http1)
            {
                Assert.AreEqual(1, setConnectionStatusChangesHandlerCount);
                Assert.AreEqual(ConnectionStatus.Connected, lastConnectionStatus);
                Assert.AreEqual(ConnectionStatusChangeReason.Connection_Ok, lastConnectionStatusChangeReason);
            }

            await ServiceSendMethodAndVerifyResponse(deviceInfo.Item1, MethodName, DeviceResponseJson, ServiceRequestJson, assertResult);

            // allow time for connection recovery
            setConnectionStatusChangesHandlerCount = 0;
            assertStatusChange = true;

            // send error command
            await deviceClient.SendEventAsync(TestUtil.ComposeErrorInjectionProperties(faultType, reason, delayInSec));

            Stopwatch sw = new Stopwatch();

            sw.Start();
            while (sw.Elapsed.Minutes < 3 && setConnectionStatusChangesHandlerCount < 2)
            {
                await Task.Delay(1000);
            }

            assertResult = new TaskCompletionSource <Tuple <bool, bool> >();
            await ServiceSendMethodAndVerifyResponse(deviceInfo.Item1, MethodName, DeviceResponseJson, ServiceRequestJson, assertResult);

            setConnectionStatusChangesHandlerCount = 0;

            assertStatusChange = false;
            await deviceClient.SetMethodHandlerAsync(MethodName, null, null);

            if (transport != Client.TransportType.Http1)
            {
                Assert.AreEqual(1, setConnectionStatusChangesHandlerCount);
                Assert.AreEqual(ConnectionStatus.Disabled, lastConnectionStatus);
                Assert.AreEqual(ConnectionStatusChangeReason.Client_Close, lastConnectionStatusChangeReason);
            }

            TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
        }
        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();

                TestUtil.RemoveDevice(deviceInfo.Item1, registryManager);
                sequentialTestSemaphore.Release(1);
            }
        }