public void Retry_success() { // Arrange the Http client var mockHttp = new MockHttpMessageHandler(); // First attempt, we return HTTP 429 which means TOO MANY REQUESTS mockHttp.Expect(HttpMethod.Get, "https://api.fictitious-vendor.com/v1/endpoint").Respond((HttpStatusCode)429); // Second attempt, we return the expected result mockHttp.Expect(HttpMethod.Get, "https://api.fictitious-vendor.com/v1/endpoint").Respond("application/json", "{'name' : 'This is a test'}"); var httpClient = new HttpClient(mockHttp); // Arrange the Request coordinator var coordinator = new RetryCoordinator( 2, (response) => response.StatusCode == (HttpStatusCode)429, (attempts, response) => TimeSpan.Zero); // Arrange the fluent htpp client var fluentClient = new FluentClient("https://api.fictitious-vendor.com/v1/", httpClient) .SetRequestCoordinator(coordinator); // Act var result = fluentClient .GetAsync("endpoint") .As <JObject>() .Result; // Assert mockHttp.VerifyNoOutstandingExpectation(); mockHttp.VerifyNoOutstandingRequest(); Assert.That(result.Value <string>("name"), Is.EqualTo("This is a test")); }
public async Task PostApiTestMethod() { var userModelObj = new UserModel() { FirstName = "Kishor", LastName = "Naik" }; IClient client = new FluentClient("http://localhost:49506/api/users"); // Post Work //var data = // await // client // .PostAsync<UserModel>("postdemo", userModelObj) // .As<UserModel>(); //// Post Array Work //var data = // await // client // .PostAsync("postdemoarray") // .As<List<UserModel>>(); var data = await client .GetAsync("getdemo/11") .As <int>(); Assert.IsNotNull(data); }
public static async Task <JObject> PostRequest_NoBody(FluentClient client, string uri, CancellationToken cancellationToken) { return(await client .PostAsync(uri) .WithCancellationToken(cancellationToken) .AsRawJsonObject()); }
protected override async Task <Action <NativeActivityContext> > ExecuteAsync(NativeActivityContext context, CancellationToken cancellationToken) { // Inputs var username = AccountUsername.Get(context); var password = AppPassword.Get(context); var passwordString = new System.Net.NetworkCredential(string.Empty, password).Password; //Prepare default header var authHeaderString = username + ":" + passwordString; // This is the format used in the HTTP request header. var base64EncodedCredentials = Base64Encode(authHeaderString); // Create client and assign default request header var defaultHttpClient = new HttpClient(); defaultHttpClient.DefaultRequestHeaders .Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64EncodedCredentials); var client = new FluentClient("https://api.bitbucket.org/2.0/", defaultHttpClient); // Send to child activities _objectContainer.Add(client); return((ctx) => { // Schedule child activities if (Body != null) { ctx.ScheduleAction <IObjectContainer>(Body, _objectContainer, OnCompleted, OnFaulted); } // Outputs }); }
public void Retry_failure() { // Arrange the Http client var mockHttp = new MockHttpMessageHandler(); // Three successive HTTP 429 (which mean TOO MANY REQUESTS) mockHttp.Expect(HttpMethod.Get, "https://api.fictitious-vendor.com/v1/endpoint").Respond((HttpStatusCode)429); mockHttp.Expect(HttpMethod.Get, "https://api.fictitious-vendor.com/v1/endpoint").Respond((HttpStatusCode)429); mockHttp.Expect(HttpMethod.Get, "https://api.fictitious-vendor.com/v1/endpoint").Respond((HttpStatusCode)429); var httpClient = new HttpClient(mockHttp); // Arrange the Request coordinator var coordinator = new RetryCoordinator( 3, (response) => response.StatusCode == (HttpStatusCode)429, (attempts, response) => TimeSpan.Zero); // Arrange the fluent http client var fluentClient = new FluentClient("https://api.fictitious-vendor.com/v1/", httpClient) .SetRequestCoordinator(coordinator); // Act Assert.ThrowsAsync <ApiException>(async() => await fluentClient.GetAsync("endpoint").As <JObject>()); // Assert mockHttp.VerifyNoOutstandingExpectation(); mockHttp.VerifyNoOutstandingRequest(); }
public void GivenACollectionOfPostsExposedAsApi() { //arrange apiUrl = "https://jsonplaceholder.typicode.com"; client = new FluentClient(); client.BaseUri = new Uri(apiUrl, UriKind.Absolute); }
public IntegrationTestsBase(ITestOutputHelper output) : base(output) { var builder = new MvcWebApplicationBuilder <Startup>() .UseSolutionRelativeContentRoot("src/Exceptionless.Api") .ConfigureBeforeStartup(Configure) .ConfigureAfterStartup(RegisterServices) .UseApplicationAssemblies(); _server = builder.Build(); var settings = GetService <Newtonsoft.Json.JsonSerializerSettings>(); _serializer = GetService <ITextSerializer>(); _client = new FluentClient(new JsonContentSerializer(settings), _server.CreateHandler()) { BaseUri = new Uri(_server.BaseAddress + "api/v2") }; _httpClient = new HttpClient(_server.CreateHandler()) { BaseAddress = new Uri(_server.BaseAddress + "api/v2/") }; _configuration = GetService <ExceptionlessElasticConfiguration>(); _configuration.DeleteIndexesAsync().GetAwaiter().GetResult(); _configuration.ConfigureIndexesAsync(beginReindexingOutdated: false).GetAwaiter().GetResult(); }
private static FluentClient CreateClient() { var client = new FluentClient(); client.BaseUri = new Uri("http://httpbin.org/", UriKind.Absolute); return(client); }
public void CreatesModel() { var model = new User { GenderId = 0, OccupationId = 0, Firstname = "", Lastname = "", Email = "", Phone = "", ShowPhone = false, LanguageCode = 1, Age = 18, AffiliateCode = "", Ip = "", }; FluentResponse<User, Error> result = new FluentClient<Error>("http://local.property.erm-api.com/v1/").Post<User>(model).Result; Assert.IsNotNull(result); Assert.IsNotNull(result.Entity); Assert.IsNotNullOrEmpty(result.Entity.Id); }
public IntegrationTestsBase(ITestOutputHelper output, AppWebHostFactory factory) : base(output) { Log.MinimumLevel = LogLevel.Information; Log.SetLogLevel <ScheduledTimer>(LogLevel.Warning); Log.SetLogLevel <InMemoryMessageBus>(LogLevel.Warning); Log.SetLogLevel <InMemoryCacheClient>(LogLevel.Warning); Log.SetLogLevel <InMemoryMetricsClient>(LogLevel.Information); Log.SetLogLevel("StartupActions", LogLevel.Warning); Log.SetLogLevel <Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager>(LogLevel.Warning); var configuredFactory = factory.Factories.FirstOrDefault(); if (configuredFactory == null) { configuredFactory = factory.WithWebHostBuilder(builder => { builder.ConfigureTestServices(RegisterServices); // happens after normal container configure and overrides services }); } _disposables.Add(_testSystemClock); _httpClient = configuredFactory.CreateClient(); _server = configuredFactory.Server; _httpClient.BaseAddress = new Uri(_server.BaseAddress + "api/v2/", UriKind.Absolute); var testScope = configuredFactory.Services.CreateScope(); _disposables.Add(testScope); ServiceProvider = testScope.ServiceProvider; var settings = GetService <JsonSerializerSettings>(); _client = new FluentClient(_httpClient, new NewtonsoftJsonSerializer(settings)); _configuration = GetService <ExceptionlessElasticConfiguration>(); }
public NetFlagrHttpClient(HttpClient httpClient, IOptions <NetFlagrConfiguration> configuration) { if (configuration.Value == null) { configuration = Options.Create <NetFlagrConfiguration>(new NetFlagrConfiguration()); } _configuration = configuration.Value; if (string.IsNullOrEmpty(_configuration.BasePath)) { throw new ArgumentException("basePath cannot be empty"); } httpClient.Timeout = TimeSpan.FromMilliseconds(_configuration.Timeout); _client = new FluentClient(new Uri(_configuration.BasePath), httpClient); _client.Filters.Clear(); if (!string.IsNullOrEmpty(_configuration.UserAgent)) { _client.SetUserAgent(_configuration.UserAgent); } else { Version version = typeof(NetFlagrApiClient).GetTypeInfo().Assembly.GetName().Version; _client.SetUserAgent($"NetFlagrHttpClient/{version} (+http://github.com/checkr/NetFlagrHttpClient)"); } }
public override AccountsResponse GetAccount(string AccountId, string bank_id, string view_id) { AccountsResponse result = new AccountsResponse(); try { LoginBindResponse loginData = doLogin(); //banks/322/accounts/21-1-99999-4-6/owner string urlData = String.Format("banks/{0}/accounts/{1}/{2}", bank_id, AccountId, view_id); string JsonResult = new FluentClient(config.Url) .GetAsync(urlData) .WithHeader("Authorization", "JWT " + loginData.token) .WithOptions(true) .AsString().Result; result.accounts = new List <Account>(); result.accounts.Add(JsonConvert.DeserializeObject <Account>(JsonResult)); result.executeStatus = getExecuteStatus(JsonResult, urlData); } catch (CustomException cEx) { result.executeStatus = cEx.convertToCustomStatus(); } catch (Exception ex) { result.executeStatus = new CustomException(ExceptionsCodes.UnexpectedException, "", ex.Message).convertToCustomStatus(); } return(result); }
protected async Task <T> GetAsync <T>(string url) { using (var client = new FluentClient(baseUri)) { return(await client.GetAsync(url).As <T>()); } }
public void CreatesModel() { var model = new User { GenderId = 0, OccupationId = 0, Firstname = "", Lastname = "", Email = "", Phone = "", ShowPhone = false, LanguageCode = 1, Age = 18, AffiliateCode = "", Ip = "", }; FluentResponse <User, Error> result = new FluentClient <Error>("http://local.property.erm-api.com/v1/").Post <User>(model).Result; Assert.IsNotNull(result); Assert.IsNotNull(result.Entity); Assert.IsNotNullOrEmpty(result.Entity.Id); }
public override ViewsResponse GetViewsByBankId(string bank_id) { ViewsResponse result = new ViewsResponse(); try { LoginBindResponse loginData = doLogin(); string urlData = String.Format("banks/{0}/accounts", bank_id); string JsonResult = new FluentClient(config.Url) .GetAsync(urlData) .WithHeader("Authorization", "JWT " + loginData.token) .WithOptions(true) .AsString().Result; result.views = JsonConvert.DeserializeObject <List <View> >(JsonResult); result.executeStatus = getExecuteStatus(JsonResult, urlData); } catch (CustomException cEx) { result.executeStatus = cEx.convertToCustomStatus(); } catch (Exception ex) { result.executeStatus = new CustomException(ExceptionsCodes.UnexpectedException, "", ex.Message).convertToCustomStatus(); } return(result); }
public override Person GetPersonByCUIT(string cuit) { Person result = new Person(); try { LoginBindResponse loginData = doLogin(); string urlData = String.Format("persons/{0}/banks", cuit); string JsonResult = new FluentClient(config.Url) .GetAsync(urlData) .WithHeader("Authorization", "JWT " + loginData.token) .WithOptions(true) .AsString().Result; result = JsonConvert.DeserializeObject <Person>(JsonResult); CustomStatus bindException; result.executeStatus = getExecuteStatus(JsonResult, urlData); } catch (CustomException cEx) { result.executeStatus = cEx.convertToCustomStatus(); } catch (Exception ex) { result.executeStatus = new CustomException(ExceptionsCodes.UnexpectedException, "", ex.Message).convertToCustomStatus(); } return(result); }
/********* ** Protected methods *********/ /// <summary>Construct an HTTP client with the JSON.NET formatter.</summary> /// <param name="url">The base URI prepended to relative request URIs.</param> protected IClient ConstructClient(string url) { IClient client = new FluentClient(url); client.Formatters.Remove(client.Formatters.JsonFormatter); client.Formatters.Add(new JsonNetFormatter()); return(client); }
private static FluentClient CreateClient(FakeResponseMode mode = FakeResponseMode.Capture) { var serializer = new JsonContentSerializer(); var fakeHttp = new FakeMessageHandler { Mode = mode }; var client = new FluentClient(serializer, fakeHttp); return client; }
public async Task <string> GetToken() { using (var fluentClient = new FluentClient($"{Addresses.ServerUrl}api/")) { //TODO: Use hash return(await(await fluentClient.GetAsync($"Authentication/terminal/hash/testing")).As <string>()); } }
internal static async Task <IDictionary <string, ModInfoModel> > CheckModUpdate(string[] modKeys, MainWindow mf) { using (IClient client = new FluentClient("https://api.smapi.io/v2.0/")) { return(await client .PostAsync("mods", new ModSearchModel(modKeys)) .As <IDictionary <string, ModInfoModel> >()); } }
public static async Task <JObject> PostRequestAsync(String uri, String parameters) { { //using (var httpClient = new HttpClient()) //{ // using (var request = new HttpRequestMessage(new HttpMethod("POST"), "https://api.bitbucket.org/2.0/repositories/WildWoz/test-repo/src")) // { // var base64authorization = Convert.ToBase64String(Encoding.ASCII.GetBytes("WildWoz:F4vTWxGmZTgQDkTYgk6m")); // request.Headers.TryAddWithoutValidation("Authorization", $"Basic {base64authorization}"); // var multipartContent = new MultipartFormDataContent(); // multipartContent.Add(new ByteArrayContent(File.ReadAllBytes("C:/Users/adam.wozniak/Desktop/NewFolder/test.txt")), "/test15.txt", Path.GetFileName("C:/Users/adam.wozniak/Desktop/NewFolder/test.txt")); // request.Content = multipartContent; // var response = await httpClient.SendAsync(request); // } //} var username = "******"; var password = "******"; var plainText_usernamePassword = System.Text.Encoding.UTF8.GetBytes(username + ":" + password); var base64encoded_usernamePassword = System.Convert.ToBase64String(plainText_usernamePassword); var defaultHttpClient = new HttpClient(); defaultHttpClient.DefaultRequestHeaders .Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", base64encoded_usernamePassword); IClient client = new FluentClient("https://api.bitbucket.org/2.0/", defaultHttpClient); var messages = new JObject(); var multipartContent = new MultipartFormDataContent(); multipartContent.Add(new ByteArrayContent(File.ReadAllBytes("C:/Users/adam.wozniak/Desktop/NewFolder/TestDoc.docx")), "/a-tashFile-docx.docx", Path.GetFileName("C:/Users/adam.wozniak/Desktop/NewFolder/TestDoc.docx")); multipartContent.Add(new StringContent("comitting Tash first docx file."), "message"); var url = "repositories/WildWoz/test-repo2/src"; var responseRaw = await client .PostAsync(url) .WithBody(multipartContent) .AsString(); var response = new JObject(); if (responseRaw == "") { response = JObject.Parse("{\"response\":\"Commit successful\"}"); } else { response = JObject.Parse(responseRaw); } Console.WriteLine(responseRaw); return(response); } }
public void RetrievesModelFromRoot() { Room room = new FluentClient <Error>("http://local.property.erm-api.com/v1/").Get <Room>("H151006172656205").Result.Entity; Assert.IsNotNull(room); Assert.AreEqual("H151006172656205", room.Id); Assert.AreEqual("my city", room.City); }
public static async Task <JObject> DeleteRequest(FluentClient client, string uri, CancellationToken cancellationToken) { var responseRaw = await client .DeleteAsync(uri) .WithCancellationToken(cancellationToken); var response = JObject.Parse("{\"response\":\"Deletion successful\"}"); return(response); }
public static Pathoschild.Http.Client.IClient GetFluentClient(MockHttpMessageHandler httpMessageHandler) { var httpClient = httpMessageHandler.ToHttpClient(); var client = new FluentClient(SENDGRID_API_BASE_URI, httpClient); client.SetRequestCoordinator(new SendGridRetryStrategy()); client.Filters.Remove <DefaultErrorFilter>(); client.Filters.Add(new SendGridErrorHandler()); return(client); }
private static IFluentClient CreateClient() { var httpClient = new HttpClient(); httpClient.BaseAddress = new Uri("http://httpbin.org/", UriKind.Absolute); var fluentClient = new FluentClient(httpClient); return(fluentClient); }
public static async Task <Responses.RemovePlayerGameBanResponse> RemovePlayerGameBan(ulong steamId) { var responseData = await FluentClient.PostAsync("ICheatReportingService/RequestPlayerGameBan/v1") .WithArgument("key", PublisherApiKey) .WithArgument("appid", AppId) .WithArgument("steamid", steamId) .As <SteamworksWebApiResponse2 <Responses.RemovePlayerGameBanResponse> >(); return(responseData.Response); }
//Devuelve los tipos de origen public async Task <Types> getSourceTypes() { using (var client = new FluentClient(_baseUrl)) { var rest = await client.GetAsync(API.ver + Config.SourceTypes) .WithHeader(Config.Header.cache, Config.cache) .WithHeader(Config.Header.key, _key).As <Types>(); return(rest); } }
//Devuelve un esquema con un id específico. public async Task <Schema> getSchemaId(string id) { using (var client = new FluentClient(_baseUrl)) { var rest = await client.GetAsync(API.ver + Config.SchemasId + id) .WithHeader(Config.Header.cache, Config.cache) .WithHeader(Config.Header.key, _key).As <Schema>(); return(rest); } }
//Verifica si la tarea de promover un schema se está ejecutando public async Task <PromoteSchema> getPromoteSchema() { using (var client = new FluentClient(_baseUrl)) { var rest = await client.GetAsync(API.ver + Config.PromoteSchema) .WithHeader(Config.Header.cache, Config.cache) .WithHeader(Config.Header.key, _key).As <PromoteSchema>(); return(rest); } }
public async Task <IEnumerable <ModEntryModel> > PostAsync([FromBody] ModSearchModel model) { using IClient client = new FluentClient("https://smapi.io/api"); Startup.ConfigureJsonNet(client.Formatters.JsonFormatter.SerializerSettings); return(await client .PostAsync(this.Request.Path) .WithBody(model) .AsArray <ModEntryModel>()); }
private FluentClient CreateClient() { var client = FluentClient.Create(c => c .Interceptor(new LogInterceptor(_output.WriteLine)) .Defaults(d => d .State("happy", "joy") .BaseUri(new Uri("http://httpbin.org/", UriKind.Absolute))) ); return(client); }
//Devuelve el estado de los procesos. public async Task <Status> getStatusProcesses() { using (var client = new FluentClient(_baseUrl)) { var rest = await client.GetAsync(API.ver + Config.ProcessesStatus) .WithHeader(Config.Header.cache, Config.cache) .WithHeader(Config.Header.key, _key).As <Status>(); return(rest); } }
private static FluentClient CreateClient() { var serializer = new JsonContentSerializer(); var fakeStore = MemoryMessageStore.Current; var fakeHttp = new FakeMessageHandler(fakeStore, FakeResponseMode.Fake); var client = new FluentClient(serializer, fakeHttp); client.BaseUri = new Uri("http://httpbin.org/", UriKind.Absolute); return client; }
public void CanUseClientForDifferentCalls() { var client = new FluentClient<Error>("http://local.property.erm-api.com/v1/"); Room room1 = client.Get<Room>("H151006172656205").Result.Entity; Room room2 = client.Get<Room>("H151006172656205").Result.Entity; Assert.IsNotNull(room1); Assert.IsNotNull(room2); }
private static FluentClient CreateClient() { var serializer = new JsonContentSerializer(); var fakeStore = new FileMessageStore(); fakeStore.StorePath = @".\GitHub\Responses"; var fakeHttp = new FakeMessageHandler(fakeStore, FakeResponseMode.Fake); var client = new FluentClient(serializer, fakeHttp); client.BaseUri = new Uri("https://api.github.com/", UriKind.Absolute); return client; }
public void HandlesNetworkFailure() { var client = new FluentClient<Error>("http://local.property.erm-api.com/v1/"); // server set up to fail on this code FluentResponse<User, Error> room = client.Get<User>("forceerror").Result; Assert.IsNotNull(room); Assert.IsNull(room.Entity); Assert.AreEqual(401, (int)room.StatusCode); Assert.AreEqual("Authenticate", room.Error.Message); }
/// <summary> /// Initializes a new instance of the <see cref="InterceptorResponseContext" /> class. /// </summary> /// <param name="client">The current <see cref="FluentClient" /> that called the interceptor.</param> /// <param name="httpResponse">The <see cref="HttpResponseMessage" /> received from the HTTP call.</param> /// <param name="exception">The exception that occurred during the HTTP request.</param> public InterceptorResponseContext(FluentClient client, HttpResponseMessage httpResponse, Exception exception) { Client = client; HttpResponse = httpResponse; Exception = exception; }
/// <summary> /// Initializes a new instance of the <see cref="InterceptorRequestContext"/> class. /// </summary> /// <param name="client">The current <see cref="FluentClient"/>.</param> /// <param name="request">The <see cref="FluentRequest"/> used to build the current request.</param> public InterceptorRequestContext(FluentClient client, FluentRequest request) { Client = client; Request = request; }
public void RetrievesModelFromRoot() { Room room = new FluentClient<Error>("http://local.property.erm-api.com/v1/").Get<Room>("H151006172656205").Result.Entity; Assert.IsNotNull(room); Assert.AreEqual("H151006172656205", room.Id); Assert.AreEqual("my city", room.City); }
public void RetreivesSubModel() { var room = new FluentClient<Error>("http://local.property.erm-api.com/v1/").Find<User>(1).Get<Room>("h123123"); }
public void RetreivesSubModel() { var room = new FluentClient<Error>("http://local.property.erm-api.com/v1/").Find<Room>("H151006172656205").Get<User>(1); }
/// <summary>Construct an <see cref="IClient"/> instance and assert that its initial state is valid.</summary> /// <param name="baseUri">The base URI prepended to relative request URIs.</param> /// <param name="inconclusiveOnFailure">Whether to throw an <see cref="InconclusiveException"/> if the initial state is invalid.</param> /// <exception cref="InconclusiveException">The initial state of the constructed client is invalid, and <paramref name="inconclusiveOnFailure"/> is <c>true</c>.</exception> /// <exception cref="AssertionException">The initial state of the constructed client is invalid, and <paramref name="inconclusiveOnFailure"/> is <c>false</c>.</exception> protected IClient ConstructClient(string baseUri = "http://example.com/", bool inconclusiveOnFailure = true) { try { // execute IClient client = new FluentClient(baseUri); // verify Assert.NotNull(client.BaseClient, "The base client is null."); Assert.AreEqual(baseUri, client.BaseClient.BaseAddress.ToString(), "The base path is invalid."); return client; } catch (AssertionException exc) { if (inconclusiveOnFailure) Assert.Inconclusive("The client could not be constructed: {0}", exc.Message); throw; } }
private static FluentClient CreateClient() { var client = new FluentClient(); client.BaseUri = new Uri("http://httpbin.org/", UriKind.Absolute); return client; }