Esempio n. 1
0
        public void InvalidServerNameThrowsNoExceptionIfSuppressed()
        {
            var apiConfiguration = new ApiConfiguration("", 443);
            var dataApiClient    = new DataApiClient(apiConfiguration, ignoreSslNameMismatch: true);

            Assert.That(() => dataApiClient.ExistsAsync <Location>("someID"), Throws.Nothing);
        }
Esempio n. 2
0
        public void ValiddServerNameThrowsNoException()
        {
            var apiConfiguration = new ApiConfiguration("", 443);
            var dataApiClient    = new DataApiClient(apiConfiguration);

            Assert.That(() => dataApiClient.ExistsAsync <Location>("someID"), Throws.Nothing);
        }
Esempio n. 3
0
        public void InvalidServerNameThrowsExceptionIfNotSuppressed()
        {
            var apiConfiguration = new ApiConfiguration("", 443);
            var dataApiClient    = new DataApiClient(apiConfiguration);

            Assert.That(() => dataApiClient.ExistsAsync <Location>("someID"), Throws.TypeOf <HttpRequestException>());
        }
Esempio n. 4
0
        private async Task <T> CallServiceAsync <T>(Func <DataApiClient, T> predicate, CancellationToken cancellationToken)
        {
            if (Authorization == null)
            {
                throw new InvalidOperationException("No access token!");
            }

            var wcfClient = new DataApiClient();

            // Refresh the access token if it expires and if its lifetime is too short to be of use.
            if (Authorization.AccessTokenExpirationUtc.HasValue)
            {
                if (await Client.RefreshAuthorizationAsync(Authorization, TimeSpan.FromSeconds(30)))
                {
                    TimeSpan timeLeft = Authorization.AccessTokenExpirationUtc.Value - DateTime.UtcNow;
                    this.authorizationLabel.Text += string.Format(CultureInfo.CurrentCulture, " - just renewed for {0} more minutes)", Math.Round(timeLeft.TotalMinutes, 1));
                }
            }

            var httpRequest = (HttpWebRequest)WebRequest.Create(wcfClient.Endpoint.Address.Uri);

            ClientBase.AuthorizeRequest(httpRequest, Authorization.AccessToken);

            var httpDetails = new HttpRequestMessageProperty();

            httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers[HttpRequestHeader.Authorization];
            using (var scope = new OperationContextScope(wcfClient.InnerChannel)) {
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpDetails;
                return(predicate(wcfClient));
            }
        }
Esempio n. 5
0
        public void CanLogInWithJwt()
        {
            var dataApiClient = new DataApiClient(ApiSetup.ApiConfiguration);

            Assume.That(dataApiClient.IsLoggedIn, Is.False);
            Assume.That(dataApiClient.LoggedInUsername, Is.Null);
            Assume.That(dataApiClient.IsAvailable());
            try
            {
                dataApiClient.Register("Test_sdfrgnbfgfdgj", "fgjerg", "sadfgfg", "egjdfbednbrgeo", "*****@*****.**");
            }
            catch (ApiException apiException)
            {
                if (apiException.StatusCode != HttpStatusCode.Conflict)
                {
                    throw;
                }
            }
            var authenticationResult = dataApiClient.Login("Test_sdfrgnbfgfdgj", "egjdfbednbrgeo");

            Assert.That(authenticationResult, Is.Not.Null);
            Assert.That(authenticationResult.IsAuthenticated, Is.True);
            Assert.That(dataApiClient.IsLoggedIn, Is.True);
            Assert.That(dataApiClient.LoggedInUsername, Is.EqualTo("test_sdfrgnbfgfdgj"));

            Assert.That(() => authenticationResult = dataApiClient.Login("invalidUser", "invalidPassword"), Throws.Nothing);
            Assert.That(authenticationResult.IsAuthenticated, Is.False);
        }
        public void GetAccounts_ShouldReturn_ListOfAccounts()
        {
            // Arrange
            // Read in response data from file
            var dataPath = Path.Combine(_executingLocation, "..", "..", "..", "..", "..", "data",
                                        "mock-accounts-response.json");
            var responseJson = File.ReadAllText(dataPath);

            // Setup mocks
            var mockHttpClient = SetupMockHttpClient($"accounts", responseJson);
            var mockCache      = SetupNullMockCache();

            // Instansiate TrueLayer DataApiClient
            var dataApiClient = new DataApiClient(mockHttpClient.Object, mockCache.Object);

            // Act
            var accounts = dataApiClient.GetAccounts("token").GetAwaiter().GetResult();

            // Assert
            // HttpClient should be called
            mockHttpClient.Verify(m => m.GetData(It.IsAny <Uri>(), It.IsAny <string>()), Times.AtLeastOnce);
            // Cache get should be called
            mockCache.Verify(m => m.GetAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()), Times.AtLeastOnce);
            // Cache set should be called
            mockCache.Verify(
                m => m.SetAsync(It.IsAny <string>(), It.IsAny <byte[]>(), It.IsAny <DistributedCacheEntryOptions>(),
                                It.IsAny <CancellationToken>()), Times.AtLeastOnce);


            Assert.AreEqual(2, accounts.Count);
        }
        public void GetTransactions_ShouldReturn_ListOfTransactions()
        {
            // Arrange
            // Read in response data from file
            var dataPath = Path.Combine(_executingLocation, "..", "..", "..", "..", "..", "data",
                                        "mock-transaction-response.json");
            var responseJson = File.ReadAllText(dataPath);

            // Fake acount id
            const string accountId = "fake-account-id";

            // Setup mocks
            var mockHttpClient = SetupMockHttpClient($"accounts/{accountId}/transactions", responseJson);
            var mockCache      = SetupNullMockCache();

            // Instansiate TrueLayer DataApiClient
            var dataApiClient = new DataApiClient(mockHttpClient.Object, mockCache.Object);

            // Act
            var transactions = dataApiClient.GetAccountTransactions("token", accountId).GetAwaiter().GetResult();

            // Assert
            // HttpClient should be called
            mockHttpClient.Verify(m => m.GetData(It.IsAny <Uri>(), It.IsAny <string>()), Times.AtLeastOnce);
            // Cache get should be called
            mockCache.Verify(m => m.GetAsync(It.IsAny <string>(), It.IsAny <CancellationToken>()), Times.AtLeastOnce);
            // Cache set should be called
            mockCache.Verify(
                m => m.SetAsync(It.IsAny <string>(), It.IsAny <byte[]>(), It.IsAny <DistributedCacheEntryOptions>(),
                                It.IsAny <CancellationToken>()), Times.AtLeastOnce);

            Assert.AreEqual(6, transactions.Count);
            Assert.AreEqual("c9ce76686887de57c5fdf67451303ed1", transactions[0].TransactionId);
            Assert.AreEqual("039ccc24c3", transactions[0].MetaData.BankTransactionId);
        }
Esempio n. 8
0
        private async Task <T> CallServiceAsync <T>(Func <DataApiClient, T> predicate)
        {
            DataApiClient client          = new DataApiClient();
            var           serviceEndpoint = new MessageReceivingEndpoint(client.Endpoint.Address.Uri, HttpDeliveryMethods.AuthorizationHeaderRequest | HttpDeliveryMethods.PostRequest);
            var           accessToken     = (AccessToken)(Session["WcfAccessToken"] ?? default(AccessToken));

            if (accessToken.Token == null)
            {
                throw new InvalidOperationException("No access token!");
            }

            var httpRequest = new HttpRequestMessage(HttpMethod.Post, client.Endpoint.Address.Uri);
            var consumer    = this.CreateConsumer();

            using (var handler = consumer.CreateMessageHandler(accessToken)) {
                handler.ApplyAuthorization(httpRequest);
            }

            HttpRequestMessageProperty httpDetails = new HttpRequestMessageProperty();

            httpDetails.Headers[HttpRequestHeader.Authorization] = httpRequest.Headers.Authorization.ToString();
            using (OperationContextScope scope = new OperationContextScope(client.InnerChannel)) {
                OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = httpDetails;
                return(predicate(client));
            }
        }
        public override Task <IProcessorResult> Process(
            DataModificationType modificationType,
            string dataType,
            string inputId,
            string inputObjectJson)
        {
            if (dataType == DataApiClient.GetCollectionName <PostponedProcessingObject>())
            {
                UpdatePostponedObjects(modificationType, inputId, inputObjectJson);
                return(Task.FromResult <IProcessorResult>(new SuccessProcessorResult("Postponed objects updated", true)));
            }

            var matchingObjects = postponedObjects.Values
                                  .Where(obj => obj.MissingData.Any(dataReference => dataReference.DataType == dataType && dataReference.Id == inputId))
                                  .ToList();

            if (!matchingObjects.Any())
            {
                return(Task.FromResult <IProcessorResult>(new NotInterestedProcessorResult()));
            }

            foreach (var obj in matchingObjects)
            {
                obj.MissingData.RemoveAll(dataReference => dataReference.DataType == dataType && dataReference.Id == inputId);
            }
            UnregisterDataTypeIfNoLongerNeeded(dataType);

            var summary       = $"{matchingObjects.Count} {nameof(PostponedProcessingObject)} were updated";
            var outputObjects = matchingObjects
                                .Select(obj => new SerializedObject(obj.Id, obj.GetType().Name, JsonConvert.SerializeObject(obj)))
                                .ToList();

            return(Task.FromResult <IProcessorResult>(new SuccessProcessorResult(summary, true, outputObjects)));
        }
Esempio n. 10
0
 public SimulatorController(
     GameSimulatorService gameSimulator,
     ResultsApiClient resultsApiClient,
     DataApiClient dataApiClient)
 {
     _gameSimulator    = gameSimulator;
     _resultsApiClient = resultsApiClient;
     _dataApiClient    = dataApiClient;
 }
Esempio n. 11
0
        public void CanSetAccessToken()
        {
            var dataApiClient = new DataApiClient(ApiSetup.ApiConfiguration);
            var accessToken   = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJ1bmlxdWVfbmFtZSI6InVuaXR0ZXN0YWRtaW4iLCJuYmYiOjE1NTY4ODExMzMsImV4cCI6MTU1Njg4NDczMywiaWF0IjoxNTU2ODgxMTMzfQ.Xe2m2KiROPMFaRt6s828ofMjNjAkEVHjHPccA5eqo2E";

            dataApiClient.SetAccessToken(accessToken);
            Assert.That(dataApiClient.IsLoggedIn, Is.True);
            Assert.That(dataApiClient.LoginMethod, Is.EqualTo(LoginMethod.JsonWebToken));
            Assert.That(dataApiClient.LoggedInUsername, Is.EqualTo("unittestadmin"));
        }
Esempio n. 12
0
 private void CleanupObjects(IEnumerable <string> inputObjectIds, IEnumerable <string> outputObjectIds)
 {
     foreach (var id in inputObjectIds)
     {
         DataApiClient.DeleteAsync <UnitTestInputObject>(id).Wait();
     }
     foreach (var id in outputObjectIds)
     {
         DataApiClient.DeleteAsync <UnitTestOutputObject>(id).Wait();
     }
 }
 public PostponedProcessingRunner(
     IDataApiClient dataApiClient,
     IEnumerable <IProcessor> processors,
     IDataProcessingServiceLogger dataProcessingServiceLogger)
     : base(nameof(PostponedProcessingRunner), DataApiClient.GetCollectionName <PostponedProcessingObject>())
 {
     this.dataApiClient = dataApiClient;
     this.dataProcessingServiceLogger = dataProcessingServiceLogger;
     this.processors = processors.ToDictionary(x => x.DisplayName, x => x);
     processorRunner = new ProcessorRunner(dataApiClient, dataProcessingServiceLogger);
 }
Esempio n. 14
0
        public void SubmitRejectsDataWithInvalidAccessToken()
        {
            var noLoginDataApiClient = new DataApiClient(ApiSetup.ApiConfiguration)
            {
                LoginMethod = LoginMethod.JsonWebToken
            };
            var testObject = new UnitTestDataObject1();

            AssertStatusCode(
                () => noLoginDataApiClient.InsertAsync(testObject).Wait(),
                HttpStatusCode.Unauthorized);
        }
        public void AnonymousUserCannotSubmitValidator()
        {
            var validatorDefinition  = new ValidatorDefinition("MyClass", ValidatorType.TextRules, "Id EXISTS");
            var noLoginDataApiClient = new DataApiClient(ApiSetup.ApiConfiguration)
            {
                LoginMethod = LoginMethod.JsonWebToken
            };

            AssertStatusCode(
                () => noLoginDataApiClient.SubmitValidatorAsync(validatorDefinition).Wait(),
                HttpStatusCode.Unauthorized);
        }
Esempio n. 16
0
        public void AnonymousCannotGetIds()
        {
            var noLoginDataApiClient = new DataApiClient(ApiSetup.ApiConfiguration)
            {
                LoginMethod = LoginMethod.JsonWebToken
            };
            var dataType = nameof(UnitTestDataObject1);

            AssertStatusCode(
                () => noLoginDataApiClient.GetNewIdAsync(dataType).Wait(),
                HttpStatusCode.Unauthorized);
        }
Esempio n. 17
0
        private ValidatorDefinition ExtractValidatorDefinition(Type type)
        {
            var rules = typeValidationRuleBuilder.Build(type, "");

            if (!rules.Any())
            {
                return(null);
            }
            var ruleset = rules.Aggregate((a, b) => a + "; " + b);

            return(new ValidatorDefinition(DataApiClient.GetCollectionName(type), ValidatorType.TextRules, ruleset));
        }
Esempio n. 18
0
        public void QueryableIntegrationTest()
        {
            var ids = new List <string> {
                "1228357", "1228358"
            };
            var dataApiClient = new DataApiClient(new ApiConfiguration("", 443));
            var queryable     = new GenericDatabase <TestObject1>(dataApiClient);
            var searchResult  = queryable.Where(x => ids.Contains(x.Id)).ToList();

            Assert.That(searchResult, Is.Not.Null);
            CollectionAssert.AreEqual(ids, searchResult.Select(x => x.Id));
        }
Esempio n. 19
0
 public static async Task AddToDataSet(DataApiClient dataApiClient, string dataSetId, string dataType, string id)
 {
     if (!await dataApiClient.ExistsAsync <DataSet>(dataSetId))
     {
         var dataSet = new DataSet(dataSetId);
         await dataApiClient.InsertAsync(dataSet, dataSetId);
     }
     var dataTag = new DataTag(
         new DataReference(dataType, id),
         dataSetId);
     await dataApiClient.InsertAsync(dataTag);
 }
        private void UnregisterUnnecessaryInputTypes()
        {
            var necessaryInputTypes = postponedObjects.Values.SelectMany(x => x.MissingData).Select(x => x.DataType)
                                      .Concat(new[] { DataApiClient.GetCollectionName <PostponedProcessingObject>() })
                                      .Distinct();
            var unnecessaryInputTypes = InputTypes.Except(necessaryInputTypes);

            foreach (var unnecessaryInputType in unnecessaryInputTypes)
            {
                UnregisterInputType(unnecessaryInputType);
            }
        }
Esempio n. 21
0
        public static AuthenticationResult RegisterAndLoginUserWithoutRoles(out IDataApiClient dataApiClient)
        {
            var username  = GenerateUsername();
            var password  = GeneratePassword();
            var email     = $"{username}@example.org";
            var firstName = "Jamie";
            var lastName  = "Doe";

            dataApiClient = new DataApiClient(ApiSetup.ApiConfiguration);
            dataApiClient.Register(username, firstName, lastName, password, email);
            return(dataApiClient.Login(username, password));
        }
Esempio n. 22
0
        public async Task DownloadFileReturnsFilename()
        {
            var dataApiClient = new DataApiClient(ApiSetup.ApiConfiguration);

            dataApiClient.Login();

            var actual = await dataApiClient.Download("DataBlob", "DCF9C0E1FD926E2C6B5E4E9E18001B3F00EEB30B");

            Assert.That(actual.Filename, Is.EqualTo("excelReferenceCache.json"));
            var data = ToByteArray(actual.Stream);

            Assert.That(data, Is.Not.Empty);
        }
Esempio n. 23
0
        public void AnonymousUserCannotCreateView()
        {
            var query   = "SELECT * FROM Computers";
            var expires = DateTime.UtcNow.AddMinutes(3);
            var noLoginDataApiClient = new DataApiClient(ApiSetup.ApiConfiguration)
            {
                LoginMethod = LoginMethod.JsonWebToken
            };

            AssertStatusCode(
                () => noLoginDataApiClient.CreateViewAsync(query, expires).Wait(),
                HttpStatusCode.Unauthorized);
        }
Esempio n. 24
0
        public DataServiceProcessor(IDataApiClient dataApiClient)
            : base(nameof(DataServiceProcessor), DataApiClient.GetCollectionName <DataServiceDefinition>())
        {
            this.dataApiClient     = dataApiClient;
            dataServiceDefinitions = LoadDataServiceDefinitions();
            var dataServiceDefinitionsCopy = dataServiceDefinitions.ToList();

            foreach (var dataServiceDefinition in dataServiceDefinitionsCopy)
            {
                var initTask = TransferExistingDataIfNewTarget(dataServiceDefinition, cancellationTokenSource.Token);
                initTasks.Add(dataServiceDefinition.Id, initTask);
            }
        }
Esempio n. 25
0
        //TODO: [TestCase(typeof(XXX))]
        public async Task GenerateValidatorForSpecificType(Type customType)
        {
            var validatorDefinition = ExtractValidatorDefinition(customType);

            if (validatorDefinition == null)
            {
                return;
            }
            var dataType = DataApiClient.GetCollectionName(customType);

            await SubmitValidator(dataType, validatorDefinition);

            await File.AppendAllLinesAsync(outputFilePath, new[] { JsonConvert.SerializeObject(validatorDefinition, Formatting.Indented) });
        }
Esempio n. 26
0
        public void GetCollectionNameReturnsRegistererdName()
        {
            var collectionName = "BinaryData";

            DataApiClient.RegisterType <DataBlob>(collectionName);
            try
            {
                Assert.That(DataApiClient.GetCollectionName <DataBlob>(), Is.EqualTo(collectionName));
            }
            finally
            {
                DataApiClient.UnregisterType <DataBlob>();
            }
        }
Esempio n. 27
0
        public void CanLogInWithActiveDirectory()
        {
            var dataApiClient = new DataApiClient(ApiSetup.ApiConfiguration);

            Assume.That(dataApiClient.IsAvailable());
            Assume.That(dataApiClient.IsLoggedIn, Is.False);
            Assume.That(dataApiClient.LoggedInUsername, Is.Null);
            //Assert.That(() => dataApiClient.Login("Test_sdfrgnbfgfdgj", "egjdfbednbrgeo"), Throws.Nothing);
            var authenticationResult = dataApiClient.Login();

            Assert.That(authenticationResult, Is.Not.Null);
            Assert.That(authenticationResult.IsAuthenticated, Is.True);
            Assert.That(dataApiClient.IsLoggedIn, Is.True);
            Assert.That(dataApiClient.LoggedInUsername, Is.EqualTo("jdoe"));
        }
Esempio n. 28
0
        private async void App_OnStartup(object sender, StartupEventArgs e)
        {
            StaticUiUpdateNotifier.Notifier = new WpfUiUpdateNotifier();
            StaticMessageBoxSpawner.Spawner = new WpfMessageBoxSpawner();

            var dataApiClient = new DataApiClient(new ApiConfiguration(Settings.Default.ApiServerAddress, Settings.Default.ApiServerPort));

            dataApiClient.Login();
            if (!dataApiClient.IsLoggedIn)
            {
                StaticMessageBoxSpawner.Show("Could not log into DataAPI. Shutting down...");
                Shutdown(-1);
                return;
            }
            var permissionCheckerResult = await DataPermissionChecker.Check(dataApiClient, new Dictionary <string, IList <Role> >
            {
                { nameof(DataServiceDefinition), new List <Role> {
                      Role.Viewer, Role.DataProducer
                  } },
                { nameof(IDataServiceTarget), new List <Role> {
                      Role.Viewer, Role.DataProducer
                  } }
            });

            if (!permissionCheckerResult.HasSufficientPermissions)
            {
                StaticMessageBoxSpawner.Show("You don't have enough permissions on the DataAPI to run this application. Please contact Inno-IT.");
                Shutdown(-1);
                return;
            }
            var dataServiceDefinitionDatabase = new GenericDatabase <DataServiceDefinition>(dataApiClient);
            var dataTypeList           = new DataApiDataTypeList(dataApiClient);
            var usernameProxy          = new DataApiUsernameProxy(dataApiClient);
            var sqlExpressionValidator = new SqlExpressionValidator(dataApiClient);
            var mainWindow             = new MainWindow();
            var mainViewModel          = new MainViewModel(
                dataApiClient,
                dataServiceDefinitionDatabase,
                mainWindow,
                dataTypeList,
                usernameProxy,
                sqlExpressionValidator);

            mainWindow.ViewModel = mainViewModel;
            mainWindow.ShowDialog();
        }
Esempio n. 29
0
        private void App_OnStartup(object sender, StartupEventArgs e)
        {
            StaticMessageBoxSpawner.Spawner = new WpfMessageBoxSpawner();
            StaticUiUpdateNotifier.Notifier = new WpfUiUpdateNotifier();

            var apiConfiguration = new ApiConfiguration(Settings.Default.ApiServerAddress, Settings.Default.ApiServerPort);
            var dataApiClient    = new DataApiClient(apiConfiguration);

            if (!dataApiClient.IsAvailable())
            {
                MessageBox.Show($"Cannot contact DataAPI @ '{apiConfiguration.ServerAddress}:{apiConfiguration.ServerPort}'. Shutting down...");
                Current.Shutdown(-1);
                return;
            }
            try
            {
                dataApiClient.Login();
            }
            catch
            {
                // Ignore. If Active Directory is not available, in some other way later.
            }

            var dataVisualizer = new DataVisualizer(new IDataVisualizationViewModelFactory[]
            {
                new ImageVisualizationViewModelFactory(dataApiClient),
                // TODO: Add more entries here to custom visualization for data types
            });
            var userDatabase        = new UserDatabase(dataApiClient);
            var dataSetDatabase     = new GenericDatabase <DataSet>(dataApiClient);
            var dataProjectDatabase = new GenericDatabase <DataProject>(dataApiClient);
            var clipboard           = new WpfClipboard();
            var mainWindow          = new MainWindow();
            var mainViewModel       = new MainViewModel(
                dataApiClient,
                dataVisualizer,
                userDatabase,
                dataSetDatabase,
                dataProjectDatabase,
                clipboard,
                mainWindow);

            mainWindow.ViewModel = mainViewModel;
            mainWindow.ShowDialog();
        }
Esempio n. 30
0
        private void App_OnStartup(object sender, StartupEventArgs e)
        {
            Current.ShutdownMode            = ShutdownMode.OnExplicitShutdown;
            StaticMessageBoxSpawner.Spawner = new WpfMessageBoxSpawner();
            StaticUiUpdateNotifier.Notifier = new WpfUiUpdateNotifier();

            var apiConfiguration = new ApiConfiguration(Settings.Default.DataApiServerAddress, Settings.Default.DataApiServerPort);
            var dataApiClient    = new DataApiClient(apiConfiguration);

            if (!dataApiClient.IsAvailable())
            {
                MessageBox.Show($"Cannot contact DataAPI @ '{apiConfiguration.ServerAddress}:{apiConfiguration.ServerPort}'. Shutting down...");
                Current.Shutdown(-1);
                return;
            }
            try
            {
                dataApiClient.Login();
            }
            catch
            {
                // Ignore. If Active Directory is not available, in some other way later.
            }

            var logEntryMonitor = new LogEntryMonitor(dataApiClient);

            var mainWindow    = new MainWindow();
            var mainViewModel = new MainViewModel(dataApiClient, logEntryMonitor, mainWindow);

            mainWindow.ViewModel = mainViewModel;
            try
            {
                mainWindow.ShowDialog();
            }
            catch (Exception exception)
            {
                MessageBox.Show(exception.ToString());
                throw;
            }

            // Shutdown
            logEntryMonitor.StopMonitoring();
            Shutdown(0);
        }