TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Raysefo
1.5k
284
150.1k
.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
using
System;
using
System.IO;
using
System.Net.Http;
using
System.Threading.Tasks;
using
Microsoft.Extensions.Configuration;
using
Microsoft.Extensions.DependencyInjection;
using
Microsoft.Extensions.Hosting;
using
Polly;
using
Polly.Extensions.Http;
using
Polly.Registry;
namespace
TrendyolGamePurchase
{
class
Program
{
static
async Task Main(
string
[] args)
{
//Read App Settings
var build =
new
ConfigurationBuilder();
BuildConfig(build);
var config = build.Build();
Console.Write(config[
"ConnectionStrings:Development"
]);
//Polly Retry
var builder =
new
HostBuilder()
.ConfigureServices((hostContext, services) =>
{
IPolicyRegistry<
string
> registry = services.AddPolicyRegistry();
//First Policy
IAsyncPolicy<HttpResponseMessage> httpWaitAndRetryPolicy =
Policy.HandleResult<HttpResponseMessage>(r => !r.IsSuccessStatusCode)
.WaitAndRetryAsync(3, retryAttempt => TimeSpan.FromSeconds(Math.Pow(3, retryAttempt)));
registry.Add(
"SimpleWaitAndRetryPolicy"
, httpWaitAndRetryPolicy);
//Second Policy
IAsyncPolicy<HttpResponseMessage> noOpPolicy = Policy.NoOpAsync()
.AsAsyncPolicy<HttpResponseMessage>();
registry.Add(
"NoOpPolicy"
, noOpPolicy);
//Third Policy
var timeOutPolicy = Policy.TimeoutAsync(TimeSpan.FromSeconds(10));
registry.Add(
"timeOutPolicy"
, timeOutPolicy);
services.AddHttpClient(
"TestClient"
, client =>
{
client.BaseAddress =
new
Uri(
"http://test//api/v2/web/game/purchase"
);
client.DefaultRequestHeaders.Add(
"Accept"
,
"application/json"
);
}).AddPolicyHandlerFromRegistry((policyRegistry, httpRequestMessage) =>
{
if
(httpRequestMessage.Method == HttpMethod.Post)
{
Console.WriteLine(DateTime.Now);
return
policyRegistry.Get<IAsyncPolicy<HttpResponseMessage>>(
"SimpleWaitAndRetryPolicy"
);
}
return
policyRegistry.Get<IAsyncPolicy<HttpResponseMessage>>(
"NoOpPolicy"
);
});
services.AddSingleton<IHostedService, BusinessService>();
});
await builder.RunConsoleAsync();
}
static
void
BuildConfig(IConfigurationBuilder builder)
{
builder.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile(
"appsettings.json"
, optional:
false
, reloadOnChange:
true
);
}
}
}
And here is the BusinessService.cs
using
System;
using
System.Collections.Generic;
using
System.Net.Http;
using
System.Net.Http.Headers;
using
System.Text;
using
System.Threading;
using
System.Threading.Tasks;
using
Microsoft.Extensions.Hosting;
namespace
TrendyolGamePurchase
{
public
class
BusinessService : IHostedService
{
private
IHttpClientFactory _httpClientFactory;
public
BusinessService(IHttpClientFactory httpClientFactory)
{
_httpClientFactory = httpClientFactory;
}
public
async Task StartAsync(CancellationToken cancellationToken)
{
await MakeTestRequestsToRemoteService();
}
public
async Task MakeTestRequestsToRemoteService()
{
HttpClient httpClient = _httpClientFactory.CreateClient(
"TestClient"
);
var authenticationBytes = Encoding.ASCII.GetBytes(
"Test:12345"
);
httpClient.DefaultRequestHeaders.Authorization =
new
AuthenticationHeaderValue(
"Basic"
,
Convert.ToBase64String(authenticationBytes));
httpClient.DefaultRequestHeaders.Accept.Add(
new
MediaTypeWithQualityHeaderValue(
"application/json"
));
var content =
new
FormUrlEncodedContent(
new
[]
{
new
KeyValuePair<
string
,
string
>(
"productCode"
,
"1"
),
new
KeyValuePair<
string
,
string
>(
"quantity"
,
"1"
),
new
KeyValuePair<
string
,
string
>(
"shopNo"
,
"Palas"
),
new
KeyValuePair<
string
,
string
>(
"safeNo"
,
"Palas"
),
new
KeyValuePair<
string
,
string
>(
"cashierNo"
,
"Palas"
)
});
var response = await httpClient.PostAsync(
"http://test//api/v2/web/game/purchase"
, content);
}
public
Task StopAsync(CancellationToken cancellationToken)
{
return
Task.CompletedTask;
}
}
}
Reply
Answers (
1
)
Hi, I am new to .Net, what should I learn first Asp.net or MVC
Running a c# command from within the active program