private async void SettingsUpdated()
        {
            connectionString = AppSettings.ConnectionString;
            deviceId         = AppSettings.DeviceId;

            if (!string.IsNullOrEmpty(connectionString) && !string.IsNullOrEmpty(deviceId))
            {
                if (client != null)
                {
                    await client.CloseAsync();
                }

                if (registryManager != null)
                {
                    await registryManager.CloseAsync();
                }

                client          = ServiceClient.CreateFromConnectionString(connectionString);
                registryManager = RegistryManager.CreateFromConnectionString(connectionString);
                GetDeviceTwinState();

                MessagingCenter.Subscribe <App>(this, "RefreshTimerElapsed", (sender) => GetDeviceTwinState());
            }

            OnPropertyChanged(nameof(IsRegistered));
            ((Command)DoorOneCommand).ChangeCanExecute();
            ((Command)DoorTwoCommand).ChangeCanExecute();
        }
Exemple #2
0
        async Task Cleanup(DeviceClient deviceClient, ServiceClient serviceClient, RegistryManager rm, string deviceName)
        {
            if (deviceClient != null)
            {
                try
                {
                    await deviceClient.CloseAsync();
                }
                catch
                {
                    // ignore
                }
            }

            if (serviceClient != null)
            {
                await serviceClient.CloseAsync();
            }

            // wait for the connection to be closed on the Edge side
            await Task.Delay(TimeSpan.FromSeconds(20));

            if (rm != null)
            {
                await RegistryManagerHelper.RemoveDevice(deviceName, rm);

                await rm.CloseAsync();
            }
        }
Exemple #3
0
        public async Task BulkOperations_UpdateTwins2Module_Ok()
        {
            var tagName  = Guid.NewGuid().ToString();
            var tagValue = Guid.NewGuid().ToString();

            TestModule testModule = await TestModule.GetTestModuleAsync(DevicePrefix, ModulePrefix).ConfigureAwait(false);

            using (RegistryManager registryManager = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString))
            {
                Twin twin = await registryManager.GetTwinAsync(testModule.DeviceId, testModule.Id).ConfigureAwait(false);

                twin.Tags          = new TwinCollection();
                twin.Tags[tagName] = tagValue;

                var result = await registryManager.UpdateTwins2Async(new List <Twin> {
                    twin
                }, true).ConfigureAwait(false);

                Assert.IsTrue(result.IsSuccessful, $"UpdateTwins2Async error:\n{ResultErrorsToString(result)}");

                Twin twinUpd = await registryManager.GetTwinAsync(testModule.DeviceId, testModule.Id).ConfigureAwait(false);

                Assert.AreEqual(twin.DeviceId, twinUpd.DeviceId, "Device ID changed");
                Assert.AreEqual(twin.ModuleId, twinUpd.ModuleId, "Module ID changed");
                Assert.IsNotNull(twinUpd.Tags, "Twin.Tags is null");
                Assert.IsTrue(twinUpd.Tags.Contains(tagName), "Twin doesn't contain the tag");
                Assert.AreEqual((string)twin.Tags[tagName], (string)twinUpd.Tags[tagName], "Tag value changed");

                await registryManager.CloseAsync().ConfigureAwait(false);
            }
        }
Exemple #4
0
 public static void UnInitializeEnvironment(RegistryManager rm)
 {
     Task.Run(async() =>
     {
         await rm.CloseAsync();
     }).Wait();
 }
Exemple #5
0
        public async Task MultipleSendersSingleReceiverTest(ITransportSettings[] transportSettings)
        {
            int.TryParse(ConfigHelper.TestConfig["StressTest_MessagesCount_MultipleSenders"], out int messagesCount);
            TestModule sender1  = null;
            TestModule sender2  = null;
            TestModule receiver = null;

            string edgeDeviceConnectionString = await SecretsHelper.GetSecretFromConfigKey("edgeCapableDeviceConnStrKey");

            IotHubConnectionStringBuilder connectionStringBuilder = IotHubConnectionStringBuilder.Create(edgeDeviceConnectionString);
            RegistryManager rm = RegistryManager.CreateFromConnectionString(edgeDeviceConnectionString);

            try
            {
                sender1 = await this.GetModule(rm, connectionStringBuilder.HostName, connectionStringBuilder.DeviceId, "senderA", false, transportSettings);

                sender2 = await this.GetModule(rm, connectionStringBuilder.HostName, connectionStringBuilder.DeviceId, "senderB", false, transportSettings);

                receiver = await this.GetModule(rm, connectionStringBuilder.HostName, connectionStringBuilder.DeviceId, "receiverA", true, transportSettings);

                Task <int> task1 = sender1.SendMessagesByCountAsync("output1", 0, messagesCount, TimeSpan.FromMinutes(8));
                Task <int> task2 = sender2.SendMessagesByCountAsync("output1", messagesCount, messagesCount, TimeSpan.FromMinutes(8));

                int[] results = await Task.WhenAll(task1, task2);

                int sentMessagesCount = results.Sum();
                Assert.Equal(messagesCount * 2, sentMessagesCount);

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

                ISet <int> receivedMessages = receiver.GetReceivedMessageIndices();

                Assert.Equal(sentMessagesCount, receivedMessages.Count);
            }
            finally
            {
                if (rm != null)
                {
                    await rm.CloseAsync();
                }

                if (sender1 != null)
                {
                    await sender1.Disconnect();
                }

                if (sender2 != null)
                {
                    await sender2.Disconnect();
                }

                if (receiver != null)
                {
                    await receiver.Disconnect();
                }
            }

            // wait for the connection to be closed on the Edge side
            await Task.Delay(TimeSpan.FromSeconds(20));
        }
Exemple #6
0
        private async Task updateDeviceIdsComboBoxes(bool runIfNullOrEmpty = true)
        {
            if (!String.IsNullOrEmpty(activeIoTHubConnectionString) || runIfNullOrEmpty)
            {
                List <string>   deviceIdsForEvent        = new List <string>();
                List <string>   deviceIdsForC2DMessage   = new List <string>();
                List <string>   deviceIdsForDeviceMethod = new List <string>();
                RegistryManager registryManager          = RegistryManager.CreateFromConnectionString(activeIoTHubConnectionString);

                var devices = await registryManager.GetDevicesAsync(MAX_COUNT_OF_DEVICES);

                foreach (var device in devices)
                {
                    deviceIdsForEvent.Add(device.Id);
                    deviceIdsForC2DMessage.Add(device.Id);
                    deviceIdsForDeviceMethod.Add(device.Id);
                }
                await registryManager.CloseAsync();

                deviceIDsComboBoxForEvent.DataSource = deviceIdsForEvent.OrderBy(c => c).ToList();
                deviceIDsComboBoxForCloudToDeviceMessage.DataSource = deviceIdsForC2DMessage.OrderBy(c => c).ToList();
                deviceIDsComboBoxForDeviceMethod.DataSource         = deviceIdsForDeviceMethod.OrderBy(c => c).ToList();

                deviceIDsComboBoxForEvent.SelectedIndex = deviceSelectedIndexForEvent;
                deviceIDsComboBoxForCloudToDeviceMessage.SelectedIndex = deviceSelectedIndexForC2DMessage;
                deviceIDsComboBoxForDeviceMethod.SelectedIndex         = deviceSelectedIndexForDeviceMethod;
            }
        }
 private static async Task DisconnectFromHub()
 {
     if (registryManager != null)
     {
         await registryManager.CloseAsync();
     }
 }
Exemple #8
0
        private async void deleteButton_Click(object sender, EventArgs e)
        {
            try
            {
                RegistryManager registryManager  = RegistryManager.CreateFromConnectionString(activeIoTHubConnectionString);
                string          selectedDeviceId = devicesGridView.CurrentRow.Cells[0].Value.ToString();
                using (new CenterDialog(this))
                {
                    var dialogResult = MessageBox.Show($"Are you sure you want to delete the following device?\n[{selectedDeviceId}]", "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (dialogResult == DialogResult.Yes)
                    {
                        await registryManager.RemoveDeviceAsync(selectedDeviceId);

                        using (new CenterDialog(this))
                        {
                            MessageBox.Show("Device deleted successfully!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        await updateDevicesGridView();

                        await registryManager.CloseAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                using (new CenterDialog(this))
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Exemple #9
0
        public async Task MultipleSendersMultipleReceivers_Count_Test(ITransportSettings[] transportSettings)
        {
            // The modules limit is because ProtocolGatewayFixture currently uses a fixed EdgeDevice
            // Need to figure out a way to create ProtocolGatewayFixture with configurable EdgeDevice
            const int ModulesCount = 2;

            int.TryParse(ConfigHelper.TestConfig["StressTest_MessagesCount_MultipleSendersMultipleReceivers"], out int messagesCount);
            List <TestModule> senders   = null;
            List <TestModule> receivers = null;

            string edgeDeviceConnectionString = await SecretsHelper.GetSecretFromConfigKey("edgeCapableDeviceConnStrKey");

            IotHubConnectionStringBuilder connectionStringBuilder = IotHubConnectionStringBuilder.Create(edgeDeviceConnectionString);
            RegistryManager rm = RegistryManager.CreateFromConnectionString(edgeDeviceConnectionString);

            try
            {
                senders = await this.GetModules(rm, connectionStringBuilder.HostName, connectionStringBuilder.DeviceId, "sender", ModulesCount, false, transportSettings);

                receivers = await this.GetModules(rm, connectionStringBuilder.HostName, connectionStringBuilder.DeviceId, "receiver", ModulesCount, true, transportSettings);

                TimeSpan timeout = TimeSpan.FromMinutes(2);
                IEnumerable <Task <int> > tasks = senders.Select(s => s.SendMessagesByCountAsync("output1", 0, messagesCount, timeout));

                int[] results = await Task.WhenAll(tasks);

                int sentMessagesCount = results.Sum();
                Assert.Equal(messagesCount * ModulesCount, sentMessagesCount);

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

                int receivedMessagesCount = 0;
                receivers.ForEach(r => receivedMessagesCount += r.GetReceivedMessageIndices().Count);

                Assert.Equal(sentMessagesCount, receivedMessagesCount);
            }
            finally
            {
                if (rm != null)
                {
                    await rm.CloseAsync();
                }

                if (senders != null)
                {
                    await Task.WhenAll(senders.Select(s => s.Disconnect()));
                }

                if (receivers != null)
                {
                    await Task.WhenAll(receivers.Select(r => r.Disconnect()));
                }

                await(rm?.CloseAsync() ?? Task.CompletedTask);
            }

            // wait for the connection to be closed on the Edge side
            await Task.Delay(TimeSpan.FromSeconds(20));
        }
Exemple #10
0
        async Task SendTelemetryMultipleInputsTest(ITransportSettings[] transportSettings)
        {
            int        messagesCount = 30;
            TestModule sender        = null;
            TestModule receiver      = null;

            string edgeDeviceConnectionString = await SecretsHelper.GetSecretFromConfigKey("edgeCapableDeviceConnStrKey");

            IotHubConnectionStringBuilder connectionStringBuilder = IotHubConnectionStringBuilder.Create(edgeDeviceConnectionString);
            RegistryManager rm = RegistryManager.CreateFromConnectionString(edgeDeviceConnectionString);

            try
            {
                sender = await TestModule.CreateAndConnect(rm, connectionStringBuilder.HostName, connectionStringBuilder.DeviceId, "sender11", transportSettings);

                receiver = await TestModule.CreateAndConnect(rm, connectionStringBuilder.HostName, connectionStringBuilder.DeviceId, "receiver11", transportSettings);

                await receiver.SetupReceiveMessageHandler("input1");

                await receiver.SetupReceiveMessageHandler("input2");

                Task <int> task1 = sender.SendMessagesByCountAsync("output1", 0, messagesCount, TimeSpan.FromMinutes(2), TimeSpan.FromSeconds(2));
                Task <int> task2 = sender.SendMessagesByCountAsync("output2", 0, messagesCount, TimeSpan.FromMinutes(2), TimeSpan.FromSeconds(3));

                int[] sentMessagesCounts = await Task.WhenAll(task1, task2);

                Assert.Equal(messagesCount, sentMessagesCounts[0]);
                Assert.Equal(messagesCount, sentMessagesCounts[1]);

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

                ISet <int> receivedMessages = receiver.GetReceivedMessageIndices("input1");
                Assert.Equal(messagesCount, receivedMessages.Count);

                receivedMessages = receiver.GetReceivedMessageIndices("input2");
                Assert.Equal(messagesCount, receivedMessages.Count);
            }
            finally
            {
                if (rm != null)
                {
                    await rm.CloseAsync();
                }

                if (sender != null)
                {
                    await sender.Disconnect();
                }

                if (receiver != null)
                {
                    await receiver.Disconnect();
                }
            }

            // wait for the connection to be closed on the Edge side
            await Task.Delay(TimeSpan.FromSeconds(10));
        }
        private async void deleteButton_Click(object sender, EventArgs e)
        {
            try
            {
                deleteDeviceButton.Enabled = false;
                RegistryManager registryManager = RegistryManager.CreateFromConnectionString(activeIoTHubConnectionString);

                List <string> selectedDeviceIds = new List <string>();

                foreach (DataGridViewRow item in devicesGridView.SelectedRows)
                {
                    selectedDeviceIds.Add(item.Cells[0].Value.ToString());
                }

                using (new CenterDialog(this))
                {
                    string deleteMessage;
                    if (selectedDeviceIds.Count > 40)
                    {
                        deleteMessage = $"Are you sure you want to delete the {selectedDeviceIds.Count} devices?";
                    }
                    else
                    {
                        deleteMessage = $"Are you sure you want to delete the following devices?\n{String.Join(Environment.NewLine, selectedDeviceIds)}";
                    }

                    var dialogResult = MessageBox.Show(deleteMessage, "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (dialogResult == DialogResult.Yes)
                    {
                        foreach (string deviceId in selectedDeviceIds)
                        {
                            await registryManager.RemoveDeviceAsync(deviceId);
                        }

                        using (new CenterDialog(this))
                        {
                            MessageBox.Show("Device(s) deleted successfully!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                        await updateDevicesGridView();

                        await registryManager.CloseAsync();
                    }
                }
            }
            catch (Exception ex)
            {
                using (new CenterDialog(this))
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            finally
            {
                deleteDeviceButton.Enabled = true;
            }
        }
        static void Main(string[] args)
        {
            MyRegistryManager = RegistryManager.CreateFromConnectionString(ConnectionString);
            RegisterDeviceAsync().Wait();
            AddTagsAndQuery().Wait();

            Console.WriteLine("\nPress Enter to exit!");
            Console.ReadLine();
            MyRegistryManager.CloseAsync().Wait();
        }
Exemple #13
0
        private async Task Twin_ServiceDoesNotCreateNullPropertyInCollection(Client.TransportType transport)
        {
            var propName1      = Guid.NewGuid().ToString();
            var propName2      = Guid.NewGuid().ToString();
            var propEmptyValue = "{}";

            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(DevicePrefix).ConfigureAwait(false);

            RegistryManager registryManager = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString);

            using (var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport))
            {
                await deviceClient.UpdateReportedPropertiesAsync(new TwinCollection
                {
                    [propName1] = null
                }).ConfigureAwait(false);

                var serviceTwin = await registryManager.GetTwinAsync(testDevice.Id).ConfigureAwait(false);

                Assert.IsFalse(serviceTwin.Properties.Reported.Contains(propName1));

                await deviceClient.UpdateReportedPropertiesAsync(new TwinCollection
                {
                    [propName1] = new TwinCollection
                    {
                        [propName2] = null
                    }
                }).ConfigureAwait(false);

                serviceTwin = await registryManager.GetTwinAsync(testDevice.Id).ConfigureAwait(false);

                Assert.IsTrue(serviceTwin.Properties.Reported.Contains(propName1));
                String value1 = serviceTwin.Properties.Reported[propName1].ToString();

                Assert.AreEqual(value1, propEmptyValue);

                await deviceClient.UpdateReportedPropertiesAsync(new TwinCollection
                {
                    [propName1] = new TwinCollection
                    {
                        [propName2] = null
                    }
                }).ConfigureAwait(false);

                serviceTwin = await registryManager.GetTwinAsync(testDevice.Id).ConfigureAwait(false);

                Assert.IsTrue(serviceTwin.Properties.Reported.Contains(propName1));
                String value2 = serviceTwin.Properties.Reported[propName1].ToString();
                Assert.AreEqual(value2, propEmptyValue);

                await deviceClient.CloseAsync().ConfigureAwait(false);
            }

            await registryManager.CloseAsync().ConfigureAwait(false);
        }
Exemple #14
0
        private async Task RegistryManagerUpdateDesiredPropertyAsync(string deviceId, string propName, string propValue)
        {
            RegistryManager registryManager = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString);
            var             twinPatch       = new Twin();

            twinPatch.Properties.Desired[propName] = propValue;

            await registryManager.UpdateTwinAsync(deviceId, twinPatch, "*").ConfigureAwait(false);

            await registryManager.CloseAsync().ConfigureAwait(false);
        }
Exemple #15
0
        protected async Task StoreLimitValidationTestAsync()
        {
            int        messagesCount = DefaultMessageCount;
            TestModule sender        = null;
            TestModule receiver      = null;

            string edgeDeviceConnectionString = await SecretsHelper.GetSecretFromConfigKey("edgeCapableDeviceConnStrKey");

            IotHubConnectionStringBuilder connectionStringBuilder = IotHubConnectionStringBuilder.Create(edgeDeviceConnectionString);
            RegistryManager rm   = RegistryManager.CreateFromConnectionString(edgeDeviceConnectionString);
            Guid            guid = Guid.NewGuid();

            try
            {
                await Task.Delay(TimeSpan.FromSeconds(10));

                sender = await TestModule.CreateAndConnect(rm, connectionStringBuilder.HostName, connectionStringBuilder.DeviceId, "sender1forstorelimits", StoreLimitTestTransportSettings, 0);

                // Send messages to ensure that the max storage size limit is reached.
                int sentMessagesCount = 0;
                await Assert.ThrowsAsync <IotHubThrottledException>(
                    async() => sentMessagesCount = await sender.SendMessagesByCountAndSizeAsync("output1", 0, messagesCount, MessageSize, TimeSpan.FromSeconds(2), TimeSpan.FromMinutes(2)));

                // Wait some more time to allow the delivered messages to be cleaned up due to TTL expiry.
                await Task.Delay(TimeSpan.FromSeconds(60));

                // Sending a few more messages should now succeed.
                messagesCount     = 2;
                sentMessagesCount = await sender.SendMessagesByCountAndSizeAsync("output1", 0, messagesCount, MessageSize, TimeSpan.FromSeconds(2), TimeSpan.FromMinutes(2));

                Assert.Equal(messagesCount, sentMessagesCount);
            }
            finally
            {
                if (rm != null)
                {
                    await rm.CloseAsync();
                }

                if (sender != null)
                {
                    await sender.Disconnect();
                }

                if (receiver != null)
                {
                    await receiver.Disconnect();
                }
            }

            // wait for the connection to be closed on the Edge side
            await Task.Delay(TimeSpan.FromSeconds(10));
        }
Exemple #16
0
 protected virtual void Dispose(bool disposing)
 {
     if (!_disposed)
     {
         if (disposing)
         {
             if (_deviceManager != null)
             {
                 _deviceManager.CloseAsync().Wait();
             }
         }
         _disposed = true;
     }
 }
        private async void buttonDisconnectFromIoTHub_Click(object sender, RoutedEventArgs e)
        {
            try{
                await registryManager.CloseAsync();

                buttonDisconnectFromIoTHub.IsEnabled = false;
                buttonConnectToIoTHub.IsEnabled      = true;
                tbIoTHubStatus.Text = "Disconnected";
                registryManager     = null;
                AddLog("Disconnected from IoT Hub.");
            }
            catch (Exception ex)
            {
                AddLog(ex.Message, true);
            }
        }
        public async Task AddDeviceIfNotExistsAsync(string deviceId, IOptions <IoTHubSettings> _iotHubSettings)
        {
            if (manager == null)
            {
                CreateManager(_iotHubSettings);
            }
            try
            {
                await manager.AddDeviceAsync(new Device(deviceId));
            }
            catch (Exception e)
            {
                Debug.WriteLine(e);
            }

            await manager.CloseAsync();
        }
Exemple #19
0
 private void updateDeviceButton_Click(object sender, EventArgs e)
 {
     try
     {
         string           selectedDeviceId = devicesGridView.CurrentRow.Cells[0].Value.ToString();
         RegistryManager  registryManager  = RegistryManager.CreateFromConnectionString(activeIoTHubConnectionString);
         DeviceUpdateForm updateForm       = new DeviceUpdateForm(registryManager, MAX_COUNT_OF_DEVICES, selectedDeviceId);
         updateForm.ShowDialog(this);
         updateForm.Dispose();
         updateDevicesGridView();
         registryManager.CloseAsync();
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
 }
        /// <summary>
        /// Factory method.
        /// IMPORTANT: Not thread safe!
        /// </summary>
        /// <param name="namePrefix"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static async Task <TestDevice> GetTestDeviceAsync(string namePrefix, TestDeviceType type = TestDeviceType.Sasl)
        {
            string prefix = namePrefix + type + "_";

            if (!s_deviceCache.TryGetValue(prefix, out TestDevice testDevice))
            {
                string deviceName = prefix + Guid.NewGuid();
                s_log.WriteLine($"{nameof(GetTestDeviceAsync)}: Device with prefix {prefix} not found. Removing old devices.");

                // Delete existing devices named this way and create a new one.
                RegistryManager rm = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString);

                s_log.WriteLine($"{nameof(GetTestDeviceAsync)}: Creating device {deviceName} with type {type}.");

                Client.IAuthenticationMethod auth = null;

                Device requestDevice = new Device(deviceName);
                if (type == TestDeviceType.X509)
                {
                    requestDevice.Authentication = new AuthenticationMechanism()
                    {
                        X509Thumbprint = new X509Thumbprint()
                        {
                            PrimaryThumbprint = Configuration.IoTHub.GetCertificateWithPrivateKey().Thumbprint
                        }
                    };

                    auth = new DeviceAuthenticationWithX509Certificate(deviceName, Configuration.IoTHub.GetCertificateWithPrivateKey());
                }

                Device device = await rm.AddDeviceAsync(requestDevice).ConfigureAwait(false);

                s_log.WriteLine($"{nameof(GetTestDeviceAsync)}: Pausing for {DelayAfterDeviceCreationSeconds}s after device was created.");
                await Task.Delay(DelayAfterDeviceCreationSeconds * 1000).ConfigureAwait(false);

                s_deviceCache[prefix] = new TestDevice(device, auth);

                await rm.CloseAsync().ConfigureAwait(false);
            }

            TestDevice ret = s_deviceCache[prefix];

            s_log.WriteLine($"{nameof(GetTestDeviceAsync)}: Using device {ret.Id}.");
            return(ret);
        }
        private async Task Twin_ServiceSetsDesiredPropertyAndDeviceReceivesEvent_WithObseleteCallbackSetter(Client.TransportType transport)
        {
            var tcs       = new TaskCompletionSource <bool>();
            var propName  = Guid.NewGuid().ToString();
            var propValue = Guid.NewGuid().ToString();

            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(DevicePrefix).ConfigureAwait(false);

            RegistryManager registryManager = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString);

            var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport);

#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).ConfigureAwait(false);

#pragma warning restore CS0618

            var twinPatch = new Twin();
            twinPatch.Properties.Desired[propName] = propValue;
            await registryManager.UpdateTwinAsync(testDevice.Id, twinPatch, "*").ConfigureAwait(false);

            await tcs.Task.ConfigureAwait(false);

            await deviceClient.CloseAsync().ConfigureAwait(false);

            await registryManager.CloseAsync().ConfigureAwait(false);
        }
Exemple #22
0
        private async Task UpdateDevicesGridView()
        {
            try
            {
                listDevicesButton.Text = "Refresh";
                devicesListed          = true;
                RegistryManager registryManager = RegistryManager.CreateFromConnectionString(activeIoTHubConnectionString);
                var             devices         = await registryManager.GetDevicesAsync(1000);

                updateDevicesGridView();
                await registryManager.CloseAsync();
            }
            catch (Exception ex)
            {
                listDevicesButton.Text = "List";
                devicesListed          = false;
                MessageBox.Show(String.Format("Unable to retrieve list of devices.\n{0}", ex.Message), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        async Task <Device> SetupDeviceAsync(string iotHubConnectionString)
        {
            IotHubConnectionStringBuilder hubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(iotHubConnectionString);
            bool deviceNameProvided;

            this.deviceId = ConfigurationManager.AppSettings["End2End.DeviceName"];
            if (!string.IsNullOrEmpty(this.deviceId))
            {
                deviceNameProvided = true;
            }
            else
            {
                deviceNameProvided = false;
                this.deviceId      = Guid.NewGuid().ToString("N");
            }

            RegistryManager registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString);

            if (!deviceNameProvided)
            {
                await registryManager.AddDeviceAsync(new Device(this.deviceId));

                this.ScheduleCleanup(async() =>
                {
                    await registryManager.RemoveDeviceAsync(this.deviceId);
                    await registryManager.CloseAsync();
                });
            }

            Device device = await registryManager.GetDeviceAsync(this.deviceId);

            this.deviceSas =
                new Client.SharedAccessSignatureBuilder
            {
                Key        = device.Authentication.SymmetricKey.PrimaryKey,
                Target     = $"{hubConnectionStringBuilder.HostName}/devices/{this.deviceId}",
                KeyName    = null,
                TimeToLive = TimeSpan.FromMinutes(20)
            }.ToSignature();

            return(device);
        }
Exemple #24
0
        private async void sasTokenButton_Click(object sender, EventArgs e)
        {
            try
            {
                RegistryManager registryManager = RegistryManager.CreateFromConnectionString(activeIoTHubConnectionString);
                SASTokenForm    sasForm         = new SASTokenForm(registryManager, MAX_COUNT_OF_DEVICES, iotHubHostName);
                sasForm.ShowDialog(this);
                sasForm.Dispose();
                await updateDevicesGridView();

                await registryManager.CloseAsync();
            }
            catch (Exception ex)
            {
                using (new CenterDialog(this))
                {
                    MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Exemple #25
0
        private async Task Twin_ServiceSetsDesiredPropertyAndDeviceReceivesItOnNextGet(Client.TransportType transport)
        {
            var propName = Guid.NewGuid().ToString();
            var propValue = Guid.NewGuid().ToString();

            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(DevicePrefix).ConfigureAwait(false);

            RegistryManager registryManager = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString);

            var twinPatch = new Twin();
            twinPatch.Properties.Desired[propName] = propValue;
            await registryManager.UpdateTwinAsync(testDevice.Id, twinPatch, "*").ConfigureAwait(false);
            
            var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, transport);
            var deviceTwin = await deviceClient.GetTwinAsync().ConfigureAwait(false);
            Assert.AreEqual<string>(deviceTwin.Properties.Desired[propName].ToString(), propValue);

            await deviceClient.CloseAsync().ConfigureAwait(false);
            await registryManager.CloseAsync().ConfigureAwait(false);
        }
Exemple #26
0
        async Task RunTestCase(ITransportSettings[] transportSettings, Func <DeviceClient, string, RegistryManager, Task> testCase)
        {
            string iotHubConnectionString = await SecretsHelper.GetSecretFromConfigKey("iotHubConnStrKey");

            RegistryManager rm = RegistryManager.CreateFromConnectionString(iotHubConnectionString);

            (DeviceClient deviceClient, string deviceName) = await InitializeDeviceClient(rm, iotHubConnectionString, transportSettings);

            try
            {
                await testCase(deviceClient, deviceName, rm);
            }
            finally
            {
                await deviceClient.CloseAsync();

                await RegistryManagerHelper.RemoveDevice(deviceName, rm);

                await rm.CloseAsync();
            }
        }
        /// <summary>
        /// Factory method.
        /// IMPORTANT: Not thread safe!
        /// </summary>
        /// <param name="namePrefix"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public static async Task <TestModule> GetTestModuleAsync(string deviceNamePrefix, string moduleNamePrefix)
        {
            var        log        = TestLogging.GetInstance();
            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(deviceNamePrefix).ConfigureAwait(false);

            string deviceName = testDevice.Id;
            string moduleName = moduleNamePrefix + Guid.NewGuid();

            RegistryManager rm = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString);

            log.WriteLine($"{nameof(GetTestModuleAsync)}: Creating module for device {deviceName}.");

            Module requestModule = new Module(deviceName, moduleName);
            Module module        = await rm.AddModuleAsync(requestModule).ConfigureAwait(false);

            await rm.CloseAsync().ConfigureAwait(false);

            TestModule ret = new TestModule(module);

            log.WriteLine($"{nameof(GetTestModuleAsync)}: Using device {ret.DeviceId} with module {ret.Id}.");
            return(ret);
        }
Exemple #28
0
        private async Task Twin_ClientHandlesRejectionInvalidPropertyName(Client.TransportType transport)
        {
            var propName1 = "$" + Guid.NewGuid().ToString();
            var propName2 = Guid.NewGuid().ToString();

            TestDevice testDevice = await TestDevice.GetTestDeviceAsync(DevicePrefix).ConfigureAwait(false);

            RegistryManager registryManager = RegistryManager.CreateFromConnectionString(Configuration.IoTHub.ConnectionString);

            using (var deviceClient = DeviceClient.CreateFromConnectionString(testDevice.ConnectionString, 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(testDevice.Id).ConfigureAwait(false);

                Assert.IsFalse(serviceTwin.Properties.Reported.Contains(propName1));

                await deviceClient.CloseAsync().ConfigureAwait(false);
            }

            await registryManager.CloseAsync().ConfigureAwait(false);
        }
Exemple #29
0
        async Task SendLargeMessageHandleExceptionTest(ITransportSettings[] transportSettings)
        {
            TestModule sender = null;

            string edgeDeviceConnectionString = await SecretsHelper.GetSecretFromConfigKey("edgeCapableDeviceConnStrKey");

            IotHubConnectionStringBuilder connectionStringBuilder = IotHubConnectionStringBuilder.Create(edgeDeviceConnectionString);
            RegistryManager rm = RegistryManager.CreateFromConnectionString(edgeDeviceConnectionString);

            try
            {
                sender = await TestModule.CreateAndConnect(rm, connectionStringBuilder.HostName, connectionStringBuilder.DeviceId, "sender1", transportSettings);

                Exception ex = null;
                try
                {
                    // create a large message
                    var message = new Message(new byte[400 * 1000]);
                    await sender.SendMessageAsync("output1", message);
                }
                catch (Exception e)
                {
                    ex = e;
                }

                Assert.NotNull(ex);
            }
            finally
            {
                if (rm != null)
                {
                    await rm.CloseAsync();
                }
            }

            // wait for the connection to be closed on the Edge side
            await Task.Delay(TimeSpan.FromSeconds(10));
        }
        private async void buttonDisconnect_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                await registryManager.CloseAsync();

                await serviceClient.CloseAsync();

                WriteLog("Disconnected.");
                buttonConnect.IsEnabled    = true;
                buttonDisconnect.IsEnabled = false;

                buttonDeviceSelect.IsEnabled = false;
                buttonAlert.IsEnabled        = false;
                buttonStop.IsEnabled         = false;
                buttonDeviceTwin.IsEnabled   = false;

                registedDeviceNames.Clear();
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }