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

            var converters = new MessageConverterProvider(new Dictionary <Type, IMessageConverter>()
            {
                { typeof(Client.Message), new DeviceClientMessageConverter() },
                { typeof(Twin), new TwinMessageConverter() },
                { typeof(TwinCollection), new TwinCollectionMessageConverter() }
            });

            ICloudConnectionProvider cloudConnectionProvider = new CloudConnectionProvider(converters, ConnectionPoolSize, new ClientProvider(), Option.None <UpstreamProtocol>(), Mock.Of <ITokenProvider>(), Mock.Of <IDeviceScopeIdentitiesCache>(), TimeSpan.FromMinutes(60), true);

            cloudConnectionProvider.BindEdgeHub(edgeHub);
            var deviceIdentity    = Mock.Of <IDeviceIdentity>(m => m.Id == ConnectionStringHelper.GetDeviceId(deviceConnectionString));
            var clientCredentials = new SharedKeyCredentials(deviceIdentity, deviceConnectionString, string.Empty);

            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());
        }
Beispiel #2
0
        public async Task CanListenForDesiredPropertyUpdates()
        {
            var    update                    = new TaskCompletionSource <IMessage>();
            var    cloudListener             = new Mock <ICloudListener>();
            string deviceConnectionStringKey = "device2ConnStrKey";

            cloudListener.Setup(x => x.OnDesiredPropertyUpdates(It.IsAny <IMessage>()))
            .Callback((IMessage m) => update.TrySetResult(m))
            .Returns(TaskEx.Done);

            ICloudProxy cloudProxy = await this.GetCloudProxyWithConnectionStringKey(deviceConnectionStringKey);

            cloudProxy.BindCloudListener(cloudListener.Object);
            await cloudProxy.SetupDesiredPropertyUpdatesAsync();

            var desired = new TwinCollection()
            {
                ["desiredPropertyTest"] = Guid.NewGuid().ToString()
            };

            await UpdateDesiredProperty(ConnectionStringHelper.GetDeviceId(await SecretsHelper.GetSecretFromConfigKey(deviceConnectionStringKey)), desired);

            await update.Task;
            await cloudProxy.RemoveDesiredPropertyUpdatesAsync();

            IMessage expected = new EdgeMessage.Builder(Encoding.UTF8.GetBytes(desired.ToJson())).Build();

            expected.SystemProperties[SystemProperties.EnqueuedTime] = "";
            expected.SystemProperties[SystemProperties.Version]      = desired.Version.ToString();
            IMessage actual = update.Task.Result;

            Assert.Equal(expected.Body, actual.Body);
            Assert.Equal(expected.Properties, actual.Properties);
            Assert.Equal(expected.SystemProperties.Keys, actual.SystemProperties.Keys);
        }
Beispiel #3
0
        public bool AuthenticateUser(UserDto user, string repositoryUrl, GeminiContext gemini)
        {
            //UserWidgetData<List<UserWidgetDataDetails>> userDataRaw = gemini.UserWidgetStore.Get<List<UserWidgetDataDetails>>(user.Entity.Id, Constants.AppId, Constants.ControlId);

            var allUserDataRaw = gemini.UserWidgetStore.GetAll().Where(f => f.AppId == Constants.AppId && f.ControlId == Constants.ControlId);

            if (allUserDataRaw == null || allUserDataRaw.Count() == 0)
            {
                return(false);
            }

            var data = allUserDataRaw.Select(f => f.Value.FromJson <List <UserWidgetDataDetails> >()).First().Find(s => s.Provider == SourceControlProvider.GitHub && s.RepositoryUrl == repositoryUrl);

            if (data == null)
            {
                return(false);
            }

            if (data.AccessToken.IsEmpty())
            {
                return(false);
            }

            Username = data.Username;

            Password = SecretsHelper.Decrypt(data.Password, SecretsHelper.EncryptionKey);

            AccessToken = data.AccessToken;

            return(true);
        }
        public async Task ConnectWithInvalidConnectionStringTest()
        {
            var edgeHub = Mock.Of <IEdgeHub>();
            ICloudConnectionProvider cloudConnectionProvider = new CloudConnectionProvider(MessageConverterProvider, ConnectionPoolSize, new ClientProvider(), Option.None <UpstreamProtocol>(), TokenProvider, DeviceScopeIdentitiesCache, TimeSpan.FromMinutes(60));

            cloudConnectionProvider.BindEdgeHub(edgeHub);
            var deviceIdentity1           = Mock.Of <IIdentity>(m => m.Id == "device1");
            var clientCredentials1        = new SharedKeyCredentials(deviceIdentity1, "dummyConnStr", null);
            Try <ICloudConnection> result = await cloudConnectionProvider.Connect(clientCredentials1, null);

            Assert.False(result.Success);
            Assert.IsType <AggregateException>(result.Exception);

            string deviceConnectionString = await SecretsHelper.GetSecretFromConfigKey("device1ConnStrKey");

            // Change the connection string key, deliberately.
            char updatedLastChar = (char)(deviceConnectionString[deviceConnectionString.Length - 1] + 1);

            deviceConnectionString = deviceConnectionString.Substring(0, deviceConnectionString.Length - 1) + updatedLastChar;
            var deviceIdentity2               = Mock.Of <IIdentity>(m => m.Id == ConnectionStringHelper.GetDeviceId(deviceConnectionString));
            var clientCredentials2            = new SharedKeyCredentials(deviceIdentity2, deviceConnectionString, null);
            Try <ICloudConnection> cloudProxy = cloudConnectionProvider.Connect(clientCredentials2, null).Result;

            Assert.False(cloudProxy.Success);
        }
Beispiel #5
0
        static async Task CheckMessageInEventHub(IList <IMessage> sentMessages, DateTime startTime)
        {
            string eventHubConnectionString = await SecretsHelper.GetSecretFromConfigKey("eventHubConnStrKey");

            var  eventHubReceiver = new EventHubReceiver(eventHubConnectionString);
            var  cloudMessages    = new List <EventData>();
            bool messagesFound    = false;

            //Add retry mechanism to make sure all the messages sent reached Event Hub. Retry 3 times.
            for (int i = 0; i < EventHubMessageReceivedRetry; i++)
            {
                cloudMessages.AddRange(await eventHubReceiver.GetMessagesFromAllPartitions(startTime));
                messagesFound = MessageHelper.CompareMessagesAndEventData(sentMessages, cloudMessages);
                if (messagesFound)
                {
                    break;
                }
                await Task.Delay(TimeSpan.FromSeconds(20));
            }

            await eventHubReceiver.Close();

            Assert.NotNull(cloudMessages);
            Assert.NotEmpty(cloudMessages);
            Assert.True(messagesFound);
        }
Beispiel #6
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));
        }
Beispiel #7
0
        // [InlineData(TransportType.Mqtt_WebSocket_Only)] // Disabled: need a valid server cert for WebSocket to work
        public async void Receive_C2D_SingleMessage_ShouldSucceed(TransportType transportType)
        {
            // Arrange
            string iotHubConnectionString = await SecretsHelper.GetSecretFromConfigKey("iotHubConnStrKey");

            RegistryManager rm = RegistryManager.CreateFromConnectionString(iotHubConnectionString);

            (string deviceName, string deviceConnectionString) = await RegistryManagerHelper.CreateDevice(DeviceNamePrefix, iotHubConnectionString, rm);

            ServiceClient serviceClient = null;
            DeviceClient  deviceClient  = null;

            try
            {
                serviceClient = ServiceClient.CreateFromConnectionString(iotHubConnectionString);
                await serviceClient.OpenAsync();

                ITransportSettings[] settings = this.GetTransportSettings(transportType);
                deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, settings);
                // Dummy ReceiveAsync to ensure mqtt subscription registration before SendAsync() is called on service client.
                await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(2));

                // Act
                Message message = this.CreateMessage(out string payload);
                await serviceClient.SendAsync(deviceName, message);

                // Assert
                await this.VerifyReceivedC2DMessage(deviceClient, payload, message.Properties[MessagePropertyName]);
            }
            finally
            {
                await this.Cleanup(deviceClient, serviceClient, rm, deviceName);
            }
        }
Beispiel #8
0
        private async Task LoadUserData()
        {
            var userName = await SecretsHelper.GetUserName();

            await Task.Delay(1000);

            Account account = await Accounts.GetAccount(userName);

            UserName = account.Url;
            Points   = account.Reputation;
            GalleryProfile galleryProfile = await Accounts.GetGalleryProfile(userName);

            Trophies = new ObservableCollection <Trophy>(galleryProfile.Trophies);
            await Task.Delay(500);

            await LoadAlbums(userName);

            await Task.Delay(500);

            await LoadImages(userName);

            await Task.Delay(500);

            await LoadFavourites(userName);
        }
Beispiel #9
0
        // ReSharper disable once UnusedMember.Local
        async Task <int> OnExecuteAsync()
        {
            try
            {
                string connectionString = this.DeviceConnectionString ??
                                          await SecretsHelper.GetSecretFromConfigKey("iotHubConnStrKey");

                string endpoint = this.EventHubCompatibleEndpointWithEntityPath ??
                                  await SecretsHelper.GetSecretFromConfigKey("eventHubConnStrKey");

                var test = new LeafDevice(
                    connectionString,
                    endpoint,
                    this.DeviceId,
                    this.CertificateFileName,
                    this.EdgeHostName);
                await test.RunAsync();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                return(1);
            }

            Console.WriteLine("Success!");
            return(0);
        }
Beispiel #10
0
            public ActionResult Authenticate(string code, int state)
            {
                GitHub gitHub = new GitHub(); //Creates a new GitHub object

                UserWidgetData <List <UserWidgetDataDetails> > userDataRaw = GeminiContext.UserWidgetStore.Get <List <UserWidgetDataDetails> >(CurrentUser.Entity.Id, Constants.AppId, Constants.ControlId);

                if (userDataRaw != null)
                {
                    var data = userDataRaw.Value.Find(f => f.Provider == SourceControlProvider.GitHub && f.AccessToken.IsEmpty());

                    // Need to check that state is the same as we've sent otherwise ABORT (cross-site request forgery attacks) !
                    if (!code.IsEmpty() && CurrentUser.Entity.Id == state)
                    {
                        if (data != null)
                        {
                            var password = SecretsHelper.Decrypt(data.Password, SecretsHelper.EncryptionKey);

                            try
                            {
                                var response = gitHub.GetResponse(string.Format("https://github.com/login/oauth/access_token?client_id={0}&client_secret={1}&code={2}&state={3}", data.Username, password, code, state), RestSharp.Method.GET);

                                if (response != null)
                                {
                                    var token = response.Content.FromJson <AuthenticateToken>();

                                    if (token.access_token.IsNullOrWhiteSpace())
                                    {
                                        GeminiApp.LogException(new Exception(response.Content.FromJson <Error>().error)
                                        {
                                            Source = "GitHub Authentication"
                                        }, false);
                                        gitHub.DeleteLoginDetails(CurrentUser, data, GeminiContext);
                                        //If request fails we need to make sure we delete the record associated with this authentication request from DB. Otherwise we'll have several records with empty access token
                                    }
                                    else
                                    {
                                        data.AccessToken = token.access_token;
                                        gitHub.SaveLoginDetails(CurrentUser, data, GeminiContext);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                GeminiApp.LogException(ex, false);
                            }
                        }
                    }
                    else
                    {
                        GeminiApp.LogException(new UnauthorizedAccessException("Code/State invalid")
                        {
                            Source = SourceControlProvider.GitHub.ToString()
                        }, false);

                        gitHub.DeleteLoginDetails(CurrentUser, data, GeminiContext);
                    }
                }

                return(Redirect(CurrentProject.HomePageUrl));
            }
Beispiel #11
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));
        }
        private async Task SignOut()
        {
            State = BUSY;
            AuthenticationHelper.SetAuthIntention(false);
            await SecretsHelper.FlushSecrets();

            State = NOT_AUTHENTICATED;
        }
Beispiel #13
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));
        }
Beispiel #14
0
        public async void Receive_C2D_SingleMessage_AfterOfflineMessage_ShouldSucceed()
        {
            // Arrange
            string iotHubConnectionString = await SecretsHelper.GetSecretFromConfigKey("iotHubConnStrKey");

            string          edgeDeviceId = ConnectionStringHelper.GetDeviceId(ConfigHelper.TestConfig[Service.Constants.ConfigKey.IotHubConnectionString]);
            RegistryManager rm           = RegistryManager.CreateFromConnectionString(iotHubConnectionString);
            var             edgeDevice   = await rm.GetDeviceAsync(edgeDeviceId);

            (string deviceName, string deviceConnectionString) = await RegistryManagerHelper.CreateDevice(DeviceNamePrefix, iotHubConnectionString, rm, scope : edgeDevice.Scope);

            ServiceClient serviceClient = null;
            DeviceClient  deviceClient  = null;

            try
            {
                serviceClient = ServiceClient.CreateFromConnectionString(iotHubConnectionString);
                await serviceClient.OpenAsync();

                ITransportSettings[] settings = this.GetTransportSettings();
                deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, settings);
                // Dummy ReceiveAsync to ensure mqtt subscription registration before SendAsync() is called on service client.
                await deviceClient.ReceiveAsync(TimeSpan.FromSeconds(1));

                var device = await rm.GetDeviceAsync(deviceName);

                // Wait for device to be connected to cloud
                await this.WaitForDeviceConnectionStateTimeoutAfter(rm, deviceName, DeviceConnectionState.Connected, TimeSpan.FromSeconds(60));

                await deviceClient.CloseAsync();

                // Wait for the connection to be closed on the Edge side by checking device connection state
                await this.WaitForDeviceConnectionStateTimeoutAfter(rm, deviceName, DeviceConnectionState.Disconnected, TimeSpan.FromSeconds(60));

                // Act
                // Send message before device is listening
                Message message = this.CreateMessage(out string payload);
                await serviceClient.SendAsync(deviceName, message);

                deviceClient = DeviceClient.CreateFromConnectionString(deviceConnectionString, settings);

                // Assert
                await this.VerifyReceivedC2DMessage(deviceClient, payload, message.Properties[MessagePropertyName]);

                // Act
                // send new message after offline was received
                message = this.CreateMessage(out payload);
                await serviceClient.SendAsync(deviceName, message);

                // Assert
                await this.VerifyReceivedC2DMessage(deviceClient, payload, message.Properties[MessagePropertyName]);
            }
            finally
            {
                await this.Cleanup(deviceClient, serviceClient, rm, deviceName);
            }
        }
Beispiel #15
0
        private async Task <JObject> ShakeHands()
        {
            string userName = await SecretsHelper.GetUserName();

            const string urlPattern = "account/{0}/images/count";
            string       url        = string.Format(urlPattern, userName);
            JObject      result     = await NetworkHelper.ExecuteRequest(url);

            return(result);
        }
Beispiel #16
0
        protected async Task StoreLimitValidationTestAsync()
        {
            int        messagesCount = DefaultMessageCount;
            TestModule sender        = null;
            TestModule receiver      = null;

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

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

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

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

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

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

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

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

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

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

            // wait for the connection to be closed on the Edge side
            await Task.Delay(TimeSpan.FromSeconds(10));
        }
Beispiel #17
0
        static async Task UpdateDesiredProperty(string deviceId, TwinCollection desired)
        {
            string connectionString = await SecretsHelper.GetSecretFromConfigKey("iotHubConnStrKey");

            RegistryManager registryManager = RegistryManager.CreateFromConnectionString(connectionString);
            Twin            twin            = await registryManager.GetTwinAsync(deviceId);

            twin.Properties.Desired = desired;
            twin = await registryManager.UpdateTwinAsync(deviceId, twin, twin.ETag);

            desired["$version"] = twin.Properties.Desired.Version;
        }
Beispiel #18
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 metadataStore    = new Mock <IMetadataStore>();

            metadataStore.Setup(m => m.GetMetadata(It.IsAny <string>())).ReturnsAsync(new ConnectionMetadata("dummyValue"));
            ICloudConnectionProvider cloudConnectionProvider = new CloudConnectionProvider(
                converters,
                ConnectionPoolSize,
                new ClientProvider(Option.None <string>()),
                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),
                false,
                Option.None <IWebProxy>(),
                metadataStore.Object,
                true,
                true);

            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, Option.None <string>(), Option.None <string>(), 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());
        }
Beispiel #19
0
        async Task <(string, string)> RegistryArgsFromSecret(string address)
        {
            // Expects our Key Vault to contain a secret with the following properties:
            //  key   - based on registry hostname (e.g.,
            //          edgerelease.azurecr.io => edgerelease-azurecr-io)
            //  value - "<user> <password>" (separated by a space)

            string key   = address.Replace('.', '-');
            string value = await SecretsHelper.GetSecret(key);

            string[] vals = value.Split(' ', StringSplitOptions.RemoveEmptyEntries);
            return(vals[0], vals[1]);
        }
        private async Task <string> UpdateFile(string file, string rtfFile)
        {
            string connectionString = SecretsHelper.GetAzureConnectionString();
            string containerName    = SecretsHelper.GetAzureContainerName();
            string containerURL     = SecretsHelper.GetAzureContainerURL();
            var    container        = new BlobContainerClient(connectionString, containerName);

            container.CreateIfNotExistsAsync();
            var blob = container.GetBlobClient(rtfFile);
            await blob.UploadAsync(rtfFile);

            return($"{containerURL}/{rtfFile}");
        }
        //Speech Button
        private async void SpeechButton_Click(object sender, RoutedEventArgs e)
        {
            var speechConfig =
                SpeechConfig.FromSubscription(SecretsHelper.GetAzureServiceApiKey(), SecretsHelper.GetAzureRegion());

            using (var audioConfig = AudioConfig.FromDefaultMicrophoneInput())
                using (var recognizer = new SpeechRecognizer(speechConfig, audioConfig))
                {
                    var result = await recognizer.RecognizeOnceAsync();

                    contentRichTextBox.Document.Blocks.Add(new Paragraph(new Run(result.Text)));
                }
        }
        public async Task ConnectTest()
        {
            ICloudConnectionProvider cloudConnectionProvider = new CloudConnectionProvider(MessageConverterProvider, ConnectionPoolSize, new ClientProvider(), Option.None <UpstreamProtocol>());
            string deviceConnectionString = await SecretsHelper.GetSecretFromConfigKey("device1ConnStrKey");

            var deviceIdentity                = Mock.Of <IDeviceIdentity>(m => m.Id == ConnectionStringHelper.GetDeviceId(deviceConnectionString));
            var clientCredentials             = new SharedKeyCredentials(deviceIdentity, deviceConnectionString, null);
            Try <ICloudConnection> cloudProxy = cloudConnectionProvider.Connect(clientCredentials, null).Result;

            Assert.True(cloudProxy.Success);
            bool result = await cloudProxy.Value.CloseAsync();

            Assert.True(result);
        }
Beispiel #23
0
        async Task StartProtocolHead()
        {
            string certificateValue = await SecretsHelper.GetSecret("IotHubMqttHeadCert");

            byte[] cert        = Convert.FromBase64String(certificateValue);
            var    certificate = new X509Certificate2(cert);

            // TODO for now this is empty as will suffice for SAS X.509 thumbprint auth but we will need other CA certs for X.509 CA validation
            var trustBundle = new List <X509Certificate2>();

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

            // TODO - After IoTHub supports MQTT, remove this and move to using MQTT for upstream connections
            await ConnectToIotHub(edgeDeviceConnectionString);

            ConfigHelper.TestConfig[EdgeHubConstants.ConfigKey.IotHubConnectionString] = edgeDeviceConnectionString;

            IDependencyManager dependencyManager = new DependencyManager(ConfigHelper.TestConfig, certificate, trustBundle, this.sslProtocols);
            Hosting            hosting           = Hosting.Initialize(ConfigHelper.TestConfig, certificate, dependencyManager, true, this.sslProtocols);

            this.hosting = hosting;
            IContainer container = hosting.Container;

            // CloudConnectionProvider and RoutingEdgeHub have a circular dependency. So set the
            // EdgeHub on the CloudConnectionProvider before any other operation
            ICloudConnectionProvider cloudConnectionProvider = await container.Resolve <Task <ICloudConnectionProvider> >();

            IEdgeHub edgeHub = await container.Resolve <Task <IEdgeHub> >();

            cloudConnectionProvider.BindEdgeHub(edgeHub);

            IConfigSource configSource = await container.Resolve <Task <IConfigSource> >();

            ConfigUpdater configUpdater = await container.Resolve <Task <ConfigUpdater> >();

            await configUpdater.Init(configSource);

            ILogger          logger           = container.Resolve <ILoggerFactory>().CreateLogger("EdgeHub");
            MqttProtocolHead mqttProtocolHead = await container.Resolve <Task <MqttProtocolHead> >();

            AmqpProtocolHead amqpProtocolHead = await container.Resolve <Task <AmqpProtocolHead> >();

            var httpProtocolHead = new HttpProtocolHead(hosting.WebHost);

            this.protocolHead = new EdgeHubProtocolHead(new List <IProtocolHead> {
                mqttProtocolHead, amqpProtocolHead, httpProtocolHead
            }, logger);
            await this.protocolHead.StartAsync();
        }
        private async Task Save()
        {
            State = BUSY;
            JObject payload = new JObject();

            payload["bio"]                   = Bio;
            payload["public_images"]         = PublicImages;
            payload["messaging_enabled"]     = MessagingEnabled;
            payload["album_privacy"]         = ToAlbumPrivacy(AlbumPrivacyIndex);
            payload["show_mature"]           = ShowMature;
            payload["newsletter_subscribed"] = SubscribeNewsletter;
            await Accounts.SaveAccountSettings(await SecretsHelper.GetUserName(), payload);

            State = AUTHENTICATED;
        }
        private async Task <string> UploadFile(string rtfFile, string fileName)
        {
            string file      = string.Empty;
            var    account   = CloudStorageAccount.Parse(SecretsHelper.GetAzureConnectionString());
            var    client    = account.CreateCloudBlobClient();
            var    container = client.GetContainerReference("notes");
            var    blob      = container.GetBlockBlobReference(fileName);

            using (FileStream fileStream = new FileStream(rtfFile, FileMode.Open))
            {
                await blob.UploadFromStreamAsync(fileStream);

                file = blob.Uri.OriginalString;
            }
            return(file);
        }
Beispiel #26
0
        public override async Task OnStartAsync(StartKind startKind, IActivatedEventArgs args)
        {
            if (AuthenticationHelper.IsAuthIntended())
            {
                splash.IsLoading = true;
                JObject result       = null;
                bool    isSuccess    = false;
                string  errorMessage = "Could not connect to the internet";

                try
                {
                    result = await ShakeHands();
                }
                catch (AuthException e)
                {
                    if (e.Reason == AuthException.AuthExceptionReason.HttpError)
                    {
                        errorMessage = e.Message;
                    }
                    else
                    {
                        isSuccess = true;
                    }
                }

                if (result != null && result.HasValues)
                {
                    isSuccess = (bool)result["success"];
                    if (!isSuccess)
                    {
                        await SecretsHelper.RefreshAccessToken();

                        result = await ShakeHands();

                        isSuccess    = (bool)result["success"];
                        errorMessage = JsonConvert.SerializeObject(result["data"], Formatting.Indented);
                    }
                }
                if (!isSuccess)
                {
                    ShowError(errorMessage, "Connection Error");
                    return;
                }
            }
            NavigationService.Navigate(typeof(FrontPage));
        }
Beispiel #27
0
        static async Task CheckMessageInEventHub(Dictionary <string, IList <IMessage> > sentMessagesByDevice, DateTime startTime)
        {
            string eventHubConnectionString = await SecretsHelper.GetSecretFromConfigKey("eventHubConnStrKey");

            var eventHubReceiver            = new EventHubReceiver(eventHubConnectionString);
            var receivedMessagesByPartition = new Dictionary <string, List <EventData> >();

            bool messagesFound = false;

            // If this test becomes flaky, use PartitionReceiver as a background Task to continuously retrieve messages.
            for (int i = 0; i < EventHubMessageReceivedRetry; i++) // Retry for event hub being slow to process messages.
            {
                foreach (string deviceId in sentMessagesByDevice.Keys)
                {
                    if (receivedMessagesByPartition.ContainsKey(deviceId))
                    {
                        receivedMessagesByPartition[deviceId].AddRange(await eventHubReceiver.GetMessagesForDevice(deviceId, startTime));
                    }
                    else
                    {
                        receivedMessagesByPartition[deviceId] = await eventHubReceiver.GetMessagesForDevice(deviceId, startTime);
                    }
                }

                messagesFound = MessageHelper.ValidateSentMessagesWereReceived(sentMessagesByDevice, receivedMessagesByPartition);

                if (messagesFound)
                {
                    break;
                }
                else
                {
                    logger.LogInformation($"Messages not found in event hub for attempt {i}");
                }

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

            foreach (string device in receivedMessagesByPartition.Keys)
            {
                Assert.NotNull(receivedMessagesByPartition[device]);
                Assert.NotEmpty(receivedMessagesByPartition[device]);
            }

            Assert.True(messagesFound);
        }
Beispiel #28
0
        public bool AuthenticateUser(IssueDto args)
        {
            UserWidgetData <UserWidgetDataDetails> userDataRaw = GeminiContext.UserWidgetStore.Get <UserWidgetDataDetails>(CurrentUser.Entity.Id, Constants.AppId, Constants.ControlId);

            if (userDataRaw == null)
            {
                return(false);
            }

            Username = userDataRaw.Value.Username;

            Password = SecretsHelper.Decrypt(userDataRaw.Value.Password, SecretsHelper.EncryptionKey);

            RepositoryUrl = userDataRaw.Value.RepositoryUrl;

            return(true);
        }
        private async Task LoadSettings()
        {
            var userName = await SecretsHelper.GetUserName();

            Account account = await Accounts.GetAccount(userName);

            Bio = account.Bio;
            await Task.Delay(100);

            AccountSettings settings = await Accounts.GetAccountSettings(userName);

            PublicImages        = settings.PublicImages;
            MessagingEnabled    = settings.MessagingEnabled;
            AlbumPrivacyIndex   = ToIndex(settings.AlbumPrivacy);
            ShowMature          = settings.ShowMature;
            SubscribeNewsletter = settings.NewsletterSubscribed;
            IsLoaded            = true;
        }
Beispiel #30
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);
        }