Thank you @Timon Yang-MSFT , this code is working. I wonder if you have any suggestions to make it more maintainable, testable, robust, and dynamic. By the way, this will be a scheduled task that runs every hour, that's why I stop the application after insertion.
class Program
{
static async Task Main(string[] args)
{
var builder = new HostBuilder()
.ConfigureServices((hostContext, services) =>
{
//Setting up API Client
services.AddHttpClient("OrdersClient", client =>
{
client.BaseAddress =
new Uri("https://test/282675/orders?status=Created");
client.DefaultRequestHeaders.Add("Accept", "application/json");
});
services.AddSingleton<IHostedService, BusinessService>();
//Setting up app settings configuration
var config = LoadConfiguration();
services.AddSingleton(config);
});
await builder.RunConsoleAsync();
}
public static IConfiguration LoadConfiguration()
{
var builder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true);
return builder.Build();
}
}
public class BusinessService : IHostedService
{
private IHttpClientFactory _httpClientFactory;
private readonly IHostApplicationLifetime _applicationLifetime;
private IConfiguration _configuration;
public BusinessService(IHttpClientFactory httpClientFactory, IHostApplicationLifetime applicationLifetime, IConfiguration configuration)
{
_httpClientFactory = httpClientFactory;
_applicationLifetime = applicationLifetime;
_configuration = configuration;
}
public async Task StartAsync(CancellationToken cancellationToken)
{
await MakeRequestsToRemoteService();
//Stop Application
_applicationLifetime.StopApplication();
}
public async Task MakeRequestsToRemoteService()
{
HttpClient httpClient = _httpClientFactory.CreateClient("OrdersClient");
var authenticationBytes = Encoding.ASCII.GetBytes("test:1234");
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic",
Convert.ToBase64String(authenticationBytes));
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await httpClient.GetAsync("https://test/282675/orders?startDate=1612126800000");
Console.WriteLine(DateTime.Now);
if (response.IsSuccessStatusCode)
{
Root orders = await response.Content.ReadAsAsync<Root>();
foreach (var content in orders.Content)
{
Console.Write(content.CustomerId + " " + content.CustomerFirstName + " " +
content.CustomerLastName + " " + content.CustomerEmail + " " + content.TotalPrice +
" " + content.InvoiceAddress.Phone + " " + content.Lines[0].ProductCode + " " +
content.Lines[0].ProductName);
InsertData(content);
}
}
}
public void InsertData(Content content)
{
Console.Write(_configuration["ConnectionStrings:Development"]);
string connString = _configuration["ConnectionStrings:Development"];
using (SqlConnection sqlConnection = new SqlConnection(connString))
{
sqlConnection.Open();
using (SqlCommand command = new SqlCommand())
{
command.Connection = sqlConnection;
string sql = @"insert into Orders (id, customerId, firstName, lastName, phone, productCode, productName, price, orderDate, status) values (@id, @customerId, @firstName, @lastName, @phone, @productCode, @productName, @price, @orderDate, @status)";
command.CommandText = sql;
try
{
command.Parameters.Add("id", SqlDbType.BigInt).Value = content.Id;
command.Parameters.Add("customerId", SqlDbType.Int).Value = content.CustomerId;
command.Parameters.Add("firstName", SqlDbType.VarChar).Value = content.CustomerFirstName;
command.Parameters.Add("lastName", SqlDbType.VarChar).Value = content.CustomerLastName;
command.Parameters.Add("phone", SqlDbType.VarChar).Value = content.InvoiceAddress.Phone;
command.Parameters.Add("productCode", SqlDbType.Int).Value = content.Lines[0].ProductCode;
command.Parameters.Add("productName", SqlDbType.VarChar).Value = content.Lines[0].ProductName;
command.Parameters.Add("price", SqlDbType.Float).Value = content.TotalPrice;
command.Parameters.Add("orderDate", SqlDbType.BigInt).Value = content.OrderDate;
command.Parameters.Add("status", SqlDbType.TinyInt).Value = 1; //Retrieved
command.ExecuteNonQuery();
}
catch (SqlException exception)
{
if (exception.Number == 2627) // Cannot insert duplicate key row in object error
{
Console.WriteLine("Duplicates...");
}
else
throw; // Throw exception if this exception is unexpected
}
}
}
}
public Task StopAsync(CancellationToken cancellationToken)
{
return Task.CompletedTask;
}
}