Raysefo

Raysefo

  • 1.4k
  • 284
  • 144.7k

.net core 2.1 console app with http client factory question

Feb 27 2021 3:17 PM
Hi guys,
I would like to implement a scheduled task which checks an API for every hour and insert data into a database if data is not in the database already. I read some articles and came out with this. I wonder if you can guide me to insert data into a SQL table if it is not already there. (By the way, most probably I will not use the Polly retry mechanism in my code.) I prefer to use raw SQL, it is much simpler for me.
 
Here is the Program.cs
 
  1. using System;  
  2. using System.IO;  
  3. using System.Net.Http;  
  4. using System.Threading.Tasks;  
  5. using Microsoft.Extensions.Configuration;  
  6. using Microsoft.Extensions.DependencyInjection;  
  7. using Microsoft.Extensions.Hosting;  
  8. using Polly;  
  9. using Polly.Extensions.Http;  
  10. using Polly.Registry;  
  11.   
  12. namespace TrendyolGamePurchase  
  13. {  
  14.     class Program  
  15.     {  
  16.         static async Task Main(string[] args)  
  17.         {  
  18.             //Read App Settings  
  19.             var build = new ConfigurationBuilder();  
  20.             BuildConfig(build);  
  21.   
  22.             var config = build.Build();  
  23.             
  24.             Console.Write(config["ConnectionStrings:Development"]);  
  25.             
  26.             //Polly Retry  
  27.             var builder = new HostBuilder()  
  28.                 .ConfigureServices((hostContext, services) =>  
  29.                 {  
  30.                     IPolicyRegistry<string> registry = services.AddPolicyRegistry();  
  31.   
  32.                     //First Policy  
  33.                     IAsyncPolicy<HttpResponseMessage> httpWaitAndRetryPolicy =  
  34.                         Policy.HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)  
  35.                             .WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(3, retryAttempt)));  
  36.   
  37.                     registry.Add("SimpleWaitAndRetryPolicy", httpWaitAndRetryPolicy);  
  38.   
  39.                     //Second Policy  
  40.                     IAsyncPolicy<HttpResponseMessage> noOpPolicy = Policy.NoOpAsync()  
  41.                         .AsAsyncPolicy<HttpResponseMessage>();  
  42.   
  43.                     registry.Add("NoOpPolicy", noOpPolicy);  
  44.   
  45.                     //Third Policy  
  46.                     var timeOutPolicy = Policy.TimeoutAsync(TimeSpan.FromSeconds(10));  
  47.                           
  48.                     registry.Add("timeOutPolicy", timeOutPolicy);  
  49.   
  50.                     services.AddHttpClient("TestClient", client =>  
  51.                     {  
  52.                         client.BaseAddress = new Uri("http://test//api/v2/web/game/purchase");  
  53.                         client.DefaultRequestHeaders.Add("Accept""application/json");  
  54.                     }).AddPolicyHandlerFromRegistry((policyRegistry, httpRequestMessage) =>  
  55.                     {  
  56.                         if (httpRequestMessage.Method == HttpMethod.Post)  
  57.                         {  
  58.                             Console.WriteLine(DateTime.Now);  
  59.                             return policyRegistry.Get<IAsyncPolicy<HttpResponseMessage>>("SimpleWaitAndRetryPolicy");  
  60.                         }  
  61.                         return policyRegistry.Get<IAsyncPolicy<HttpResponseMessage>>("NoOpPolicy");  
  62.                     });  
  63.   
  64.                     services.AddSingleton<IHostedService, BusinessService>();  
  65.                 });  
  66.   
  67.             await builder.RunConsoleAsync();  
  68.         }  
  69.         static void BuildConfig(IConfigurationBuilder builder)  
  70.         {  
  71.             builder.SetBasePath(Directory.GetCurrentDirectory())  
  72.                 .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);  
  73.   
  74.   
  75.         }  
  76.     }  

 And here is the BusinessService.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Net.Http;  
  4. using System.Net.Http.Headers;  
  5. using System.Text;  
  6. using System.Threading;  
  7. using System.Threading.Tasks;  
  8. using Microsoft.Extensions.Hosting;  
  9.   
  10. namespace TrendyolGamePurchase  
  11. {  
  12.     public class BusinessService : IHostedService  
  13.     {  
  14.         private IHttpClientFactory _httpClientFactory;  
  15.         public BusinessService(IHttpClientFactory httpClientFactory)  
  16.         {  
  17.             _httpClientFactory = httpClientFactory;  
  18.         }  
  19.   
  20.         public async Task StartAsync(CancellationToken cancellationToken)  
  21.         {  
  22.             await MakeTestRequestsToRemoteService();  
  23.         }  
  24.   
  25.         public async Task MakeTestRequestsToRemoteService()  
  26.         {  
  27.             HttpClient httpClient = _httpClientFactory.CreateClient("TestClient");  
  28.   
  29.             var authenticationBytes = Encoding.ASCII.GetBytes("Test:12345");  
  30.   
  31.             httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",  
  32.                 Convert.ToBase64String(authenticationBytes));  
  33.             httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));  
  34.   
  35.             var content = new FormUrlEncodedContent(new[]  
  36.             {  
  37.                 new KeyValuePair<stringstring>("productCode""1"),  
  38.                 new KeyValuePair<stringstring>("quantity","1"),  
  39.                 new KeyValuePair<stringstring>("shopNo","Palas"),  
  40.                 new KeyValuePair<stringstring>("safeNo","Palas"),  
  41.                 new KeyValuePair<stringstring>("cashierNo","Palas")  
  42.   
  43.             });  
  44.             var response = await httpClient.PostAsync("http://test//api/v2/web/game/purchase", content);  
  45.               
  46.   
  47.         }  
  48.   
  49.         public Task StopAsync(CancellationToken cancellationToken)  
  50.         {  
  51.             return Task.CompletedTask;  
  52.         }  
  53.     }  

 

Answers (1)