Esempio n. 1
0
        private Tuple <Mock <IHttpClientHelper>, ServiceClient, PurgeMessageQueueResult> SetupPurgeMessageQueueTests()
        {
            // Create expected return object
            var deviceId       = "TestDevice";
            var expectedResult = new PurgeMessageQueueResult()
            {
                DeviceId            = deviceId,
                TotalMessagesPurged = 1
            };

            // Mock IHttpClientHelper to return expected object on DeleteAsync
            var restOpMock = new Mock <IHttpClientHelper>();

            restOpMock.Setup(restOp => restOp.DeleteAsync <PurgeMessageQueueResult>(
                                 It.IsAny <Uri>(), It.IsAny <IDictionary <HttpStatusCode, Func <HttpResponseMessage, Task <Exception> > > >(), null, It.IsAny <CancellationToken>())
                             ).ReturnsAsync(expectedResult);

            // Instantiate AmqpServiceClient with Mock IHttpClientHelper
            var authMethod = new ServiceAuthenticationWithSharedAccessPolicyKey("test", "dGVzdFN0cmluZzE=");
            var builder    = IotHubConnectionStringBuilder.Create("acme.azure-devices.net", authMethod);
            Func <TimeSpan, Task <AmqpSession> > onCreate = _ => Task.FromResult(new AmqpSession(null, new AmqpSessionSettings(), null));
            Action <AmqpSession> onClose = _ => { };
            // Instantiate AmqpServiceClient with Mock IHttpClientHelper and IotHubConnection
            var connection    = new IotHubConnection(onCreate, onClose);
            var serviceClient = new ServiceClient(connection, restOpMock.Object);

            return(Tuple.Create(restOpMock, serviceClient, expectedResult));
        }
Esempio n. 2
0
        public void DeviceScopeMuxConnection_MaxDevicesPerConnectionTest()
        {
            // Arrange

            var amqpConnectionPoolSettings = new AmqpConnectionPoolSettings();

            // Reduce poolsize to 1. This will mux all devices onto one connection
            amqpConnectionPoolSettings.MaxPoolSize = 1;
            var    amqpTransportSettings  = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only, 200, amqpConnectionPoolSettings);
            string connectionString       = "HostName=acme.azure-devices.net;DeviceId=device1;SharedAccessKey=CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8=";
            var    iotHubConnectionString = IotHubConnectionStringBuilder.Create(connectionString).ToIotHubConnectionString();
            var    connectionCache        = new Mock <IotHubConnectionCache>();
            var    connectionPool         = new IotHubDeviceScopeConnectionPool(connectionCache.Object, iotHubConnectionString, amqpTransportSettings);

            // Act

            // Create 995 Muxed Device Connections
            for (int i = 0; i < AmqpConnectionPoolSettings.MaxDevicesPerConnection; i++)
            {
                connectionPool.GetConnection(iotHubConnectionString + "DeviceId=" + Guid.NewGuid().ToString());
            }

            // try one more. This should throw invalid operation exception
            var connection = connectionPool.GetConnection(iotHubConnectionString + "DeviceId=" + Guid.NewGuid().ToString());
        }
Esempio n. 3
0
        async Task ConfigureAsync(string deviceConnectionString, Option <Uri> proxy, CancellationToken token)
        {
            string hostname = (await File.ReadAllTextAsync("/proc/sys/kernel/hostname", token)).Trim();
            IotHubConnectionStringBuilder builder = IotHubConnectionStringBuilder.Create(deviceConnectionString);

            var    properties = new object[] { hostname, builder.DeviceId };
            string message    = "Configured edge daemon for device '{Device}' registered as '{Id}'";

            proxy.ForEach(
                p =>
            {
                message   += " with proxy '{ProxyUri}'";
                properties = properties.Concat(new object[] { p }).ToArray();
            });

            await Profiler.Run(
                async() =>
            {
                await this.InternalStopAsync(token);

                var yaml = new DaemonConfiguration();
                yaml.SetDeviceConnectionString(deviceConnectionString);
                yaml.SetDeviceHostname(hostname);
                proxy.ForEach(p => yaml.AddHttpsProxy(p));
                yaml.Update();

                await this.InternalStartAsync(token);
            },
                message,
                properties);
        }
Esempio n. 4
0
        protected Task ConfigureBootstrapper()
        {
            Console.WriteLine("Configuring bootstrapper.");
            DeviceProvisioningMethod method = this.dpsAttestation.Match(
                dps => { return(new DeviceProvisioningMethod(dps)); },
                () =>
            {
                IotHubConnectionStringBuilder builder =
                    IotHubConnectionStringBuilder.Create(this.context.IotHubConnectionString);
                Device device           = this.context.Device.Expect(() => new InvalidOperationException("Expected a valid device instance"));
                string connectionString =
                    $"HostName={builder.HostName};" +
                    $"DeviceId={device.Id};" +
                    $"SharedAccessKey={device.Authentication.SymmetricKey.PrimaryKey}";

                return(new DeviceProvisioningMethod(connectionString));
            });

            Option <string> agentImage = Option.None <string>();

            if (this.initializeWithAgentArtifact)
            {
                agentImage = Option.Some <string>(this.EdgeAgentImage());
            }

            return(this.bootstrapper.Configure(method, agentImage, this.hostname, this.deviceCaCert, this.deviceCaPk, this.deviceCaCerts, this.runtimeLogLevel));
        }
Esempio n. 5
0
        public DependencyManager(IConfigurationRoot configuration, X509Certificate2 serverCertificate, IList <X509Certificate2> trustBundle)
        {
            this.configuration     = Preconditions.CheckNotNull(configuration, nameof(configuration));
            this.serverCertificate = Preconditions.CheckNotNull(serverCertificate, nameof(serverCertificate));
            this.trustBundle       = Preconditions.CheckNotNull(trustBundle, nameof(trustBundle));

            string edgeHubConnectionString = this.configuration.GetValue <string>(Constants.ConfigKey.IotHubConnectionString);

            if (!string.IsNullOrWhiteSpace(edgeHubConnectionString))
            {
                IotHubConnectionStringBuilder iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(edgeHubConnectionString);
                this.iotHubHostname     = iotHubConnectionStringBuilder.HostName;
                this.edgeDeviceId       = iotHubConnectionStringBuilder.DeviceId;
                this.edgeModuleId       = iotHubConnectionStringBuilder.ModuleId;
                this.edgeDeviceHostName = this.configuration.GetValue(Constants.ConfigKey.EdgeDeviceHostName, string.Empty);
                this.connectionString   = Option.Some(edgeHubConnectionString);
            }
            else
            {
                this.iotHubHostname     = this.configuration.GetValue <string>(Constants.ConfigKey.IotHubHostname);
                this.edgeDeviceId       = this.configuration.GetValue <string>(Constants.ConfigKey.DeviceId);
                this.edgeModuleId       = this.configuration.GetValue <string>(Constants.ConfigKey.ModuleId);
                this.edgeDeviceHostName = this.configuration.GetValue <string>(Constants.ConfigKey.EdgeDeviceHostName);
                this.connectionString   = Option.None <string>();
            }

            this.versionInfo = VersionInfo.Get(Constants.VersionInfoFileName);
        }
Esempio n. 6
0
        public DockerModule(
            string edgeDeviceConnectionString,
            string gatewayHostName,
            Uri dockerHostname,
            IEnumerable <AuthConfig> dockerAuthConfig,
            Option <UpstreamProtocol> upstreamProtocol,
            Option <IWebProxy> proxy,
            Option <string> productInfo,
            bool closeOnIdleTimeout,
            TimeSpan idleTimeout,
            bool useServerHeartbeat)
        {
            this.edgeDeviceConnectionString = Preconditions.CheckNonWhiteSpace(edgeDeviceConnectionString, nameof(edgeDeviceConnectionString));
            this.gatewayHostName            = Preconditions.CheckNonWhiteSpace(gatewayHostName, nameof(gatewayHostName));
            IotHubConnectionStringBuilder connectionStringParser = IotHubConnectionStringBuilder.Create(this.edgeDeviceConnectionString);

            this.deviceId           = connectionStringParser.DeviceId;
            this.iotHubHostName     = connectionStringParser.HostName;
            this.dockerHostname     = Preconditions.CheckNotNull(dockerHostname, nameof(dockerHostname));
            this.dockerAuthConfig   = Preconditions.CheckNotNull(dockerAuthConfig, nameof(dockerAuthConfig));
            this.upstreamProtocol   = Preconditions.CheckNotNull(upstreamProtocol, nameof(upstreamProtocol));
            this.proxy              = Preconditions.CheckNotNull(proxy, nameof(proxy));
            this.productInfo        = productInfo;
            this.closeOnIdleTimeout = closeOnIdleTimeout;
            this.idleTimeout        = idleTimeout;
            this.useServerHeartbeat = useServerHeartbeat;
        }
Esempio n. 7
0
        public void Configure(IApplicationBuilder app)
        {
            app.UseWebSockets();

            var webSocketListenerRegistry = app.ApplicationServices.GetService(typeof(IWebSocketListenerRegistry)) as IWebSocketListenerRegistry;

            app.UseWebSocketHandlingMiddleware(webSocketListenerRegistry);

            string edgeHubConnectionString = this.configuration.GetValue <string>(Constants.ConfigKey.IotHubConnectionString);
            string iotHubHostname;
            string edgeDeviceId;

            if (!string.IsNullOrWhiteSpace(edgeHubConnectionString))
            {
                IotHubConnectionStringBuilder iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(edgeHubConnectionString);
                iotHubHostname = iotHubConnectionStringBuilder.HostName;
                edgeDeviceId   = iotHubConnectionStringBuilder.DeviceId;
            }
            else
            {
                iotHubHostname = this.configuration.GetValue <string>(Constants.ConfigKey.IotHubHostname);
                edgeDeviceId   = this.configuration.GetValue <string>(Constants.ConfigKey.DeviceId);
            }

            app.UseAuthenticationMiddleware(iotHubHostname, edgeDeviceId);

            app.Use(async(context, next) =>
            {
                // Response header is added to prevent MIME type sniffing
                context.Response.Headers.Add("X-Content-Type-Options", "nosniff");
                await next();
            });

            app.UseMvc();
        }
Esempio n. 8
0
        protected async Task GetOrCreateEdgeDeviceIdentity()
        {
            Console.WriteLine("Getting or Creating device Identity.");
            var settings = new HttpTransportSettings();

            this.proxy.ForEach(p => settings.Proxy = p);
            IotHubConnectionStringBuilder builder = IotHubConnectionStringBuilder.Create(this.iothubConnectionString);
            RegistryManager rm = RegistryManager.CreateFromConnectionString(builder.ToString(), settings);

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

            if (device != null)
            {
                Console.WriteLine($"Device '{device.Id}' already registered on IoT hub '{builder.HostName}'");
                Console.WriteLine($"Clean up Existing device? {this.cleanUpExistingDeviceOnSuccess}");
                this.context = new DeviceContext(device, this.iothubConnectionString, rm, this.cleanUpExistingDeviceOnSuccess);
            }
            else
            {
                // if dpsAttestion is enabled, do not create a device as the
                // ESD will register with DPS to create the device in IoT Hub
                if (this.dpsAttestation.HasValue)
                {
                    this.context = new DeviceContext(this.deviceId, this.iothubConnectionString, rm, this.cleanUpExistingDeviceOnSuccess);
                }
                else
                {
                    await this.CreateEdgeDeviceIdentity(rm);
                }
            }
        }
        private void parseIoTHubConnectionString(string connectionString, bool skipException = false)
        {
            try
            {
                var builder = IotHubConnectionStringBuilder.Create(connectionString);
                iotHubHostName = builder.HostName;

                targetTextBox.Text   = builder.HostName;
                keyValueTextBox.Text = builder.SharedAccessKey;
                keyNameTextBox.Text  = builder.SharedAccessKeyName;

                string iotHubName = builder.HostName.Split('.')[0];
                iotHubNameTextBox.Text                = iotHubName;
                eventHubNameTextBoxForDataTab.Text    = iotHubName;
                iotHubNameTextBoxForDeviceMethod.Text = iotHubName;

                activeIoTHubConnectionString = connectionString;
            }
            catch (Exception ex)
            {
                if (!skipException)
                {
                    throw new ArgumentException("Invalid IoTHub connection string. " + ex.Message);
                }
            }
        }
Esempio n. 10
0
        public async Task DeviceAuthenticationWithSakRefresh_SharedAccessKeyConnectionString_HasRefresher()
        {
            var csBuilder = IotHubConnectionStringBuilder.Create(
                TestIoTHubName,
                new DeviceAuthenticationWithRegistrySymmetricKey(TestDeviceId, TestSharedAccessKey));

            IotHubConnectionString cs = csBuilder.ToIotHubConnectionString();

            Assert.IsNotNull(cs.TokenRefresher);
            Assert.IsInstanceOfType(cs.TokenRefresher, typeof(DeviceAuthenticationWithSakRefresh));

            var auth    = (IAuthorizationProvider)cs;
            var cbsAuth = (ICbsTokenProvider)cs;

            string token1 = await auth.GetPasswordAsync().ConfigureAwait(false);

            CbsToken token2 = await cbsAuth.GetTokenAsync(new Uri("amqp://" + TestIoTHubName), "testAppliesTo", null).ConfigureAwait(false);

            Assert.IsNull(cs.SharedAccessSignature);
            Assert.AreEqual(TestDeviceId, cs.DeviceId);

            Assert.IsNotNull(token1);
            Assert.IsNotNull(token2);
            Assert.AreEqual(token1, token2.TokenValue);
        }
Esempio n. 11
0
 private static void ValidateConnectionString(string[] args)
 {
     if (args.Any())
     {
         try
         {
             var cs = IotHubConnectionStringBuilder.Create(args[0]);
             s_connectionString = cs.ToString();
         }
         catch (Exception)
         {
             Console.WriteLine($"Error: Unrecognizable parameter '{args[0]}' as connection string.");
             Environment.Exit(1);
         }
     }
     else
     {
         try
         {
             _ = IotHubConnectionStringBuilder.Create(s_connectionString);
         }
         catch (Exception)
         {
             Console.WriteLine("This sample needs a device connection string to run. Program.cs can be edited to specify it, or it can be included on the command-line as the only parameter.");
             Environment.Exit(1);
         }
     }
 }
Esempio n. 12
0
        async Task CreateEdgeDeviceIdentity(RegistryManager rm)
        {
            var device = new Device(this.deviceId)
            {
                Authentication = new AuthenticationMechanism()
                {
                    Type = AuthenticationType.Sas
                },
                Capabilities = new DeviceCapabilities()
                {
                    IotEdge = true
                }
            };

            IotHubConnectionStringBuilder builder = IotHubConnectionStringBuilder.Create(this.iothubConnectionString);

            Console.WriteLine($"Registering device '{device.Id}' on IoT hub '{builder.HostName}'");

            device = await rm.AddDeviceAsync(device);

            this.context = new DeviceContext
            {
                Device = device,
                IotHubConnectionString = this.iothubConnectionString,
                RegistryManager        = rm,
                RemoveDevice           = true
            };
        }
Esempio n. 13
0
        protected async Task GetOrCreateEdgeDeviceIdentity()
        {
            IotHubConnectionStringBuilder builder = IotHubConnectionStringBuilder.Create(this.iothubConnectionString);
            RegistryManager rm = RegistryManager.CreateFromConnectionString(builder.ToString());

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

            if (device != null)
            {
                Console.WriteLine($"Device '{device.Id}' already registered on IoT hub '{builder.HostName}'");
                Console.WriteLine($"Clean up Existing device? {this.cleanUpExistingDeviceOnSuccess}");

                this.context = new DeviceContext
                {
                    Device = device,
                    IotHubConnectionString = this.iothubConnectionString,
                    RegistryManager        = rm,
                    RemoveDevice           = this.cleanUpExistingDeviceOnSuccess
                };
            }
            else
            {
                await this.CreateEdgeDeviceIdentity(rm);
            }
        }
Esempio n. 14
0
        public async Task DeviceScopeMuxConnection_ConnectionIdleTimeoutTest()
        {
            // Arrange

            var amqpConnectionPoolSettings = new AmqpConnectionPoolSettings();

            amqpConnectionPoolSettings.ConnectionIdleTimeout = TimeSpan.FromSeconds(5);
            var    amqpTransportSettings  = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only, 200, amqpConnectionPoolSettings);
            string connectionString       = "HostName=acme.azure-devices.net;DeviceId=device1;SharedAccessKey=CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8=";
            var    iotHubConnectionString = IotHubConnectionStringBuilder.Create(connectionString).ToIotHubConnectionString();
            var    connectionCache        = new Mock <IotHubConnectionCache>();
            var    connectionPool         = new IotHubDeviceScopeConnectionPool(connectionCache.Object, iotHubConnectionString, amqpTransportSettings);

            // Act

            var connections = new IotHubDeviceMuxConnection[10];

            // Create 10 Muxed Device Connections - these should hash into different mux connections
            for (int i = 0; i < 10; i++)
            {
                connections[i] = (IotHubDeviceMuxConnection)connectionPool.GetConnection(i.ToString());
            }

            for (int j = 0; j < 10; j++)
            {
                connectionPool.RemoveDeviceFromConnection(connections[j], j.ToString());
            }

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

            // Assert
            Assert.IsTrue(connectionPool.GetCount() == 0, "Did not cleanup all Connection objects");
        }
Esempio n. 15
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));
        }
Esempio n. 16
0
        public Device(string connectionString)
        {
            this.connectionString = connectionString;

            var builder = IotHubConnectionStringBuilder.Create(connectionString);

            deviceId = builder.DeviceId;
        }
Esempio n. 17
0
        public void ConstructorWithValidConnectionStringTest()
        {
            var authMethod      = new ServiceAuthenticationWithSharedAccessPolicyKey("test", "CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8=");
            var builder         = IotHubConnectionStringBuilder.Create("acme.azure-devices.net", authMethod);
            var registryManager = RegistryManager.CreateFromConnectionString(builder.ToString());

            Assert.IsNotNull(registryManager);
        }
Esempio n. 18
0
        public IClientCredentials GetWithConnectionString(string connectionString)
        {
            Preconditions.CheckNonWhiteSpace(connectionString, nameof(connectionString));
            IotHubConnectionStringBuilder iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString);
            IIdentity identity = this.GetIdentity(iotHubConnectionStringBuilder.DeviceId, iotHubConnectionStringBuilder.ModuleId);

            return(new SharedKeyCredentials(identity, connectionString, this.callerProductInfo));
        }
Esempio n. 19
0
        /// <summary>
        /// Creates the Connection String formatted as it is expected by the Microsoft.Azure.Clients SDK
        /// </summary>
        /// <param name="gatewayHostName">Gateway FQDN</param>
        /// <param name="deviceId">Device id</param>
        /// <param name="primaryKey">Primary key</param>
        /// <returns>Connection String formatted as it is expected by the Microsoft.Azure.Clients SDK</returns>
        protected string CreateModuleConnectionString(string gatewayHostName, string deviceId, string primaryKey)
        {
            var authMethod =
                AuthenticationMethodFactory.CreateAuthenticationWithRegistrySymmetricKey(deviceId, AuthenticationData.ModuleName, primaryKey);
            var builder = IotHubConnectionStringBuilder.Create(gatewayHostName, authMethod);

            return(builder.ToString());
        }
        public Thermostat(string connectionString, int transportTypeInt) : this(transportTypeInt)
        {
            client = DeviceClient.CreateFromConnectionString(connectionString, this.transportType);
            var connectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString);
            DeviceId = connectionStringBuilder.DeviceId;

            Setup();
        }
Esempio n. 21
0
        public DeviceDeployment(string iotHubConnectionString, string deploymentTemplate)
        {
            manager  = RegistryManager.CreateFromConnectionString(iotHubConnectionString);
            template = deploymentTemplate;
            IotHubConnectionStringBuilder builder = IotHubConnectionStringBuilder.Create(iotHubConnectionString);

            hubName = builder.IotHubName;
        }
Esempio n. 22
0
        /// <summary>
        /// Get IoTHub connection string from either the user provided value or the configuration
        /// </summary>
        public void SetCurrentIotHub()
        {
            string connString = this.connectionStringManager.GetIotHubConnectionString();

            this.registry       = this.registry.CreateFromConnectionString(connString);
            this.ioTHubHostName = IotHubConnectionStringBuilder.Create(connString).HostName;
            this.log.Info("Selected active IoT Hub for devices", () => new { this.ioTHubHostName });
        }
        public void IotHubConnectionStringBuilder_ParamConnectionString_ParsesSharedAccessKeyName()
        {
            var connectionString = $"HostName={HostName};DeviceId={DeviceId};SharedAccessKeyName={SharedAccessKeyName};SharedAccessKey={SharedAccessKey}";
            var csBuilder        = IotHubConnectionStringBuilder.Create(connectionString);

            csBuilder.SharedAccessKeyName.Should().Be(SharedAccessKeyName);
            csBuilder.AuthenticationMethod.Should().BeOfType <DeviceAuthenticationWithSharedAccessPolicyKey>();
        }
Esempio n. 24
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));
        }
Esempio n. 25
0
        public async Task ManuallyProvisionEdgeAsync()
        {
            await Profiler.Run(
                async() =>
            {
                using (var cts = new CancellationTokenSource(Context.Current.SetupTimeout))
                {
                    // NUnit's [Timeout] attribute isn't supported in .NET Standard
                    // and even if it were, it doesn't run the teardown method when
                    // a test times out. We need teardown to run, to remove the
                    // device registration from IoT Hub and stop the daemon. So
                    // we have our own timeout mechanism.
                    DateTime startTime      = DateTime.Now;
                    CancellationToken token = cts.Token;

                    EdgeDevice device = await EdgeDevice.GetOrCreateIdentityAsync(
                        Context.Current.DeviceId,
                        this.iotHub,
                        token);
                    Context.Current.DeleteList.TryAdd(device.Id, device);

                    IotHubConnectionStringBuilder builder =
                        IotHubConnectionStringBuilder.Create(device.ConnectionString);

                    await this.daemon.ConfigureAsync(
                        config =>
                    {
                        config.SetDeviceConnectionString(device.ConnectionString);
                        config.Update();
                        return(Task.FromResult((
                                                   "with connection string for device '{Identity}'",
                                                   new object[] { builder.DeviceId })));
                    },
                        token);

                    try
                    {
                        await this.daemon.WaitForStatusAsync(EdgeDaemonStatus.Running, token);

                        var agent = new EdgeAgent(device.Id, this.iotHub);
                        await agent.WaitForStatusAsync(EdgeModuleStatus.Running, token);
                        await agent.PingAsync(token);
                    }

                    // ReSharper disable once RedundantCatchClause
                    catch
                    {
                        throw;
                    }
                    finally
                    {
                        await NUnitLogs.CollectAsync(startTime, token);
                    }
                }
            },
                "Completed edge manual provisioning");
        }
        public IoTDeviceService(IConfiguration config)
        {
            string connectionString = config["IoTHubConnectionString"];

            IotHubConnectionStringBuilder connectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString);

            _hostname = connectionStringBuilder.HostName;
            _manager  = RegistryManager.CreateFromConnectionString(connectionStringBuilder.ToString());
        }
Esempio n. 27
0
        public void DeviceClient_ConnectionString_DefaultScope_DefaultCredentialType_Test()
        {
            string connectionString = "HostName=acme.azure-devices.net;SharedAccessKeyName=AllAccessKey;DeviceId=device1;SharedAccessKey=CQN2K33r45/0WeIjpqmErV5EIvX8JZrozt3NEHCEkG8=";
            var    deviceClient     = AmqpTransportHandler.CreateFromConnectionString(connectionString);

            Assert.IsNotNull(deviceClient.Connection);
            Assert.IsNotNull(deviceClient.Connection.ConnectionString);
            var iotHubConnectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString);
        }
Esempio n. 28
0
        public UpdateAgent(string connectionString, IUpdateableDevice device)
        {
            managedDevice = device;
            Status        = UpdateStatus.Idle;
            client        = DeviceClient.CreateFromConnectionString(connectionString, TransportType.Amqp);
            var connectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString);

            DeviceId = connectionStringBuilder.DeviceId;
        }
        public void IotHubConnectionStringBuilder_ParamConnectionString_ParsesX509False(string x509)
        {
            var connectionString = $"HostName={HostName};DeviceId={DeviceId};SharedAccessKey={SharedAccessKey};{x509}=false";
            var csBuilder        = IotHubConnectionStringBuilder.Create(connectionString);

            csBuilder.SharedAccessKey.Should().Be(SharedAccessKey);
            csBuilder.AuthenticationMethod.Should().BeOfType <DeviceAuthenticationWithRegistrySymmetricKey>();
            csBuilder.UsingX509Cert.Should().BeFalse("SharedAccessKey and X509 are mutually exclusive");
        }
Esempio n. 30
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));
        }