Esempio n. 1
0
        async Task <ICloudProxy> GetCloudProxyFromConnectionStringKey(string connectionStringConfigKey, IEdgeHub edgeHub)
        {
            const int ConnectionPoolSize     = 10;
            string    deviceConnectionString = await SecretsHelper.GetSecretFromConfigKey(connectionStringConfigKey);

            string deviceId       = ConnectionStringHelper.GetDeviceId(deviceConnectionString);
            string iotHubHostName = ConnectionStringHelper.GetHostName(deviceConnectionString);
            string sasKey         = ConnectionStringHelper.GetSharedAccessKey(deviceConnectionString);
            var    converters     = new MessageConverterProvider(
                new Dictionary <Type, IMessageConverter>()
            {
                { typeof(Message), new DeviceClientMessageConverter() },
                { typeof(Twin), new TwinMessageConverter() },
                { typeof(TwinCollection), new TwinCollectionMessageConverter() }
            });

            var credentialsCache = Mock.Of <ICredentialsCache>();
            var productInfoStore = Mock.Of <IProductInfoStore>();
            ICloudConnectionProvider cloudConnectionProvider = new CloudConnectionProvider(
                converters,
                ConnectionPoolSize,
                new ClientProvider(),
                Option.None <UpstreamProtocol>(),
                Mock.Of <Util.ITokenProvider>(),
                Mock.Of <IDeviceScopeIdentitiesCache>(),
                credentialsCache,
                Mock.Of <IIdentity>(i => i.Id == $"{deviceId}/$edgeHub"),
                TimeSpan.FromMinutes(60),
                true,
                TimeSpan.FromSeconds(20),
                Option.None <IWebProxy>(),
                productInfoStore);

            cloudConnectionProvider.BindEdgeHub(edgeHub);

            var    clientTokenProvider = new ClientTokenProvider(new SharedAccessKeySignatureProvider(sasKey), iotHubHostName, deviceId, TimeSpan.FromHours(1));
            string token = await clientTokenProvider.GetTokenAsync(Option.None <TimeSpan>());

            var deviceIdentity    = new DeviceIdentity(iotHubHostName, deviceId);
            var clientCredentials = new TokenCredentials(deviceIdentity, token, string.Empty, false);

            Try <ICloudConnection> cloudConnection = await cloudConnectionProvider.Connect(clientCredentials, (_, __) => { });

            Assert.True(cloudConnection.Success);
            Assert.True(cloudConnection.Value.IsActive);
            Assert.True(cloudConnection.Value.CloudProxy.HasValue);
            return(cloudConnection.Value.CloudProxy.OrDefault());
        }
Esempio n. 2
0
        public async Task QueryClient_GetAllDevicesTwinsWithTag()
        {
            string testDeviceId = $"QueryDevice{GetRandom()}";

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

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

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

                    tryCount++;

                    // Adding a delay to account for query cache sync.
                    await Delay(5000);
                }

                twinsFound.Count.Should().Be(1);
                twinsFound.First().DeviceId.Should().Be(testDeviceId);

                // Delete the device
                // Deleting the device happens in the finally block as cleanup.
            }
            finally
            {
                await CleanupAsync(client, device).ConfigureAwait(false);
            }
        }
Esempio n. 3
0
        private void OpenSelectDeviceDialog(DeviceIdentity selectedDeviceIdentity)
        {
            ResetGUI();
            DisplayMessage("Device configuration");
            EnableGUI(false);

            try
            {
                SelectDeviceWindow selectDevice = new SelectDeviceWindow(selectedDeviceIdentity, this);
                if (_fpScanner != null)
                {
                    selectDevice.FingerPrintScanner = _fpScanner;
                }

                selectDevice.ShowDialog();

                if (selectDevice.DialogResult.HasValue && selectDevice.DialogResult.Value)
                {
                    DisplayMessage("Opening device");

                    _fpScanner = selectDevice.FingerPrintScanner;
                    if (_fpScanner != null)
                    {
                        ResetGUI();
                        EnableGUI(true);

                        /*
                         * if(xamlListBoxUsers.Items.Count > 0)
                         * {
                         *  xamlListBoxUsers.SelectedIndex = 0;
                         * }
                         */
                    }
                }
                else
                {
                    DisplayError("No device selected");
                    if (selectDevice.FingerPrintScanner != null)
                    {
                        selectDevice.FingerPrintScanner.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayError(ex.Message);
            }
        }
 internal async Task <AmqpIotSendingLink> OpenTelemetrySenderLinkAsync(
     DeviceIdentity deviceIdentity,
     TimeSpan timeout)
 {
     return(await OpenSendingAmqpLinkAsync(
                deviceIdentity,
                _amqpSession,
                null,
                null,
                CommonConstants.DeviceEventPathTemplate,
                CommonConstants.ModuleEventPathTemplate,
                AmqpIotConstants.TelemetrySenderLinkSuffix,
                null,
                timeout)
            .ConfigureAwait(false));
 }
 internal async Task <AmqpIotReceivingLink> OpenMessageReceiverLinkAsync(
     DeviceIdentity deviceIdentity,
     TimeSpan timeout)
 {
     return(await OpenReceivingAmqpLinkAsync(
                deviceIdentity,
                _amqpSession,
                null,
                (byte)ReceiverSettleMode.Second,
                CommonConstants.DeviceBoundPathTemplate,
                CommonConstants.ModuleBoundPathTemplate,
                AmqpIotConstants.TelemetryReceiveLinkSuffix,
                null,
                timeout)
            .ConfigureAwait(false));
 }
Esempio n. 6
0
        public void SetInactiveMakesInactive()
        {
            var twinHandler         = Mock.Of <ITwinHandler>();
            var m2mHandler          = Mock.Of <IModuleToModuleMessageHandler>();
            var c2dHandler          = Mock.Of <ICloud2DeviceMessageHandler>();
            var directMethodHandler = Mock.Of <IDirectMethodHandler>();
            var identity            = new DeviceIdentity("hub", "device_id");

            var sut = new DeviceProxy(identity, twinHandler, m2mHandler, c2dHandler, directMethodHandler);

            Assert.True(sut.IsActive);

            sut.SetInactive();

            Assert.False(sut.IsActive);
        }
 internal async Task <AmqpIotReceivingLink> OpenEventsReceiverLinkAsync(
     DeviceIdentity deviceIdentity,
     TimeSpan timeout)
 {
     return(await OpenReceivingAmqpLinkAsync(
                deviceIdentity,
                _amqpSession,
                null,
                (byte)ReceiverSettleMode.First,
                CommonConstants.DeviceEventPathTemplate,
                CommonConstants.ModuleEventPathTemplate,
                AmqpIotConstants.EventsReceiverLinkSuffix,
                null,
                timeout)
            .ConfigureAwait(false));
 }
        // Token: 0x06000C55 RID: 3157 RVA: 0x00041294 File Offset: 0x0003F494
        public MailboxLogger(MailboxSession mailboxSession, DeviceIdentity deviceIdentity, bool clearOldLogs)
        {
            ArgumentValidator.ThrowIfNull("mailboxSession", mailboxSession);
            ArgumentValidator.ThrowIfNull("deviceIdentity", deviceIdentity);
            string clientName = deviceIdentity.DeviceType + "_" + deviceIdentity.DeviceId;

            this.mailboxLoggerHelper = new MailboxLogger(mailboxSession, deviceIdentity.Protocol, clientName);
            if (this.Enabled)
            {
                this.currentDataTable = new Dictionary <MailboxLogDataName, string>();
                if (clearOldLogs)
                {
                    this.mailboxLoggerHelper.ClearOldLogs(5000, 10485760L);
                }
            }
        }
Esempio n. 9
0
        public async Task TestConnectionReauthentication_AuthenticationFailureTest()
        {
            // Arrange
            var      connectionManager          = new Mock <IConnectionManager>(MockBehavior.Strict);
            var      authenticator              = new Mock <IAuthenticator>(MockBehavior.Strict);
            var      credentialsStore           = new Mock <ICredentialsCache>(MockBehavior.Strict);
            var      deviceScopeIdentitiesCache = Mock.Of <IDeviceScopeIdentitiesCache>();
            TimeSpan reauthFrequency            = TimeSpan.FromSeconds(3);

            var deviceIdentity = new DeviceIdentity(IoTHubHostName, "d1");
            var moduleIdentity = new ModuleIdentity(IoTHubHostName, "d1", "m1");
            var clients        = new List <IIdentity>
            {
                deviceIdentity,
                moduleIdentity
            };

            connectionManager.Setup(c => c.GetConnectedClients()).Returns(clients);
            connectionManager.Setup(c => c.RemoveDeviceConnection("d1")).Returns(Task.CompletedTask);
            connectionManager.Setup(c => c.RemoveDeviceConnection("d1/m1")).Returns(Task.CompletedTask);

            var deviceCredentials = Mock.Of <IClientCredentials>(c => c.Identity == deviceIdentity && c.AuthenticationType == AuthenticationType.SasKey);
            var moduleCredentials = Mock.Of <IClientCredentials>(c => c.Identity == moduleIdentity && c.AuthenticationType == AuthenticationType.SasKey);

            credentialsStore.Setup(c => c.Get(deviceIdentity)).ReturnsAsync(Option.Some(deviceCredentials));
            credentialsStore.Setup(c => c.Get(moduleIdentity)).ReturnsAsync(Option.Some(moduleCredentials));

            authenticator.Setup(a => a.ReauthenticateAsync(deviceCredentials)).ReturnsAsync(false);
            authenticator.Setup(a => a.ReauthenticateAsync(moduleCredentials)).ReturnsAsync(false);

            // Act
            var connectionReauthenticator = new ConnectionReauthenticator(connectionManager.Object, authenticator.Object, credentialsStore.Object, deviceScopeIdentitiesCache, reauthFrequency, Mock.Of <IIdentity>(e => e.Id == "ed/$edgeHub"));

            connectionReauthenticator.Init();

            // Assert
            connectionManager.Verify(c => c.GetConnectedClients(), Times.Never);

            await Task.Delay(reauthFrequency + TimeSpan.FromSeconds(1));

            connectionManager.Verify(c => c.GetConnectedClients(), Times.Once);
            connectionManager.VerifyAll();
            authenticator.VerifyAll();
            credentialsStore.VerifyAll();
            Mock.Get(deviceScopeIdentitiesCache).VerifyAll();
        }
Esempio n. 10
0
 internal static DeviceInfo GetDeviceInfo(MailboxSession mailboxSession, MobileDeviceIdParameter identity)
 {
     DeviceInfo[] allDeviceInfo = DeviceInfo.GetAllDeviceInfo(mailboxSession, MobileClientType.EAS | MobileClientType.MOWA);
     if (allDeviceInfo != null)
     {
         foreach (DeviceInfo deviceInfo in allDeviceInfo)
         {
             string protocol = null;
             DeviceIdentity.TryGetProtocol(identity.ClientType, out protocol);
             if (deviceInfo.DeviceIdentity.Equals(identity.DeviceId, identity.DeviceType, protocol))
             {
                 return(deviceInfo);
             }
         }
     }
     return(null);
 }
Esempio n. 11
0
        public async Task DesiredUpdateRequiresVersion()
        {
            var(connectionRegistry, identityProvider) = GetHandlerDependencies();
            var connector = GetConnector();

            var identity = new DeviceIdentity("hub", "device_id");
            var twin     = new EdgeMessage.Builder(new byte[] { 1, 2, 3 }).Build();

            var sut = new TwinHandler(connectionRegistry, identityProvider);

            sut.SetConnector(connector);

            await sut.SendDesiredPropertiesUpdate(twin, identity, true);

            Mock.Get(connector)
            .Verify(c => c.SendAsync(It.IsAny <string>(), It.IsAny <byte[]>()), Times.Never());
        }
Esempio n. 12
0
        private Task <PayloadVoid> OnGetAll(DeviceIdentity devid, KeyValueData data)
        {
            foreach (var item in _valuesDig)
            {
                item.Value.LastSyncTime = DateTime.MinValue;
            }
            foreach (var item in _valuesStr)
            {
                item.Value.LastSyncTime = DateTime.MinValue;
            }
            foreach (var item in _settingsDict)
            {
                item.Value.LastSyncTime = DateTime.MinValue;
            }

            return(Task.FromResult(PayloadVoid.Default));
        }
 internal async Task <AmqpIotSendingLink> OpenTwinSenderLinkAsync(
     DeviceIdentity deviceIdentity,
     string correlationIdSuffix,
     TimeSpan timeout)
 {
     return(await OpenSendingAmqpLinkAsync(
                deviceIdentity,
                _amqpSession,
                (byte)SenderSettleMode.Settled,
                (byte)ReceiverSettleMode.First,
                CommonConstants.DeviceTwinPathTemplate,
                CommonConstants.ModuleTwinPathTemplate,
                AmqpIotConstants.TwinSenderLinkSuffix,
                AmqpIotConstants.TwinCorrelationIdPrefix + correlationIdSuffix,
                timeout)
            .ConfigureAwait(false));
 }
Esempio n. 14
0
        public async Task SendsMessageDataAsPayload()
        {
            var capture   = new SendCapture();
            var connector = GetConnector(capture);

            var(connectionRegistry, identityProvider) = GetHandlerDependencies();
            var identity = new DeviceIdentity("hub", "device_id");
            var method   = new DirectMethodRequest("12345", "method", new byte[] { 1, 2, 3 }, TimeSpan.FromSeconds(5));

            var sut = new DirectMethodHandler(connectionRegistry, identityProvider);

            sut.SetConnector(connector);

            await sut.CallDirectMethodAsync(method, identity, true);

            Assert.Equal(new byte[] { 1, 2, 3 }, capture.Content);
        }
Esempio n. 15
0
        public async Task EncodesDeviceNameInTopic()
        {
            var capture   = new SendCapture();
            var connector = GetConnector(capture);

            var(connectionRegistry, identityProvider) = GetHandlerDependencies();
            var identity = new DeviceIdentity("hub", "device_id");
            var method   = new DirectMethodRequest("12345", "method", new byte[] { 1, 2, 3 }, TimeSpan.FromSeconds(5));

            var sut = new DirectMethodHandler(connectionRegistry, identityProvider);

            sut.SetConnector(connector);

            await sut.CallDirectMethodAsync(method, identity, true);

            Assert.Equal("$edgehub/device_id/methods/post/method/?$rid=" + method.CorrelationId, capture.Topic);
        }
Esempio n. 16
0
        public async Task DevicesClient_DeviceTwinLifecycle()
        {
            string testDeviceId = $"TwinLifecycleDevice{GetRandom()}";

            DeviceIdentity device = null;

            IotHubServiceClient client = GetClient();

            try
            {
                // Create a device
                // Creating a device also creates a twin for the device.
                Response <DeviceIdentity> createResponse = await client.Devices.CreateOrUpdateIdentityAsync(
                    new DeviceIdentity
                {
                    DeviceId = testDeviceId
                }).ConfigureAwait(false);

                device = createResponse.Value;

                // Get the device twin
                Response <TwinData> getResponse = await client.Devices.GetTwinAsync(testDeviceId).ConfigureAwait(false);

                TwinData deviceTwin = getResponse.Value;

                deviceTwin.DeviceId.Should().BeEquivalentTo(testDeviceId, "DeviceId on the Twin should match that of the device.");

                // Update device twin
                string propName  = "username";
                string propValue = "userA";
                deviceTwin.Properties.Desired.Add(new KeyValuePair <string, object>(propName, propValue));

                // TODO: (azabbasi) We should leave the IfMatchPrecondition to be the default value once we know more about the fix.
                Response <TwinData> updateResponse = await client.Devices.UpdateTwinAsync(deviceTwin, IfMatchPrecondition.UnconditionalIfMatch).ConfigureAwait(false);

                updateResponse.Value.Properties.Desired.Where(p => p.Key == propName).First().Value.Should().Be(propValue, "Desired property value is incorrect.");

                // Delete the device
                // Deleting the device happens in the finally block as cleanup.
            }
            finally
            {
                await CleanupAsync(client, device).ConfigureAwait(false);
            }
        }
        public SelectDeviceWindow2(DeviceIdentity selectedDeviceIdentity, Window owner)
        {
            _selectedDeviceIdentity = selectedDeviceIdentity;
            this.Owner = owner;

            InitializeComponent();

            this.Closing += SelectDeviceWindow_Closing;

            displayMessage("Loading Devices");
            xamlButtonOK.IsEnabled = false;

            _thread = new Thread(() =>
            {
                try
                {
                    DeviceInformations[] dinfos = FPScanner.GetAttachedDevices(_selectedDeviceIdentity); //Get all Fingerprint Scanners

                    //Display all Fingerprint-Scanners in GUI
                    Application.Current.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        xamlProgressBar.Visibility = System.Windows.Visibility.Hidden;
                        displayMessage("Select Fingerprint-Scanner");
                        foreach (DeviceInformations dinfo in dinfos)
                        {
                            DeviceInfos di = new DeviceInfos(dinfo.index, dinfo.name);
                            xamlListBoxDevices.Items.Add(di);
                        }
                        if (xamlListBoxDevices.Items.Count > 0)
                        {
                            xamlListBoxDevices.SelectedIndex = 0;
                        }
                    }));
                }
                catch (Exception ex)
                {
                    Application.Current.Dispatcher.BeginInvoke((Action)(() =>
                    {
                        DialogResult = false;
                        MessageBox.Show(ex.Message, "ERROR");
                    }));
                }
            });
            _thread.Start();
        }
Esempio n. 18
0
        public void Receive(Message received_message)
        {
            /*
             * D2C messages are filtered for a macAddress property and the absence of
             * a deviceName/deviceKey property or a source property set to "mapping"
             */
            bool macInProps      = received_message.Properties.ContainsKey("macAddress");
            bool identityinProps = received_message.Properties.ContainsKey("deviceKey") ||
                                   received_message.Properties.ContainsKey("deviceName");
            bool sourceIsMapping = received_message.Properties["source"] == "mapping";

            if (macInProps && !identityinProps && !sourceIsMapping)
            {
                //look up the device's deviceKey and DeviceId
                DeviceIdentity deviceIdentity = devices[received_message.Properties["macAddress"]];

                //Create a message to publish to the broker, that will be received by the IoT-Hub module
                Message msg = this.CreateMessage(deviceIdentity.DeviceId, deviceIdentity.DeviceKey,
                                                 received_message);

                //publish to broker
                this.Publish(msg);
            }

            /*
             * C2D messages are filtered for a "source" property set to "iothub" and a deviceName property
             */
            if (received_message.Properties["source"] == "iothub" &&
                received_message.Properties.ContainsKey("deviceName"))
            {
                Console.WriteLine("Mapper receives message from iothub");
                //look up the MAC-address
                string deviceId   = received_message.Properties["deviceName"];
                string macAddress = devices.Keys.Where(p => devices[p].DeviceId == deviceId).
                                    Single().ToString();

                //Create a message for the device
                //with the given MAC-address
                Message msg = CreateMessage(macAddress, null,
                                            received_message);

                //publish to broker
                this.Publish(msg);
            }
        }
        public async Task ModulesClient_BulkCreation_ModuleWithTwin()
        {
            string testDevicePrefix  = $"bulkDeviceWithTwin";
            string testModulePrefix  = $"bulkModuleWithTwin";
            string userPropertyName  = "user";
            string userPropertyValue = "userA";

            IotHubServiceClient client = GetClient();

            string         deviceId       = $"{testDevicePrefix}{GetRandom()}";
            DeviceIdentity deviceIdentity = new DeviceIdentity()
            {
                DeviceId = deviceId
            };

            IDictionary <string, object> desiredProperties = new Dictionary <string, object>
            {
                { userPropertyName, userPropertyValue }
            };

            // We will build a single device with multiple modules, and each module will have the same initial twin.
            IDictionary <ModuleIdentity, TwinData> modulesAndTwins = BuildModulesAndTwins(deviceId, testModulePrefix, BULK_MODULE_COUNT, desiredProperties);

            try
            {
                // Create device to house the modules
                await client.Devices.CreateOrUpdateIdentityAsync(deviceIdentity).ConfigureAwait(false);

                // Create the modules with an initial twin in bulk
                Response <BulkRegistryOperationResponse> createResponse = await client.Modules.CreateIdentitiesWithTwinAsync(modulesAndTwins).ConfigureAwait(false);

                // TODO: (azabbasi) Once the issue with the error parsing is resolved, include the error message in the message of the assert statement.
                Assert.IsTrue(createResponse.Value.IsSuccessful, "Bulk module creation ended with errors");

                // Verify that the desired properties were set
                // For quicker test run, we will only verify the first device on the list.
                Response <TwinData> getResponse = await client.Modules.GetTwinAsync(modulesAndTwins.Keys.First().DeviceId, modulesAndTwins.Keys.First().ModuleId).ConfigureAwait(false);

                getResponse.Value.Properties.Desired[userPropertyName].Should().Be(userPropertyValue);
            }
            finally
            {
                await CleanupAsync(client, deviceIdentity).ConfigureAwait(false);
            }
        }
Esempio n. 20
0
        public async Task EncodesDeviceNameInTopic()
        {
            var capture            = new SendCapture();
            var connector          = GetConnector(capture);
            var connectionRegistry = GetConnectionRegistry();
            var identity           = new DeviceIdentity("hub", "device_id");
            var message            = new EdgeMessage
                                     .Builder(new byte[] { 0x01, 0x02, 0x03 })
                                     .Build();

            var sut = new Cloud2DeviceMessageHandler(connectionRegistry);

            sut.SetConnector(connector);

            await sut.SendC2DMessageAsync(message, identity);

            Assert.Equal("$edgehub/device_id/messages/c2d/post/", capture.Topic);
        }
Esempio n. 21
0
        public async Task SendsMessageDataAsPayload()
        {
            var capture            = new SendCapture();
            var connector          = GetConnector(capture);
            var connectionRegistry = GetConnectionRegistry();
            var identity           = new DeviceIdentity("hub", "device_id");
            var message            = new EdgeMessage
                                     .Builder(new byte[] { 0x01, 0x02, 0x03 })
                                     .Build();

            var sut = new Cloud2DeviceMessageHandler(connectionRegistry);

            sut.SetConnector(connector);

            await sut.SendC2DMessageAsync(message, identity);

            Assert.Equal(new byte[] { 0x01, 0x02, 0x03 }, capture.Content);
        }
        public async Task DoesNotSendToDevice()
        {
            var connector          = GetConnector();
            var connectionRegistry = GetConnectionRegistry();
            var identity           = new DeviceIdentity("hub", "device_id");
            var message            = new EdgeMessage
                                     .Builder(new byte[] { 0x01, 0x02, 0x03 })
                                     .Build();

            var sut = new ModuleToModuleMessageHandler(connectionRegistry);

            sut.SetConnector(connector);

            await sut.SendModuleToModuleMessageAsync(message, "some_input", identity);

            Mock.Get(connector)
            .Verify(c => c.SendAsync(It.IsAny <string>(), It.IsAny <byte[]>()), Times.Never());
        }
        private static async Task <string> CallApiUsingDeviceIdentityAsync(DeviceIdentity deviceIdentity)
        {
            try
            {
                var client = ConfidentialClientApplicationBuilder.Create(deviceIdentity.AppId)
                             .WithTenantId(deviceIdentity.TenantId)
                             .WithClientSecret(deviceIdentity.ClientSecret)
                             .Build();
                var graphService = new GraphServiceClient(new ClientCredentialProvider(client));
                var users        = await graphService.Users.Request().GetAsync();

                return($"Successfully retrieved {users.Count} users from the Graph API using the identity of device \"{deviceIdentity.DisplayName}\" in tenant \"{deviceIdentity.TenantId}\", which demonstrates that the device is able to access the Graph API using its provisioned identity.");
            }
            catch (Exception exc)
            {
                return($"Failed to retrieve users from the Graph API using the identity of device \"{deviceIdentity.DisplayName}\" in tenant \"{deviceIdentity.TenantId}\": {exc.Message}.");
            }
        }
        public async Task ModulesClient_BulkCreation_OneAlreadyExists()
        {
            string testDevicePrefix = $"bulkDeviceCreate";
            string testModulePrefix = $"bulkModuleCreate";

            IotHubServiceClient client = GetClient();

            string deviceId       = $"{testDevicePrefix}{GetRandom()}";
            var    deviceIdentity = new DeviceIdentity()
            {
                DeviceId = deviceId
            };

            IList <ModuleIdentity> modules = BuildMultipleModules(deviceId, testModulePrefix, BULK_MODULE_COUNT - 1);

            try
            {
                // We first create a single device to house these bulk modules.
                await client.Devices.CreateOrUpdateIdentityAsync(deviceIdentity).ConfigureAwait(false);

                // Create a single module on that device that will be used to cause a conflict later
                await client.Modules.CreateOrUpdateIdentityAsync(
                    new ModuleIdentity()
                {
                    DeviceId = deviceId,
                    ModuleId = modules.ElementAt(0).ModuleId     //Use the same module id as the first module in the bulk list
                }).ConfigureAwait(false);

                // Create all devices
                Response <BulkRegistryOperationResponse> createResponse = await client.Modules.CreateIdentitiesAsync(modules).ConfigureAwait(false);

                // TODO: (azabbasi) Once the issue with the error parsing is resolved, include the error message in the message of the assert statement.
                Assert.IsTrue(createResponse.Value.IsSuccessful, "Bulk device creation failed with errors");
                createResponse.Value.Errors.Count.Should().Be(1);

                // Since there is exactly one error, it is safe to just look at the first one here
                var error = createResponse.Value.Errors.First();
                error.ModuleId.Should().Be(modules.ElementAt(0).ModuleId, "Error should have been tied to the moduleId that was already created");
            }
            finally
            {
                await CleanupAsync(client, deviceIdentity).ConfigureAwait(false);
            }
        }
        public async Task InitializeAndGetCloudProxyTest()
        {
            string iothubHostName = "test.azure-devices.net";
            string deviceId       = "device1";

            ITokenCredentials GetClientCredentialsWithNonExpiringToken()
            {
                string token    = TokenHelper.CreateSasToken(iothubHostName, DateTime.UtcNow.AddMinutes(10));
                var    identity = new DeviceIdentity(iothubHostName, deviceId);

                return(new TokenCredentials(identity, token, string.Empty, Option.None <string>(), Option.None <string>(), false));
            }

            IClient client = GetMockDeviceClient();
            var     deviceClientProvider = new Mock <IClientProvider>();

            deviceClientProvider.Setup(dc => dc.Create(It.IsAny <IIdentity>(), It.IsAny <ITokenProvider>(), It.IsAny <ITransportSettings[]>(), Option.None <string>()))
            .Returns(() => client);

            var transportSettings        = new ITransportSettings[] { new AmqpTransportSettings(TransportType.Amqp_Tcp_Only) };
            var messageConverterProvider = new MessageConverterProvider(new Dictionary <Type, IMessageConverter> {
                [typeof(TwinCollection)] = Mock.Of <IMessageConverter>()
            });

            ITokenCredentials          clientCredentialsWithNonExpiringToken = GetClientCredentialsWithNonExpiringToken();
            ClientTokenCloudConnection cloudConnection = await ClientTokenCloudConnection.Create(
                clientCredentialsWithNonExpiringToken,
                (_, __) => { },
                transportSettings,
                messageConverterProvider,
                deviceClientProvider.Object,
                Mock.Of <ICloudListener>(),
                TimeSpan.FromMinutes(60),
                true,
                TimeSpan.FromSeconds(20),
                DummyProductInfo,
                Option.None <string>());

            Option <ICloudProxy> cloudProxy = cloudConnection.CloudProxy;

            Assert.True(cloudProxy.HasValue);
            Assert.True(cloudProxy.OrDefault().IsActive);
            Mock.Get(client).Verify(c => c.OpenAsync(), Times.Once);
        }
Esempio n. 26
0
        public async Task CloseForwarded()
        {
            var connectionHandler   = Mock.Of <IConnectionRegistry>();
            var twinHandler         = Mock.Of <ITwinHandler>();
            var m2mHandler          = Mock.Of <IModuleToModuleMessageHandler>();
            var c2dHandler          = Mock.Of <ICloud2DeviceMessageHandler>();
            var directMethodHandler = Mock.Of <IDirectMethodHandler>();
            var identity            = new DeviceIdentity("hub", "device_id");

            Mock.Get(connectionHandler)
            .Setup(h => h.CloseConnectionAsync(It.Is <IIdentity>(i => i == identity)))
            .Returns(Task.CompletedTask);

            var sut = new DeviceProxy(identity, true, connectionHandler, twinHandler, m2mHandler, c2dHandler, directMethodHandler);

            await sut.CloseAsync(new Exception());

            Mock.Get(connectionHandler).VerifyAll();
        }
Esempio n. 27
0
        // Token: 0x06000556 RID: 1366 RVA: 0x0001EDD0 File Offset: 0x0001CFD0
        public static DeviceBehavior GetDeviceBehavior(Guid userGuid, DeviceIdentity deviceIdentity, GlobalInfo globalInfo, object traceObject, ProtocolLogger protocolLogger)
        {
            string token = DeviceBehaviorCache.GetToken(userGuid, deviceIdentity);

            globalInfo.DeviceBehavior.ProtocolLogger = protocolLogger;
            globalInfo.DeviceBehavior.CacheToken     = token;
            DeviceBehavior deviceBehavior;

            if (globalInfo.DeviceADObjectId == null || !DeviceBehaviorCache.TryGetAndRemoveValue(userGuid, deviceIdentity, out deviceBehavior))
            {
                if (protocolLogger != null)
                {
                    protocolLogger.SetValue(ProtocolLoggerData.DeviceBehaviorLoaded, 7);
                }
                AirSyncDiagnostics.TraceInfo(ExTraceGlobals.RequestsTracer, traceObject, "No device in cache, return GlobalInfo.DeviceBehavior");
                return(globalInfo.DeviceBehavior);
            }
            if (deviceBehavior.AutoBlockReason != globalInfo.DeviceBehavior.AutoBlockReason)
            {
                if (protocolLogger != null)
                {
                    protocolLogger.SetValue(ProtocolLoggerData.DeviceBehaviorLoaded, 1);
                }
                AirSyncDiagnostics.TraceInfo(ExTraceGlobals.RequestsTracer, traceObject, "AutoBlockReason changed, return GlobalInfo.DeviceBehavior");
                return(globalInfo.DeviceBehavior);
            }
            int num = globalInfo.DeviceBehavior.IsNewerThan(deviceBehavior.WhenLoaded);

            if (num > -1)
            {
                string arg = DeviceBehavior.dateCollections[num];
                if (protocolLogger != null)
                {
                    protocolLogger.SetValue(ProtocolLoggerData.DeviceBehaviorLoaded, num + 2);
                }
                AirSyncDiagnostics.TraceInfo <string>(ExTraceGlobals.RequestsTracer, traceObject, "{0} is newer, return GlobalInfo.DeviceBehavior", arg);
                return(globalInfo.DeviceBehavior);
            }
            AirSyncDiagnostics.TraceInfo(ExTraceGlobals.RequestsTracer, traceObject, "Return cached DeviceBehavior");
            deviceBehavior.Owner          = globalInfo;
            deviceBehavior.ProtocolLogger = protocolLogger;
            return(deviceBehavior);
        }
Esempio n. 28
0
        public async Task CloudProxyCallbackTest2()
        {
            string             device                   = "device1";
            var                deviceIdentity           = new DeviceIdentity("iotHub", device);
            IClientCredentials deviceCredentials        = new TokenCredentials(deviceIdentity, "dummyToken", DummyProductInfo, true);
            ITokenCredentials  updatedDeviceCredentials = new TokenCredentials(deviceIdentity, "dummyToken", DummyProductInfo, true);

            Action <string, CloudConnectionStatus> callback = null;
            var cloudProxy      = Mock.Of <ICloudProxy>(c => c.IsActive);
            var cloudConnection = Mock.Of <IClientTokenCloudConnection>(
                cp => cp.IsActive && cp.CloudProxy == Option.Some(cloudProxy));
            bool updatedCredentialsPassed = false;

            Mock.Get(cloudConnection).Setup(c => c.UpdateTokenAsync(updatedDeviceCredentials))
            .Callback(() => updatedCredentialsPassed = true)
            .ReturnsAsync(cloudProxy);
            var cloudProxyProviderMock = new Mock <ICloudConnectionProvider>();

            cloudProxyProviderMock.Setup(c => c.Connect(It.IsAny <IClientCredentials>(), It.IsAny <Action <string, CloudConnectionStatus> >()))
            .Callback <IClientCredentials, Action <string, CloudConnectionStatus> >((i, c) => callback = c)
            .ReturnsAsync(Try.Success(cloudConnection as ICloudConnection));

            var deviceProxy = new Mock <IDeviceProxy>(MockBehavior.Strict);

            var credentialsCache = new Mock <ICredentialsCache>(MockBehavior.Strict);

            credentialsCache.Setup(c => c.Get(deviceIdentity)).ReturnsAsync(Option.Some((IClientCredentials)updatedDeviceCredentials));
            var connectionManager = new ConnectionManager(cloudProxyProviderMock.Object, credentialsCache.Object, GetIdentityProvider());
            await connectionManager.AddDeviceConnection(deviceCredentials.Identity, deviceProxy.Object);

            Try <ICloudProxy> cloudProxyTry = await connectionManager.GetOrCreateCloudConnectionAsync(deviceCredentials);

            Assert.True(cloudProxyTry.Success);
            Assert.NotNull(callback);

            callback.Invoke(device, CloudConnectionStatus.TokenNearExpiry);

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

            deviceProxy.VerifyAll();
            credentialsCache.VerifyAll();
            Assert.True(updatedCredentialsPassed);
        }
Esempio n. 29
0
        private void OpenSelectDeviceDialog(DeviceIdentity selectedDeviceIdentity)
        {
            //ResetGUI();
            //DisplayMessage("Device configuration");
            //EnableGUI(false);

            try
            {
                //IWin32Window win32Window = new WindowWrapper(this);
                SelectDeviceWindow_new selectDevice = new SelectDeviceWindow_new(selectedDeviceIdentity, this);
                if (_fpScanner != null)
                {
                    selectDevice.FingerPrintScanner = _fpScanner;
                }

                selectDevice.ShowDialog();

                if (selectDevice.rDialogResult)
                //if (selectDevice.rDialogResult.HasValue && selectDevice.DialogResult.Value)
                {
                    // DisplayMessage("Opening device");

                    _fpScanner = selectDevice.FingerPrintScanner;
                    if (_fpScanner != null)
                    {
                        //ResetGUI();
                        //EnableGUI(true);
                    }
                }
                else
                {
                    DisplayError("No device selected");
                    if (selectDevice.FingerPrintScanner != null)
                    {
                        selectDevice.FingerPrintScanner.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                DisplayError(ex.Message);
            }
        }
Esempio n. 30
0
        public AmqpUnit(
            DeviceIdentity deviceIdentity,
            IAmqpConnectionHolder amqpConnectionHolder,
            Func <MethodRequestInternal, Task> onMethodCallback,
            Action <Twin, string, TwinCollection, IotHubException> twinMessageListener,
            Func <string, Message, Task> onModuleMessageReceivedCallback,
            Func <Message, Task> onDeviceMessageReceivedCallback,
            Action onUnitDisconnected)
        {
            _deviceIdentity                  = deviceIdentity;
            _onMethodCallback                = onMethodCallback;
            _twinMessageListener             = twinMessageListener;
            _onModuleMessageReceivedCallback = onModuleMessageReceivedCallback;
            _onDeviceMessageReceivedCallback = onDeviceMessageReceivedCallback;
            _amqpConnectionHolder            = amqpConnectionHolder;
            _onUnitDisconnected              = onUnitDisconnected;

            Logging.Associate(this, _deviceIdentity, nameof(_deviceIdentity));
        }