public async Task GetFormattedAddressFromCoordinate() { var handler = new HttpClientHandler(); if (handler.SupportsAutomaticDecompression) { handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } using (var client = new HttpClient(handler, true)) { client.BaseAddress = new Uri("http://dev.virtualearth.net/REST/v1/"); string key = CredentialStore.RetrieveObject("bing.key.json").Key; dynamic proxy = new HttpClientProxy(client); var result = await proxy.Locations("44.9108238220215,-93.1702041625977").get(includeEntityTypes: "Address,PopulatedPlace,Postcode1,AdminDivision1,CountryRegion", key: key); Assert.AreEqual(200, (int)result.statusCode); Assert.IsTrue(result.resourceSets.Count > 0); Assert.IsTrue(result.resourceSets[0].resources.Count > 0); var address = result.resourceSets[0].resources[0].address.formattedAddress; Assert.AreEqual("1012 Davern St, St Paul, MN 55116", (string)address); } }
public void TestInitialize() { this.retryCounts = new TestRetryCounts(); this.testServer = TestUtils.CreateTestServer( services => { services.AddSingleton <TestRetryCounts>(this.retryCounts); services.AddTransient <TestControllerForRetry>(); services.AddMvc( options => { options.EnableEndpointRouting = false; }); }); var httpClient = this.testServer.CreateClient(); var testServiceProxy = new HttpClientProxy <ITestServiceWithRetry>( "http://localhost", new HttpClientProxyOptions() { HttpClient = httpClient }); this.testService = testServiceProxy.GetProxyObject(); }
public async Task CoordinateFromPostalCode() { var handler = new HttpClientHandler(); if (handler.SupportsAutomaticDecompression) { handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } using (var client = new HttpClient(handler, true)) { client.BaseAddress = new Uri("http://dev.virtualearth.net/REST/v1/"); string key = CredentialStore.RetrieveObject("bing.key.json").Key; dynamic proxy = new HttpClientProxy(client); var result = await proxy.Locations.get(postalCode : "55116", countryRegion : "US", key : key); Assert.AreEqual(200, (int)result.statusCode); Assert.IsTrue(result.resourceSets.Count > 0); Assert.IsTrue(result.resourceSets[0].resources.Count > 0); var r = result.resourceSets[0].resources[0].point.coordinates; Assert.IsTrue((44.9108238220215).AboutEqual((double)r[0])); Assert.IsTrue((-93.1702041625977).AboutEqual((double)r[1])); } }
public async Task Test() { var handler = new TestHttpMessageHandler( async(req) => { await Task.Yield(); if (req.Content is MultipartFormDataContent multipartFormData) { if (req.Content.Headers.ContentType.ToString().StartsWith("multipart/")) { return(new HttpResponseMessage(HttpStatusCode.OK)); } } return(new HttpResponseMessage(HttpStatusCode.InternalServerError)); }); var httpClient = new HttpClient(handler); var testContract = new HttpClientProxy <ITestMultipart>( "http://localhost", new HttpClientProxyOptions() { HttpClient = httpClient }); var proxy = testContract.GetProxyObject(); using (var stream = new MemoryStream(Encoding.UTF8.GetBytes("Hello World"))) { var response = await proxy.UploadFile("myfile.png", stream); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); } }
public async Task GetMethod2PathAsProperty2Params() { var handler = new HttpClientHandler(); if (handler.SupportsAutomaticDecompression) { handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } using (var client = new HttpClient(handler, true)) { client.BaseAddress = new Uri("http://openstates.org/api/v1/"); string key = CredentialStore.RetrieveObject("sunlight.key.json").Key; client.DefaultRequestHeaders.Add("X-APIKEY", key); dynamic proxy = new HttpClientProxy(client); var parameters = new Dictionary <string, object>() { { "lat", 44.926868 }, { "long", -93.214049 } // since long is a keyword we need to pass arguments in a Dictionary }; var result = await proxy.legislators.geo.get(paramList : parameters); Assert.IsNotNull(result); Assert.IsTrue(result.Count > 0); } }
private async void btnGetById_Click(object sender, EventArgs e) { var id = int.Parse(txtId.Text); var item = await HttpClientProxy.GetProductByIdAsync(id); txtLog.Text += item.ID + "\t" + item.Name + "\t" + item.Category + "\t" + item.Price; }
// [Ignore] // - this test requires user interaction public async Task GetUserProfile() { var auth = new GoogleOAuth2("email profile"); _token = await auth.Authenticate(_token); Assert.IsNotNull(_token, "auth failed"); var handler = new HttpClientHandler(); if (handler.SupportsAutomaticDecompression) { handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } using (var client = new HttpClient(handler, true)) { client.BaseAddress = new Uri("https://www.googleapis.com"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", _token); dynamic proxy = new HttpClientProxy(client); var profile = await proxy.oauth2.v1.userinfo.get(); Assert.IsNotNull(profile); Assert.AreEqual("Kackman", (string)profile.family_name); } }
// [Ignore] // - this test requires user interaction public async Task CreateCalendar() { var auth = new GoogleOAuth2("email profile https://www.googleapis.com/auth/calendar"); _token = await auth.Authenticate(_token); Assert.IsNotNull(_token, "auth failed"); var handler = new HttpClientHandler(); if (handler.SupportsAutomaticDecompression) { handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } using (var client = new HttpClient(handler, true)) { client.BaseAddress = new Uri("https://www.googleapis.com/calendar/v3/"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", _token); dynamic proxy = new HttpClientProxy(client); dynamic calendar = new ExpandoObject(); calendar.summary = "unit_testing"; var list = await proxy.calendars.post(calendar); Assert.IsNotNull(list); Assert.AreEqual("unit_testing", (string)list.summary); } }
public ValidationUiController() { // CONSIDER: Use the Unity DI container to inject dependencies, rather than // instantiating them by hand. IFileSystem fileSystem = new FileSystem(); IHttpClientProxy httpClientProxy = new HttpClientProxy(); _validationUiService = new ValidationUiService(fileSystem, httpClientProxy); }
private async void btnPost_Click(object sender, EventArgs e) { var product = new PRODUCT { Name = "Name", Category = "Category", Price = int.Parse(txtId.Text) }; var response = await HttpClientProxy.CreateProductAsync(product); txtLog.Text += response.ID + "\t" + response.Name + "\t" + response.Category + "\t" + response.Price; }
public static string GetNewIDByBM(string bmno) { string newid = string.Empty; var url = ConfigurationManager.AppSettings[Config_Api_BaseUri].ToString(); url += "/api/NewID?ruleno=" + bmno; url = url.Replace("//", "/"); url = url.Replace("http:/", "http://"); newid = HttpClientProxy.Get <string>(url); return(newid); }
public async Task CanUseHttpClientProxy() { var uri = new Uri(@"https://www.viperfisch.de/wakek/"); var sut = new HttpClientProxy { BaseAddress = uri }; Assert.AreEqual(uri, sut.BaseAddress); var result = await sut.GetStringAsync("helloworld.php"); Assert.AreEqual("Hello World", result); }
static void Main() { //-- APIのルートURL設定 HttpClientProxy.SetRootUri(ConfigurationManager.AppSettings["RootUri"]); ApiClient.SetRootUrl(new Uri(ConfigurationManager.AppSettings["RootUri"])); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new LoginForm()); //TODO Application.Run(new MainForm()); }
/// <summary> /// Sets the proxy with timeout. /// If the WebRequestHandler has a timeout value, the lowest timeout value in HttpClient and WebRequestHandler will be used. /// </summary> /// <param name="timeSpan">The time span.</param> /// <param name="httpClientHandler">The HTTP client handler.</param> public void SetProxyWithTimeout(TimeSpan timeSpan, HttpClientHandler httpClientHandler) { var httpClient = new HttpClient(httpClientHandler) { BaseAddress = BaseAddress, Timeout = timeSpan }; var proxy = new HttpClientProxy(httpClient); // Set proxy in service description Conn.ServiceDescription.SetProxy(proxy); }
protected RepositoryBase(IAppSettings settings, Uri hostAddress) { Settings = settings; if (hostAddress == null) { _proxy = new HttpClientProxy(); } else { _proxy = new HttpClientProxy(hostAddress); } Task.Run(Reload).Wait(); }
static async Task Main(string[] args) { var lua = new Lua(); lua["http"] = new HttpClientProxy(); var func = lua.LoadFile("./http.lua"); var result = await(func.Call()[0] as Task <string>); Console.WriteLine(result); Console.ReadKey(); }
public DBMetadataResult GetMetadataInfo(string metadataName) { DBMetadataResult metadata = null; var baseurl = DllConfigurationManager.AppSettings[Config_Api_BaseUri].ToString(); var path = string.Format("{0}/{1}/{2}", baseurl, DBMetadata, metadataName); var connectionsresult = HttpClientProxy.Get <ResultData <DBMetadataResult> >(path); if (connectionsresult != null) { metadata = connectionsresult.Data; } return(metadata); }
private static (HttpClientProxy httpClientProxy, Configuration configuration, RestClientWithSecurity restClient) GetHttpClientProxyConfigurationRestClient() { var securityConfiguration = new SecurityConfiguration(); var logger = new InternalLogger(securityConfiguration); var webContext = new WebContext(); var jwtTokenRequestClient = new JwtTokenRequestClient(securityConfiguration, logger, new UserProfileId(webContext, logger), new JwtTokenCache(webContext)); var securityTokenServiceProxy = new SecurityTokenServiceProxy(jwtTokenRequestClient, securityConfiguration); var httpClientProxy = new HttpClientProxy(securityTokenServiceProxy); var configuration = new Configuration(); var restClient = new RestClientWithSecurity(configuration, httpClientProxy); return(httpClientProxy, configuration, restClient); }
public static BaseValueSegmentProxy GetBaseValueSegmentProxy() { var securityConfiguration = new SecurityConfiguration(); var logger = new InternalLogger(securityConfiguration); var webContext = new WebContext(); var jwtTokenRequestClient = new JwtTokenRequestClient(securityConfiguration, logger, new UserProfileId(webContext, logger), new JwtTokenCache(webContext)); var securityTokenServiceProxy = new SecurityTokenServiceProxy(jwtTokenRequestClient, securityConfiguration); var httpClientProxy = new HttpClientProxy(securityTokenServiceProxy); var configuration = new Configuration(); var restClient = new RestClient(configuration, httpClientProxy); return(new BaseValueSegmentProxy(httpClientProxy, new UrlServices(restClient, configuration))); }
public async Task <ActionResult> Index() { HttpClientProxy proxy = new HttpClientProxy("http://localhost/webapi/api/"); NumberResponse response = await proxy.Execute(new NumberAddContract() { Request = new NumberRequest() { First = 3, Second = 4 } }); return(Content(response.Result.ToString())); }
public string GetConnectionString(string databaseName) { string connectionstring = string.Empty; var key = DllConfigurationManager.AppSettings[Config_Api_BaseUri].ToString(); var path = string.Format("{0}/{1}/{2}", key, DBConnection, databaseName); var connectionsresult = HttpClientProxy.Get <ResultData <string> >(path); if (connectionsresult != null && string.IsNullOrEmpty(connectionsresult.Data)) { connectionstring = connectionsresult.Data; } return(connectionstring); }
public async Task CallService_WithUriBuilderParameter() { const string Url = "http://dynamic.com"; var id = Guid.NewGuid().ToString(); Uri requestUri = null; var mock = new Mock <IHttpRequestSender>(); mock.Setup(m => m.SendAsync( It.IsAny <IHttpRequestBuilder>(), It.IsAny <HttpCompletionOption>())) .Returns <IHttpRequestBuilder, HttpCompletionOption>( (builder, options) => { var request = builder.Build(); requestUri = request.RequestUri; return(Task.FromResult( new HttpResponseMessage() { StatusCode = HttpStatusCode.OK })); }); var sp = this.BuildServices(mock.Object); var clientProxy = new HttpClientProxy <IDynamicUriClient>( new HttpClientProxyOptions() { Services = sp }); var mockUriBuilder = new Mock <IUriBuilder>(); mockUriBuilder.Setup(m => m.BuildUri()).Returns(new Uri(Url)); var client = clientProxy.GetProxyObject(); var response = await client.GetWidgetAsync(mockUriBuilder.Object, id); Assert.IsNotNull(response); Assert.AreEqual(HttpStatusCode.OK, response.StatusCode); Assert.IsNotNull(requestUri); Assert.AreEqual($"{Url}/api/test/widgets/{id}", requestUri.ToString()); mock.Verify(m => m.SendAsync( It.IsAny <IHttpRequestBuilder>(), It.IsAny <HttpCompletionOption>()), Times.Once); }
public void CreatingHttpClientProxy_ReturnsProxy() { // Arrange var proxy = new HttpClientProxy(null, null); _serviceProviderMock .Setup(f => f.GetService(typeof(HttpClientProxy))) .Returns(proxy); // Act var actualProxy = _sut.Create(); // Assert actualProxy.Should().Be(proxy); }
/// <summary> /// プロダクトテーブル情報を取得します。 /// </summary> /// <returns>レコード</returns> public static async Task <IEnumerable <PRODUCT> > GetAllProductsAsync(int?id) { var url = (id == null) ? "products/" : $"products/?id={id}"; var response = await HttpClientProxy.Create().GetAsync(url).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { throw new Exception(response.ReasonPhrase); } var body = await response.Content.ReadAsStringAsync().ConfigureAwait(false); return(JsonConvert.DeserializeObject <IEnumerable <PRODUCT> >(body)); //return product?.ToArray(); }
public void GetLegalPartySearchUri() { var configuration = new Dev1Configuration(); var securityTokenServiceProxy = new Mock <ISecurityTokenServiceProxy>(); securityTokenServiceProxy.Setup(x => x.GetAccessToken()).Returns("HELLO"); var httpClientProxy = new HttpClientProxy(securityTokenServiceProxy.Object); var urlService = new UrlServices(new RestClient(configuration, httpClientProxy), configuration); var uri = urlService.GetServiceUri("service.legalpartysearch"); Assert.That(uri.ToString(), Is.EqualTo("http://c592xfglumwb1.ecomqc.tlrg.com/service.legalpartysearch")); }
// [Ignore] // - this test requires user interaction public async Task UpdateCalendar() { var auth = new GoogleOAuth2("email profile https://www.googleapis.com/auth/calendar"); _token = await auth.Authenticate(_token); Assert.IsNotNull(_token, "auth failed"); var handler = new HttpClientHandler(); if (handler.SupportsAutomaticDecompression) { handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } using (var client = new HttpClient(handler, true)) { client.BaseAddress = new Uri("https://www.googleapis.com/calendar/v3/"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", _token); dynamic proxy = new HttpClientProxy(client); var list = await proxy.users.me.calendarList.get(); Assert.IsNotNull(list); string id = ((IEnumerable <dynamic>)(list.items)).Where(cal => cal.summary == "unit_testing").Select(cal => (string)cal.id).FirstOrDefault(); Assert.IsFalse(string.IsNullOrEmpty(id)); var guid = Guid.NewGuid().ToString(); dynamic calendar = new ExpandoObject(); calendar.summary = "unit_testing"; calendar.description = guid; var result = await proxy.calendars(id).put(calendar); Assert.IsNotNull(result); list = await proxy.users.me.calendarList.get(); Assert.IsNotNull(list); string description = ((IEnumerable <dynamic>)(list.items)).Where(cal => cal.summary == "unit_testing").Select(cal => (string)cal.description).FirstOrDefault(); Assert.AreEqual(guid, description); } }
public static WebexTeamsChatHelper CreateWebexTeamsChatHelper(WebexTeamsSettings settings) { var httpClient = new HttpClient { BaseAddress = new Uri("https://api.ciscospark.com/v1") }; var httpClientProxy = new HttpClientProxy(httpClient, new OptionsWrapper <WebexTeamsSettings>(settings)); var apiService = new WebexTeamsApiService(httpClientProxy); var mapper = WebexTeamsMapperFactory.CreateMapper(); var messageParser = new WebexTeamsMessageParser(mapper); var messageHandler = new WebexTeamsMessageHandler(apiService, messageParser, mapper); var personHandler = new WebexTeamsPersonHandler(apiService, mapper); var roomHandler = new WebexTeamsRoomHandler(apiService, mapper); var webhooks = new WebexTeamsWebhookHandler(apiService, new OptionsWrapper <WebexTeamsSettings>(settings), mapper, messageParser); return(new WebexTeamsChatHelper(messageHandler, personHandler, roomHandler, webhooks)); }
// [Ignore] // - this test requires user interaction public async Task DeleteCalendar() { var auth = new GoogleOAuth2("email profile https://www.googleapis.com/auth/calendar"); _token = await auth.Authenticate(_token); Assert.IsNotNull(_token, "auth failed"); var handler = new HttpClientHandler(); if (handler.SupportsAutomaticDecompression) { handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } using (var client = new HttpClient(handler, true)) { client.BaseAddress = new Uri("https://www.googleapis.com/calendar/v3/"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("OAuth", _token); dynamic proxy = new HttpClientProxy(client); var list = await proxy.users.me.calendarList.get(); Assert.IsNotNull(list); string id = ((IEnumerable <dynamic>)(list.items)).Where(cal => cal.summary == "unit_testing").Select(cal => (string)cal.id).FirstOrDefault(); Assert.IsFalse(string.IsNullOrEmpty(id), "calendar does not exist so we can't delete it"); var result = await proxy.calendars(id).delete(); Assert.IsNull(result); //var list2 = await proxy.users.me.calendarList.get(); //Assert.IsNotNull(list2); //var id2 = ((IEnumerable<dynamic>)(list2.items)).Where(cal => cal.summary == "unit_testing").Select(cal => (string)cal.id).FirstOrDefault(); //Assert.IsTrue(string.IsNullOrEmpty(id2), "calendar seems to have not been deleted"); } }
public void TestInitialize() { this.testServer = TestUtils.CreateTestServer( services => { services.AddTransient <TestControllerWithHeaders>(); services.AddMvc( options => { options.EnableEndpointRouting = false; }); }); this.clientProxy = new HttpClientProxy <ITestServiceWithHeaders>( "http://localhost", new HttpClientProxyOptions() { HttpClient = this.testServer.CreateClient() }); this.testService = this.clientProxy.GetProxyObject(); }
public async Task GetMethodSegmentWithArgs() { var handler = new HttpClientHandler(); if (handler.SupportsAutomaticDecompression) { handler.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate; } using (var client = new HttpClient(handler, true)) { client.BaseAddress = new Uri("http://openstates.org/api/v1/"); string key = CredentialStore.RetrieveObject("sunlight.key.json").Key; client.DefaultRequestHeaders.Add("X-APIKEY", key); dynamic proxy = new HttpClientProxy(client); var result = await proxy.bills.mn("2013s1")("SF 1").get(); Assert.IsNotNull(result); Assert.AreEqual("MNB00017167", result.id); } }