internal static IAuthenticationMethod GetAuthenticationMethod(IotHubConnectionStringBuilder iotHubConnectionStringBuilder)
        {
            if (iotHubConnectionStringBuilder.SharedAccessKeyName != null)
            {
                return new DeviceAuthenticationWithSharedAccessPolicyKey(
                    iotHubConnectionStringBuilder.DeviceId, iotHubConnectionStringBuilder.SharedAccessKeyName, iotHubConnectionStringBuilder.SharedAccessKey);
            }
            else if (iotHubConnectionStringBuilder.SharedAccessKey != null)
            {
                return new DeviceAuthenticationWithRegistrySymmetricKey(
                    iotHubConnectionStringBuilder.DeviceId, iotHubConnectionStringBuilder.SharedAccessKey);
            }       
            else if (iotHubConnectionStringBuilder.SharedAccessSignature != null)
            {
                return new DeviceAuthenticationWithToken(iotHubConnectionStringBuilder.DeviceId, iotHubConnectionStringBuilder.SharedAccessSignature);
            }
#if !NETMF && !WINDOWS_UWP && !PCL
            else if (iotHubConnectionStringBuilder.UsingX509Cert)
            {
                return new DeviceAuthenticationWithX509Certificate(iotHubConnectionStringBuilder.DeviceId, iotHubConnectionStringBuilder.Certificate);
            }
#endif

#if NETMF
            throw new InvalidOperationException("Unsupported Authentication Method " + iotHubConnectionStringBuilder.ToString());
#else
            throw new InvalidOperationException("Unsupported Authentication Method {0}".FormatInvariant(iotHubConnectionStringBuilder));
#endif
        }
 protected DeviceRunner(IEventLoopGroup eventLoopGroup, string deviceKey, string iotHubConnectionString, IPEndPoint endpoint, string tlsHostName)
 {
     this.deviceKey = deviceKey;
     this.endpoint = endpoint;
     this.tlsHostName = tlsHostName;
     this.connectionStringBuilder = IotHubConnectionStringBuilder.Create(iotHubConnectionString.Contains("DeviceId=") ? iotHubConnectionString : iotHubConnectionString + ";DeviceId=abc");
     this.bootstrap = new Bootstrap()
         .Group(eventLoopGroup)
         .Channel<TcpSocketChannel>()
         .Option(ChannelOption.TcpNodelay, false);
 }
        /// <summary>
        /// Populates an <see cref="IotHubConnectionStringBuilder"/> instance based on the properties of the current instance.
        /// </summary>
        /// <param name="iotHubConnectionStringBuilder">Instance to populate.</param>
        /// <returns>The populated <see cref="IotHubConnectionStringBuilder"/> instance.</returns>
        public IotHubConnectionStringBuilder Populate(IotHubConnectionStringBuilder iotHubConnectionStringBuilder)
        {
            if (iotHubConnectionStringBuilder == null)
            {
                throw new ArgumentNullException("iotHubConnectionStringBuilder");
            }

            iotHubConnectionStringBuilder.DeviceId = this.DeviceId;
            iotHubConnectionStringBuilder.SharedAccessSignature = this.Token;
            iotHubConnectionStringBuilder.SharedAccessKey = null;
            iotHubConnectionStringBuilder.SharedAccessKeyName = null;

            return iotHubConnectionStringBuilder;
        }
Exemple #4
0
        public async Task TestGetModulesIdentity_WithUpdatedModules_AuthTypeNotSas_ShouldUpdateIdentities()
        {
            const string Name         = "test-filters";
            string       primaryKey   = Convert.ToBase64String(Encoding.UTF8.GetBytes("primarySymmetricKey"));
            string       secondaryKey = Convert.ToBase64String(Encoding.UTF8.GetBytes("secondarySymmetricKey"));

            var serviceModuleIdentity = new Module("device1", Name);

            serviceModuleIdentity.Authentication      = new AuthenticationMechanism();
            serviceModuleIdentity.Authentication.Type = AuthenticationType.CertificateAuthority;
            var thumbprint = new X509Thumbprint();

            thumbprint.PrimaryThumbprint   = primaryKey;
            thumbprint.SecondaryThumbprint = secondaryKey;

            serviceModuleIdentity.Authentication.X509Thumbprint = thumbprint;

            var    serviceClient   = new Mock <IServiceClient>();
            string hostname        = "hostname.fake.com";
            string deviceId        = "deviceId";
            string gatewayHostName = "localhost";

            Module[] serviceIdentities = { serviceModuleIdentity };
            serviceClient.Setup(sc => sc.GetModules()).Returns(Task.FromResult(serviceIdentities.AsEnumerable()));
            serviceClient.Setup(sc => sc.UpdateModules(It.IsAny <IEnumerable <Module> >())).Callback(
                (IEnumerable <Module> modules) =>
            {
                foreach (Module m in modules)
                {
                    m.Authentication.SymmetricKey            = new SymmetricKey();
                    m.Authentication.SymmetricKey.PrimaryKey = primaryKey;
                }
            }).Returns(Task.FromResult(serviceIdentities));

            var module = new TestModule(Name, "v1", "test", ModuleStatus.Running, new TestConfig("image"), RestartPolicy.OnUnhealthy, ImagePullPolicy.OnCreate, Constants.DefaultStartupOrder, DefaultConfigurationInfo, EnvVars);

            IImmutableDictionary <string, IModuleIdentity> modulesIdentities = await new ModuleIdentityLifecycleManager(serviceClient.Object, hostname, deviceId, gatewayHostName)
                                                                               .GetModuleIdentitiesAsync(ModuleSet.Create(new IModule[] { module }), ModuleSet.Empty);

            serviceClient.Verify(sc => sc.UpdateModules(It.IsAny <IEnumerable <Module> >()), Times.Once());
            Assert.True(modulesIdentities.Count() == 1);
            var creds = modulesIdentities.First().Value.Credentials as ConnectionStringCredentials;

            Assert.NotNull(creds);
            IotHubConnectionStringBuilder connectionString = IotHubConnectionStringBuilder.Create(creds.ConnectionString);

            Assert.NotNull(connectionString.SharedAccessKey);
        }
Exemple #5
0
        async Task SendTelemetryTest(ITransportSettings[] transportSettings)
        {
            int        messagesCount = 10;
            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, "sender1", transportSettings);

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

                await receiver.SetupReceiveMessageHandler();

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

                int sentMessagesCount = await task1;
                Assert.Equal(messagesCount, sentMessagesCount);

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

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

                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));
        }
        /// <summary>
        /// Create a DeviceClient from individual parameters
        /// </summary>
        /// <param name="hostname">The fully-qualified DNS hostname of IoT Hub</param>
        /// <param name="authenticationMethod">The authentication method that is used</param>
        /// <returns>DeviceClient</returns>
        public static AmqpTransportHandler Create(string hostname, IAuthenticationMethod authenticationMethod)
        {
            if (hostname == null)
            {
                throw new ArgumentNullException(nameof(hostname));
            }

            if (authenticationMethod == null)
            {
                throw new ArgumentNullException(nameof(authenticationMethod));
            }

            IotHubConnectionStringBuilder connectionStringBuilder = IotHubConnectionStringBuilder.Create(hostname, authenticationMethod);

            return(CreateFromConnectionString(connectionStringBuilder.ToString()));
        }
Exemple #7
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferred = taskInstance.GetDeferral();
            try
            {
                taskInstance.Canceled += TaskInstance_Canceled;

                _bmp280 = new BMP280();
                await _bmp280.Initialize();

                var connectionString = "HostName=CMS-IotHub.azure-devices.net;DeviceId=myFirstDevice;SharedAccessKey=tSnbYN51pXJN1Mg9JyDTLNN9dVpIeyykklcgRnV8Rmo=";
                //var connectionString = "HostName=CMS-IotHub.azure-devices.net;SharedAccessKeyName=iothubowner;SharedAccessKey=7MOT33FRh2v7Pv2tQZq93ZixTVu88FPbVkDP1SeCPpc=";
                var connectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString);
                //_deviceClient = DeviceClient.CreateFromConnectionString(connectionString);

                deviceClient = DeviceClient.Create(iotHubUri, new DeviceAuthenticationWithRegistrySymmetricKey("myFirstDevice", deviceKey));

                await deviceClient.OpenAsync();

                _lastReport   = DateTime.UtcNow.AddMinutes(5 * -1);
                _tempuratures = new List <float>();
                _pressures    = new List <float>();
                _altitudes    = new List <float>();

                while (!_isCancelled)
                {
                    await ProcessSensorData();

                    if (_lastReport.AddMinutes(5) < DateTime.UtcNow)
                    {
                        await SendSensorDataToIoTHub(connectionStringBuilder.DeviceId);

                        _lastReport = DateTime.UtcNow;
                    }

                    await Task.Delay(5000);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error during run RaspberryCMS: {ex.Message}");
            }
            finally
            {
                _deferred.Complete();
            }
        }
Exemple #8
0
        public Deployments(
            IServicesConfig config,
            ILogger logger)
        {
            if (config == null)
            {
                throw new ArgumentNullException(nameof(config));
            }

            IoTHubConnectionHelper.CreateUsingHubConnectionString(config.IoTHubConnString, (conn) =>
            {
                this.registry       = RegistryManager.CreateFromConnectionString(conn);
                this.ioTHubHostName = IotHubConnectionStringBuilder.Create(conn).HostName;
            });

            this.log = logger;
        }
Exemple #9
0
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferred = taskInstance.GetDeferral();
            try
            {
                taskInstance.Canceled += TaskInstance_Canceled;

                _bmp280 = new BMP280();
                await _bmp280.Initialize();

                var connectionString        = "HostName=MarcoIoTHub.azure-devices.net;DeviceId=WeatherStation1;SharedAccessKey=PdYBupq+DB5SxQhGYHNGanTSU0qs3H2d1dV13j5jvyM=";
                var connectionStringBuilder = IotHubConnectionStringBuilder.Create(connectionString);
                _deviceClient = DeviceClient.CreateFromConnectionString(connectionString);
                await _deviceClient.OpenAsync();

                var geoLocator = new Geolocator();
                _location = await geoLocator.GetGeopositionAsync();

                _lastReport   = DateTime.UtcNow.AddMinutes(5 * -1);
                _tempuratures = new List <float>();
                _pressures    = new List <float>();
                _altitudes    = new List <float>();

                while (!_isCancelled)
                {
                    await ProcessSensorData();

                    if (_lastReport.AddMinutes(5) < DateTime.UtcNow)
                    {
                        await SendSensorDataToIoTHub(connectionStringBuilder.DeviceId);

                        _lastReport = DateTime.UtcNow;
                    }

                    await Task.Delay(5000);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Error during run WeatherStation: {ex.Message}");
            }
            finally
            {
                _deferred.Complete();
            }
        }
        public async Task PurgeMessageQueueDeviceNotFoundTest()
        {
            // Arrange Moq
            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>())
                             ).Throws(new DeviceNotFoundException("device-id"));

            // Instantiate AmqpServiceClient with Mock IHttpClientHelper
            var authMethod    = new ServiceAuthenticationWithSharedAccessPolicyKey("test", "dGVzdFN0cmluZzE=");
            var builder       = IotHubConnectionStringBuilder.Create("acme.azure-devices.net", authMethod);
            var serviceClient = new AmqpServiceClient(restOpMock.Object);

            // Execute method under test
            PurgeMessageQueueResult result = await serviceClient.PurgeMessageQueueAsync("TestDevice", CancellationToken.None).ConfigureAwait(false);
        }
        public IoTHelper()
        {
            var connectionString = ConfigurationManager.AppSettings["IoTHubConnectionString"];
            var connBuilder      = IotHubConnectionStringBuilder.Create(connectionString);

            if (connBuilder.UsingX509Cert)
            {
                var x509Certificate = new X509Certificate2("deviceCertificate.pfx", "devicecertificate");
                var authMethod      = new DeviceAuthenticationWithX509Certificate(connBuilder.DeviceId, x509Certificate);

                deviceClient = DeviceClient.Create(connBuilder.HostName, authMethod, TransportType.Amqp);
            }
            else
            {
                deviceClient = DeviceClient.CreateFromConnectionString(connectionString, TransportType.Amqp);
            }
        }
Exemple #12
0
        public Devices(
            IServicesConfig config,
            IConfigService configService)
        {
            if (config == null)
            {
                throw new ArgumentNullException("config");
            }

            IoTHubConnectionHelper.CreateUsingHubConnectionString(config.IoTHubConnString, (conn) =>
            {
                this.registry       = RegistryManager.CreateFromConnectionString(conn);
                this.ioTHubHostName = IotHubConnectionStringBuilder.Create(conn).HostName;
            });

            this.configService = configService;
        }
        public static MessagingBridgeFactoryFunc PrepareFactory(string baseConnectionString, int connectionPoolSize,
                                                                TimeSpan?connectionIdleTimeout, IotHubClientSettings settings, Action <IotHubBridge> initHandler)
        {
            MessagingBridgeFactoryFunc mqttCommunicatorFactory = async(deviceIdentity, cancellationToken) =>
            {
                var csb      = IotHubConnectionStringBuilder.Create(baseConnectionString);
                var identity = (IotHubDeviceIdentity)deviceIdentity;
                csb.AuthenticationMethod = DeriveAuthenticationMethod(csb.AuthenticationMethod, identity);
                csb.HostName             = identity.IotHubHostName;
                string connectionString = csb.ToString();
                var    bridge           = await CreateFromConnectionStringAsync(identity.Id, connectionString, connectionPoolSize, connectionIdleTimeout, settings, cancellationToken);

                initHandler(bridge);
                return(bridge);
            };

            return(mqttCommunicatorFactory);
        }
Exemple #14
0
        static async Task SendMessages(ModuleClient moduleClient)
        {
            string moduleId = IotHubConnectionStringBuilder.Create(ModuleConnectionString).ModuleId;

            Console.WriteLine("Device sending {0} messages to IoT Hub...\n", MESSAGE_COUNT);

            for (int count = 0; count < MESSAGE_COUNT; count++)
            {
                temperature = rnd.Next(20, 35);
                humidity    = rnd.Next(60, 80);
                string dataBuffer   = string.Format("{{\"deviceId\":\"{0}\",\"messageId\":{1},\"temperature\":{2},\"humidity\":{3}}}", moduleId, count, temperature, humidity);
                var    eventMessage = new Message(Encoding.UTF8.GetBytes(dataBuffer));
                eventMessage.Properties.Add("temperatureAlert", (temperature > TEMPERATURE_THRESHOLD) ? "true" : "false");
                Console.WriteLine("\t{0}> Sending message: {1}, Data: [{2}]", DateTime.Now.ToLocalTime(), count, dataBuffer);

                await moduleClient.SendEventAsync("sample/test/", eventMessage);
            }
        }
        public static async Task <string> CreateDevice(string hubConnectionString, string deviceId)
        {
            IotHubConnectionStringBuilder connection = IotHubConnectionStringBuilder.Create(hubConnectionString);
            RegistryManager registryManager          = RegistryManager.CreateFromConnectionString(connection.ToString());

            Device device;

            try
            {
                device = await registryManager.AddDeviceAsync(new Device(deviceId));
            }
            catch (Exception)
            {
                device = await registryManager.GetDeviceAsync(deviceId);
            }

            return("HostName=" + connection.HostName + ";DeviceId=" + deviceId + ";SharedAccessKey=" + device.Authentication.SymmetricKey.PrimaryKey);
        }
Exemple #16
0
        public void DeviceScopeMuxConnection_PoolingOnNegativeReleaseTest()
        {
            // Arrange
            var    amqpConnectionPoolSettings = new AmqpConnectionPoolSettings();
            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);

            connectionCache.Setup(cache => cache.GetConnection(It.IsAny <IotHubConnectionString>(), It.IsAny <AmqpTransportSettings>())).Returns(connectionPool.GetConnection("device1"));

            // Act
            var connection = connectionCache.Object.GetConnection(iotHubConnectionString, amqpTransportSettings);

            // throw exception if you release a device that is not in the pool
            connection.Release("device2");
        }
Exemple #17
0
        public async Task ManuallyProvisionEdgeSasAsync(EdgeDevice device, DateTime startTime, CancellationToken token)
        {
            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);

            await this.WaitForConfiguredStatusAsync(device, startTime, token);
        }
        /// <summary>
        /// Create sdk factory
        /// </summary>
        /// <param name="hub">Outer hub abstraction</param>
        /// <param name="config">Module framework configuration</param>
        public IoTHubClientFactory(IIoTHub hub, IModuleConfig config)
        {
            _hub = hub ?? throw new ArgumentNullException(nameof(hub));
            if (string.IsNullOrEmpty(config.EdgeHubConnectionString))
            {
                throw new InvalidConfigurationException(
                          "Must have connection string or module id to create clients.");
            }
            var cs = IotHubConnectionStringBuilder.Create(config.EdgeHubConnectionString);

            if (string.IsNullOrEmpty(cs.DeviceId))
            {
                throw new InvalidConfigurationException(
                          "Connection string is not a device or module connection string.");
            }
            DeviceId = cs.DeviceId;
            ModuleId = cs.ModuleId;
        }
        public async Task <string> GetModulePrimaryKey(RequestedResource sr)
        {
            var credentials = SdkContext.AzureCredentialsFactory.FromMSI(new MSILoginInformation(MSIResourceType.AppService),
                                                                         AzureEnvironment.AzureGlobalCloud);
            var azure = Azure
                        .Configure()
                        .WithLogLevel(HttpLoggingDelegatingHandler.Level.Basic)
                        .Authenticate(credentials)
                        .WithDefaultSubscription();

            string iothubowner = string.Empty;

            var    azureServiceTokenProvider = new AzureServiceTokenProvider();
            string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com");

            IotHubClient hubClient = new IotHubClient(new TokenCredentials(accessToken))
            {
                SubscriptionId = azure.GetCurrentSubscription().SubscriptionId
            };
            var listHubs = await hubClient.IotHubResource.ListBySubscriptionAsync();

            do
            {
                var hub = listHubs.Where(iothub => string.Equals(iothub.Name, sr.iotHubName)).FirstOrDefault();
                if (!string.IsNullOrEmpty(hub.Id))
                {
                    iothubowner = (await hubClient.IotHubResource.GetKeysForKeyNameAsync(GetResourceGroupName(hub.Id), hub.Name, "iothubowner")).PrimaryKey;
                    break;
                }
            } while (!string.IsNullOrEmpty(listHubs.NextPageLink));

            if (string.IsNullOrEmpty(iothubowner))
            {
                throw new Exception("Failed to retrieve IoT Hub Primary Key string");
            }

            string iotHubConnString = IotHubConnectionStringBuilder.Create(sr.iotHubFQDN, new ServiceAuthenticationWithSharedAccessPolicyKey("iothubowner", iothubowner)).ToString();

            RegistryManager registryManager = RegistryManager.CreateFromConnectionString(iotHubConnString);

            var modulesOnDevice = await registryManager.GetModuleAsync(sr.deviceId, sr.moduleId);

            return(!string.IsNullOrEmpty(modulesOnDevice.Authentication.SymmetricKey.PrimaryKey) ? modulesOnDevice.Authentication.SymmetricKey.PrimaryKey : null);
        }
Exemple #20
0
        private async Task RegisterEventProcessorFactoryWithBlobCheckpointingAsync()
        {
            var storageCredentials = new StorageCredentials(
                config.IoTHubConfig.CheckpointingConfig.StorageConfig.AzureBlobConfig.Account,
                config.IoTHubConfig.CheckpointingConfig.StorageConfig.AzureBlobConfig.Key);

            var storageAccount = new CloudStorageAccount(
                storageCredentials,
                config.IoTHubConfig.CheckpointingConfig.StorageConfig.AzureBlobConfig.EndpointSuffix,
                config.IoTHubConfig.CheckpointingConfig.StorageConfig.AzureBlobConfig.Protocol == "https");

            var iotHubConnectionBuilder = IotHubConnectionStringBuilder.Create(config.IoTHubConfig.ConnectionConfig.AccessConnString);

            if (!Uri.TryCreate(config.IoTHubConfig.ConnectionConfig.HubEndpoint, UriKind.Absolute, out Uri endpoint))
            {
                if (!Uri.TryCreate($"sb://{config.IoTHubConfig.ConnectionConfig.HubEndpoint}/", UriKind.Absolute, out endpoint))
                {
                    throw new InvalidConfigurationException($"Invalid IoTHub endpoint {config.IoTHubConfig.ConnectionConfig.HubEndpoint}");
                }
            }

            var eventHubConntionStringBuilder = new EventHubsConnectionStringBuilder(
                endpoint,
                config.IoTHubConfig.ConnectionConfig.HubName,
                iotHubConnectionBuilder.SharedAccessKeyName,
                iotHubConnectionBuilder.SharedAccessKey);

            eventProcessorHost = new EventProcessorHost(
                config.IoTHubConfig.ConnectionConfig.HubName,
                config.IoTHubConfig.StreamingConfig.ConsumerGroup,
                eventHubConntionStringBuilder.ToString(),
                storageAccount.ToString(true),
                config.IoTHubConfig.CheckpointingConfig.StorageConfig.Namespace);

            var options = new EventProcessorOptions
            {
                InitialOffsetProvider = InitialOffset,
                MaxBatchSize          = config.IoTHubConfig.StreamingConfig.ReceiveBatchSize,
                ReceiveTimeout        = config.IoTHubConfig.StreamingConfig.ReceiveTimeout,
                InvokeProcessorAfterReceiveTimeout = true
            };

            await eventProcessorHost.RegisterEventProcessorFactoryAsync(processorFactory, options);
        }
Exemple #21
0
        // Set IoTHub connection strings, using either the user provided value or the configuration,
        // initialize the IoT Hub registry, and perform other initializations.
        // TODO: use the simulation object to decide which conn string to use
        public async Task InitAsync()
        {
            this.instance.InitOnce();

            try
            {
                // TODO: use the simulation object to decide which conn string to use
                // Retrieve connection string from file/storage
                this.connString = await this.connectionStrings.GetAsync();

                // Parse connection string, this triggers an exception if the string is invalid
                IotHubConnectionStringBuilder connStringBuilder = IotHubConnectionStringBuilder.Create(this.connString);

                // Prepare registry class used to create/retrieve devices
                this.registry.Init(this.connString);
                this.log.Debug("Device registry object ready", () => new { this.ioTHubHostName });

                // Prepare hostname used to build device connection strings
                this.ioTHubHostName = connStringBuilder.HostName;
                this.log.Info("Selected active IoT Hub for devices", () => new { this.ioTHubHostName });

                // Prepare the auth key used for all the devices
                this.fixedDeviceKey = connStringBuilder.SharedAccessKey;
                this.log.Debug("Device authentication key defined", () => new { this.ioTHubHostName });

                this.instance.InitComplete();
            }
            catch (Exception e) when(e is ArgumentException || e is FormatException)
            {
                const string MSG = "Invalid IoT Hub connection string";

                this.log.Error(MSG, e);
                this.diagnosticsLogger.LogServiceError(MSG, e.Message);
                throw new InvalidIotHubConnectionStringFormatException(MSG, e);
            }
            catch (Exception e)
            {
                const string MSG = "IoT Hub connection setup failed";
                this.log.Error(MSG, e);
                this.diagnosticsLogger.LogServiceError(MSG, e.Message);
                throw;
            }
        }
Exemple #22
0
        public async Task SendMessageMultipleDevicesTest()
        {
            IList <IMessage> messages  = MessageHelper.GenerateMessages(4);
            DateTime         startTime = DateTime.UtcNow.Subtract(ClockSkew);

            string device2ConnectionString = await SecretsHelper.GetSecretFromConfigKey(Device2ConnStrKey);

            string device3ConnectionString = await SecretsHelper.GetSecretFromConfigKey(Device3ConnStrKey);

            string deviceId2 = IotHubConnectionStringBuilder.Create(device2ConnectionString).DeviceId;
            string deviceId3 = IotHubConnectionStringBuilder.Create(device3ConnectionString).DeviceId;

            ICloudProxy cloudProxy2 = await this.GetCloudProxyFromConnectionStringKey(Device2ConnStrKey);

            ICloudProxy cloudProxy3 = await this.GetCloudProxyFromConnectionStringKey(Device3ConnStrKey);

            Dictionary <string, IList <IMessage> > sentMessagesByDevice = new Dictionary <string, IList <IMessage> >();

            sentMessagesByDevice.Add(deviceId2, new List <IMessage>());
            sentMessagesByDevice.Add(deviceId3, new List <IMessage>());

            for (int i = 0; i < messages.Count; i = i + 2)
            {
                IMessage device2Message = messages[i];
                IMessage device3Message = messages[i + 1];

                await cloudProxy2.SendMessageAsync(device2Message);

                await cloudProxy3.SendMessageAsync(device3Message);

                sentMessagesByDevice[deviceId2].Add(device2Message);
                sentMessagesByDevice[deviceId3].Add(device3Message);
            }

            bool disconnectResult = await cloudProxy2.CloseAsync();

            Assert.True(disconnectResult);
            disconnectResult = await cloudProxy3.CloseAsync();

            Assert.True(disconnectResult);

            await CheckMessageInEventHub(sentMessagesByDevice, startTime);
        }
Exemple #23
0
 public HubReceiver(IStressDataProvider provider)
 {
     try
     {
         var builder = IotHubConnectionStringBuilder.Create(provider.HubOwnerConectionString);
         configSettings = new Settings();
         configSettings.ConnectionString    = $"Endpoint={provider.EventHubEndpoint};SharedAccessKeyName={builder.SharedAccessKeyName};SharedAccessKey={builder.SharedAccessKey}";
         configSettings.Path                = builder.HostName.Split('.').First();
         configSettings.PartitionId         = "0";
         configSettings.GroupName           = "$Default";
         configSettings.StartingDateTimeUtc = DateTime.UtcNow - TimeSpan.FromMinutes(2);
         pause      = false;
         workThread = new Thread(() => FetchHubData());
         workThread.Start();
     }
     catch
     {
     }
 }
Exemple #24
0
        public DockerModule(
            string edgeDeviceConnectionString,
            string gatewayHostName,
            Uri dockerHostname,
            IEnumerable <AuthConfig> dockerAuthConfig,
            Option <UpstreamProtocol> upstreamProtocol,
            Option <string> productInfo)
        {
            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.productInfo      = productInfo;
        }
        static internal IAuthenticationMethod GetAuthenticationMethod(IotHubConnectionStringBuilder iotHubConnectionStringBuilder)
        {
            if (iotHubConnectionStringBuilder.SharedAccessKeyName != null)
            {
                return new DeviceAuthenticationWithSharedAccessPolicyKey(
                    iotHubConnectionStringBuilder.DeviceId, iotHubConnectionStringBuilder.SharedAccessKeyName, iotHubConnectionStringBuilder.SharedAccessKey);
            }
            else if (iotHubConnectionStringBuilder.SharedAccessKey != null)
            {
                return new DeviceAuthenticationWithRegistrySymmetricKey(
                    iotHubConnectionStringBuilder.DeviceId, iotHubConnectionStringBuilder.SharedAccessKey);
            }       
            else if (iotHubConnectionStringBuilder.SharedAccessSignature != null)
            {
                return new DeviceAuthenticationWithToken(iotHubConnectionStringBuilder.DeviceId, iotHubConnectionStringBuilder.SharedAccessSignature);
            }

            throw new InvalidOperationException("Unsupported Authentication Method {0}".FormatInvariant(iotHubConnectionStringBuilder));
        }
Exemple #26
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);
                string connectionString =
                    $"HostName={builder.HostName};" +
                    $"DeviceId={this.context.Device.Id};" +
                    $"SharedAccessKey={this.context.Device.Authentication.SymmetricKey.PrimaryKey}";

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

            return(this.bootstrapper.Configure(method, this.EdgeAgentImage(), this.hostname, this.deviceCaCert, this.deviceCaPk, this.deviceCaCerts, this.runtimeLogLevel));
        }
Exemple #27
0
        static async Task <int> Main(string[] args)
        {
            var secretUri = args.ElementAtOrDefault(0);
            var transport = args.ElementAtOrDefault(1);

            if (string.IsNullOrWhiteSpace(secretUri))
            {
                Console.Error.WriteLine("Missing argument for secretUri");
                PrintUsage();
                return(1);
            }

            if (string.IsNullOrWhiteSpace(transport) || !Parse(transport, out TransportType transportType))
            {
                Console.Error.WriteLine("Invalid or missing argument for transport");
                PrintUsage();
                return(1);
            }

            var secret = await GetSecretAsync(secretUri);

            var builder          = IotHubConnectionStringBuilder.Create(secret);
            var connectionString = builder.ToString();

            var message = $"{DateTime.UtcNow} Hello world!";

            if (string.IsNullOrEmpty(builder.ModuleId))
            {
                Console.Write($"Sending an event as {builder.DeviceId}: {message}...");
                var client = DeviceClient.CreateFromConnectionString(connectionString, transportType);
                await client.SendEventAsync(new Message(Encoding.ASCII.GetBytes(message)));
            }
            else
            {
                Console.Write($"Sending an event as {builder.DeviceId}/{builder.ModuleId}: {message}...");
                var client = ModuleClient.CreateFromConnectionString(connectionString, transportType);
                await client.SendEventAsync(new Message(Encoding.ASCII.GetBytes(message)));
            }

            Console.WriteLine("done");

            return(0);
        }
            /// <summary>
            /// Helper to create module client
            /// </summary>
            /// <param name="cs"></param>
            /// <param name="transportSetting"></param>
            /// <returns></returns>
            private static async Task <ModuleClient> CreateAsync(IotHubConnectionStringBuilder cs,
                                                                 ITransportSettings transportSetting)
            {
                if (transportSetting == null)
                {
                    if (cs == null)
                    {
                        return(await ModuleClient.CreateFromEnvironmentAsync());
                    }
                    return(ModuleClient.CreateFromConnectionString(cs.ToString()));
                }
                var ts = new ITransportSettings[] { transportSetting };

                if (cs == null)
                {
                    return(await ModuleClient.CreateFromEnvironmentAsync(ts));
                }
                return(ModuleClient.CreateFromConnectionString(cs.ToString(), ts));
            }
        internal static async Task <DeviceClient> ProvisionDeviceWithSasKeyAsync(string scopeId, string deviceId, string deviceKey, string modelId, ILogger log)
        {
            using (var transport = new ProvisioningTransportHandlerMqtt())
            {
                using (var security = new SecurityProviderSymmetricKey(deviceId, deviceKey, null))
                {
                    DeviceRegistrationResult provResult;
                    var provClient = ProvisioningDeviceClient.Create("global.azure-devices-provisioning.net", scopeId, security, transport);

                    if (!string.IsNullOrEmpty(modelId))
                    {
                        provResult = await provClient.RegisterAsync(GetProvisionPayload(modelId)).ConfigureAwait(false);
                    }
                    else
                    {
                        provResult = await provClient.RegisterAsync().ConfigureAwait(false);
                    }

                    log.LogInformation($"Provioning Result. Status [{provResult.Status}] SubStatus [{provResult.Substatus}]");

                    if (provResult.Status == ProvisioningRegistrationStatusType.Assigned)
                    {
                        log.LogWarning($"Device {provResult.DeviceId} in Hub {provResult.AssignedHub}");
                        log.LogInformation($"LastRefresh {provResult.LastUpdatedDateTimeUtc} RegistrationId {provResult.RegistrationId}");
                        var    csBuilder        = IotHubConnectionStringBuilder.Create(provResult.AssignedHub, new DeviceAuthenticationWithRegistrySymmetricKey(provResult.DeviceId, security.GetPrimaryKey()));
                        string connectionString = csBuilder.ToString();
                        return(await Task.FromResult(
                                   DeviceClient.CreateFromConnectionString(
                                       connectionString, TransportType.Mqtt,
                                       new ClientOptions()
                        {
                            ModelId = modelId
                        })));
                    }
                    else
                    {
                        string errorMessage = $"Device not provisioned. Message: {provResult.ErrorMessage}";
                        log.LogError(errorMessage);
                        throw new IotHubException(errorMessage);
                    }
                }
            }
        }
Exemple #30
0
            /// <summary>
            /// Factory
            /// </summary>
            /// <param name="product"></param>
            /// <param name="cs"></param>
            /// <param name="deviceId"></param>
            /// <param name="transportSetting"></param>
            /// <param name="timeout"></param>
            /// <param name="retry"></param>
            /// <param name="onConnectionLost"></param>
            /// <param name="logger"></param>
            /// <returns></returns>
            public static async Task<IClient> CreateAsync(string product,
                IotHubConnectionStringBuilder cs, string deviceId,
                ITransportSettings transportSetting, TimeSpan timeout,
                IRetryPolicy retry, Action onConnectionLost, ILogger logger) {
                var client = Create(cs, transportSetting);
                var adapter = new DeviceClientAdapter(client);

                // Configure
                client.OperationTimeoutInMilliseconds = (uint)timeout.TotalMilliseconds;
                client.SetConnectionStatusChangesHandler((s, r) =>
                    adapter.OnConnectionStatusChange(deviceId, onConnectionLost, logger, s, r));
                if (retry != null) {
                    client.SetRetryPolicy(retry);
                }
                client.DiagnosticSamplingPercentage = 5;
                client.ProductInfo = product;

                await client.OpenAsync();
                return adapter;
            }
        public void DeviceScopeMuxConnection_PoolingOnPositiveReleaseTest()
        {
            // Arrange
            var    amqpConnectionPoolSettings = new AmqpConnectionPoolSettings();
            var    amqpTransportSettings      = new AmqpTransportSettings(TransportType.Amqp_Tcp_Only, 200, amqpConnectionPoolSettings);
            string connectionString           = "HostName=acme.azure-devices.net;DeviceId=device1;SharedAccessKey=dGVzdFN0cmluZzE=";
            var    iotHubConnectionString     = IotHubConnectionStringBuilder.Create(connectionString).ToIotHubConnectionString();
            var    connectionCache            = new Mock <IotHubConnectionCache>();
            var    connectionPool             = new IotHubDeviceScopeConnectionPool(connectionCache.Object, iotHubConnectionString, amqpTransportSettings);

            connectionCache.Setup(
                cache => cache.GetConnection(It.IsAny <IotHubConnectionString>(), It.IsAny <AmqpTransportSettings>())).Returns(connectionPool.GetConnection("device1"));

            // Act
            var connection = connectionCache.Object.GetConnection(iotHubConnectionString, amqpTransportSettings);

            connection.Release("device1");

            // Success - Device1 was in the pool and released
        }
        public static DeviceClientFactoryFunc PreparePoolFactory(string baseConnectionString, string poolId, int connectionPoolSize)
        {
            IotHubConnectionStringBuilder csb = IotHubConnectionStringBuilder.Create(baseConnectionString);

            string[] connectionIds   = Enumerable.Range(1, connectionPoolSize).Select(index => poolId + index).ToArray();
            int      connectionIndex = 0;
            DeviceClientFactoryFunc deviceClientFactory = deviceCredentials =>
            {
                if (++connectionIndex >= connectionPoolSize)
                {
                    connectionIndex = 0;
                }
                //csb.GroupName = connectionIds[connectionIndex]; // todo: uncommment once explicit control over connection pooling is available
                csb.AuthenticationMethod = Util.DeriveAuthenticationMethod(csb.AuthenticationMethod, deviceCredentials);
                string connectionString = csb.ToString();
                return(CreateFromConnectionStringAsync(connectionString));
            };

            return(deviceClientFactory);
        }
        private static string DoActivation()
        {
            //connect to activation service, get back activation record, build iot hub connection string
            var client  = new RestClient(ConfigurationManager.AppSettings["ActivationUri"]);
            var code    = ConfigurationManager.AppSettings["ActivationKey"];
            var request = new RestRequest("/api/Device/activate/" + code, Method.POST);
            var results = client.Execute <ActivationDto>(request);

            if (null == results || results.Data == null)
            {
                Console.WriteLine("activation failed. hit any key to exit");
                Console.Read();
                throw new InvalidOperationException();
            }
            var activation = results.Data;
            var connection = IotHubConnectionStringBuilder.Create(activation.hostName,
                                                                  new DeviceAuthenticationWithRegistrySymmetricKey(activation.deviceId, activation.key));

            return(connection.ToString());
        }
        public void IotHubConnectionStringBuilder_ParamConnectionString_ParsesX509Mix(string x509CertValue, string x509Value)
        {
            var connectionString = $"HostName={HostName};DeviceId={DeviceId}";

            if (x509CertValue != null)
            {
                connectionString += $";X509Cert={x509CertValue}";
            }
            if (x509Value != null)
            {
                connectionString += $";x509={x509Value}";
            }
            var csBuilder = IotHubConnectionStringBuilder.Create(connectionString);

            csBuilder.UsingX509Cert.Should().BeTrue();

            csBuilder.SharedAccessKey.Should().BeNull();
            csBuilder.SharedAccessKeyName.Should().BeNull();
            csBuilder.SharedAccessSignature.Should().BeNull();
        }
        public IotHubConnectionString(IotHubConnectionStringBuilder builder)
        {
            if (builder == null)
            {
                throw new ArgumentNullException("builder");
            }

            this.HostName = builder.HostName;
            this.SharedAccessKeyName = builder.SharedAccessKeyName;
            this.SharedAccessKey = builder.SharedAccessKey;
            this.SharedAccessSignature = builder.SharedAccessSignature; 
            this.IotHubName = builder.IotHubName;
            this.DeviceId = builder.DeviceId;
#if WINDOWS_UWP
            this.HttpsEndpoint = new UriBuilder("https", builder.HostName).Uri;
#else
            this.HttpsEndpoint = new UriBuilder(Uri.UriSchemeHttps, builder.HostName).Uri;
#endif
#if !WINDOWS_UWP
            this.AmqpEndpoint = new UriBuilder(CommonConstants.AmqpsScheme, builder.HostName, AmqpConstants.DefaultSecurePort).Uri;
#endif
        }
        static ITransportSettings[] PopulateCertificateInTransportSettings(IotHubConnectionStringBuilder connectionStringBuilder, ITransportSettings[] transportSettings)
        {
            foreach (var transportSetting in  transportSettings)
            {
                switch (transportSetting.GetTransportType())
                {
                    case TransportType.Amqp_WebSocket_Only:
                    case TransportType.Amqp_Tcp_Only:
                        ((AmqpTransportSettings)transportSetting).ClientCertificate = connectionStringBuilder.Certificate;
                        break;
                    case TransportType.Http1:
                        ((Http1TransportSettings)transportSetting).ClientCertificate = connectionStringBuilder.Certificate;
                        break;
                    case TransportType.Mqtt:
                        ((MqttTransportSettings)transportSetting).ClientCertificate = connectionStringBuilder.Certificate;
                        break;
                    default:
                        throw new InvalidOperationException("Unsupported Transport {0}".FormatInvariant(transportSetting.GetTransportType()));
                }
            }

            return transportSettings;
        }
 static ITransportSettings[] PopulateCertificateInTransportSettings(IotHubConnectionStringBuilder connectionStringBuilder, TransportType transportType)
 {
     switch (transportType)
     {
         case TransportType.Amqp:
             return new ITransportSettings[]
             {
                 new AmqpTransportSettings(TransportType.Amqp_Tcp_Only)
                 {
                     ClientCertificate = connectionStringBuilder.Certificate
                 },
                 new AmqpTransportSettings(TransportType.Amqp_WebSocket_Only)
                 {
                     ClientCertificate = connectionStringBuilder.Certificate
                 },
             };
         case TransportType.Amqp_Tcp_Only:
             return new ITransportSettings[]
             {
                 new AmqpTransportSettings(TransportType.Amqp_Tcp_Only)
                 {
                     ClientCertificate = connectionStringBuilder.Certificate
                 }
             };
         case TransportType.Amqp_WebSocket_Only:
             return new ITransportSettings[]
             {
                 new AmqpTransportSettings(TransportType.Amqp_WebSocket_Only)
                 {
                     ClientCertificate = connectionStringBuilder.Certificate
                 }
             };
         case TransportType.Http1:
             return new ITransportSettings[]
             {
                 new Http1TransportSettings()
                 {
                     ClientCertificate = connectionStringBuilder.Certificate
                 }
             };
         case TransportType.Mqtt:
             return new ITransportSettings[]
             {
                 new MqttTransportSettings(TransportType.Mqtt) 
                 {
                     ClientCertificate = connectionStringBuilder.Certificate
                 }
             };
         default:
             throw new InvalidOperationException("Unsupported Transport {0}".FormatInvariant(transportType));
     }
 }