public void LinkedInApiCall() { var url = "https://www.linkedin.com/uas/oauth2/authorization?response_type=code" + "&client_id=" + "751ku61912s1ly" + "&state=STATE" + "&redirect_uri=" + Uri.EscapeDataString("https://www.google.ca/"); var client = new HttpClientService(); var authToken = "AQTd0nkkOxSqs1ClSG5WkBQWJe3RZgjctq9-IBe5dIghrvQichPnRDg5xwGbjtYnmjzEt9Zgw-Fu-SO8PfgbQngj8W3LD3Got5K_I2J-dMrj_Ibb2k0"; var sign = "grant_type=authorization_code" + "&code=" + authToken + "&redirect_uri=" + Uri.EscapeDataString("https://www.google.ca/") + "&client_id=" + "751ku61912s1ly" + "&client_secret=" + "mhN9E3rMW2bP8V2H"; var content = new StringContent(sign); content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); var data = client.Post(new HttpParameters() { Content = content, DefaultHeaders = new Dictionary<string, string>() { {"Content-type","application/json"} }, BaseUrl = "https://www.linkedin.com/", ResourceUrl = "uas/oauth2/accessToken" }); }
public async Task <ActionResult> CategoryNews(string seoLink, int page = 1, int pageSize = 12) { var requestUrl = _configuration.GetApiUrl(); var apiService = _configuration.GetApiServiceInfo(); var httpClientService = new HttpClientService(); var categoryInfo = await httpClientService.GetAsync <CategoryTranslationViewModel>($"{requestUrl.ApiGatewayUrl}/api/v1/website/categories/category/{apiService.TenantId}/{seoLink}/{CultureInfo.CurrentCulture.Name}"); ViewBag.CategoryInfo = categoryInfo; if (categoryInfo?.ChildCount > 0) { var listCategoryWidthNews = await httpClientService.GetAsync <SearchResult <CategoryWidthNewsViewModel> >($"{requestUrl.ApiGatewayUrl}/api/v1/website/news/get-list-category-width-news/{apiService.TenantId}/{seoLink}/5/{CultureInfo.CurrentCulture.Name}"); ViewBag.ListCategoryWidthNews = listCategoryWidthNews?.Items; } else { var listNews = await httpClientService.GetAsync <SearchResult <NewsSearchViewModel> >($"{requestUrl.ApiGatewayUrl}/api/v1/website/news/getNewsByCategory/{apiService.TenantId}/{seoLink}/{page}/{pageSize}/{CultureInfo.CurrentCulture.Name}"); ViewBag.ListNews = listNews?.Items; ViewBag.TotalRows = listNews?.TotalRows; } ViewBag.SeoLink = seoLink; ViewBag.Page = page; var breadcrumbs = new List <Breadcrumb> { new Breadcrumb() { Name = categoryInfo.Name, IsCurrent = true, }, }; ViewBag.Breadcrumb = breadcrumbs; return(View()); }
public static void Main(string[] args) { HttpClientService httpClientService = new HttpClientService(); // Read data from Http Service string jsonData = httpClientService.Get(); // Deserialize json data InputData data = new InputData(); data.ownerAndTheirPets = JsonDeSerializer.FromJson(jsonData); if (data.ownerAndTheirPets != null) { // Get Pets of Pet types listed List <PetType> getPetsOfType = new List <PetType>() { PetType.Cat }; IPetService petService = new PetService(); OutputService outPutService = new OutputService(); var stratergyFactory = new PetStrategyFactory(petService, data); // Determine the strategy and get pets based on PetType and Owner Gender foreach (PetType petType in getPetsOfType) { var Strategy = stratergyFactory.Resolve(petType); List <string> maleOwnerPets = Strategy.GetPetsOfMaleOwner(); List <string> femaleOwnerCats = Strategy.GetPetsOfFemaleOwner(); outPutService.PrintOutput(petType, maleOwnerPets, femaleOwnerCats); } } else { Console.WriteLine("No data to process"); } Console.ReadKey(); }
public async Task should_success_PutAsync() { //Setup Mock <IIdentityService> identity = new Mock <IIdentityService>(); identity.Setup(s => s.Username).Returns("usernameTest"); HttpClientService httpClient = new HttpClientService(identity.Object); MemoItemModel model = new MemoItemModel() { CurrencyCode = "Rp", Interest = 2 }; var stringContent = new StringContent(JsonConvert.SerializeObject(model), Encoding.UTF8, "application/json"); //Act var result = await httpClient.PutAsync("https://stackoverflow.com/", stringContent); //Assert Assert.NotNull(result); }
public async Task <IActionResult> Index() { var requestUrl = _configuration.GetApiUrl(); var apiService = _configuration.GetApiServiceInfo(); var httpClientService = new HttpClientService(); var listAlbum = await httpClientService.GetAsync <SearchResult <AlbumViewModel> > ($"{requestUrl.ApiGatewayUrl}/api/v1/website/albums/{apiService.TenantId}/groups/{(int)AlbumType.Video}/{CultureInfo.CurrentCulture.Name}"); ViewBag.ListAlbum = listAlbum?.Items; var breadcrumbs = new List <Breadcrumb> { new Breadcrumb() { Name = "Video", IsCurrent = true, } }; ViewBag.Breadcrumb = breadcrumbs; return(View()); }
public async Task <IActionResult> Index() { var requestUrl = _configuration.GetApiUrl(); var apiService = _configuration.GetApiServiceInfo(); var httpClientService = new HttpClientService(); var listEvent = await httpClientService.GetAsync <SearchResult <EventViewModel> >($"{requestUrl.ApiGatewayUrl}/api/v1/events/events/all/{apiService.TenantId}/1/9/{CultureInfo.CurrentCulture.Name}"); ViewBag.Events = listEvent?.Items; var breadcrumbs = new List <Breadcrumb> { new Breadcrumb() { Name = Resources.Resource.Events, IsCurrent = true, } }; ViewBag.Breadcrumb = breadcrumbs; return(View()); }
private void buttonTest_Click(object sender, EventArgs e) { Config config = new Config(textBoxDatabase.Text, textBoxS3bucket.Text, 1000, textBoxAccessKeyId.Text, textBoxSecretKey.Text, comboBoxRegion.SelectedItem.ToString()); try { Response response = HttpClientService.Post(JsonConvert.SerializeObject(config), String.Format("{0}test-connection", MainController.Uri)); if (response.Status.Equals(TextConstants.SUCCEEDED, StringComparison.OrdinalIgnoreCase)) { MessageBox.Show(TextConstants.SuccessConnection, TextConstants.Information, MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show(TextConstants.FailedConnection, TextConstants.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); } } catch (Exception ex) { MessageBox.Show(ex.Message, TextConstants.Error, MessageBoxButtons.OK, MessageBoxIcon.Error); Process.GetCurrentProcess().Kill(); } }
private WebsiteSetting GetSetting() { if (_cache.TryGetValue(CacheParam.Setting, out WebsiteSetting setting)) { return(setting); } var requestUrl = _configuration.GetApiUrl(); var apiService = _configuration.GetApiServiceInfo(); string convention = typeof(WebsiteSetting).Namespace; var listSettings = new HttpClientService() .GetAsync <SearchResult <Setting> >($"{requestUrl.ApiGatewayUrl}/api/v1/website/settings/get-setting/{apiService.TenantId}"); var settings = listSettings.Result?.Items; var websiteSetting = new WebsiteSetting(); if (settings == null) { return(websiteSetting); } websiteSetting.Brand = Common.GetSettingValue(settings, string.Format("{0}.Brand", convention)); websiteSetting.Favicon = Common.GetSettingValue(settings, string.Format("{0}.Favicon", convention)); websiteSetting.Instruction = Common.GetSettingValue(settings, string.Format("{0}.Instruction", convention)); websiteSetting.IpBlocking = Common.GetSettingValue(settings, string.Format("{0}.IpBlocking", convention)); websiteSetting.MetaDescription = Common.GetSettingValue(settings, string.Format("{0}.MetaDescription", convention)); websiteSetting.MetaTitle = Common.GetSettingValue(settings, string.Format("{0}.MetaTitle", convention)); websiteSetting.Logo = Common.GetSettingValue(settings, string.Format("{0}.Logo", convention)); websiteSetting.MetaKeyword = Common.GetSettingValue(settings, string.Format("{0}.MetaKeyword", convention)); websiteSetting.Fanpage = Common.GetSettingValue(settings, string.Format("{0}.Fanpage", convention)); websiteSetting.GoogleMap = Common.GetSettingValue(settings, string.Format("{0}.GoogleMap", convention)); websiteSetting.Hotline = Common.GetSettingValue(settings, string.Format("{0}.Hotline", convention)); _cache.Set(CacheParam.Setting, websiteSetting, TimeSpan.FromHours(2)); return(websiteSetting); }
public async Task <IActionResult> RegisterEvent(string seoLink) { seoLink = "digital-blading--dot-pha-de-khac-biet"; var requestUrl = _configuration.GetApiUrl(); var apiService = _configuration.GetApiServiceInfo(); var httpClientService = new HttpClientService(); var eventInfo = await httpClientService.GetAsync <ActionResultResponse <EventShowClientViewModel> >($"{requestUrl.ApiGatewayUrl}/api/v1/events/events/get-detail/{apiService.TenantId}/{seoLink}/{CultureInfo.CurrentCulture.Name}"); if (eventInfo != null) { var listVideo = eventInfo?.Data?.Albums?.Where(x => x.Type == Constants.AlbumType.Video).FirstOrDefault()?.AlbumItems; ViewBag.Videos = listVideo; } ViewBag.EventInfo = eventInfo?.Data; var listNews = await httpClientService.GetAsync <SearchResult <SocialNetworkViewModel> >($"{requestUrl.ApiGatewayUrl}/api/v1/website/social-networks/{apiService.TenantId}/alls"); ViewBag.SocialNetwork = listNews?.Items; return(View()); }
private void CreatePlayer() { Debug.Log("Game Controller CreatePlayer running"); var playerView = player.GetComponent <PlayerView>(); if (playerView == null) { Debug.Log("couldn't locate PlayerView in main menu"); } PlayerModelFactory PlayerModelFactory = new PlayerModelFactory(); PlayerModelFactory.Model.Id = new Guid("11111111-1111-1111-1111-111111111112"); PlayerModelFactory.Model.Position = new WGVector3(); PlayerControllerBuilder PlayerControllerBuilder = new PlayerControllerBuilder(PlayerModelFactory.Model, playerView); IPlayerControllerOptions options = new PlayerControllerOptions(); if (Debug.isDebugBuild) { options.Uri = new Uri("https://marblemotiondev.wolfgamesllc.com/api/players/"); } if (Application.isEditor) { options.Uri = new Uri("https://localhost:44340/api/players/"); } options.Uri = new Uri("https://localhost:44340/api/players/"); IHttpClientService httpClient = new HttpClientService(mainMenu.GetComponent <NonAsyncHttpClient>(), new UnityJsonConverter()); Debug.Log("cookie = {" + httpClient.HandleGetCookieClicked() + "}"); PlayerControllerBuilder.Configure(options).ConfigureHttpClientService(httpClient).Build(); }
public void ShouldGetHttpClientswithTimeout() { int timeout = 23; Mock <IHttpClientFactory> mockHttpClientFactory = new Mock <IHttpClientFactory>(); mockHttpClientFactory.Setup(s => s.CreateClient(It.IsAny <string>())).Returns(new HttpClient()); Dictionary <string, string> configDictionary = new Dictionary <string, string> { { "HttpClient:Timeout", $"00:00:{timeout}" }, }; IConfiguration config = new ConfigurationBuilder() .AddInMemoryCollection(configDictionary) .Build(); HttpClientService service = new HttpClientService(mockHttpClientFactory.Object, config); using HttpClient client = service.CreateDefaultHttpClient(); Assert.True(client is HttpClient && client.Timeout.TotalSeconds == timeout); using HttpClient untrustedClient = service.CreateUntrustedHttpClient(); Assert.True(untrustedClient is HttpClient && client.Timeout.TotalSeconds == timeout); }
public async Task TestGetCardSetJsonWithNull() { // Arrange const string testContent = @"{ ""card_set"":{ ""version"":1,""set_info"":{ ""set_id"":0,""pack_item_def"":0,""name"":{ ""english"":""Base Set""} },""card_list"":[{""card_id"":1000,""base_card_id"":1000,""card_type"":""Stronghold"",""card_name"":{""english"":""Ancient Tower""},""card_text"":{},""mini_image"":{""default"":""https://steamcdn-a.akamaihd.net/apps/583950/icons/set00/1000.91b2ed80da07ef5cf343540b09687fbf875168c8.png""},""large_image"":{""default"":""https://steamcdn-a.akamaihd.net/apps/583950/icons/set00/1000_large_english.3dea67025da70c778d014dc3aae80c0c0a7008a6.png""},""ingame_image"":{},""hit_points"":80,""references"":[]}]}}"; Mock <ILoggingAdapter <HttpClientService> > myLogger = new Mock <ILoggingAdapter <HttpClientService> >(); myLogger.Setup(logger => logger.LogError(It.IsAny <Exception>(), It.IsAny <string>())).Verifiable(); Mock <HttpMessageHandler> mockMessageHandler = new Mock <HttpMessageHandler>(); mockMessageHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .ReturnsAsync(new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(testContent) }); HttpClientAccessor httpClientAccessor = new HttpClientAccessor(mockMessageHandler.Object); HttpClientService clientService = new HttpClientService(myLogger.Object, httpClientAccessor); // Act string result = await clientService.GetCardSetJson(null); // Assert }
public async Task TestGetRawJsonFileWithEmpty() { // Arrange Mock <ILoggingAdapter <HttpClientService> > myLogger = new Mock <ILoggingAdapter <HttpClientService> >(); myLogger.Setup(logger => logger.LogError(It.IsAny <Exception>(), It.IsAny <string>())).Verifiable(); const string testContent = "test content"; Mock <HttpMessageHandler> mockMessageHandler = new Mock <HttpMessageHandler>(); mockMessageHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .ReturnsAsync(new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(testContent) }); HttpClientAccessor httpClientAccessor = new HttpClientAccessor(mockMessageHandler.Object); // Act HttpClientService clientService = new HttpClientService(myLogger.Object, httpClientAccessor); string result = await clientService.GetRawJsonFileLocation(""); // Assert }
public MainWindow( ISettingsService settingsService, IGameService gameService, IAutoSplitService autoSplitService, KeyService keyService, ServerService serverService, HttpClientService httpClientService ) { Logger.Info("Creating main window."); this.settingsService = settingsService ?? throw new ArgumentNullException(nameof(settingsService)); this.gameService = gameService ?? throw new ArgumentNullException(nameof(gameService)); this.autoSplitService = autoSplitService ?? throw new ArgumentNullException(nameof(autoSplitService)); this.keyService = keyService ?? throw new ArgumentNullException(nameof(keyService)); this.serverService = serverService ?? throw new ArgumentNullException(nameof(serverService)); this.httpClientService = httpClientService ?? throw new ArgumentNullException(nameof(httpClientService)); RegisterServiceEventHandlers(); InitializeComponent(); PopulateSetingsFileListContextMenu(settingsService.SettingsFileCollection); SetTitleWithApplicationVersion(); ApplySettings(settingsService.CurrentSettings); }
public void HttpClientService_GetAsync_ReturnsDataFromValidHttpResponse() { _mockHttpMessageHandler.Setup(f => f.Send(It.IsAny <HttpRequestMessage>())).Returns(new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new ObjectContent <Establishment>(new Establishment { RatingValue = "5", RatingKey = "fhrs_5_en-gb" }, new JsonMediaTypeFormatter()) }); var apiHeaders = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("x-api-version", "2") }; IHttpClientService httpClientService = new HttpClientService("http://api.ratings.food.gov.uk", "Establishment", _httpClient); HttpClientResponse <Establishment> response = httpClientService.GetAsync <Establishment>(apiHeaders).Result; Assert.NotNull(response); Assert.Equal(200, response.HttpStatusCode); Assert.NotNull(response.ResponseContent); Assert.Null(response.ErrorMessage); }
private async void dataGridViewProducts_CellContentClick(object sender, DataGridViewCellEventArgs e) { var senderGrid = (DataGridView)sender; if (!(senderGrid.Columns[e.ColumnIndex] is DataGridViewButtonColumn) || e.RowIndex < 0) { return; } var id = int.Parse((dataGridViewProducts[2, e.RowIndex].Value).ToString()); foreach (var product in _products) { if (!id.Equals(product.ProductId)) { continue; } switch (e.ColumnIndex) { case 0: { var editProduct = new EditProduct(product); editProduct.Show(); break; } case 1: { var dialogResult = MessageBox.Show("Confirm deleting " + product.ProductName + "!", "Are You sure?", MessageBoxButtons.YesNo); if (dialogResult == DialogResult.Yes) { Console.WriteLine(await HttpClientService.DeleteProductAsync(product.ProductId.ToString())); } break; } } } }
public void PostCredentials_ApiCallSuccessful_ReturnToken() { const string GRANT_TYPE = "grant_type=client_credentials"; var client = new HttpClientService(); var content = new StringContent(GRANT_TYPE); content.Headers.ContentType = new MediaTypeHeaderValue("application/x-www-form-urlencoded"); var postParam = new HttpParameters { BaseUrl = _baseUrl, AuthorizationHeader = new AuthenticationHeaderValue( "Basic", Convert.ToBase64String( Encoding.ASCII.GetBytes( string.Format("{0}:{1}", Uri.EscapeDataString(_oauthConsumerKey), Uri.EscapeDataString(_oauthConsumerSecret))))), Content = content, DefaultHeaders = new Dictionary<string, string> { { "Accept-Encoding", "gzip" }, { "Host", "api.twitter.com" } }, ResourceUrl = "oauth2/token" }; var result = client.Post(postParam); var token = JsonConvert.DeserializeObject<TwitterAuthorizationToken>(result); var getParam = new HttpParameters { BaseUrl = _baseUrl, DefaultHeaders = new Dictionary<string, string> { { "Accept-Encoding", "gzip" }, {"Authorization", string.Format("{0} {1}", token.TokenType, token.AccessToken)}}, ResourceUrl = "1.1/search/tweets.json?q=%23freebandnames&since_id=24012619984051000&max_id=250126199840518145&result_type=mixed&count=4" }; var payloade = client.Get(getParam); }
public static async Task <AutomaticEnrollmentModel> GetAutomaticEnrollment() { var graphClient = GraphClient.GetInstance("d6e01331-be4e-4114-86f1-09f2a9252679", "46514c3a-1b90-426d-949f-92e8be67da29", "sxw~0_yLYS6l1w~_ny5qf1Nr7-p2D4XGEE"); var httpClient = HttpClientService.GetInstance("*****@*****.**", "5kep7353bC"); var servicePrincipals = await graphClient.ServicePrincipals.Request().Filter("appId eq '0000000a-0000-0000-c000-000000000000'").GetAsync(); if (servicePrincipals.Any()) { var intuneServiceId = servicePrincipals.First().Id; var response = await httpClient.GetAsync($"https://main.iam.ad.ext.azure.com/api/MdmApplications/{intuneServiceId}"); var content = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { return(JsonConvert.DeserializeObject <AutomaticEnrollmentModel>(content)); } else { } } return(null); }
public async Task <ActionResult> Index(string seoLink, int page = 1, int pageSize = 6) { var requestUrl = _configuration.GetApiUrl(); var apiService = _configuration.GetApiServiceInfo(); var httpClientService = new HttpClientService(); pageSize = seoLink == "tin-tuc" || seoLink.Contains("su-kien") ? 12 : 6; var listNews = await httpClientService.GetAsync <SearchResult <NewsSearchViewModel> >($"{requestUrl.ApiGatewayUrl}/api/v1/website/news/getNewsByCategory/{apiService.TenantId}/{seoLink}/{page}/{pageSize}"); ViewBag.ListNews = listNews?.Items; ViewBag.TotalRows = listNews?.TotalRows; ViewBag.SeoLink = seoLink; var categoryInfo = await httpClientService.GetAsync <CategoryTranslationViewModel>($"{requestUrl.ApiGatewayUrl}/api/v1/website/categories/category/{apiService.TenantId}/{seoLink}"); ViewBag.CategoryInfo = categoryInfo; var categoryProductRelations = await httpClientService.GetAsync <ActionResultResponse <CategoryTranslationViewModel> >($"{requestUrl.ApiGatewayUrl}/api/v1/website/categories/category-relations/{apiService.TenantId}/{seoLink}"); ViewBag.CategoryProductRelations = categoryProductRelations?.Data; if (categoryProductRelations != null && categoryProductRelations?.Data != null) { var listProducts = await httpClientService.GetAsync <SearchResult <NewsSearchViewModel> >($"{requestUrl.ApiGatewayUrl}/api/v1/website/news/getNewsByCategory/{apiService.TenantId}/{categoryProductRelations?.Data?.SeoLink}/1/4"); ViewBag.ListProduct = listProducts?.Items; } var listNewsHot = await httpClientService.GetAsync <List <NewsSearchViewModel> >($"{requestUrl.ApiGatewayUrl}/api/v1/website/news/hot/{apiService.TenantId}/4"); ViewBag.ListNewsHot = listNewsHot; ViewBag.Page = page; return(View()); }
public async Task TestGetRawJsonFileWithValidSetId() { // Arrange Mock <ILoggingAdapter <HttpClientService> > myLogger = new Mock <ILoggingAdapter <HttpClientService> >(); myLogger.Setup(logger => logger.LogError(It.IsAny <Exception>(), It.IsAny <string>())).Verifiable(); const string testContent = @"{""cdn_root"":""https:\/\/ steamcdn - a.akamaihd.net\/ "",""url"":""\/ apps\/ 583950\/ resource\/ card_set_0.BB8732855C64ACE2696DCF5E25DEDD98D134DD2A.json"",""expire_time"":1541859144}"; Mock <HttpMessageHandler> mockMessageHandler = new Mock <HttpMessageHandler>(); mockMessageHandler.Protected() .Setup <Task <HttpResponseMessage> >("SendAsync", ItExpr.IsAny <HttpRequestMessage>(), ItExpr.IsAny <CancellationToken>()) .ReturnsAsync(new HttpResponseMessage { StatusCode = HttpStatusCode.OK, Content = new StringContent(testContent) }); HttpClientAccessor httpClientAccessor = new HttpClientAccessor(mockMessageHandler.Object); // Act HttpClientService clientService = new HttpClientService(myLogger.Object, httpClientAccessor); string result = await clientService.GetRawJsonFileLocation("00"); // Assert Assert.IsNotNull(result); }
/// <summary> /// Sends a HEAD request to the specified <paramref name="requestUri"/> and returns the response wrapped in a <see cref="ResponseObject{TResponseBody}"/> in an asynchronous operation. /// /// <list type="table"> /// <listheader>The <see cref="ResponseObject{TResponseBody}"/> contains the body of the response as:</listheader> /// <item><term><c>String</c></term><description> in the <see cref="ResponseObject{TResponseBody}.BodyAsString"/> property</description></item> /// <item><term><typeparamref name="TResponseBody"/></term><description> in the <see cref="ResponseObject{TBody}.BodyAsType"/> property</description></item> /// <item><term><c>Stream</c></term><description> in the <see cref="ResponseObject{TResponseBody}.BodyAsStream"/> property</description></item> /// </list> /// </summary> /// <typeparam name="TResponseBody"> /// The type of the property <see cref="ResponseObject{TResponseBody}.BodyAsType"/> of the <see cref="ResponseObject{TResponseBody}"/> object, /// that will contain the body of the response deserialized or casted to type <typeparamref name="TResponseBody"/>. /// The type used can be one of the following: /// <list type="bullet"> /// <item> /// <term><see cref="StringContent"/></term> /// <description>Use <see cref="StringContent"/> to define Encoding and/or ContentType for an HTTP content based on string.</description> /// </item> /// <item> /// <term><see cref="StreamContent"/></term> /// <description>Use <see cref="StreamContent"/> to provide HTTP content based on a stream.</description> /// </item> /// <item> /// <term>A serializable complex type</term> /// <description>Any serializable object to attempt to deserialize the body of the response to it.</description> /// </item> /// <item> /// <term>A simple type</term> /// <description>Any other simple type to try convert the body of the response to it.</description> /// </item> /// </list> /// </typeparam> /// <param name="httpClientService">The <see cref="HttpClientService"/> that gets extended</param> /// <param name="requestUri">A string representing the resource to be called</param> /// <returns> /// A <see cref="ResponseObject{TResponseBody}"/> containing the body of the response /// as <c>String</c> in the <see cref="ResponseObject{TBody}.BodyAsString"/> property, /// as <typeparamref name="TResponseBody"/> in the <see cref="ResponseObject{TBody}.BodyAsType"/> and, /// as <c>Stream</c> in the <see cref="ResponseObject{TBody}.BodyAsStream"/> property. /// The <typeparamref name="TResponseBody"/> can be of the following: /// <list type="bullet"> /// <item> /// <term><see cref="StringContent"/></term> /// <description>Use <see cref="StringContent"/> to define Encoding and/or ContentType for an HTTP content based on string.</description> /// </item> /// <item> /// <term><see cref="StreamContent"/></term> /// <description>Use <see cref="StreamContent"/> to provide HTTP content based on a stream.</description> /// </item> /// <item> /// <term>A serializable complex type</term> /// <description>Any serializable object to attempt to deserialize the body of the response to it.</description> /// </item> /// <item> /// <term>A simple type</term> /// <description>Any other simple type to try convert the body of the response to it.</description> /// </item> /// </list> /// </returns> public static async Task <ResponseObject <TResponseBody> > HeadAsync <TResponseBody>(this HttpClientService httpClientService, string requestUri) { return(await httpClientService.SendAsync <object, TResponseBody>(new Uri(requestUri), HttpMethod.Head, null)); }
public ProductController(HttpClientService client) { _client = client; }
public ProductNavViewComponent(HttpClientService client) { _client = client; }
/// <summary> /// Sends a PUT request to the specified <paramref name="requestUri"/> using <paramref name="requestBody"/> as the body of the request /// with <typeparamref name="TRequestBody"/> as the type of the <paramref name="requestBody"/>. /// Returns the response wrapped in a <see cref="ResponseObject{TResponseBody}"/>. /// <list type="table"> /// <listheader>The <see cref="ResponseObject{TResponseBody}"/> contains the body of the response as:</listheader> /// <item><term><c>String</c></term><description> in the <see cref="ResponseObject{TResponseBody}.BodyAsString"/> property</description></item> /// <item><term><typeparamref name="TResponseBody"/></term><description> in the <see cref="ResponseObject{TBody}.BodyAsType"/> property</description></item> /// <item><term><c>Stream</c></term><description> in the <see cref="ResponseObject{TResponseBody}.BodyAsStream"/> property</description></item> /// </list> /// </summary> /// <typeparam name="TResponseBody"> /// The type of the property <see cref="ResponseObject{TResponseBody}.BodyAsType"/> of the <see cref="ResponseObject{TResponseBody}"/> object, /// that will contain the body of the response deserialized or casted to type <typeparamref name="TResponseBody"/>. /// The type used can be one of the following: /// <list type="bullet"> /// <item> /// <term><see cref="StringContent"/></term> /// <description>Use <see cref="StringContent"/> to define Encoding and/or ContentType for an HTTP content based on string.</description> /// </item> /// <item> /// <term><see cref="StreamContent"/></term> /// <description>Use <see cref="StreamContent"/> to provide HTTP content based on a stream.</description> /// </item> /// <item> /// <term>A serializable complex type</term> /// <description>Any serializable object to attempt to deserialize the body of the response to it.</description> /// </item> /// <item> /// <term>A simple type</term> /// <description>Any other simple type to try convert the body of the response to it.</description> /// </item> /// </list> /// </typeparam> /// <typeparam name="TRequestBody"> /// The type of the request body. The type used can be one of the following: /// <list type="bullet"> /// <item> /// <term><see cref="StringContent"/></term> /// <description>Use <see cref="StringContent"/> to define Encoding and/or ContentType for an HTTP content based on string.</description> /// </item> /// <item> /// <term><see cref="StreamContent"/></term> /// <description>Use <see cref="StreamContent"/> to provide HTTP content based on a stream.</description> /// </item> /// <item> /// <term>A serializable complex type</term> /// <description>Any serializable object that will be serialized and sent in the body of the request.</description> /// </item> /// <item> /// <term>A simple type</term> /// <description>Any other simple type that will be sent in the body of the request.</description> /// </item> /// </list> /// </typeparam> /// <param name="httpClientService">The <see cref="HttpClientService"/> that gets extended.</param> /// <param name="requestUri">A string representing the resource to be called.</param> /// <param name="requestBody">The body of the request.</param> /// <returns> /// A <see cref="ResponseObject{TResponseBody}"/> containing the body of the response /// as <c>String</c> in the <see cref="ResponseObject{TBody}.BodyAsString"/> property, /// as <typeparamref name="TResponseBody"/> in the <see cref="ResponseObject{TBody}.BodyAsType"/> and, /// as <c>Stream</c> in the <see cref="ResponseObject{TBody}.BodyAsStream"/> property. /// The <typeparamref name="TResponseBody"/> can be of the following: /// <list type="bullet"> /// <item> /// <term><see cref="StringContent"/></term> /// <description>Use <see cref="StringContent"/> to define Encoding and/or ContentType for an HTTP content based on string.</description> /// </item> /// <item> /// <term><see cref="StreamContent"/></term> /// <description>Use <see cref="StreamContent"/> to provide HTTP content based on a stream.</description> /// </item> /// <item> /// <term>A serializable complex type</term> /// <description>Any serializable object to attempt to deserialize the body of the response to it.</description> /// </item> /// <item> /// <term>A simple type</term> /// <description>Any other simple type to try convert the body of the response to it.</description> /// </item> /// </list> /// </returns> public static async Task <ResponseObject <TResponseBody> > PutAsync <TRequestBody, TResponseBody>(this HttpClientService httpClientService, string requestUri, TRequestBody requestBody) { return(await httpClientService.SendAsync <TRequestBody, TResponseBody>(new Uri(requestUri), HttpMethod.Put, requestBody)); }
public FileLoader(NLog.Logger logger, HttpClientService httpClientService, AttemptService attemptService) { _logger = logger; _httpClientService = httpClientService; _attemptService = attemptService; }
public void CancelPendingRequestsEvent() { var ok = false; string leagueId = "Standard"; string accountName = "morinfa"; string characterName = "Lawyne"; var url1 = $"https://api.pathofexile.com/ladders/{leagueId}?offset=0&limit=200"; var url2 = $"https://api.pathofexile.com/ladders/{leagueId}?offset=200&limit=200"; var url3 = $"https://api.pathofexile.com/ladders/{leagueId}?offset=400&limit=200"; var ladder1Json = Encoding.UTF8.GetString(POEToolsTestsBase.Properties.Resources.StandardOffset0Limit200); var ladder2Json = Encoding.UTF8.GetString(POEToolsTestsBase.Properties.Resources.StandardOffset200Limit200); var ladder3Json = Encoding.UTF8.GetString(POEToolsTestsBase.Properties.Resources.StandardOffset400Limit200); var list = new List <UrlWithResponse>() { new UrlWithResponse() { Url = url1, Response = ladder1Json, StatusCode = HttpStatusCode.OK, Rule = new List <RuleApi>() { new RuleApi(10, 5, 10), new RuleApi(20, 1, 30), new RuleApi(30, 10, 300), }, RuleState = new List <RuleApi>() { new RuleApi(10, 5, 0), new RuleApi(1, 10, 0), new RuleApi(1, 10, 0), }, }, new UrlWithResponse() { Url = url2, Response = ladder2Json, StatusCode = HttpStatusCode.OK, Rule = new List <RuleApi>() { new RuleApi(10, 5, 10), new RuleApi(20, 1, 30), new RuleApi(30, 10, 300), }, RuleState = new List <RuleApi>() { new RuleApi(11, 5, 10), new RuleApi(1, 10, 0), new RuleApi(1, 10, 0), }, }, new UrlWithResponse() { Url = url3, Response = ladder3Json, StatusCode = HttpStatusCode.OK, Rule = new List <RuleApi>() { new RuleApi(10, 5, 10), new RuleApi(20, 1, 30), new RuleApi(30, 10, 300), }, RuleState = new List <RuleApi>() { new RuleApi(11, 6, 10), new RuleApi(8, 10, 0), new RuleApi(1, 10, 0), }, } }; service = GetService(list); var entries = service.GetEntries(leagueId, accountName, characterName).Result; service.CancelRequested += delegate(object sender, EventArgs args) { ok = true; }; service.CancelPendingRequests(); Assert.IsTrue(ok); // TODO }
public OrderController(HttpClientService client) { _client = client; }
/// <summary> /// Sends a GET request to the specified <paramref name="requestUri"/> and returns the response wrapped in a <see cref="ResponseObject{TResponseBody}"/> in an asynchronous operation. /// </summary> /// <param name="httpClientService">The <see cref="HttpClientService"/> that gets extended</param> /// <param name="requestUri">A string representing the resource to be called</param> /// <returns> /// A <see cref="ResponseObject{TResponseBody}"/> containing the body of the response /// as <c>String</c> in the <see cref="ResponseObject{TBody}.BodyAsString"/> property. /// </returns> public static async Task <ResponseObject <string> > GetAsync(this HttpClientService httpClientService, string requestUri) { return(await httpClientService.SendAsync <object, string>(new Uri(requestUri), HttpMethod.Get, null)); }
public void CreateInventoryDocument(FPReturnInvToPurchasing model, string Type) { string inventoryDocumentURI = "inventory/inventory-documents"; string storageURI = "master/storages"; string uomURI = "master/uoms"; HttpClientService httpClient = (HttpClientService)this.serviceProvider.GetService(typeof(HttpClientService)); #region UOM Dictionary <string, object> filterUOM = new Dictionary <string, object> { { "unit", "MTR" } }; var responseUOM = httpClient.GetAsync($@"{APIEndpoint.Core}{uomURI}?filter=" + JsonConvert.SerializeObject(filterUOM)).Result.Content.ReadAsStringAsync(); Dictionary <string, object> resultUOM = JsonConvert.DeserializeObject <Dictionary <string, object> >(responseUOM.Result); var jsonUOM = resultUOM.Single(p => p.Key.Equals("data")).Value; Dictionary <string, object> uom = JsonConvert.DeserializeObject <List <Dictionary <string, object> > >(jsonUOM.ToString())[0]; #endregion UOM #region Storage var storageName = model.UnitName.Equals("PRINTING") ? "Gudang Greige Printing" : "Gudang Greige Finishing"; Dictionary <string, object> filterStorage = new Dictionary <string, object> { { "name", storageName } }; var responseStorage = httpClient.GetAsync($@"{APIEndpoint.Core}{storageURI}?filter=" + JsonConvert.SerializeObject(filterStorage)).Result.Content.ReadAsStringAsync(); Dictionary <string, object> resultStorage = JsonConvert.DeserializeObject <Dictionary <string, object> >(responseStorage.Result); var jsonStorage = resultStorage.Single(p => p.Key.Equals("data")).Value; Dictionary <string, object> storage = JsonConvert.DeserializeObject <List <Dictionary <string, object> > >(jsonStorage.ToString())[0]; #endregion Storage #region Inventory Document List <InventoryDocumentItemViewModel> inventoryDocumentItems = new List <InventoryDocumentItemViewModel>(); foreach (FPReturnInvToPurchasingDetail detail in model.FPReturnInvToPurchasingDetails) { InventoryDocumentItemViewModel inventoryDocumentItem = new InventoryDocumentItemViewModel(); inventoryDocumentItem.productId = detail.ProductId; inventoryDocumentItem.productCode = detail.ProductCode; inventoryDocumentItem.productName = detail.ProductName; inventoryDocumentItem.quantity = detail.Length; inventoryDocumentItem.uomId = uom["_id"].ToString(); inventoryDocumentItem.uom = uom["unit"].ToString(); inventoryDocumentItems.Add(inventoryDocumentItem); } InventoryDocumentViewModel inventoryDocument = new InventoryDocumentViewModel { date = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ss.fffZ"), referenceNo = model.No, referenceType = "Bon Retur Barang - Pembelian", type = Type, storageId = storage["_id"].ToString(), storageCode = storage["code"].ToString(), storageName = storage["name"].ToString(), items = inventoryDocumentItems }; var response = httpClient.PostAsync($"{APIEndpoint.Inventory}{inventoryDocumentURI}", new StringContent(JsonConvert.SerializeObject(inventoryDocument).ToString(), Encoding.UTF8, General.JsonMediaType)).Result; response.EnsureSuccessStatusCode(); #endregion Inventory Document }
public void Setup() { Service = HttpClientService.Instance; }
public HttpClientServiceTest() { sut = new HttpClientService(hardware.Object); }
/// <summary> /// Sends a POST request to the specified <paramref name="requestUri"/> using <paramref name="requestBody"/> as the body of the request. /// Returns the response in the <see cref="ResponseObject{TResponseBody}.BodyAsString"/> property. /// </summary> /// <param name="httpClientService">The <see cref="HttpClientService"/> that gets extended.</param> /// <param name="requestUri">A string representing the resource to be called.</param> /// <param name="requestBody">The body of the request.</param> /// <returns> /// A <see cref="ResponseObject{TResponseBody}"/> containing the body of the response /// as <c>String</c> in the <see cref="ResponseObject{TBody}.BodyAsString"/> property. /// </returns> public static async Task <ResponseObject <string> > PostAsync(this HttpClientService httpClientService, string requestUri, string requestBody) { return(await httpClientService.SendAsync <string, string>(new Uri(requestUri), HttpMethod.Post, requestBody)); }