Notes
Notes - notes.io |
{
HttpClient Client;
private int executionCount = 0;
private readonly ILogger _logger;
private readonly IAccessToken accessToken;
private readonly IEmployee employee;
private readonly IJobDivaAPIService jobDivaAPIService;
private readonly IEmployeeTimesheetAPI employeeTimesheetAPI;
private readonly IDeduction deduction;
private readonly IReimbursements reimbursements;
private readonly ApplicationDbContext _db;
HttpClientHandler clientHandler;
public ScopedProcessingService(ILogger<ScopedProcessingService> logger,
IEmployee employee,
IAccessToken accessToken,
IJobDivaAPIService jobDivaAPIService,
ApplicationDbContext db,
IEmployeeTimesheetAPI employeeTimesheetAPI,
IDeduction deduction,
IReimbursements reimbursements)
{
_logger = logger;
this.employee = employee;
this.accessToken = accessToken;
this.jobDivaAPIService = jobDivaAPIService;
this.employeeTimesheetAPI = employeeTimesheetAPI;
clientHandler = new HttpClientHandler();
Client = new HttpClient(clientHandler);
Client.DefaultRequestHeaders.Accept.Clear();
Client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue(AppConstants.ApplicationJson));
_db = db;
this.deduction = deduction;
this.reimbursements = reimbursements;
}
public async Task DoWork(CancellationToken stoppingToken)
{
try
{
while (!stoppingToken.IsCancellationRequested)
{
executionCount++;
_logger.LogInformation(AppConstants.ScopedProcessingServiceIsWorking, executionCount);
Console.WriteLine(AppConstants.ExecutionStarted);
////Auto Deductions
//var deductionsList = await deduction.GetDeductionsList();
//if (deductionsList.DeductionModelList?.Any() == true)
//{
// var srNo = 1;
// foreach (var deductions in deductionsList.DeductionModelList)
// {
// var deductionId = deductions.DeductionsId;
// //var employeeId = deductions.EmployeeId;
// Console.WriteLine(srNo + AppConstants.ExecutionProcessForUpdateDeductions + deductionId);
// await deduction.UpdateDeductionById(Convert.ToInt32(deductionId));
// //DateTime deductionUpdateDate = Convert.ToDateTime(deductions.DeductionUpdateDate);
// //var month = deductionUpdateDate.AddMonths(1);
// //if (Convert.ToDateTime(month) == DateTime.Today)
// //{
// // Console.WriteLine(srNo + AppConstants.ExecutionProcessForUpdateDeductions + deductionId);
// // await deduction.UpdateDeductionById(Convert.ToInt32(deductionId));
// //}
// srNo = srNo + 1;
// }
//}
////Auto Reimbursements
//var reimbursementsList = await reimbursements.GetReimbursementsList();
//if (reimbursementsList.ReimbursementModelList?.Any() == true)
//{
// var srNo = 1;
// foreach (var reimbursement in reimbursementsList.ReimbursementModelList)
// {
// var reimbursementId = reimbursement.ReimbursementId;
// Console.WriteLine(srNo + AppConstants.ExecutionProcessForUpdateReimbursements + reimbursementId);
// await reimbursements.UpdateReimbursementById(Convert.ToInt32(reimbursementId));
// //DateTime reimbursementUpdateDate = Convert.ToDateTime(reimbursement.ReimbursementUpdateDate);
// //var month = reimbursementUpdateDate.AddMonths(1);
// //if (Convert.ToDateTime(month) == DateTime.Today)
// //{
// // Console.WriteLine(srNo + AppConstants.ExecutionProcessForUpdateReimbursements + reimbursementId);
// // await reimbursements.UpdateReimbursementById(Convert.ToInt32(reimbursementId));
// //}
// srNo = srNo + 1;
// }
//}
var employeeList = await employee.GetEmployeeIdList();
if (employeeList.EmployeeTableModelList != null && employeeList.EmployeeTableModelList?.Any() == true)
{
//Update Employee Assignment Records Detail
var SerialNo = 1;
var getToken = await accessToken.GetAccessTokenAsync();
foreach (var employee in employeeList.EmployeeTableModelList.DistinctBy(x => x.id))
{
var employeeId = employee.id;
EmployeeAssignmentResponseModel obj = new EmployeeAssignmentResponseModel();
var apiUrl = AppURL.JobDivaEmployeeAssignmentRecordsDetailURL + employeeId;
var content = new StringContent(JsonConvert.SerializeObject(obj), Encoding.UTF8, AppConstants.ApplicationJson);
Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(getToken);
using (var response = await Client.GetAsync(apiUrl))
{
response.EnsureSuccessStatusCode();
if (response.IsSuccessStatusCode)
{
var responseBody = await response.Content.ReadAsStringAsync();
obj = JsonConvert.DeserializeObject<EmployeeAssignmentResponseModel>(responseBody);
Console.WriteLine(SerialNo + AppConstants.ExecutionProcessForEmployeeAssignment + employeeId);
await jobDivaAPIService.StoreEmpDataToDB(obj);
}
SerialNo = SerialNo + 1;
}
}
////Update Employee Timesheets
//var srNo = 1;
////var getAccessToken = await accessToken.GetAccessTokenAsync();
//foreach (var employee in employeeList.EmployeeTableModelList.DistinctBy(x => x.id))
//{
// var employeeId = employee.id;
// var getAccessToken = await accessToken.GetAccessTokenAsync();
// EmployeeTimesheetResponseModel employeeTimesheetResponseModel = new EmployeeTimesheetResponseModel();
// var timesheetAPIUrl = AppURL.EmployeeTimesheetURL + employeeId;
// var timesheetContent = new StringContent(JsonConvert.SerializeObject(employeeTimesheetResponseModel), Encoding.UTF8, AppConstants.ApplicationJson);
// Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(getAccessToken);
// using (var response = await Client.GetAsync(timesheetAPIUrl))
// {
// response.EnsureSuccessStatusCode();
// if (response.IsSuccessStatusCode)
// {
// var timesheetResponseBody = await response.Content.ReadAsStringAsync();
// employeeTimesheetResponseModel = JsonConvert.DeserializeObject<EmployeeTimesheetResponseModel>(timesheetResponseBody);
// Console.WriteLine(srNo + AppConstants.ExecutionProcessForEmployeeTimesheet + employeeId);
// await employeeTimesheetAPI.StoreEmployeeTimesheetDataToDB(employeeTimesheetResponseModel);
// }
// srNo = srNo + 1;
// }
//}
}
Console.WriteLine(AppConstants.ExecutionCompleted);
await Task.Delay(getJobRunDelay(), stoppingToken);
//await Task.Delay(TimeSpan.FromMinutes(6), stoppingToken);
}
}
catch (Exception ex)
{
throw;
}
}
private static TimeSpan getScheduledParsedTime()
{
string[] formats = { @"hh:mm:ss", "hh\:mm" };
string jobStartTime = "22:17";
TimeSpan.TryParseExact(jobStartTime, formats, CultureInfo.InvariantCulture, out TimeSpan ScheduledTimespan);
return ScheduledTimespan;
}
private static TimeSpan getJobRunDelay()
{
TimeSpan scheduledParsedTime = getScheduledParsedTime();
TimeSpan curentTimeOftheDay = TimeSpan.Parse(DateTime.Now.TimeOfDay.ToString("hh\:mm"));
TimeSpan delayTime = scheduledParsedTime >= curentTimeOftheDay
? scheduledParsedTime - curentTimeOftheDay // Initial Run, when ETA is within 24 hours
: new TimeSpan(24, 0, 0) - curentTimeOftheDay + scheduledParsedTime; // For every other subsequent runs
return delayTime;
}
}
public class ConsumeScopedServiceHostedService : BackgroundService
{
private readonly ILogger<ConsumeScopedServiceHostedService> _logger;
public ConsumeScopedServiceHostedService(IServiceProvider services,
ILogger<ConsumeScopedServiceHostedService> logger)
{
Services = services;
_logger = logger;
}
public IServiceProvider Services { get; }
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
try
{
_logger.LogInformation(AppConstants.ConsumeScopedServiceHostedServiceRunning);
await DoWork(stoppingToken);
}
catch (Exception ex)
{
Log.Error(ex.Message);
throw;
}
}
private async Task DoWork(CancellationToken stoppingToken)
{
try
{
_logger.LogInformation(AppConstants.ConsumeScopedServiceHostedServiceWorking);
using (var scope = Services.CreateScope())
{
var scopedProcessingService =
scope.ServiceProvider
.GetRequiredService<IScopedProcessingService>();
await scopedProcessingService.DoWork(stoppingToken);
}
}
catch (Exception ex)
{
Log.Error(ex.Message);
throw;
}
}
public override async Task StopAsync(CancellationToken stoppingToken)
{
try
{
_logger.LogInformation(AppConstants.ConsumeScopedServiceHostedServiceStopping);
await base.StopAsync(stoppingToken);
}
catch (Exception ex)
{
Log.Error(ex.Message);
throw;
}
}
}
private static void Main(string[] args)
{
var host = new HostBuilder()
.ConfigureHostConfiguration(configHost =>
{
})
.ConfigureServices((hostContext, services) =>
{
services.AddDbContext<ApplicationDbContext>(options =>
//options.UseMySQL("server=10.0.5.13;port=1009;database=Smxservice_QA; Username=smxservice;password=Smxservice@123"));
//options.UseMySQL("server=192.168.40.13;port=3306; database=Smxservices_UAT; Username=smxservices;password=Smxservices@123;SslMode=none;"));
options.UseMySQL("server=localhost;port=3306;database=SMXServicesConsulting;user=root;password=Chetu@123"));
services.AddHostedService<ConsumeScopedServiceHostedService>();
services.AddScoped<IScopedProcessingService, ScopedProcessingService>();
services.AddScoped<IEmployee, Employee>();
services.AddScoped<IAccessToken, AccessToken>();
services.AddScoped<IJobDivaAPIService, JobDivaAPIService>();
services.AddScoped<IEmployeeTimesheetAPI, EmployeeTimesheetAPI>();
services.AddScoped<IDeduction, Deduction>();
services.AddScoped<IReimbursements, Reimbursements>();
services.AddAutoMapper(typeof(MappingProfile));
})
.UseConsoleLifetime()
.Build();
//run the host
host.Run();
}
![]() |
Notes is a web-based application for online taking notes. You can take your notes and share with others people. If you like taking long notes, notes.io is designed for you. To date, over 8,000,000,000+ notes created and continuing...
With notes.io;
- * You can take a note from anywhere and any device with internet connection.
- * You can share the notes in social platforms (YouTube, Facebook, Twitter, instagram etc.).
- * You can quickly share your contents without website, blog and e-mail.
- * You don't need to create any Account to share a note. As you wish you can use quick, easy and best shortened notes with sms, websites, e-mail, or messaging services (WhatsApp, iMessage, Telegram, Signal).
- * Notes.io has fabulous infrastructure design for a short link and allows you to share the note as an easy and understandable link.
Fast: Notes.io is built for speed and performance. You can take a notes quickly and browse your archive.
Easy: Notes.io doesn’t require installation. Just write and share note!
Short: Notes.io’s url just 8 character. You’ll get shorten link of your note when you want to share. (Ex: notes.io/q )
Free: Notes.io works for 14 years and has been free since the day it was started.
You immediately create your first note and start sharing with the ones you wish. If you want to contact us, you can use the following communication channels;
Email: [email protected]
Twitter: http://twitter.com/notesio
Instagram: http://instagram.com/notes.io
Facebook: http://facebook.com/notesio
Regards;
Notes.io Team
