public async Task <decimal> GetCurrentPriceAsync(string symbol)
        {
            var apiPath = $"v3/ticker/price?symbol={symbol}";
            var price   = await _httpClientFactory.GetAsync <TickerPrice>(apiPath);

            return(price.Price);
        }
Exemple #2
0
        //[Fact]
        public async Task Should_Return_OK_When_Get_By_User_Async()
        {
            var client = new HttpClientFactory(MockStartup <Startup> .Instance.GetCliente());
            await client.AddAuthorizationAsync();

            var entity = new OrderDTO()
            {
                Date         = DateTime.Now,
                ExchangeId   = Guid.NewGuid(),
                BaseAssetId  = Guid.NewGuid(),
                QuoteAssetId = Guid.NewGuid(),
                OrderItems   = new List <OrderItemDTO>()
                {
                    new OrderItemDTO()
                    {
                        Price      = 1,
                        Quantity   = 1,
                        Fee        = 1,
                        FeeAssetId = Guid.NewGuid()
                    }
                }
            };
            var result = await client.PostAsync(ROUTE_PATH, entity);

            Assert.Equal(HttpStatusCode.OK, result.StatusCode);

            client = new HttpClientFactory(MockStartup <Startup> .Instance.GetCliente());
            await client.AddAuthorizationAsync();

            result = await client.GetAsync($"{ROUTE_PATH}/GetOrderDetailsByApplicationUser");

            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
        }
        //[Fact]
        public async Task Should_Return_Unauthorized_When_Not_Using_Token()
        {
            HttpClientFactory client = new HttpClientFactory(MockStartup <Startup> .Instance.GetCliente());
            var result = await client.GetAsync(ROUTE_PATH);

            Assert.Equal(HttpStatusCode.Unauthorized, result.StatusCode);
        }
Exemple #4
0
        public async Task TestGetWebAsync()
        {
            // Setup
            var logger      = Log.Logger;
            var eventBridge = new EventBridge();
            var factory     = new HttpTunnelHandlerFactory(eventBridge, null, logger);
            var client      = new HttpClientFactory(factory, logger).CreateClient("msft");

            var adapter     = new MethodHandlerAdapter(factory.YieldReturn());
            var chunkServer = new TestChunkServer(100, (method, buffer, type) => {
                Assert.Equal(MethodNames.Response, method);
                return(adapter.InvokeAsync(method, buffer, type).Result);
            });

            var server = new HttpTunnelServer(chunkServer.CreateClient(),
                                              new Http.Default.HttpClient(new HttpClientFactory(logger), logger), logger);

            eventBridge.Handler = server;

            // Act

            var result = await client.GetAsync("https://www.microsoft.com");

            // Assert

            Assert.NotNull(result);
            Assert.True(result.IsSuccessStatusCode);
            Assert.NotNull(result.Content);
            var payload = await result.Content.ReadAsStringAsync();

            Assert.NotNull(payload);
            Assert.NotNull(result.Headers);
            Assert.True(result.Headers.Any());
            Assert.Contains("<!DOCTYPE html>", payload);
        }
        //[Fact]
        public async Task Should_Return_User_Info_When_AccessToken_IsValid()
        {
            HttpClientFactory client = new HttpClientFactory(MockStartup <Startup> .Instance.GetCliente());
            await client.AddAuthorizationAsync();

            var result = await client.GetAsync(ROUTE_PATH);

            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
        }
Exemple #6
0
        public void return_a_correct_response_for_a_default_get_request()
        {

            using (var httpClient = new HttpClientFactory().Create())
            {
                var response = httpClient.GetAsync("").Result;

                Assert.True(response.IsSuccessStatusCode, "Status code: " + response.StatusCode);
            }
        }
Exemple #7
0
        //[Fact]
        public async Task Should_Return_NotFound_When_GetByIdAsync()
        {
            HttpClientFactory client = new HttpClientFactory(MockStartup <Startup> .Instance.GetCliente());
            await client.AddAuthorizationAsync();

            var id     = Guid.NewGuid();
            var result = await client.GetAsync($"{ROUTE_PATH}/{id}");

            Assert.Equal(HttpStatusCode.NotFound, result.StatusCode);
        }
Exemple #8
0
        public async Task TestGetAsync()
        {
            // Setup
            var logger      = Log.Logger;
            var eventBridge = new EventBridge();
            var factory     = new HttpTunnelHandlerFactory(eventBridge, _serializer, null, logger);
            var client      = new HttpClientFactory(factory, logger).CreateClient("msft");

            var adapter     = new MethodHandlerAdapter(factory.YieldReturn());
            var chunkServer = new TestChunkServer(_serializer, 1000, (method, buffer, type) => {
                Assert.Equal(MethodNames.Response, method);
                return(adapter.InvokeAsync(method, buffer, type).Result);
            });

            var rand           = new Random();
            var fix            = new Fixture();
            var responseBuffer = new byte[10000];

            rand.NextBytes(responseBuffer);
            var response = Mock.Of <IHttpResponse>(r =>
                                                   r.Content == responseBuffer &&
                                                   r.StatusCode == System.Net.HttpStatusCode.OK);
            var httpclientMock = Mock.Of <IHttpClient>();

            Mock.Get(httpclientMock)
            .Setup(m => m.GetAsync(It.IsAny <IHttpRequest>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(response));
            var server = new HttpTunnelServer(httpclientMock,
                                              chunkServer.CreateClient(), _serializer, logger);

            eventBridge.Handler = server;

            // Act

            var result = await client.GetAsync("https://test/test/test?test=test");

            // Assert

            Assert.NotNull(result);
            Assert.Equal(System.Net.HttpStatusCode.OK, result.StatusCode);
            Assert.NotNull(result.Content);
            var payload = await result.Content.ReadAsByteArrayAsync();

            Assert.Equal(response.Content.Length, payload.Length);
            Assert.Equal(responseBuffer, payload);
            Assert.NotNull(result.Headers);
            Assert.Empty(result.Headers);
        }
        public RoadStatusQueryResponse ProcessRoadStatusRequest(RoadStatusQueryRequest request)
        {
            var roadStatusQueryResponse = new RoadStatusQueryResponse();

            using (var httpClient = new HttpClientFactory().BuildClient())
            {
                var response = httpClient.GetAsync(_roadStatusUriBuilder.BuildQueryUri(request.RoadId));
                var payload  = response.Result.Content.ReadAsStringAsync().Result;
                roadStatusQueryResponse.ApiPayload = payload;

                if (response.Result.StatusCode == HttpStatusCode.OK)
                {
                    roadStatusQueryResponse.RoadIdIsValid     = true;
                    roadStatusQueryResponse.RoadStatusDetails = new RoadStatusDetailsBuilder().Build(payload);
                }
            }

            return(roadStatusQueryResponse);
        }
Exemple #10
0
        //[Fact]
        public async Task Should_Return_OK_When_GetByIdAsync()
        {
            HttpClientFactory client = new HttpClientFactory(MockStartup <Startup> .Instance.GetCliente());
            await client.AddAuthorizationAsync();

            var entity = new AssetDTO()
            {
                Name        = "Teste",
                Description = "teste",
                Symbol      = "T"
            };
            var result = await client.PostAsync(ROUTE_PATH, entity);

            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
            entity = JsonConvert.DeserializeObject <AssetDTO>(await result.Content.ReadAsStringAsync());
            result = await client.GetAsync($"{ROUTE_PATH}/{entity.Id}");

            Assert.Equal(HttpStatusCode.OK, result.StatusCode);
        }
Exemple #11
0
        public void return_a_posted_entry_after_a_post_request()
        {
            using (var httpClient = new HttpClientFactory().Create())
            {
                var json =
                    new 
                    {
                        id = new Guid(),
                        name = "John Smith",
                        email = "*****@*****.**",
                        active = true,
                        creationTime = new DateTime(2016, 1, 1)
                    };
                var expected = json.ToJObject();
                httpClient.PostAsJsonAsync("", json).Wait();

                var response = httpClient.GetAsync("").Result;

                var actual = response.Content.ReadAsJsonAsync().Result;
                Assert.Contains(expected, actual.appUsers);
            }
        }
Exemple #12
0
        public void return_a_correct_data_from_database_for_a_default_get_request()
        {
            var aGuid = Guid.NewGuid();
            dynamic entry = new ExpandoObject();
            entry.id = aGuid;
            entry.name = "John Smith";
            entry.email = "*****@*****.**";
            entry.active = true;
            entry.creationTime = new DateTime(2016, 1, 1);

            var expected = ((object) entry).ToJObject();

            var appUser = new AppUser
            {
                Id = aGuid,
                Name = "John Smith",
                Email = "*****@*****.**",
                Active = true,
                CreationTime = new DateTime(2016, 1, 1)
            };
            var connectionString = ConfigurationManager.ConnectionStrings["CraftingTable"].ConnectionString;

            using (IDbConnection sqlConnection = new SqlConnection(connectionString))
            {
                sqlConnection.Execute(
                    @"insert AppUsers(Id, Name, Email, Active, CreationTime)
                      values (@Id, @Name, @Email, @Active, @CreationTime)",
                    appUser);
                sqlConnection.Close();
            }

            using (var httpClient = new HttpClientFactory().Create())
            {
                var response = httpClient.GetAsync("").Result;

                var actual = response.Content.ReadAsJsonAsync().Result;
                foreach (var user in actual.appUsers)
                {
                    Console.WriteLine(user.ToString());
                }
                Assert.Contains(expected, actual.appUsers);
            }
        }
        private async Task <ExternalUser> SearchForUser(string subjectId)
        {
            var settings             = _appConfig.IdentityServerConfidentialClientSettings;
            var fabricIdentityClient = "fabric-identity-client";

            if (string.IsNullOrEmpty(settings.Authority))
            {
                throw new FabricConfigurationException("IdentityServerConfidentialClientSettings.Authority is not set, Please set the Authority to the appropriate url.");
            }

            var authority = settings.Authority.EnsureTrailingSlash();

            var tokenUriAddress = $"{authority}connect/token";

            this._logger.Information($"Getting access token for ClientId: {fabricIdentityClient} at {tokenUriAddress}");

            var tokenClient = new TokenClient(tokenUriAddress, fabricIdentityClient, settings.ClientSecret);

            var accessTokenResponse = await tokenClient.RequestClientCredentialsAsync("fabric/idprovider.searchusers");

            if (accessTokenResponse.IsError)
            {
                this._logger.Error($"Failed to get access token, error message is: {accessTokenResponse.ErrorDescription}");
            }

            using (var httpClient = new HttpClientFactory(
                       tokenUriAddress,
                       fabricIdentityClient,
                       settings.ClientSecret,
                       null,
                       null).CreateWithAccessToken(new Uri(_appConfig.IdentityProviderSearchSettings.BaseUrl),
                                                   accessTokenResponse.AccessToken))
            {
                httpClient.DefaultRequestHeaders.Add("Accept", "application/json");

                var searchServiceUrl = $"{_appConfig.IdentityProviderSearchSettings.GetUserEndpoint}{subjectId}";

                try
                {
                    _logger.Information($"searching for user with url: {_appConfig.IdentityProviderSearchSettings.BaseUrl}{searchServiceUrl}");

                    var response = await httpClient.GetAsync(searchServiceUrl);

                    var responseContent =
                        response.Content == null ? string.Empty : await response.Content.ReadAsStringAsync();

                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        _logger.Error(
                            $"no user principal was found for subject id: {subjectId}. response status code: {response.StatusCode}.");
                        _logger.Error($"response from search service: {responseContent}");
                        return(null);
                    }

                    var result = JsonConvert.DeserializeObject <UserSearchResponse>(responseContent);

                    return(new ExternalUser
                    {
                        FirstName = result.FirstName,
                        LastName = result.LastName,
                        MiddleName = result.MiddleName,
                        SubjectId = result.SubjectId
                    });
                }
                catch (HttpRequestException e)
                {
                    var baseException = e.GetBaseException();

                    _logger.Error($"there was an error connecting to the search service: {baseException.Message}");
                    return(null);
                }
            }
        }