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);
            }
        }
Beispiel #2
0
        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]));
            }
        }
Beispiel #4
0
        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);
            }
        }
Beispiel #5
0
        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);
            }
        }
Beispiel #6
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;
        }
Beispiel #7
0
        //  [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);
            }
        }
Beispiel #8
0
        // [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);
            }
        }
Beispiel #9
0
        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);
        }
Beispiel #10
0
        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;
        }
Beispiel #11
0
        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);
        }
Beispiel #12
0
        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);
        }
Beispiel #13
0
        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());
        }
Beispiel #14
0
        /// <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);
        }
Beispiel #15
0
 protected RepositoryBase(IAppSettings settings, Uri hostAddress)
 {
     Settings = settings;
     if (hostAddress == null)
     {
         _proxy = new HttpClientProxy();
     }
     else
     {
         _proxy = new HttpClientProxy(hostAddress);
     }
     Task.Run(Reload).Wait();
 }
Beispiel #16
0
        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();
        }
Beispiel #17
0
        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);
        }
Beispiel #18
0
        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);
        }
Beispiel #19
0
        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)));
        }
Beispiel #20
0
        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()));
        }
Beispiel #21
0
        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);
        }
Beispiel #22
0
        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);
        }
Beispiel #24
0
        /// <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();
        }
Beispiel #25
0
        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"));
        }
Beispiel #26
0
        //  [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));
        }
Beispiel #28
0
        //  [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");
            }
        }
Beispiel #29
0
        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();
        }
Beispiel #30
0
        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);
            }
        }