From a1a9fd1dc51b069eda6cb08808046905472b65b9 Mon Sep 17 00:00:00 2001 From: Reginald Cherenfant Jasmin Date: Mon, 4 Sep 2023 21:31:41 -0400 Subject: [PATCH] Update SeedData to be executed when MS launched, Enable other properties in SurveyResponse --- .../Interfaces/IAnswersProvider.cs | 1 + .../DamageAssesment.Api.Answers/Program.cs | 2 + .../Providers/AnswerProvider.cs | 5 +- .../Providers/AttachmentsProvider.cs | 2 +- .../Interfaces/IEmployeesProvider.cs | 1 + .../DamageAssesment.Api.Employees/Program.cs | 7 + .../Providers/EmployeesProvider.cs | 4 +- .../LocationsServiceTest.cs | 5 - .../Controllers/RegionsController.cs | 2 +- .../Interfaces/ILocationsProvider.cs | 1 + .../Interfaces/IRegionsProvider.cs | 1 + .../DamageAssesment.Api.Locations/Program.cs | 9 + .../Providers/LocationsProvider.cs | 4 +- .../Providers/RegionsProvider.cs | 5 +- .../Interfaces/IQuestionsProvider.cs | 1 + .../DamageAssesment.Api.Questions/Program.cs | 7 + .../Providers/QuestionsProvider.cs | 2 +- .../Bases/ServiceProviderBase.cs | 12 +- .../Controllers/SurveyResponsesController.cs | 12 +- .../Db/SurveyResponse.cs | 13 +- .../Interfaces/IHttpUtil.cs | 9 + .../Models/SurveyResponse.cs | 20 +-- .../Program.cs | 36 +--- .../Providers/AnswerServiceProvider.cs | 45 ++--- .../Providers/AttachmentServiceProvider.cs | 32 +--- .../Providers/EmployeeServiceProvider.cs | 26 ++- .../Providers/LocationServiceProvider.cs | 14 +- .../Providers/QuestionServiceProvider.cs | 36 ++-- .../Providers/RegionServiceProvider.cs | 14 +- .../Providers/SurveyResponsesProvider.cs | 159 ++++++++---------- .../Providers/SurveyServiceProvider.cs | 25 ++- .../Utils/HttpUtil.cs | 43 +++++ .../Interfaces/ISurveyProvider.cs | 1 + .../DamageAssesment.Api.Surveys/Program.cs | 7 + .../Providers/SurveysProvider.cs | 4 +- 35 files changed, 279 insertions(+), 288 deletions(-) create mode 100644 DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/IHttpUtil.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Utils/HttpUtil.cs diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Interfaces/IAnswersProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Interfaces/IAnswersProvider.cs index fa76fcf..d6c2cac 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Interfaces/IAnswersProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Interfaces/IAnswersProvider.cs @@ -9,5 +9,6 @@ Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> PostAnswerAsync(Models.Answer Answer); Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> UpdateAnswerAsync(Models.Answer Answer); Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> DeleteAnswerAsync(int Id); + void SeedData(); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Program.cs index 373d300..7229cf9 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Program.cs @@ -25,8 +25,10 @@ builder.Services.AddDbContext(option => { option.UseInMemoryDatabase("Answers"); }); + var app = builder.Build(); + // Configure the HTTP request pipeline. if (app.Environment.IsDevelopment()) { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs index 37a80a7..0b535da 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs @@ -18,12 +18,11 @@ namespace DamageAssesment.Api.Answers.Providers this.answerDbContext = answerDbContext; this.logger = logger; this.mapper = mapper; - SeedData(); + //SeedData(); } public async Task<(bool IsSuccess, IEnumerable Answers, string ErrorMessage)> GetAnswersAsync() { - try { logger?.LogInformation("Query Question"); @@ -188,7 +187,7 @@ namespace DamageAssesment.Api.Answers.Providers return answerDbContext.Answers.AsNoTracking().Count(e => e.Id == id) > 0; } - private void SeedData() + public void SeedData() { if (!answerDbContext.Answers.Any()) { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/AttachmentsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/AttachmentsProvider.cs index c18cd05..518639e 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/AttachmentsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/AttachmentsProvider.cs @@ -21,7 +21,7 @@ namespace DamageAssesment.Api.Attachments.Providers this.logger = logger; this.mapper = mapper; this.uploadservice = uploadservice; - SeedData(); + // SeedData(); } public async Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> GetAttachmentsAsync() { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Interfaces/IEmployeesProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Interfaces/IEmployeesProvider.cs index 529141c..8083d2c 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Interfaces/IEmployeesProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Interfaces/IEmployeesProvider.cs @@ -7,5 +7,6 @@ Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> PostEmployeeAsync(Models.Employee Employee); Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> UpdateEmployeeAsync(string Id, Models.Employee Employee); Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> DeleteEmployeeAsync(string Id); + void SeedData(); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Program.cs index 7d5dbff..1e88127 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Program.cs @@ -34,6 +34,13 @@ if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); + + using (var serviceScope = app.Services.CreateScope()) + { + var services = serviceScope.ServiceProvider; + var employeesProvider = services.GetRequiredService(); + employeesProvider.SeedData(); + } } app.UseAuthorization(); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Providers/EmployeesProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Providers/EmployeesProvider.cs index 67ca1eb..533763f 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Providers/EmployeesProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Providers/EmployeesProvider.cs @@ -19,7 +19,7 @@ namespace DamageAssesment.Api.Employees.Providers this.EmployeeDbContext = EmployeeDbContext; this.logger = logger; this.mapper = mapper; - SeedData(); + // SeedData(); } public async Task<(bool IsSuccess, IEnumerable Employees, string ErrorMessage)> GetEmployeesAsync() @@ -145,7 +145,7 @@ namespace DamageAssesment.Api.Employees.Providers return EmployeeDbContext.Employees.AsNoTracking().Count(e => e.Id.ToLower() == id.ToLower()) > 0; } - private void SeedData() + public void SeedData() { if (!EmployeeDbContext.Employees.Any()) { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/LocationsServiceTest.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/LocationsServiceTest.cs index 8be1910..94e518d 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/LocationsServiceTest.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/LocationsServiceTest.cs @@ -1,11 +1,6 @@ -using AutoMapper; using DamageAssesment.Api.Locations.Controllers; -using DamageAssesment.Api.Locations.Db; using DamageAssesment.Api.Locations.Interfaces; -using DamageAssesment.Api.Locations.Profiles; -using DamageAssesment.Api.Locations.Providers; using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; using Moq; using Xunit; diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/RegionsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/RegionsController.cs index 81725e4..f69e7ce 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/RegionsController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/RegionsController.cs @@ -14,7 +14,7 @@ namespace DamageAssesment.Api.Locations.Controllers this.regionProvider = regionProvider; } /// - /// Get all regions. + /// Get all regions.2 /// [HttpGet] diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/ILocationsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/ILocationsProvider.cs index ff0ee55..55b847b 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/ILocationsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/ILocationsProvider.cs @@ -9,5 +9,6 @@ namespace DamageAssesment.Api.Locations.Interfaces Task<(bool IsSuccess, Models.Location Question, string ErrorMessage)> PostLocationAsync(Models.Location Location); Task<(bool IsSuccess, string ErrorMessage)> UpdateLocationAsync(Models.Location Location); Task<(bool IsSuccess, string ErrorMessage)> DeleteLocationAsync(string Id); + void SeedData(); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/IRegionsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/IRegionsProvider.cs index 1df0776..65f8d0b 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/IRegionsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/IRegionsProvider.cs @@ -7,5 +7,6 @@ Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> PostRegionAsync(Models.Region region); Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> PutRegionAsync(Models.Region region); Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> DeleteRegionAsync(string Id); + void SeedData(); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Program.cs index c152e61..200e39b 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Program.cs @@ -33,6 +33,15 @@ if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); + + using (var serviceScope = app.Services.CreateScope()) + { + var services = serviceScope.ServiceProvider; + var locationProvider = services.GetRequiredService(); + var regionProvider = services.GetRequiredService(); + locationProvider.SeedData(); + regionProvider.SeedData(); + } } app.UseAuthorization(); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/LocationsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/LocationsProvider.cs index cf0e978..85da34c 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/LocationsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/LocationsProvider.cs @@ -17,7 +17,7 @@ namespace DamageAssesment.Api.Locations.Providers this.locationDbContext = locationDbContext; this.logger = logger; this.mapper = mapper; - SeedData(); + //SeedData(); } public async Task<(bool IsSuccess, IEnumerable locations, string ErrorMessage)> GetLocationsAsync() @@ -127,7 +127,7 @@ namespace DamageAssesment.Api.Locations.Providers { return locationDbContext.Locations.AsNoTracking().Count(e => e.Id == id) > 0; } - private void SeedData() + public void SeedData() { if (!locationDbContext.Locations.Any()) { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/RegionsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/RegionsProvider.cs index 9d78ce7..0ea0b3f 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/RegionsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/RegionsProvider.cs @@ -1,7 +1,6 @@ using AutoMapper; using DamageAssesment.Api.Locations.Db; using DamageAssesment.Api.Locations.Interfaces; -using DamageAssesment.Api.Locations.Models; using Microsoft.EntityFrameworkCore; namespace DamageAssesment.Api.Locations.Providers @@ -17,7 +16,7 @@ namespace DamageAssesment.Api.Locations.Providers this.locationDbContext = regionDbContext; this.logger = logger; this.mapper = mapper; - SeedData(); + //SeedData(); } public async Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> GetRegionByIdAsync(string Id) @@ -150,7 +149,7 @@ namespace DamageAssesment.Api.Locations.Providers } } - private void SeedData() + public void SeedData() { if (!locationDbContext.Regions.Any()) { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Interfaces/IQuestionsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Interfaces/IQuestionsProvider.cs index 43aa2e3..58def79 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Interfaces/IQuestionsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Interfaces/IQuestionsProvider.cs @@ -17,5 +17,6 @@ namespace DamageAssesment.Api.Questions.Interfaces Task<(bool IsSuccess, Models.QuestionCategory QuestionCategory, string ErrorMessage)> PostQuestionCategoryAsync(Models.QuestionCategory QuestionCategory); Task<(bool IsSuccess, Models.QuestionCategory QuestionCategory, string ErrorMessage)> UpdateQuestionCategoryAsync(Models.QuestionCategory QuestionCategory); Task<(bool IsSuccess, Models.QuestionCategory QuestionCategory, string ErrorMessage)> DeleteQuestionCategoryAsync(int Id); + void SeedData(); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Program.cs index 321c989..b978465 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Program.cs @@ -37,6 +37,13 @@ if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); + + using (var serviceScope = app.Services.CreateScope()) + { + var services = serviceScope.ServiceProvider; + var questionProvider = services.GetRequiredService(); + questionProvider.SeedData(); + } } app.UseAuthorization(); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs index 719fb5f..7ec55fa 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs @@ -24,7 +24,7 @@ namespace DamageAssesment.Api.Questions.Providers SeedData(); } - private void SeedData() + public void SeedData() { if (!questionDbContext.QuestionsTranslations.Any()) diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Bases/ServiceProviderBase.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Bases/ServiceProviderBase.cs index 71a37b6..7db6371 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Bases/ServiceProviderBase.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Bases/ServiceProviderBase.cs @@ -1,18 +1,20 @@ -namespace DamageAssesment.Api.SurveyResponses.Bases +using DamageAssesment.Api.SurveyResponses.Interfaces; + +namespace DamageAssesment.Api.SurveyResponses.Bases { public class ServiceProviderBase { protected readonly IConfiguration configuration; - protected readonly HttpClient httpClient; - protected private readonly ILogger logger; + protected readonly IHttpUtil httpUtil; + protected readonly ILogger logger; protected string ressource; protected string urlBase; - public ServiceProviderBase(IConfiguration configuration, HttpClient httpClient, ILogger logger, string ressource, string urlBase) + public ServiceProviderBase(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger, string ressource, string urlBase) { this.configuration = configuration; - this.httpClient = httpClient; + this.httpUtil = httpUtil; this.logger = logger; this.ressource = ressource; this.urlBase = urlBase; diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Controllers/SurveyResponsesController.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Controllers/SurveyResponsesController.cs index c650d1d..5b141a8 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Controllers/SurveyResponsesController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Controllers/SurveyResponsesController.cs @@ -118,10 +118,10 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers /// /// The ID of the survey response to be retrieved. - [HttpGet("SurveyResponse/{responseId}")] - public async Task GetSurveyResponseByIdAsync(int responseId) + [HttpGet("SurveyResponse/{Id}")] + public async Task GetSurveyResponseByIdAsync(int Id) { - var result = await this.surveyResponseProvider.GetSurveyResponseByIdAsync(responseId); + var result = await this.surveyResponseProvider.GetSurveyResponseByIdAsync(Id); if (result.IsSuccess) { return Ok(result.SurveyResponse); @@ -185,12 +185,6 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers [HttpPost("SurveyResponses/Answers")] public async Task PostSurveyAnswersAsync(Request request) { - /* var result = await this.surveyResponseProvider.PostSurveyAnswersAsync(surveyAnswers); - if (result.IsSuccess) - { - return Ok(result.SurveyResponse); - } - return BadRequest(result.ErrorMessage);*/ var result = await this.surveyResponseProvider.PostSurveyAnswersAsync(request); if (result.IsSuccess) diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Db/SurveyResponse.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Db/SurveyResponse.cs index c1e5db1..ea9ed5e 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Db/SurveyResponse.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Db/SurveyResponse.cs @@ -19,12 +19,15 @@ namespace DamageAssesment.Api.SurveyResponses.Db [ForeignKey("Employee")] public string EmployeeId { get; set; } - //public DateTime? CreatedDate { get; set; } + public DateTime? CreatedDate { get; set; } = DateTime.Now; - //[StringLength(50)] - // public string ClientDevice { get; set; } + [StringLength(50)] + public string? ClientDevice { get; set; } + + [StringLength(250)] + public string? KeyAnswerResult { get; set; } + public double? Longitute { get; set; } + public double? Latitude { get; set; } - // [StringLength(250)] - //public string KeyAnswerResult { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/IHttpUtil.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/IHttpUtil.cs new file mode 100644 index 0000000..e3f1e66 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/IHttpUtil.cs @@ -0,0 +1,9 @@ +using DamageAssesment.Api.SurveyResponses.Models; + +namespace DamageAssesment.Api.SurveyResponses.Interfaces +{ + public interface IHttpUtil + { + Task SendAsync(HttpMethod method, string url, string JsonInput); + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/SurveyResponse.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/SurveyResponse.cs index 12ed615..ccaffdc 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/SurveyResponse.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/SurveyResponse.cs @@ -5,24 +5,14 @@ namespace DamageAssesment.Api.SurveyResponses.Models { public class SurveyResponse { - [Key] public int Id { get; set; } - - [ForeignKey("Survey")] public int SurveyId { get; set; } - - [ForeignKey("Location")] public string LocationId { get; set; } - - [ForeignKey("Employee")] public string EmployeeId { get; set; } - - //public DateTime? CreatedDate { get; set; } - - //[StringLength(50)] - //public string ClientDevice { get; set; } - - //[StringLength(250)] - //public string KeyAnswerResult { get; set; } + public DateTime? CreatedDate { get; set; } + public string? ClientDevice { get; set; } + public string? KeyAnswerResult { get; set; } + public double? Longitute { get; set; } + public double? Latitude { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Program.cs index cf41624..7b1fe15 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Program.cs @@ -1,10 +1,9 @@ using DamageAssesment.Api.SurveyResponses.Db; using DamageAssesment.Api.SurveyResponses.Interfaces; using DamageAssesment.Api.SurveyResponses.Providers; -using Microsoft.AspNetCore.DataProtection.XmlEncryption; +using DamageAssesment.Api.SurveyResponses.Utils; using Microsoft.EntityFrameworkCore; using Polly; -using System.Net.Http; using System.Reflection; var builder = WebApplication.CreateBuilder(args); @@ -20,35 +19,18 @@ builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddScoped(); -//builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddScoped(); -builder.Services.AddHttpClient(). - AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(maxApiCallRetries, _ => TimeSpan.FromSeconds(intervalToRetry))). - AddTransientHttpErrorPolicy(policy => policy.CircuitBreakerAsync(maxRetryForCircuitBraker, TimeSpan.FromSeconds(intervalForCircuitBraker) )); - -builder.Services.AddHttpClient(). +builder.Services.AddHttpClient(). AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(maxApiCallRetries, _ => TimeSpan.FromSeconds(intervalToRetry))). AddTransientHttpErrorPolicy(policy => policy.CircuitBreakerAsync(maxRetryForCircuitBraker, TimeSpan.FromSeconds(intervalForCircuitBraker))); -builder.Services.AddHttpClient(). - AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(maxApiCallRetries, _ => TimeSpan.FromSeconds(intervalToRetry))). - AddTransientHttpErrorPolicy(policy => policy.CircuitBreakerAsync(maxRetryForCircuitBraker, TimeSpan.FromSeconds(intervalForCircuitBraker))); - -builder.Services.AddHttpClient(). - AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(maxApiCallRetries, _ => TimeSpan.FromSeconds(intervalToRetry))). - AddTransientHttpErrorPolicy(policy => policy.CircuitBreakerAsync(maxRetryForCircuitBraker, TimeSpan.FromSeconds(intervalForCircuitBraker))); - -builder.Services.AddHttpClient(). - AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(maxApiCallRetries, _ => TimeSpan.FromSeconds(intervalToRetry))). - AddTransientHttpErrorPolicy(policy => policy.CircuitBreakerAsync(maxRetryForCircuitBraker, TimeSpan.FromSeconds(intervalForCircuitBraker))); - -builder.Services.AddHttpClient(). - AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(maxApiCallRetries, _ => TimeSpan.FromSeconds(intervalToRetry))). - AddTransientHttpErrorPolicy(policy => policy.CircuitBreakerAsync(maxRetryForCircuitBraker, TimeSpan.FromSeconds(intervalForCircuitBraker))); - -builder.Services.AddHttpClient(). - AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(maxApiCallRetries, _ => TimeSpan.FromSeconds(intervalToRetry))). - AddTransientHttpErrorPolicy(policy => policy.CircuitBreakerAsync(maxRetryForCircuitBraker, TimeSpan.FromSeconds(intervalForCircuitBraker))); builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); builder.Services.AddEndpointsApiExplorer(); diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AnswerServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AnswerServiceProvider.cs index cb638bc..19ed7eb 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AnswerServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AnswerServiceProvider.cs @@ -14,28 +14,25 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { public class AnswerServiceProvider : ServiceProviderBase, IAnswerServiceProvider { - - public AnswerServiceProvider(IConfiguration configuration, HttpClient httpClient, ILogger logger, IRegionServiceProvider regionServiceProvider, ILocationServiceProvider locationServiceProvider) : base(configuration, httpClient, logger, "/api/Answers", configuration.GetValue("EndPointSettings:AnswerUrlBase")) + public AnswerServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, "/api/Answers", configuration.GetValue("EndPointSettings:AnswerUrlBase")) { } public async Task> getAnswersAsync() { try { - httpClient.BaseAddress = new Uri(urlBase); - var response = await httpClient.GetAsync(ressource); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var answers = JsonConvert.DeserializeObject>(responseString); + var url = urlBase + ressource; + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var answers = JsonConvert.DeserializeObject>(responseJsonString); if (answers == null || !answers.Any()) - return null; + return new List(); else return answers; } catch (Exception ex) { logger?.LogError($"Exception Found : {ex.Message} - Ref: AnswerServiceProvider.getAnswersAsync()"); - return null; + return new List(); } } @@ -43,21 +40,18 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { try { - httpClient.BaseAddress = new Uri(urlBase); - - var response = await httpClient.GetAsync("/api/AnswersByResponse/" + responseId); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var answers = JsonConvert.DeserializeObject>(responseString); + var url = urlBase + "/api/AnswersByResponse/" + responseId; + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var answers = JsonConvert.DeserializeObject>(responseJsonString); if (answers == null || !answers.Any()) - return null; + return new List(); else return answers; } catch (Exception ex) { logger?.LogError($"Exception Found : {ex.Message} - Ref: AnswerServiceProvider.GetAnswersByResponseId()"); - return null; + return new List(); } } @@ -66,25 +60,16 @@ namespace DamageAssesment.Api.SurveyResponses.Providers try { var url = urlBase + ressource; - var request = new HttpRequestMessage(HttpMethod.Post, url); - request.Headers.Accept.Clear(); - request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - //request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); - - var jsonObject = JsonConvert.SerializeObject(answer); - request.Content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json"); - var response = await httpClient.SendAsync(request, CancellationToken.None); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var answers = JsonConvert.DeserializeObject(responseString); + var requestJsonString = JsonConvert.SerializeObject(answer); + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Post, url, requestJsonString); + var answers = JsonConvert.DeserializeObject(responseJsonString); if (answers == null) { - logger?.LogError($"Answer cannot be added - Ref: AnswerServiceProvider.PostAnswersAsync()"); + logger?.LogError($"Answers cannot be added - Ref: AnswerServiceProvider.PostAnswersAsync()"); return null; } else return answers; - } catch (Exception ex) { diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AttachmentServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AttachmentServiceProvider.cs index 04f8121..ae19cbb 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AttachmentServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AttachmentServiceProvider.cs @@ -1,18 +1,15 @@ using DamageAssesment.Api.SurveyResponses.Bases; using DamageAssesment.Api.SurveyResponses.Interfaces; using DamageAssesment.Api.SurveyResponses.Models; -using Microsoft.Extensions.Logging; using Newtonsoft.Json; -using System.Net.Http; using System.Net.Http.Headers; -using System.Runtime.Intrinsics.Arm; using System.Text; namespace DamageAssesment.Api.SurveyResponses.Providers { public class AttachmentServiceProvider : ServiceProviderBase, IAttachmentServiceProvider { - public AttachmentServiceProvider(IConfiguration configuration, HttpClient httpClient, ILogger logger) : base(configuration, httpClient, logger, "/api/Attachments", configuration.GetValue("EndPointSettings:AttachmentUrlBase")) + public AttachmentServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, "/api/Attachments", configuration.GetValue("EndPointSettings:AttachmentUrlBase")) { } @@ -20,20 +17,18 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { try { - httpClient.BaseAddress = new Uri(urlBase); - var response = await httpClient.GetAsync(ressource); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var attachments = JsonConvert.DeserializeObject>(responseString); + var url = urlBase + ressource; + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var attachments = JsonConvert.DeserializeObject>(responseJsonString); if (attachments == null || !attachments.Any()) - return null; + return new List(); else return attachments; } catch (Exception ex) { logger?.LogError($"Exception Found : {ex.Message} - Ref: AttachmentServiceProvider.getAttachmentsAsync()"); - return null; + return new List(); } } @@ -41,19 +36,10 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { try { - var url = urlBase + ressource; - var request = new HttpRequestMessage(HttpMethod.Post, url); - request.Headers.Accept.Clear(); - request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); - //request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); - - var jsonObject = JsonConvert.SerializeObject(attachmentInfo); - request.Content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json"); - var response = await httpClient.SendAsync(request, CancellationToken.None); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var attachments = JsonConvert.DeserializeObject>(responseString); + var requestJsonString = JsonConvert.SerializeObject(attachmentInfo); + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Post, url, requestJsonString); + var attachments = JsonConvert.DeserializeObject>(responseJsonString); if (attachments == null) { diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/EmployeeServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/EmployeeServiceProvider.cs index faf31ff..56d876e 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/EmployeeServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/EmployeeServiceProvider.cs @@ -1,6 +1,7 @@ using DamageAssesment.Api.SurveyResponses.Bases; using DamageAssesment.Api.SurveyResponses.Interfaces; using DamageAssesment.Api.SurveyResponses.Models; +using DamageAssesment.Api.SurveyResponses.Utils; using Newtonsoft.Json; using System.Reflection; @@ -8,7 +9,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { public class EmployeeServiceProvider :ServiceProviderBase, IEmployeeServiceProvider { - public EmployeeServiceProvider(IConfiguration configuration, HttpClient httpClient, ILogger logger) : base(configuration, httpClient, logger, "/api/Employees", configuration.GetValue("EndPointSettings:EmployeeUrlBase")) + public EmployeeServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, "/api/Employees", configuration.GetValue("EndPointSettings:EmployeeUrlBase")) { } @@ -16,33 +17,28 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { try { - httpClient.BaseAddress = new Uri(urlBase); - var response = await httpClient.GetAsync(ressource); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var employees = JsonConvert.DeserializeObject>(responseString); + var url = urlBase + ressource; + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var employees = JsonConvert.DeserializeObject>(responseJsonString); if (employees == null || !employees.Any()) - return null; + return new List(); else return employees; } catch (Exception ex) { logger?.LogError($"Exception Found : {ex.Message} - Ref: EmployeeServiceProvider.getEmployeesAsync()"); - return null; + return new List(); } } - public async Task getEmployeeAsync(string employeeID) + public async Task getEmployeeAsync(string employeeId) { try { - httpClient.BaseAddress = new Uri(urlBase); - //ressource = ressource + "/" + employeeID; - var response = await httpClient.GetAsync("/api/Employees/"+ employeeID); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var employee = JsonConvert.DeserializeObject(responseString); + var url = urlBase + "/api/Employees/" + employeeId; + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var employee = JsonConvert.DeserializeObject(responseJsonString); if (employee == null ) return null; diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/LocationServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/LocationServiceProvider.cs index d5c9161..d45e7b4 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/LocationServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/LocationServiceProvider.cs @@ -7,7 +7,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { public class LocationServiceProvider :ServiceProviderBase, ILocationServiceProvider { - public LocationServiceProvider(IConfiguration configuration, HttpClient httpClient, ILogger logger) : base(configuration, httpClient, logger, "/api/Locations", configuration.GetValue("EndPointSettings:LocationUrlBase")) + public LocationServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, "/api/Locations", configuration.GetValue("EndPointSettings:LocationUrlBase")) { } @@ -15,20 +15,18 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { try { - httpClient.BaseAddress = new Uri(urlBase); - var response = await httpClient.GetAsync(ressource); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var locations = JsonConvert.DeserializeObject>(responseString); + var url = urlBase + ressource; + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var locations = JsonConvert.DeserializeObject>(responseJsonString); if (locations == null || !locations.Any()) - return null; + return new List(); else return locations; } catch (Exception ex) { logger?.LogError($"Exception Found : {ex.Message} - Ref: LocationServiceProvider.getLocationsAsync()"); - return null; + return new List(); } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/QuestionServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/QuestionServiceProvider.cs index 2d9e915..2dd90cb 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/QuestionServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/QuestionServiceProvider.cs @@ -3,13 +3,11 @@ using DamageAssesment.Api.SurveyResponses.Interfaces; using DamageAssesment.Api.SurveyResponses.Models; using Newtonsoft.Json; - - namespace DamageAssesment.Api.SurveyResponses.Providers { public class QuestionServiceProvider : ServiceProviderBase, IQuestionServiceProvider { - public QuestionServiceProvider(IConfiguration configuration, HttpClient httpClient, ILogger logger) : base(configuration, httpClient, logger, "/api/Questions", configuration.GetValue("EndPointSettings:QuestionUrlBase")) + public QuestionServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, "/api/Questions", configuration.GetValue("EndPointSettings:QuestionUrlBase")) { } @@ -17,20 +15,18 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { try { - httpClient.BaseAddress = new Uri(urlBase); - var response = await httpClient.GetAsync(ressource); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var questions = JsonConvert.DeserializeObject>(responseString); + var url = urlBase + ressource; + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var questions = JsonConvert.DeserializeObject>(responseJsonString); if (questions == null || !questions.Any()) - return null; + return new List(); else return questions; } catch (Exception ex) { logger?.LogError($"Exception Found : {ex.Message} - Ref: QuestionServiceProvider.getQuestionsAsync()"); - return null; + return new List(); } } @@ -38,20 +34,18 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { try { - httpClient.BaseAddress = new Uri(urlBase); - var response = await httpClient.GetAsync("/api/GetSurveyQuestions/" + surveyId); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var questions = JsonConvert.DeserializeObject>(responseString); + var url = urlBase + "/api/GetSurveyQuestions/" + surveyId; + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var questions = JsonConvert.DeserializeObject>(responseJsonString); if (questions == null || !questions.Any()) - return null; + return new List() ; else return questions; } catch (Exception ex) { logger?.LogError($"Exception Found : {ex.Message} - Ref: QuestionServiceProvider.getSurveyQuestionsAsync()"); - return null; + return new List(); } } @@ -60,11 +54,9 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { try { - httpClient.BaseAddress = new Uri(urlBase); - var response = await httpClient.GetAsync("/api/Questions/" + questionId); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var question = JsonConvert.DeserializeObject(responseString); + var url = urlBase + "/api/Questions/" + questionId; + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var question = JsonConvert.DeserializeObject(responseJsonString); if (question == null) return null; diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/RegionServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/RegionServiceProvider.cs index a435081..5cbee97 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/RegionServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/RegionServiceProvider.cs @@ -7,27 +7,25 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { public class RegionServiceProvider : ServiceProviderBase, IRegionServiceProvider { - public RegionServiceProvider(IConfiguration configuration, HttpClient httpClient, ILogger logger) : base(configuration, httpClient, logger, "/api/Regions", configuration.GetValue("EndPointSettings:LocationUrlBase")) + public RegionServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, "/api/Regions", configuration.GetValue("EndPointSettings:LocationUrlBase")) { } public async Task> getRegionsAsync() { try { - httpClient.BaseAddress = new Uri(urlBase); - var response = await httpClient.GetAsync(ressource); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var regions = JsonConvert.DeserializeObject>(responseString); + var url = urlBase + ressource; + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var regions = JsonConvert.DeserializeObject>(responseJsonString); if (regions == null || !regions.Any()) - return null; + return new List(); else return regions; } catch (Exception ex) { logger?.LogError($"Exception Found : {ex.Message} - Ref: RegionServiceProvider.getRegionsAsync()"); - return null; + return new List(); } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyResponsesProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyResponsesProvider.cs index 98c138d..ec5bcc3 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyResponsesProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyResponsesProvider.cs @@ -3,11 +3,6 @@ using DamageAssesment.Api.SurveyResponses.Db; using DamageAssesment.Api.SurveyResponses.Interfaces; using DamageAssesment.Api.SurveyResponses.Models; using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Internal; -using Newtonsoft.Json; -using System.Diagnostics; -using System.Text; -using static Microsoft.EntityFrameworkCore.DbLoggerCategory; namespace DamageAssesment.Api.SurveyResponses.Providers { @@ -36,21 +31,19 @@ namespace DamageAssesment.Api.SurveyResponses.Providers this.questionServiceProvider = questionServiceProvider; this.surveyServiceProvider = surveyServiceProvider; this.mapper = mapper; - - seedData(); + //seedData(); } private void seedData() { if (!surveyResponseDbContext.SurveyResponses.Any()) { - surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { Id = 1, SurveyId = 1, EmployeeId = "Emp1", LocationId = "Loc1" }); - surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { Id = 2, SurveyId = 1, EmployeeId = "Emp2", LocationId = "Loc2" }); - surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { Id = 3, SurveyId = 3, EmployeeId = "Emp4", LocationId = "Loc1" }); - surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { Id = 4, SurveyId = 4, EmployeeId = "Emp1", LocationId = "Loc2" }); - surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { Id = 5, SurveyId = 1, EmployeeId = "Emp3", LocationId = "Loc3" }); - surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { Id = 6, SurveyId = 1, EmployeeId = "Emp4", LocationId = "Loc2" }); - surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { Id = 7, SurveyId = 1, EmployeeId = "Emp4", LocationId = "Loc3" }); + surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { Id = 1, SurveyId = 1, EmployeeId = "Emp1", LocationId = "Loc1", ClientDevice = "Mobile", Latitude = 98.8767, Longitute = -129.9897, KeyAnswerResult = "", CreatedDate = DateTime.Now }); + surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { Id = 2, SurveyId = 1, EmployeeId = "Emp2", LocationId = "Loc2", ClientDevice = "Desktop", Latitude = 98.8767, Longitute = -129.9897, KeyAnswerResult = "", CreatedDate = DateTime.Now }); + surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { Id = 3, SurveyId = 3, EmployeeId = "Emp4", LocationId = "Loc1", ClientDevice = "Mobile", Latitude = 98.8767, Longitute = -129.9897, KeyAnswerResult = "", CreatedDate = DateTime.Now }); + surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { Id = 4, SurveyId = 4, EmployeeId = "Emp1", LocationId = "Loc2", ClientDevice = "Desktop", Latitude = 98.8767, Longitute = -129.9897, KeyAnswerResult = "", CreatedDate = DateTime.Now }); + surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { Id = 6, SurveyId = 1, EmployeeId = "Emp4", LocationId = "Loc2", ClientDevice = "Desktop", Latitude = 98.8767, Longitute = -129.9897, KeyAnswerResult = "", CreatedDate = DateTime.Now }); + surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { Id = 7, SurveyId = 1, EmployeeId = "Emp4", LocationId = "Loc3", ClientDevice = "Desktop", Latitude = 98.8767, Longitute = -129.9897, KeyAnswerResult = "", CreatedDate = DateTime.Now }); surveyResponseDbContext.SaveChanges(); } } @@ -214,7 +207,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers var question = await questionServiceProvider.getQuestionsAsync(questionId); bool IsCorrectAnswer = answer.ToLower().Equals("yes") || answer.ToLower().Equals("no") ? true : false; - + if (survey != null && question != null && IsCorrectAnswer) { var answers = await getSurveyResponsesByAnswerAsync(survey, question, answer); @@ -230,7 +223,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers else { return (false, null, "Not found"); - } + } } catch (Exception ex) { @@ -300,6 +293,10 @@ namespace DamageAssesment.Api.SurveyResponses.Providers _SurveyResponse.SurveyId = SurveyResponse.SurveyId; _SurveyResponse.EmployeeId = SurveyResponse.EmployeeId; _SurveyResponse.LocationId = SurveyResponse.LocationId; + _SurveyResponse.ClientDevice = SurveyResponse.ClientDevice; + _SurveyResponse.KeyAnswerResult = SurveyResponse.KeyAnswerResult; + _SurveyResponse.Longitute = SurveyResponse.Longitute; + _SurveyResponse.Latitude = SurveyResponse.Latitude; await surveyResponseDbContext.SaveChangesAsync(); return (true, mapper.Map(_SurveyResponse), "Successful"); } @@ -340,7 +337,6 @@ namespace DamageAssesment.Api.SurveyResponses.Providers logger?.LogInformation($"SurveyReponseId = {Id} Not found"); return (false, null, "Not Found"); } - } catch (Exception ex) { @@ -435,35 +431,35 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { try { - var surveyResonses = await surveyResponseDbContext.SurveyResponses.Where(x => x.Id == surveyResponse.Id).ToListAsync(); - //var surveyResponse = surveyResonses.SingleOrDefault(); var employee = await employeeServiceProvider.getEmployeeAsync(surveyResponse.EmployeeId); var answers = await answerServiceProvider.GetAnswersByResponseIdAsync(surveyResponse.Id); var allQuestions = await questionServiceProvider.getQuestionsAsync(); - var questions = allQuestions.Where(s=> s.SurveyId == surveyResponse.Id); + var questions = allQuestions.Where(s => s.SurveyId == surveyResponse.SurveyId); var attachments = await attachmentServiceProvider.getAttachmentsAsync(); - - var result = from r in surveyResonses - select new - { - r.Id, - r.SurveyId, - r.LocationId, - r.EmployeeId, - Employee = employee, - answers = from ans in answers - select new - { - ans.QuestionId, - ans.Id, - ans.AnswerText, - ans.Comment, - Questions = (from q in questions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Questions }).SingleOrDefault(), - Attachments = from att in attachments where att.AnswerId == ans.Id select new { att.Id, att.URI } - } - }; - return result.SingleOrDefault(); + var result = new + { + surveyResponse.Id, + surveyResponse.SurveyId, + surveyResponse.LocationId, + surveyResponse.EmployeeId, + surveyResponse.ClientDevice, + surveyResponse.KeyAnswerResult, + surveyResponse.Longitute, + surveyResponse.Latitude, + Employee = employee, + answers = from ans in answers + select new + { + ans.QuestionId, + ans.Id, + ans.AnswerText, + ans.Comment, + Questions = (from q in questions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Questions }).SingleOrDefault(), + Attachments = from att in attachments where att.AnswerId == ans.Id select new { att.Id, att.URI } + } + }; + return result; } catch (Exception ex) { @@ -495,6 +491,10 @@ namespace DamageAssesment.Api.SurveyResponses.Providers r.SurveyId, r.LocationId, r.EmployeeId, + r.ClientDevice, + r.KeyAnswerResult, + r.Longitute, + r.Latitude, Employee = (from e in employees where e.Id == r.EmployeeId select new { e.Id, e.Name, e.BirthDate, e.Email, e.OfficePhoneNumber }).SingleOrDefault(), answers = from ans in answers where ans.SurveyResponseId == r.Id @@ -531,6 +531,8 @@ namespace DamageAssesment.Api.SurveyResponses.Providers var questions = await questionServiceProvider.getQuestionsAsync(); var attachments = await attachmentServiceProvider.getAttachmentsAsync(); + + var result = from r in surveyResonses select new { @@ -538,6 +540,10 @@ namespace DamageAssesment.Api.SurveyResponses.Providers r.SurveyId, r.LocationId, r.EmployeeId, + r.ClientDevice, + r.KeyAnswerResult, + r.Longitute, + r.Latitude, Employee = (from e in employees where r.EmployeeId == e.Id select new { e.Id, e.Name, e.BirthDate, e.Email, e.OfficePhoneNumber }).SingleOrDefault(), answers = from ans in answers where ans.SurveyResponseId == r.Id @@ -641,6 +647,10 @@ namespace DamageAssesment.Api.SurveyResponses.Providers r.SurveyId, r.LocationId, r.EmployeeId, + r.ClientDevice, + r.KeyAnswerResult, + r.Longitute, + r.Latitude, Employee = (from e in employees where r.EmployeeId == e.Id select new { e.Id, e.Name, e.BirthDate, e.Email, e.OfficePhoneNumber }).SingleOrDefault(), answers = from ans in answers where ans.SurveyResponseId == r.Id @@ -671,8 +681,6 @@ namespace DamageAssesment.Api.SurveyResponses.Providers try { var surveyResponses = await surveyResponseDbContext.SurveyResponses.Where(x => x.SurveyId == survey.Id).ToListAsync(); - //var questions = await questionServiceProvider.getQuestionsAsync(); - var answers = await answerServiceProvider.getAnswersAsync(); var employees = await employeeServiceProvider.getEmployeesAsync(); var attachments = await attachmentServiceProvider.getAttachmentsAsync(); @@ -684,6 +692,10 @@ namespace DamageAssesment.Api.SurveyResponses.Providers r.SurveyId, r.LocationId, r.EmployeeId, + r.ClientDevice, + r.KeyAnswerResult, + r.Longitute, + r.Latitude, Employee = (from e in employees where r.EmployeeId == e.Id select new { e.Id, e.Name, e.BirthDate, e.Email, e.OfficePhoneNumber }).SingleOrDefault(), answers = from ans in answers where ans.SurveyResponseId == r.Id @@ -714,23 +726,23 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { if (answerRequest != null) { - var answer = await answerServiceProvider.PostAnswersAsync(new Models.Answer {QuestionId = answerRequest.QuestionId, AnswerText = answerRequest.AnswerText, Comment = answerRequest.Comment, SurveyResponseId = surveyResponseId }); - if (answer != null) - { - List listAnswerInfo = new List(); - listAnswerInfo.Add(new AnswerInfo { AnswerId = answer.Id, postedFiles = answerRequest.PostedFiles }); - var attachments = attachmentServiceProvider.PostAttachmentsAsync(new AttachmentInfo { ResponseId = surveyResponseId, Answers = listAnswerInfo }); + var answer = await answerServiceProvider.PostAnswersAsync(new Models.Answer { QuestionId = answerRequest.QuestionId, AnswerText = answerRequest.AnswerText, Comment = answerRequest.Comment, SurveyResponseId = surveyResponseId }); + if (answer != null) + { + List listAnswerInfo = new List(); + listAnswerInfo.Add(new AnswerInfo { AnswerId = answer.Id, postedFiles = answerRequest.PostedFiles }); + var attachments = attachmentServiceProvider.PostAttachmentsAsync(new AttachmentInfo { ResponseId = surveyResponseId, Answers = listAnswerInfo }); - string message = $"Answer for question {answerRequest.QuestionId} saved to the database"; - logger?.LogInformation(message); - return (true); - } - else - { - string message = $"Answer for question {answerRequest.QuestionId} cannot be saved to the database"; - logger?.LogInformation(message); - return (false); - } + string message = $"Answer for question {answerRequest.QuestionId} saved to the database"; + logger?.LogInformation(message); + return (true); + } + else + { + string message = $"Answer for question {answerRequest.QuestionId} cannot be saved to the database"; + logger?.LogInformation(message); + return (false); + } } else { @@ -747,37 +759,12 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { if (request != null) { - var response = await PostSurveyResponseAsync(new Models.SurveyResponse {SurveyId = request.SurveyId, EmployeeId = request.EmployeeId, LocationId = request.LocationId }); + var response = await PostSurveyResponseAsync(new Models.SurveyResponse { SurveyId = request.SurveyId, EmployeeId = request.EmployeeId, LocationId = request.LocationId }); if (response.IsSuccess) { var surveyResponse = response.SurveyResponse; - var tasks = request.Answers.Select(x => ProcessAnswers(x,surveyResponse.Id)); - - // foreach (AnswerRequest ans in request.Answers) - // { - // answer = new Models.Answer { QuestionId = ans.QuestionId, AnswerText = ans.AnswerText, Comment = ans.Comment, SurveyResponseId = surveyResponse.Id }; - - //var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json"); - - //await Task.Delay(500); - // var rep = await answerServiceProvider.PostAnswersAsync(answer); - // var jsonObject = JsonConvert.SerializeObject(rep); - //x = x + jsonObject.ToString() + " "; - //i++; - // answer = new Models.Answer { QuestionId = ans.QuestionId, AnswerText = ans.AnswerText, Comment = ans.Comment, SurveyResponseId = surveyResponse.Id }; - // await answerServiceProvider.PostAnswersAsync(answer); - //ProcessAnswers(ans, surveyResponse.Id); - //var stopwatch = new Stopwatch(); - //stopwatch.Start(); - // var task = Task.Run(() => ProcessAnswers(ans, surveyResponse.Id)); - //var task = await ProcessAnswers(ans, surveyResponse.Id); - //answerTasks.Add(task); - - - //stopwatch.Stop(); - //answerTasks.Add(ProcessAnswers(ans, surveyResponse.Id)); - // } + var tasks = request.Answers.Select(x => ProcessAnswers(x, surveyResponse.Id)); await Task.WhenAll(tasks); return (true, surveyResponse, null); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyServiceProvider.cs index 06b1eed..fa65c74 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyServiceProvider.cs @@ -8,7 +8,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { public class SurveyServiceProvider :ServiceProviderBase, ISurveyServiceProvider { - public SurveyServiceProvider(IConfiguration configuration, HttpClient httpClient, ILogger logger) : base(configuration, httpClient, logger, "/api/Surveys", configuration.GetValue("EndPointSettings:SurveyUrlBase")) + public SurveyServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, "/api/Surveys", configuration.GetValue("EndPointSettings:SurveyUrlBase")) { } @@ -16,20 +16,19 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { try { - httpClient.BaseAddress = new Uri(urlBase); - var response = await httpClient.GetAsync(ressource); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var surveys = JsonConvert.DeserializeObject>(responseString); + + var url = urlBase + ressource; + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var surveys = JsonConvert.DeserializeObject>(responseJsonString); if (surveys == null || !surveys.Any()) - return null; + return new List(); else return surveys; } catch (Exception ex) { logger?.LogError($"Exception Found : {ex.Message} - Ref: SurveyServiceProvider.getSurveysAsync()"); - return null; + return new List(); } } @@ -37,11 +36,9 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { try { - httpClient.BaseAddress = new Uri(urlBase); - var response = await httpClient.GetAsync(ressource+"/"+ surveyId); - response.EnsureSuccessStatusCode(); - var responseString = await response.Content.ReadAsStringAsync(); - var survey = JsonConvert.DeserializeObject(responseString); + var url = urlBase + ressource + "/" + surveyId; + var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); + var survey = JsonConvert.DeserializeObject(responseJsonString); if (survey == null ) return null; @@ -53,7 +50,5 @@ namespace DamageAssesment.Api.SurveyResponses.Providers return null; } } - - } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Utils/HttpUtil.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Utils/HttpUtil.cs new file mode 100644 index 0000000..02dfd3d --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Utils/HttpUtil.cs @@ -0,0 +1,43 @@ +using DamageAssesment.Api.SurveyResponses.Bases; +using DamageAssesment.Api.SurveyResponses.Interfaces; +using System.Net.Http.Headers; +using System.Text; + +namespace DamageAssesment.Api.SurveyResponses.Utils +{ + public class HttpUtil : IHttpUtil + { + private readonly HttpClient httpClient; + private readonly ILogger logger; + + public HttpUtil(HttpClient httpClient, ILogger logger) + { + this.httpClient = httpClient; + this.logger = logger; + } + public async Task SendAsync(HttpMethod method, string url, string JsonInput) + { + try + { + var request = new HttpRequestMessage(method, url); + request.Headers.Accept.Clear(); + request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); + //request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token); + if (method == HttpMethod.Post) + { + request.Content = new StringContent(JsonInput, Encoding.UTF8, "application/json"); + } + + var response = await httpClient.SendAsync(request, CancellationToken.None); + response.EnsureSuccessStatusCode(); + var responseString = await response.Content.ReadAsStringAsync(); + return responseString; + } + catch (Exception ex) + { + logger?.LogError($"Exception Message : {ex.Message} - Ref: HttpUtil.SendAsync()"); + return null; + } + } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Interfaces/ISurveyProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Interfaces/ISurveyProvider.cs index 5cfded9..46743d3 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Interfaces/ISurveyProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Interfaces/ISurveyProvider.cs @@ -7,6 +7,7 @@ Task<(bool IsSuccess, Models.Survey Survey, string ErrorMessage)> PostSurveyAsync(Models.Survey Survey); Task<(bool IsSuccess, Models.Survey Survey, string ErrorMessage)> PutSurveyAsync(int Id,Models.Survey Survey); Task<(bool IsSuccess, Models.Survey Survey, string ErrorMessage)> DeleteSurveyAsync(int Id); + void seedData(); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Program.cs index 98fa8a3..fadf4de 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Program.cs @@ -53,6 +53,13 @@ if (app.Environment.IsDevelopment()) { app.UseSwagger(); app.UseSwaggerUI(); + + using (var serviceScope = app.Services.CreateScope()) + { + var services = serviceScope.ServiceProvider; + var surveyProvider = services.GetRequiredService(); + surveyProvider.seedData(); + } } app.UseAuthentication(); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs index 38ea756..c756738 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs @@ -18,10 +18,10 @@ namespace DamageAssesment.Api.Surveys.Providers this.surveyDbContext = surveysDbContext; this.logger = logger; this.mapper = mapper; - seedData(); + //seedData(); } - private void seedData() + public void seedData() { if (!surveyDbContext.Surveys.Any()) {