From 22261f42cad2ea7a5e1a8ea6db5c570e745abfd7 Mon Sep 17 00:00:00 2001 From: Reginald Cherenfant Jasmin Date: Fri, 18 Aug 2023 15:30:34 -0400 Subject: [PATCH 01/19] User Role and Authorization features added --- .../DamageAssesment.Api.Answers.csproj | 1 + .../appsettings.json | 3 + .../DamageAssesment.Api.Attachments.csproj | 1 + .../appsettings.json | 3 + .../DamageAssesment.Api.Employees.csproj | 1 + .../appsettings.json | 3 + .../DamageAssesment.Api.Locations.csproj | 1 + .../appsettings.json | 3 + .../DamageAssesment.Api.Questions.csproj | 1 + .../appsettings.json | 3 + ...DamageAssesment.Api.SurveyResponses.csproj | 2 +- .../Controllers/SurveysController.cs | 2 + .../DamageAssesment.Api.Survey.csproj | 1 + .../DamageAssesment.Api.Surveys/Program.cs | 22 ++ .../Providers/SurveysProvider.cs | 8 +- .../appsettings.json | 3 + .../Bases/ServiceProviderBase.cs | 21 ++ .../Controllers/UsersAccessController.cs | 97 +++++ .../DamageAssesment.Api.UsersAccess.csproj | 19 + .../Db/Role.cs | 21 ++ .../Db/Token.cs | 17 + .../Db/User.cs | 27 ++ .../Db/UsersAccessDbContext.cs | 17 + .../Interfaces/IEmployeeServiceProvider.cs | 10 + .../Interfaces/IRoleProvider.cs | 12 + .../Interfaces/ITokenServiceProvider.cs | 11 + .../Interfaces/IUsersAccessProvider.cs | 16 + .../Models/Employee.cs | 21 ++ .../Models/JwtSettings.cs | 9 + .../Models/Role.cs | 9 + .../Models/Token.cs | 10 + .../Models/TokenResponse.cs | 8 + .../Models/User.cs | 12 + .../Models/UserCredentials.cs | 5 + .../Profiles/UsersAccessProfile.cs | 14 + .../Program.cs | 77 ++++ .../Properties/launchSettings.json | 31 ++ .../Providers/EmployeeServiceProvider.cs | 58 +++ .../Providers/TokenServiceProvider.cs | 57 +++ .../Providers/UserAccessProvider.cs | 341 ++++++++++++++++++ .../appsettings.Development.json | 8 + .../appsettings.json | 15 + DamageAssesmentApi/DamageAssesment.sln | 7 + 43 files changed, 1003 insertions(+), 5 deletions(-) create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Bases/ServiceProviderBase.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Controllers/UsersAccessController.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/DamageAssesment.Api.UsersAccess.csproj create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/Role.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/Token.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/User.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/UsersAccessDbContext.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IEmployeeServiceProvider.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IRoleProvider.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/ITokenServiceProvider.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IUsersAccessProvider.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Employee.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/JwtSettings.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Role.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Token.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/TokenResponse.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/User.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/UserCredentials.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Profiles/UsersAccessProfile.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Program.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Properties/launchSettings.json create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/EmployeeServiceProvider.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/TokenServiceProvider.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/UserAccessProvider.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/appsettings.Development.json create mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/appsettings.json diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/DamageAssesment.Api.Answers.csproj b/DamageAssesmentApi/DamageAssesment.Api.Answers/DamageAssesment.Api.Answers.csproj index ca5ee38..260a911 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/DamageAssesment.Api.Answers.csproj +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/DamageAssesment.Api.Answers.csproj @@ -8,6 +8,7 @@ + diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/appsettings.json b/DamageAssesmentApi/DamageAssesment.Api.Answers/appsettings.json index 10f68b8..ff5949d 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/appsettings.json +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/appsettings.json @@ -1,4 +1,7 @@ { + "JwtSettings": { + "securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk=" + }, "Logging": { "LogLevel": { "Default": "Information", diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/DamageAssesment.Api.Attachments.csproj b/DamageAssesmentApi/DamageAssesment.Api.Attachments/DamageAssesment.Api.Attachments.csproj index 3454bff..4d9cb44 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/DamageAssesment.Api.Attachments.csproj +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/DamageAssesment.Api.Attachments.csproj @@ -9,6 +9,7 @@ + diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/appsettings.json b/DamageAssesmentApi/DamageAssesment.Api.Attachments/appsettings.json index ceb0a25..78aa6b5 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/appsettings.json +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/appsettings.json @@ -1,4 +1,7 @@ { + "JwtSettings": { + "securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk=" + }, "Logging": { "LogLevel": { "Default": "Information", diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/DamageAssesment.Api.Employees.csproj b/DamageAssesmentApi/DamageAssesment.Api.Employees/DamageAssesment.Api.Employees.csproj index 53e8700..515ad43 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/DamageAssesment.Api.Employees.csproj +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/DamageAssesment.Api.Employees.csproj @@ -8,6 +8,7 @@ + diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/appsettings.json b/DamageAssesmentApi/DamageAssesment.Api.Employees/appsettings.json index 1cf89f5..1a1f3fe 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/appsettings.json +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/appsettings.json @@ -1,4 +1,7 @@ { + "JwtSettings": { + "securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk=" + }, "Logging": { "LogLevel": { "Default": "Information", diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/DamageAssesment.Api.Locations.csproj b/DamageAssesmentApi/DamageAssesment.Api.Locations/DamageAssesment.Api.Locations.csproj index 47751c7..5264699 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/DamageAssesment.Api.Locations.csproj +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/DamageAssesment.Api.Locations.csproj @@ -8,6 +8,7 @@ + diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/appsettings.json b/DamageAssesmentApi/DamageAssesment.Api.Locations/appsettings.json index 10f68b8..ff5949d 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/appsettings.json +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/appsettings.json @@ -1,4 +1,7 @@ { + "JwtSettings": { + "securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk=" + }, "Logging": { "LogLevel": { "Default": "Information", diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/DamageAssesment.Api.Questions.csproj b/DamageAssesmentApi/DamageAssesment.Api.Questions/DamageAssesment.Api.Questions.csproj index 53e8700..515ad43 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/DamageAssesment.Api.Questions.csproj +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/DamageAssesment.Api.Questions.csproj @@ -8,6 +8,7 @@ + diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/appsettings.json b/DamageAssesmentApi/DamageAssesment.Api.Questions/appsettings.json index 10f68b8..ff5949d 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/appsettings.json +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/appsettings.json @@ -1,4 +1,7 @@ { + "JwtSettings": { + "securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk=" + }, "Logging": { "LogLevel": { "Default": "Information", diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/DamageAssesment.Api.SurveyResponses.csproj b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/DamageAssesment.Api.SurveyResponses.csproj index a2383fa..fec1ec5 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/DamageAssesment.Api.SurveyResponses.csproj +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/DamageAssesment.Api.SurveyResponses.csproj @@ -8,9 +8,9 @@ + - diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs index 56f2e29..a68fd9f 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs @@ -1,4 +1,5 @@ using DamageAssesment.Api.Surveys.Interfaces; +using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; @@ -25,6 +26,7 @@ namespace DamageAssesment.Api.Surveys.Controllers } return NoContent(); } + [HttpGet("{Id}")] public async Task GetSurveysAsync(int Id) { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/DamageAssesment.Api.Survey.csproj b/DamageAssesmentApi/DamageAssesment.Api.Surveys/DamageAssesment.Api.Survey.csproj index 53e8700..515ad43 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/DamageAssesment.Api.Survey.csproj +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/DamageAssesment.Api.Survey.csproj @@ -8,6 +8,7 @@ + diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Program.cs index ebb638f..91e052c 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Program.cs @@ -1,11 +1,32 @@ using DamageAssesment.Api.Surveys.Db; using DamageAssesment.Api.Surveys.Interfaces; using DamageAssesment.Api.Surveys.Providers; +using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.EntityFrameworkCore; +using Microsoft.IdentityModel.Tokens; +using System.Text; var builder = WebApplication.CreateBuilder(args); // Add services to the container. +var authkey = builder.Configuration.GetValue("JwtSettings:securitykey"); +builder.Services.AddAuthentication(item => +{ + item.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + item.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; +}).AddJwtBearer(item => +{ + item.RequireHttpsMetadata = true; + item.SaveToken = true; + item.TokenValidationParameters = new TokenValidationParameters() + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authkey)), + ValidateIssuer = false, + ValidateAudience = false, + ClockSkew = TimeSpan.Zero + }; +}); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle @@ -26,6 +47,7 @@ if (app.Environment.IsDevelopment()) app.UseSwaggerUI(); } +app.UseAuthentication(); app.UseAuthorization(); app.MapControllers(); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs index c85ed4c..3eb111c 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs @@ -26,7 +26,7 @@ namespace DamageAssesment.Api.Surveys.Providers surveyDbContext.Surveys.Add(new Db.Survey { Id = 1, Title = "Sample Survey Title:Damage Assesment 2014", IsEnabled = true, StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(90) }); surveyDbContext.Surveys.Add(new Db.Survey { Id = 2, Title = "Sample Survey Title: Damage Assesment 2016", IsEnabled = true, StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(90) }); surveyDbContext.Surveys.Add(new Db.Survey { Id = 3, Title = "Sample Survey Title: Damage Assesment 2018", IsEnabled = true, StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(90) }); - surveyDbContext.SaveChanges(); + surveyDbContext.SaveChangesAsync(); } } @@ -80,7 +80,7 @@ namespace DamageAssesment.Api.Surveys.Providers var surveys = await surveyDbContext.Surveys.ToListAsync(); survey.Id = surveys.Count + 1; surveyDbContext.Surveys.Add(mapper.Map(survey)); - surveyDbContext.SaveChanges(); + await surveyDbContext.SaveChangesAsync(); return (true, survey, "Successful"); } else @@ -110,7 +110,7 @@ namespace DamageAssesment.Api.Surveys.Providers _survey.IsEnabled = survey.IsEnabled; _survey.StartDate = survey.StartDate; _survey.EndDate = survey.EndDate; - surveyDbContext.SaveChanges(); + await surveyDbContext.SaveChangesAsync(); return (true, mapper.Map(_survey), "Successful"); } else @@ -141,7 +141,7 @@ namespace DamageAssesment.Api.Surveys.Providers if (survey != null) { surveyDbContext.Surveys.Remove(survey); - surveyDbContext.SaveChanges(); + await surveyDbContext.SaveChangesAsync(); return (true, mapper.Map(survey), $"Survey Id: {Id} deleted Successfuly"); } else diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/appsettings.json b/DamageAssesmentApi/DamageAssesment.Api.Surveys/appsettings.json index 10f68b8..ff5949d 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/appsettings.json +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/appsettings.json @@ -1,4 +1,7 @@ { + "JwtSettings": { + "securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk=" + }, "Logging": { "LogLevel": { "Default": "Information", diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Bases/ServiceProviderBase.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Bases/ServiceProviderBase.cs new file mode 100644 index 0000000..799f082 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Bases/ServiceProviderBase.cs @@ -0,0 +1,21 @@ +namespace DamageAssesment.Api.UsersAccess.Bases +{ + public class ServiceProviderBase + { + protected readonly IConfiguration configuration; + protected readonly HttpClient httpClient; + protected private readonly ILogger logger; + protected string ressource; + protected string urlBase; + + + public ServiceProviderBase(IConfiguration configuration, HttpClient httpClient, ILogger logger, string ressource, string urlBase) + { + this.configuration = configuration; + this.httpClient = httpClient; + this.logger = logger; + this.ressource = ressource; + this.urlBase = urlBase; + } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Controllers/UsersAccessController.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Controllers/UsersAccessController.cs new file mode 100644 index 0000000..5e16362 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Controllers/UsersAccessController.cs @@ -0,0 +1,97 @@ +using DamageAssesment.Api.UsersAccess.Interfaces; +using DamageAssesment.Api.UsersAccess.Models; +using Microsoft.AspNetCore.Mvc; + +namespace DamageAssesment.Api.UsersAccess.Controllers +{ + [Route("api")] + [ApiController] + public class UsersAccessController : ControllerBase + { + private IUsersAccessProvider userAccessProvider; + + public UsersAccessController(IUsersAccessProvider userAccessProvider) + { + this.userAccessProvider = userAccessProvider; + } + [HttpPost("authenticate")] + public async Task AuthenticateAsync(UserCredentials userCredentials) + { + var result = await userAccessProvider.AuthenticateAsync(userCredentials); + if (result.IsSuccess) + { + return Ok(result.TokenResponse); + } + return Unauthorized(result.ErrorMessage); + } + + [HttpPost("refreshToken")] + public async Task RefreshTokenAsync(TokenResponse tokenResponse) + { + var result = await userAccessProvider.RefreshTokenAsync(tokenResponse); + if (result.IsSuccess) + { + return Ok(result.TokenResponse); + } + return Unauthorized(result.ErrorMessage); + } + + [HttpGet("users")] + public async Task GetUsersAsync() + { + var result = await userAccessProvider.GetUsersAsync(); + if (result.IsSuccess) + { + return Ok(result.Users); + } + return NoContent(); + } + + [HttpGet("users/{Id}")] + public async Task GetUsersAsync(int Id) + { + var result = await userAccessProvider.GetUsersAsync(Id); + if (result.IsSuccess) + { + return Ok(result.User); + } + return NotFound(); + } + + [HttpPost("users")] + public async Task PostUserAsync(User user) + { + var result = await userAccessProvider.PostUserAsync(user); + if (result.IsSuccess) + { + return Ok(result.User); + } + return BadRequest(result.ErrorMessage); + } + + [HttpPut("users/{Id}")] + public async Task PutUserAsync(int Id, User user) + { + var result = await userAccessProvider.PutUserAsync(Id, user); + if (result.IsSuccess) + { + return Ok(result.User); + } + if (result.ErrorMessage == "Not Found") + return NotFound(result.ErrorMessage); + + return BadRequest(result.ErrorMessage); + } + + [HttpDelete("users/{Id}")] + public async Task DeleteSurveysAsync(int Id) + { + var result = await userAccessProvider.DeleteUserAsync(Id); + if (result.IsSuccess) + { + return Ok(result.User); + } + return NotFound(); + } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/DamageAssesment.Api.UsersAccess.csproj b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/DamageAssesment.Api.UsersAccess.csproj new file mode 100644 index 0000000..d56ba51 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/DamageAssesment.Api.UsersAccess.csproj @@ -0,0 +1,19 @@ + + + + net6.0 + enable + enable + + + + + + + + + + + + + diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/Role.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/Role.cs new file mode 100644 index 0000000..93e522a --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/Role.cs @@ -0,0 +1,21 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Text.Json.Serialization; + +namespace DamageAssesment.Api.UsersAccess.Db +{ + public class Role + { + [Key] + public int Id { get; set; } + + [StringLength(100)] + [Required] + public string Name { get; set; } + + // add a status field + + [StringLength(100)] + public string? Description { get; set; } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/Token.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/Token.cs new file mode 100644 index 0000000..cfea1e2 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/Token.cs @@ -0,0 +1,17 @@ +using Microsoft.EntityFrameworkCore.Metadata.Internal; +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; + +namespace DamageAssesment.Api.UsersAccess.Db +{ + public class Token + { + [Key] + public string Id { get; set; } + [Required] + [ForeignKey("User")] + public int UserId { get; set; } + public string? RefreshToken { get; set; } + public bool? IsActive { get; set; } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/User.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/User.cs new file mode 100644 index 0000000..d5fc4ee --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/User.cs @@ -0,0 +1,27 @@ +using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; +using System.Text.Json.Serialization; + +namespace DamageAssesment.Api.UsersAccess.Db +{ + public class User + { + [Key] + public int Id { get; set; } + + [ForeignKey("Employee")] + public string EmployeeId { get; set; } + + [ForeignKey("Role")] + [Required] + public int RoleId { get; set; } + [Required] + public bool? IsActive { get; set; } = true; + + [Required] + public DateTime? CreateDate { get; set; } = DateTime.Now; + + public DateTime? UpdateDate { get; set; } + + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/UsersAccessDbContext.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/UsersAccessDbContext.cs new file mode 100644 index 0000000..a46a10d --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/UsersAccessDbContext.cs @@ -0,0 +1,17 @@ +using Microsoft.EntityFrameworkCore; + +namespace DamageAssesment.Api.UsersAccess.Db +{ + public class UsersAccessDbContext:DbContext + { + public DbSet Users { get; set; } + public DbSet Roles { get; set; } + public DbSet Tokens { get; set; } + public UsersAccessDbContext(DbContextOptions options) : base(options) + { + + } + + + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IEmployeeServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IEmployeeServiceProvider.cs new file mode 100644 index 0000000..fc35b00 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IEmployeeServiceProvider.cs @@ -0,0 +1,10 @@ +using DamageAssesment.Api.UsersAccess.Models; + +namespace DamageAssesment.Api.UsersAccess.Interfaces +{ + public interface IEmployeeServiceProvider + { + Task> getEmployeesAsync(); + Task getEmployeeAsync(string employeeID); + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IRoleProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IRoleProvider.cs new file mode 100644 index 0000000..6ca0209 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IRoleProvider.cs @@ -0,0 +1,12 @@ +namespace DamageAssesment.Api.UsersAccess.Interfaces +{ + public interface IRoleProvider + { + Task<(bool IsSuccess, IEnumerable< Models.Role> Roles, string ErrorMessage)> GetRolesAsync(); + Task<(bool IsSuccess, Models.Role Roles, string ErrorMessage)> GetRolesAsync(int Id); + Task<(bool IsSuccess, Models.Role Role, string ErrorMessage)> PostRoleAsync(Models.Role Role); + Task<(bool IsSuccess, Models.Role Role, string ErrorMessage)> PutRoleAsync(int Id,Models.Role Role); + Task<(bool IsSuccess, Models.Role Role, string ErrorMessage)> DeleteRoleAsync(int Id); + + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/ITokenServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/ITokenServiceProvider.cs new file mode 100644 index 0000000..58574b7 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/ITokenServiceProvider.cs @@ -0,0 +1,11 @@ +using DamageAssesment.Api.UsersAccess.Models; +using System.Security.Claims; + +namespace DamageAssesment.Api.UsersAccess.Interfaces +{ + public interface ITokenServiceProvider + { + Task GenerateToken(User user); + Task TokenAuthenticate(User user, Claim[] claims); + } +} \ No newline at end of file diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IUsersAccessProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IUsersAccessProvider.cs new file mode 100644 index 0000000..7e39e11 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IUsersAccessProvider.cs @@ -0,0 +1,16 @@ +using DamageAssesment.Api.UsersAccess.Models; + +namespace DamageAssesment.Api.UsersAccess.Interfaces +{ + public interface IUsersAccessProvider + { + public Task<(bool IsSuccess, IEnumerable< Models.User> Users, string ErrorMessage)> GetUsersAsync(); + public Task<(bool IsSuccess, Models.User User, string ErrorMessage)> GetUsersAsync(int Id); + public Task<(bool IsSuccess, Models.User User, string ErrorMessage)> PostUserAsync(Models.User User); + public Task<(bool IsSuccess, Models.User User, string ErrorMessage)> PutUserAsync(int Id,Models.User User); + public Task<(bool IsSuccess, Models.User User, string ErrorMessage)> DeleteUserAsync(int Id); + public Task<(bool IsSuccess, IEnumerable Roles, string ErrorMessage)> GetRolesAsync(); + public Task<(bool IsSuccess, Models.TokenResponse TokenResponse, string ErrorMessage)> AuthenticateAsync(UserCredentials userCredentials); + public Task<(bool IsSuccess, Models.TokenResponse TokenResponse, string ErrorMessage)>RefreshTokenAsync(TokenResponse tokenResponse); + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Employee.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Employee.cs new file mode 100644 index 0000000..e14f27d --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Employee.cs @@ -0,0 +1,21 @@ +using System.ComponentModel.DataAnnotations; + +namespace DamageAssesment.Api.UsersAccess.Models +{ + public class Employee + { + public string Id { get; set; } + + [StringLength(50)] + public string Name { get; set; } + + public DateTime BirthDate { get; set; } + + [StringLength(50)] + public string OfficePhoneNumber { get; set; } + + [StringLength(50)] + public string Email { get; set; } + public bool IsActive { get; set; } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/JwtSettings.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/JwtSettings.cs new file mode 100644 index 0000000..3f9dadf --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/JwtSettings.cs @@ -0,0 +1,9 @@ +using System.ComponentModel.DataAnnotations; +namespace DamageAssesment.Api.UsersAccess.Models +{ + + public class JwtSettings + { + public string securitykey { get; set; } + } +} \ No newline at end of file diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Role.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Role.cs new file mode 100644 index 0000000..809e677 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Role.cs @@ -0,0 +1,9 @@ +using System.ComponentModel.DataAnnotations; +namespace DamageAssesment.Api.UsersAccess.Models +{ + public class Role { + public int Id { get; set; } + public string Name { get; set; } + public string? Description { get; set; } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Token.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Token.cs new file mode 100644 index 0000000..9c46d81 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Token.cs @@ -0,0 +1,10 @@ +namespace DamageAssesment.Api.UsersAccess.Models +{ + public class Token + { + public string Id { get; set; } + public int UserId { get; set; } + public string? RefreshToken { get; set; } + public bool? IsActive { get; set; } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/TokenResponse.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/TokenResponse.cs new file mode 100644 index 0000000..4d0b6da --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/TokenResponse.cs @@ -0,0 +1,8 @@ +namespace DamageAssesment.Api.UsersAccess.Models +{ + public class TokenResponse + { + public string? jwttoken { get; set; } + public string? refreshtoken { get; set; } + } +} \ No newline at end of file diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/User.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/User.cs new file mode 100644 index 0000000..f3c9971 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/User.cs @@ -0,0 +1,12 @@ +namespace DamageAssesment.Api.UsersAccess.Models +{ + public class User + { + public int Id { get; set; } + public string EmployeeId { get; set; } + public int RoleId { get; set; } + public bool? IsActive { get; set; } + public DateTime? CreateDate { get; set; } + public DateTime? UpdateDate { get; set; } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/UserCredentials.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/UserCredentials.cs new file mode 100644 index 0000000..a23a43b --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/UserCredentials.cs @@ -0,0 +1,5 @@ +public class UserCredentials +{ + public string? username { get; set; } + // public string? password { get; set; } +} \ No newline at end of file diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Profiles/UsersAccessProfile.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Profiles/UsersAccessProfile.cs new file mode 100644 index 0000000..bf744eb --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Profiles/UsersAccessProfile.cs @@ -0,0 +1,14 @@ +namespace DamageAssesment.Api.UsersAccess.Profiles +{ + public class UsersAccessProfile : AutoMapper.Profile + { + public UsersAccessProfile() + { + CreateMap(); + CreateMap(); + + CreateMap(); + CreateMap(); + } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Program.cs new file mode 100644 index 0000000..a7fb1ac --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Program.cs @@ -0,0 +1,77 @@ +using DamageAssesment.Api.UsersAccess.Db; +using DamageAssesment.Api.UsersAccess.Interfaces; +using DamageAssesment.Api.UsersAccess.Providers; +using DamageAssesment.Api.UsersAccess.Models; +using Microsoft.AspNetCore.Authentication.JwtBearer; +using Microsoft.EntityFrameworkCore; +using Microsoft.IdentityModel.Tokens; +using System.Text; +using Polly; +using DamageAssesment.Api.SurveyResponses.Providers; + +const int maxApiCallRetries = 3; +const int intervalToRetry = 2; //2 seconds +const int maxRetryForCircuitBraker = 5; +const int intervalForCircuitBraker = 5; //5 seconds + +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. +var authkey = builder.Configuration.GetValue("JwtSettings:securitykey"); +builder.Services.AddAuthentication(item => +{ + item.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + item.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; +}).AddJwtBearer(item => +{ + item.RequireHttpsMetadata = true; + item.SaveToken = true; + item.TokenValidationParameters = new TokenValidationParameters() + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authkey)), + ValidateIssuer = false, + ValidateAudience = false, + ClockSkew = TimeSpan.Zero + }; +}); + +var _jwtsettings = builder.Configuration.GetSection("JwtSettings"); +builder.Services.Configure(_jwtsettings); + + + +builder.Services.AddHttpClient(). + AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(maxApiCallRetries, _ => TimeSpan.FromSeconds(intervalToRetry))). + AddTransientHttpErrorPolicy(policy => policy.CircuitBreakerAsync(maxRetryForCircuitBraker, TimeSpan.FromSeconds(intervalForCircuitBraker))); + +builder.Services.AddControllers(); +// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle +builder.Services.AddScoped(); +builder.Services.AddScoped(); +builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); +builder.Services.AddEndpointsApiExplorer(); +builder.Services.AddSwaggerGen(); +builder.Services.AddDbContext(option => +{ + option.UseInMemoryDatabase("UsersAccess"); +}); + + + + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +if (app.Environment.IsDevelopment()) +{ + app.UseSwagger(); + app.UseSwaggerUI(); +} + +app.UseAuthentication(); +app.UseAuthorization(); + +app.MapControllers(); + +app.Run(); diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Properties/launchSettings.json b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Properties/launchSettings.json new file mode 100644 index 0000000..859e680 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Properties/launchSettings.json @@ -0,0 +1,31 @@ +{ + "$schema": "https://json.schemastore.org/launchsettings.json", + "iisSettings": { + "windowsAuthentication": false, + "anonymousAuthentication": true, + "iisExpress": { + "applicationUrl": "http://localhost:28382", + "sslPort": 0 + } + }, + "profiles": { + "DamageAssesment.Api.Users": { + "commandName": "Project", + "dotnetRunMessages": true, + "launchBrowser": true, + "launchUrl": "swagger", + "applicationUrl": "http://localhost:5027", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + }, + "IIS Express": { + "commandName": "IISExpress", + "launchBrowser": true, + "launchUrl": "swagger", + "environmentVariables": { + "ASPNETCORE_ENVIRONMENT": "Development" + } + } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/EmployeeServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/EmployeeServiceProvider.cs new file mode 100644 index 0000000..ace59ee --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/EmployeeServiceProvider.cs @@ -0,0 +1,58 @@ +using DamageAssesment.Api.UsersAccess.Bases; +using DamageAssesment.Api.UsersAccess.Interfaces; +using DamageAssesment.Api.UsersAccess.Models; +using Newtonsoft.Json; +using System.Reflection; + +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 async Task> getEmployeesAsync() + { + 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); + + if (employees == null || !employees.Any()) + return null; + else return employees; + } + catch (Exception ex) + { + logger?.LogError($"Exception Found : {ex.Message} - Ref: EmployeeServiceProvider.getEmployeesAsync()"); + return null; + } + } + + 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); + + if (employee == null ) + return null; + else return employee; + } + catch (Exception ex) + { + logger?.LogError($"Exception Found : {ex.Message} - Ref: EmployeeServiceProvider.getEmployeeAsync()"); + return null; + } + } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/TokenServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/TokenServiceProvider.cs new file mode 100644 index 0000000..a77d6bc --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/TokenServiceProvider.cs @@ -0,0 +1,57 @@ +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Security.Cryptography; +using System.Text; +using DamageAssesment.Api.UsersAccess.Db; +using DamageAssesment.Api.UsersAccess.Interfaces; +using DamageAssesment.Api.UsersAccess.Models; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.Tokens; + +public class TokenServiceProvider : ITokenServiceProvider +{ + private readonly UsersAccessDbContext usersAccessDbContext; + private readonly JwtSettings jwtSettings; + public TokenServiceProvider(IOptions options,UsersAccessDbContext usersAccessDbContext) + { + this.usersAccessDbContext = usersAccessDbContext; + this.jwtSettings = options.Value; + } + public async Task GenerateToken(DamageAssesment.Api.UsersAccess.Models.User user) + { + var randomnumber = new byte[32]; + using (var ramdomnumbergenerator = RandomNumberGenerator.Create()) + { + ramdomnumbergenerator.GetBytes(randomnumber); + string refreshtoken = Convert.ToBase64String(randomnumber); + var token = await usersAccessDbContext.Tokens.FirstOrDefaultAsync(item => item.UserId == user.Id); + if (token != null) + { + token.RefreshToken = refreshtoken; + } + else + { + usersAccessDbContext.Tokens.Add(new DamageAssesment.Api.UsersAccess.Db.Token() + { + Id = new Random().Next().ToString(), + UserId = user.Id, + RefreshToken = refreshtoken, + IsActive = true + }); + } + await usersAccessDbContext.SaveChangesAsync(); + + return refreshtoken; + } + } + + public async Task TokenAuthenticate(DamageAssesment.Api.UsersAccess.Models.User user, Claim[] claims) + { + var token = new JwtSecurityToken(claims: claims, expires: DateTime.Now.AddSeconds(20), + signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.securitykey)), SecurityAlgorithms.HmacSha256) + ); + var jwttoken = new JwtSecurityTokenHandler().WriteToken(token); + return new TokenResponse() { jwttoken = jwttoken, refreshtoken = await GenerateToken(user) }; + } +} \ No newline at end of file diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/UserAccessProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/UserAccessProvider.cs new file mode 100644 index 0000000..6188d92 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/UserAccessProvider.cs @@ -0,0 +1,341 @@ +using AutoMapper; +using DamageAssesment.Api.UsersAccess.Db; +using DamageAssesment.Api.UsersAccess.Interfaces; +using DamageAssesment.Api.UsersAccess.Models; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.Options; +using Microsoft.IdentityModel.Tokens; +using System.Data; +using System.IdentityModel.Tokens.Jwt; +using System.Security.Claims; +using System.Text; + +namespace DamageAssesment.Api.UsersAccess.Providers +{ + public class UsersAccessProvider : IUsersAccessProvider + { + private readonly UsersAccessDbContext userAccessDbContext; + private readonly ILogger logger; + private readonly IMapper mapper; + private readonly IEmployeeServiceProvider employeeServiceProvider; + private readonly JwtSettings jwtSettings; + private readonly ITokenServiceProvider tokenServiceProvider; + + public UsersAccessProvider(IOptions options, ITokenServiceProvider tokenServiceProvider, UsersAccessDbContext userAccessDbContext, IEmployeeServiceProvider employeeServiceProvider, ILogger logger, IMapper mapper) + { + this.userAccessDbContext = userAccessDbContext; + this.employeeServiceProvider = employeeServiceProvider; + this.logger = logger; + this.mapper = mapper; + jwtSettings = options.Value; + this.tokenServiceProvider = tokenServiceProvider; + seedData(); + } + + private void seedData() + { + if (!userAccessDbContext.Users.Any()) + { + userAccessDbContext.Users.Add(new Db.User { Id = 1, EmployeeId = "Emp1", RoleId = 1 }); + userAccessDbContext.Users.Add(new Db.User { Id = 2, EmployeeId = "Emp2", RoleId = 2 }); + userAccessDbContext.Users.Add(new Db.User { Id = 3, EmployeeId = "Emp3", RoleId = 3 }); + userAccessDbContext.SaveChanges(); + } + + if (!userAccessDbContext.Roles.Any()) + { + userAccessDbContext.Roles.Add(new Db.Role { Id = 1, Name = "admin" }); + userAccessDbContext.Roles.Add(new Db.Role { Id = 2, Name = "user" }); + userAccessDbContext.Roles.Add(new Db.Role { Id = 3, Name = "survey" }); + userAccessDbContext.Roles.Add(new Db.Role { Id = 4, Name = "report" }); + userAccessDbContext.Roles.Add(new Db.Role { Id = 5, Name = "document" }); + userAccessDbContext.SaveChanges(); + } + } + + public async Task<(bool IsSuccess, IEnumerable Users, string ErrorMessage)> GetUsersAsync() + { + try + { + logger?.LogInformation("Gell all Users from DB"); + var users = await userAccessDbContext.Users.ToListAsync(); + if (users != null) + { + logger?.LogInformation($"{users.Count} Items(s) found"); + var result = mapper.Map, IEnumerable>(users); + return (true, result, null); + } + return (false, null, "Not found"); + } + catch (Exception ex) + { + logger?.LogError(ex.ToString()); + return (false, null, ex.Message); + } + } + + public async Task<(bool IsSuccess, Models.User User, string ErrorMessage)> GetUsersAsync(int Id) + { + try + { + logger?.LogInformation("Querying Users table"); + var user = await userAccessDbContext.Users.SingleOrDefaultAsync(s => s.Id == Id); + if (user != null) + { + logger?.LogInformation($"User Id: {Id} found"); + var result = mapper.Map(user); + return (true, result, null); + } + return (false, null, "Not found"); + } + catch (Exception ex) + { + logger?.LogError(ex.ToString()); + return (false, null, ex.Message); + } + } + + public async Task<(bool IsSuccess, Models.User User, string ErrorMessage)> PostUserAsync(Models.User user) + { + try + { + if (user != null) + { + var users = await userAccessDbContext.Users.ToListAsync(); + int count = users.Where(u => u.EmployeeId == user.EmployeeId).Count(); + if (count == 0) + { + user.Id = users.Count + 1; + userAccessDbContext.Users.Add(mapper.Map(user)); + await userAccessDbContext.SaveChangesAsync(); + return (true, user, "Successful"); + } + else + { + logger?.LogInformation($"Employee Id: {user.EmployeeId} is already exist"); + return (false, null, $"Employee Id: {user.EmployeeId} is already exist"); + } + } + else + { + logger?.LogInformation($"Employee Id: {user.EmployeeId} cannot be added"); + return (false, null, $"Employee Id: {user.EmployeeId} cannot be added"); + } + } + catch (Exception ex) + { + logger?.LogError(ex.ToString()); + return (false, null, ex.Message); + } + } + + public async Task<(bool IsSuccess, Models.User User, string ErrorMessage)> PutUserAsync(int Id, Models.User user) + { + try + { + if (user != null) + { + var _user = await userAccessDbContext.Users.Where(s => s.Id == Id).SingleOrDefaultAsync(); + + if (_user != null) + { + int count = userAccessDbContext.Users.Where(u => u.Id != user.Id && u.EmployeeId == user.EmployeeId).Count(); + if (count == 0) + { + _user.EmployeeId = user.EmployeeId; + _user.RoleId = user.RoleId; + _user.IsActive = user.IsActive; + _user.UpdateDate = DateTime.Now; + await userAccessDbContext.SaveChangesAsync(); + + + logger?.LogInformation($"Employee Id: {user.EmployeeId} updated successfuly"); + return (true, mapper.Map(_user), $"Employee Id: {_user.EmployeeId} updated successfuly"); + } + else + { + logger?.LogInformation($"Employee Id: {user.EmployeeId} is already exist"); + return (false, null, $"Employee Id: {user.EmployeeId} is already exist"); + } + } + else + { + logger?.LogInformation($"User Id : {Id} Not found"); + return (false, null, "Not Found"); + } + } + else + { + logger?.LogInformation($"User Id: {Id} Bad Request"); + return (false, null, "Bad request"); + } + } + catch (Exception ex) + { + logger?.LogError(ex.ToString()); + return (false, null, ex.Message); + } + } + + public async Task<(bool IsSuccess, Models.User User, string ErrorMessage)> DeleteUserAsync(int Id) + { + try + { + var user = await userAccessDbContext.Users.Where(x => x.Id == Id).SingleOrDefaultAsync(); + + if (user != null) + { + userAccessDbContext.Users.Remove(user); + await userAccessDbContext.SaveChangesAsync(); + logger?.LogInformation($"User Id: {Id} deleted Successfuly"); + return (true, mapper.Map(user), $"User Id: {Id} deleted Successfuly"); + } + else + { + logger?.LogInformation($"User Id : {Id} Not found"); + return (false, null, "Not Found"); + } + } + catch (Exception ex) + { + logger?.LogError(ex.ToString()); + return (false, null, ex.Message); + } + } + + public async Task<(bool IsSuccess, TokenResponse TokenResponse, string ErrorMessage)> AuthenticateAsync(UserCredentials userCredentials) + { + + if (userCredentials != null) + { + //implementation for dadeschools authentication + + var employee = await employeeServiceProvider.getEmployeeAsync(userCredentials.username); + + if (employee != null) + { + var result = await GetUsersAsync(); + + if (result.IsSuccess) + { + var user = result.Users.Where(x => x.IsActive == true && x.EmployeeId.ToLower().Equals(userCredentials.username.ToLower())).SingleOrDefault(); + + if (user != null) + { + + var r = await GetRolesAsync(); + var role = r.Roles.Where(x => x.Id == user.RoleId).SingleOrDefault(); + + var authClaims = new List { + new Claim(ClaimTypes.Name, user.EmployeeId), + new Claim(ClaimTypes.Role, role.Name), + new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString()) + + }; + + /// Generate Token + var tokenhandler = new JwtSecurityTokenHandler(); + var tokenkey = Encoding.UTF8.GetBytes(jwtSettings.securitykey); + var tokendesc = new SecurityTokenDescriptor + { + Audience = "", + NotBefore = DateTime.Now, + Subject = new ClaimsIdentity(authClaims), + Expires = DateTime.Now.AddMinutes(30), + SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(tokenkey), SecurityAlgorithms.HmacSha256) + }; + var token = tokenhandler.CreateToken(tokendesc); + string finaltoken = tokenhandler.WriteToken(token); + + var response = new TokenResponse() { jwttoken = finaltoken, refreshtoken = await tokenServiceProvider.GenerateToken(user) }; + + + return (true, response, "Authentication success and token issued."); + + } + else + { + return (false, null, "user inactive or not exist."); + } + } + else + { + return (false, null, "users list empty."); + } + } + else + { + return (false, null, "Employee not exist."); + } + } + else + { + return (false, null, "Credentials are required to authenticate."); + + } + + } + public async Task<(bool IsSuccess, IEnumerable Roles, string ErrorMessage)> GetRolesAsync() + { + try + { + logger?.LogInformation("Gell all Roles from DB"); + var roles = await userAccessDbContext.Roles.ToListAsync(); + if (roles != null) + { + logger?.LogInformation($"{roles.Count} Items(s) found"); + var result = mapper.Map, IEnumerable>(roles); + return (true, result, null); + } + return (false, null, "Not found"); + } + catch (Exception ex) + { + logger?.LogError(ex.ToString()); + return (false, null, ex.Message); + } + } + + public async Task<(bool IsSuccess, Models.TokenResponse TokenResponse, string ErrorMessage)> RefreshTokenAsync(TokenResponse tokenResponse) + { + //Generate token + var tokenhandler = new JwtSecurityTokenHandler(); + var tokenkey = Encoding.UTF8.GetBytes(this.jwtSettings.securitykey); + SecurityToken securityToken; + var principal = tokenhandler.ValidateToken(tokenResponse.jwttoken, new TokenValidationParameters + { + ValidateIssuerSigningKey = true, + IssuerSigningKey = new SymmetricSecurityKey(tokenkey), + ValidateIssuer = false, + ValidateAudience = false, + + }, out securityToken); + + var token = securityToken as JwtSecurityToken; + if (token != null && !token.Header.Alg.Equals(SecurityAlgorithms.HmacSha256)) + { + return (false, null, "Unauthorized"); + } + var username = principal.Identity?.Name; + + var tokens = await userAccessDbContext.Tokens.ToListAsync(); + var users = await userAccessDbContext.Users.ToListAsync(); + + var user = (from u in users + join t in tokens + on u.Id equals t.UserId + where u.EmployeeId == username + && t.RefreshToken == tokenResponse.refreshtoken + select u).FirstOrDefault(); + + if (user == null) + return (false, null, "Invalid Token Response object provided"); + + var _user = mapper.Map(user); + var response = tokenServiceProvider.TokenAuthenticate(_user, principal.Claims.ToArray()).Result; + return (true, response, "Token authenticated and refreshed."); + } + + + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/appsettings.Development.json b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/appsettings.Development.json new file mode 100644 index 0000000..0c208ae --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/appsettings.Development.json @@ -0,0 +1,8 @@ +{ + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/appsettings.json b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/appsettings.json new file mode 100644 index 0000000..4a1b1b5 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/appsettings.json @@ -0,0 +1,15 @@ +{ + "JwtSettings": { + "securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk=" + }, + "Logging": { + "LogLevel": { + "Default": "Information", + "Microsoft.AspNetCore": "Warning" + } + }, + "EndPointSettings": { + "EmployeeUrlBase": "http://localhost:5135" + }, + "AllowedHosts": "*" +} diff --git a/DamageAssesmentApi/DamageAssesment.sln b/DamageAssesmentApi/DamageAssesment.sln index a8b1fcc..8deb2aa 100644 --- a/DamageAssesmentApi/DamageAssesment.sln +++ b/DamageAssesmentApi/DamageAssesment.sln @@ -37,6 +37,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DamageAssesment.Api.Employe EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DamageAssesment.Api.Employees.Test", "DamageAssesment.Api.Employees.Test\DamageAssesment.Api.Employees.Test.csproj", "{D6BF9AE9-72FA-4726-A326-35A35D27FFB8}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DamageAssesment.Api.UsersAccess", "DamageAssesment.Api.UsersAccess\DamageAssesment.Api.UsersAccess.csproj", "{83177BB9-DD23-4A85-A000-D60F843D0835}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -64,6 +66,7 @@ Global {D11808FE-AD1C-4BA6-87FD-9D18B2DC81F2}.Release|Any CPU.ActiveCfg = Release|Any CPU {D11808FE-AD1C-4BA6-87FD-9D18B2DC81F2}.Release|Any CPU.Build.0 = Release|Any CPU {35CD9231-034D-4999-BCFC-1786DD007ED2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {35CD9231-034D-4999-BCFC-1786DD007ED2}.Debug|Any CPU.Build.0 = Debug|Any CPU {35CD9231-034D-4999-BCFC-1786DD007ED2}.Release|Any CPU.ActiveCfg = Release|Any CPU {35CD9231-034D-4999-BCFC-1786DD007ED2}.Release|Any CPU.Build.0 = Release|Any CPU {ADFB79E3-83C9-454F-A070-49D167BD28CC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU @@ -98,6 +101,10 @@ Global {D6BF9AE9-72FA-4726-A326-35A35D27FFB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {D6BF9AE9-72FA-4726-A326-35A35D27FFB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {D6BF9AE9-72FA-4726-A326-35A35D27FFB8}.Release|Any CPU.Build.0 = Release|Any CPU + {83177BB9-DD23-4A85-A000-D60F843D0835}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {83177BB9-DD23-4A85-A000-D60F843D0835}.Debug|Any CPU.Build.0 = Debug|Any CPU + {83177BB9-DD23-4A85-A000-D60F843D0835}.Release|Any CPU.ActiveCfg = Release|Any CPU + {83177BB9-DD23-4A85-A000-D60F843D0835}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From 9345ee2ca52c4ffcd4cfab7e7ec869088ea882b5 Mon Sep 17 00:00:00 2001 From: uppuv Date: Tue, 22 Aug 2023 17:05:51 -0400 Subject: [PATCH 02/19] Removed QuestionGroup from the Question model and from the db entity --- .../Providers/EmployeesProvider.cs | 4 +-- .../Db/Question.cs | 1 - .../Models/Question.cs | 1 - .../Providers/QuestionsProvider.cs | 30 +++++++++---------- .../MockData.cs | 4 +-- 5 files changed, 18 insertions(+), 22 deletions(-) diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Providers/EmployeesProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Providers/EmployeesProvider.cs index b2ec99b..8e31e82 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Providers/EmployeesProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Providers/EmployeesProvider.cs @@ -151,8 +151,8 @@ namespace DamageAssesment.Api.Employees.Providers EmployeeDbContext.Employees.Add(new Db.Employee() { Id = "Emp2", Name = "ABC2", Email = "abc2@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-22), IsActive = true, PreferredLanguage = "fr" }); EmployeeDbContext.Employees.Add(new Db.Employee() { Id = "Emp3", Name = "ABC3", Email = "abc3@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-30) ,IsActive = true, PreferredLanguage = "fr" }); EmployeeDbContext.Employees.Add(new Db.Employee() { Id = "Emp4", Name = "ABC4", Email = "abc4@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-20) ,IsActive = true, PreferredLanguage = "en" }); - EmployeeDbContext.Employees.Add(new Db.Employee() { Id = "Emp5", Name = "ABC5", Email = "abc5@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-23) ,IsActive = true, PreferredLanguage = "sp" }); - EmployeeDbContext.Employees.Add(new Db.Employee() { Id = "Emp6", Name = "ABC6", Email = "abc6@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-32) ,IsActive = true, PreferredLanguage = "sp" }); + EmployeeDbContext.Employees.Add(new Db.Employee() { Id = "Emp5", Name = "ABC5", Email = "abc5@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-23) ,IsActive = true, PreferredLanguage = "es" }); + EmployeeDbContext.Employees.Add(new Db.Employee() { Id = "Emp6", Name = "ABC6", Email = "abc6@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-32) ,IsActive = true, PreferredLanguage = "es" }); EmployeeDbContext.SaveChanges(); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/Question.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/Question.cs index 846df86..29d0c64 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/Question.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/Question.cs @@ -20,7 +20,6 @@ namespace DamageAssesment.Api.Questions.Db public bool Key { get; set; } [ForeignKey("Survey")] public int? SurveyId { get; set; } - public string QuestionGroup { get; set; } [ForeignKey("QuestionCategory")] public int CategoryId { get; set; } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/Question.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/Question.cs index e181f1f..b694f5b 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/Question.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/Question.cs @@ -17,7 +17,6 @@ namespace DamageAssesment.Api.Questions.Models public bool Key { get; set; } public int? SurveyId { get; set; } - public string QuestionGroup { get; set; } public int CategoryId { get; set; } // public int? Survey_SurveyID { get; set; } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs index 647f640..565a16b 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs @@ -37,35 +37,33 @@ namespace DamageAssesment.Api.Questions.Providers questionDbContext.QuestionsTranslations.Add(new Db.QuestionsTranslation() { Id = 4, QuestionId = 2, QuestionText = "Les terrains sont-ils inondés ?", Language = "fr" }); questionDbContext.QuestionsTranslations.Add(new Db.QuestionsTranslation() { Id = 5, QuestionId = 3, QuestionText = "Is the access blocked by flooding ?", Language = "en" }); questionDbContext.QuestionsTranslations.Add(new Db.QuestionsTranslation() { Id = 6, QuestionId = 3, QuestionText = "L'accès est-il bloqué par les inondations ?", Language = "fr" }); - questionDbContext.QuestionsTranslations.Add(new Db.QuestionsTranslation() { Id = 7, QuestionId = 1, QuestionText = "Puedes abrir ?", Language = "sp" }); - questionDbContext.QuestionsTranslations.Add(new Db.QuestionsTranslation() { Id = 8, QuestionId = 2, QuestionText = "¿Están inundados los terrenos?", Language = "sp" }); - questionDbContext.QuestionsTranslations.Add(new Db.QuestionsTranslation() { Id = 9, QuestionId = 3, QuestionText = "¿El acceso está bloqueado por inundaciones?", Language = "sp" }); + questionDbContext.QuestionsTranslations.Add(new Db.QuestionsTranslation() { Id = 7, QuestionId = 1, QuestionText = "Puedes abrir ?", Language = "es" }); + questionDbContext.QuestionsTranslations.Add(new Db.QuestionsTranslation() { Id = 8, QuestionId = 2, QuestionText = "¿Están inundados los terrenos?", Language = "es" }); + questionDbContext.QuestionsTranslations.Add(new Db.QuestionsTranslation() { Id = 9, QuestionId = 3, QuestionText = "¿El acceso está bloqueado por inundaciones?", Language = "es" }); questionDbContext.SaveChanges(); } if (!questionDbContext.Questions.Any()) { - questionDbContext.Questions.Add(new Db.Question() { Id = 1, QuestionTypeId = 2, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, QuestionGroup = "group1",CategoryId=1 }); - questionDbContext.Questions.Add(new Db.Question() { Id = 2, QuestionTypeId = 1, SurveyId = 1, QuestionNumber = 2, IsRequired = false, Comment = true, Key = false, QuestionGroup = "group1", CategoryId = 1 }); - questionDbContext.Questions.Add(new Db.Question() { Id = 3, QuestionTypeId = 1, SurveyId = 1, QuestionNumber = 3, IsRequired = true, Comment = false, Key = true, QuestionGroup = "group1", CategoryId = 2 }); + questionDbContext.Questions.Add(new Db.Question() { Id = 1, QuestionTypeId = 2, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId=1 }); + questionDbContext.Questions.Add(new Db.Question() { Id = 2, QuestionTypeId = 1, SurveyId = 1, QuestionNumber = 2, IsRequired = false, Comment = true, Key = false, CategoryId = 1 }); + questionDbContext.Questions.Add(new Db.Question() { Id = 3, QuestionTypeId = 1, SurveyId = 1, QuestionNumber = 3, IsRequired = true, Comment = false, Key = true, CategoryId = 2 }); questionDbContext.SaveChanges(); } if (!questionDbContext.QuestionTypes.Any()) { - questionDbContext.QuestionTypes.Add(new Db.QuestionType() { Id = 1, TypeText = "Text 1" }); - questionDbContext.QuestionTypes.Add(new Db.QuestionType() { Id = 2, TypeText = "Text 2" }); - questionDbContext.QuestionTypes.Add(new Db.QuestionType() { Id = 3, TypeText = "Text 3" }); - questionDbContext.QuestionTypes.Add(new Db.QuestionType() { Id = 4, TypeText = "Text 4" }); - questionDbContext.QuestionTypes.Add(new Db.QuestionType() { Id = 5, TypeText = "Text 5" }); + questionDbContext.QuestionTypes.Add(new Db.QuestionType() { Id = 1, TypeText = "RadioButton" }); + questionDbContext.QuestionTypes.Add(new Db.QuestionType() { Id = 2, TypeText = "CheckBox" }); + questionDbContext.QuestionTypes.Add(new Db.QuestionType() { Id = 3, TypeText = "TextBox" }); questionDbContext.SaveChanges(); } if (!questionDbContext.QuestionCategories.Any()) { - questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 1, CategoryName = "Category 1", CategoryImage="img1" }); - questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 2, CategoryName = "Category 2", CategoryImage = "img1" }); - questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 3, CategoryName = "Category 3", CategoryImage = "img1" }); - questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 4, CategoryName = "Category 4", CategoryImage = "img1" }); - questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 5, CategoryName = "Category 5", CategoryImage = "img1" }); + questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 1, CategoryName = "Flooding", CategoryImage= "https://example.com/images/img1.png" }); + questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 2, CategoryName = "Electrical", CategoryImage = "https://example.com/images/img2.png" }); + questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 3, CategoryName = "Structural", CategoryImage = "https://example.com/images/img3.png" }); + questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 4, CategoryName = "Utility", CategoryImage = "https://example.com/images/img4.png" }); + questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 5, CategoryName = "Debris", CategoryImage = "https://example.com/images/img5.png" }); questionDbContext.SaveChanges(); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/MockData.cs b/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/MockData.cs index f9c0c87..be919ed 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/MockData.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/MockData.cs @@ -18,7 +18,7 @@ namespace DamageAssesment.Api.Questions.Test for (int i = 0; i < 10; i++) { - list.Append(new Questions.Models.Question { Id = i, TypeText = "Text" + i, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, QuestionGroup = "group1",CategoryId=i }); + list.Append(new Questions.Models.Question { Id = i, TypeText = "Text" + i, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId=i }); } return (true, list, null); } @@ -79,7 +79,7 @@ namespace DamageAssesment.Api.Questions.Test }; List QuestionsTranslations = new List(); QuestionsTranslations.Add(QuestionsTranslation); - return new Questions.Models.Question { Id = 1, Questions=QuestionsTranslations, TypeText = "Text 1", SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, QuestionGroup = "group1" ,CategoryId=1}; + return new Questions.Models.Question { Id = 1, Questions=QuestionsTranslations, TypeText = "Text 1", SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId=1}; } From e56ffae1a4b2e332be3a8839db66b81c6e0dbda5 Mon Sep 17 00:00:00 2001 From: Santhosh S <913341@dadeschools.net> Date: Thu, 24 Aug 2023 21:25:38 -0400 Subject: [PATCH 03/19] Swagger Documentation Enhancement (273) --- .../Controllers/AnswersController.cs | 34 ++++++++--- .../DamageAssesment.Api.Answers.csproj | 1 + .../DamageAssesment.Api.Answers/Program.cs | 10 +++- .../Controllers/AttachmentsController.cs | 22 ++++++-- .../DamageAssesment.Api.Attachments.csproj | 1 + .../Program.cs | 10 +++- .../Controllers/EmployeesController.cs | 30 ++++++++-- .../DamageAssesment.Api.Employees.csproj | 3 +- .../DamageAssesment.Api.Employees/Program.cs | 11 +++- .../Controllers/LocationsController.cs | 25 +++++++-- .../Controllers/RegionsController.cs | 17 +++++- .../DamageAssesment.Api.Locations.csproj | 1 + .../DamageAssesment.Api.Locations/Program.cs | 11 +++- .../Controllers/QuestionsController.cs | 56 +++++++++++++++---- .../DamageAssesment.Api.Questions.csproj | 3 +- .../DamageAssesment.Api.Questions/Program.cs | 10 +++- .../Controllers/SurveyResponsesController.cs | 49 +++++++++++++++- ...DamageAssesment.Api.SurveyResponses.csproj | 1 + .../Program.cs | 10 +++- .../Controllers/SurveysController.cs | 19 ++++++- .../DamageAssesment.Api.Survey.csproj | 3 +- .../DamageAssesment.Api.Surveys/Program.cs | 10 +++- 22 files changed, 288 insertions(+), 49 deletions(-) diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs index 27f5c3c..a8fefff 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs @@ -14,7 +14,10 @@ namespace DamageAssesment.Api.Answers.Controllers public AnswersController(IAnswersProvider answersProvider) { this.answerProvider=answersProvider; } - //get all answers + /// + /// Get all answers + /// + [HttpGet("Answers")] public async Task GetAnswersAsync() { @@ -26,7 +29,11 @@ namespace DamageAssesment.Api.Answers.Controllers return NoContent(); } - //get answer based on answerid + /// + /// Get an answer based on answerId. + /// + + [HttpGet("Answers/{Id}")] public async Task GetAnswerByIdAsync(int Id) { @@ -39,7 +46,9 @@ namespace DamageAssesment.Api.Answers.Controllers return NotFound(); } - // get all answers based on response id + /// + /// Get all answers based on responseId. + /// [HttpGet("AnswersByResponse/{ResponseId}")] public async Task GetAnswersByResponseId(int ResponseId) { @@ -50,7 +59,10 @@ namespace DamageAssesment.Api.Answers.Controllers } return NoContent(); } - // get all answers based on question id + /// + /// Get all answers based on questionId. + /// + [HttpGet("AnswersByQuestion/{QuestionId}")] public async Task AnswersByQuestionId(int QuestionId) { @@ -61,7 +73,9 @@ namespace DamageAssesment.Api.Answers.Controllers } return NotFound(); } - //update existing answer + /// + /// Update an existing answer. + /// [HttpPut("Answers")] public async Task UpdateAnswer(Db.Answer answer) @@ -80,7 +94,10 @@ namespace DamageAssesment.Api.Answers.Controllers } return NotFound(); } - //save new answer + /// + /// Save a new answer. + /// + [HttpPost("Answers")] public async Task CreateAnswer(Db.Answer answer) { @@ -95,7 +112,10 @@ namespace DamageAssesment.Api.Answers.Controllers } return CreatedAtRoute("DefaultApi", new { id = answer.Id }, answer); } - //delete existing answer + /// + /// Delete an existing answer. + /// + [HttpDelete("Answers/{id}")] public async Task DeleteAnswer(int id) { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/DamageAssesment.Api.Answers.csproj b/DamageAssesmentApi/DamageAssesment.Api.Answers/DamageAssesment.Api.Answers.csproj index ca5ee38..b60fc33 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/DamageAssesment.Api.Answers.csproj +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/DamageAssesment.Api.Answers.csproj @@ -4,6 +4,7 @@ net6.0 enable enable + True diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Program.cs index 7630089..373d300 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Program.cs @@ -2,6 +2,7 @@ using DamageAssesment.Api.Answers.Db; using DamageAssesment.Api.Answers.Interfaces; using DamageAssesment.Api.Answers.Providers; using Microsoft.EntityFrameworkCore; +using System.Reflection; var builder = WebApplication.CreateBuilder(args); @@ -10,7 +11,14 @@ var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); +//builder.Services.AddSwaggerGen(); +builder.Services.AddSwaggerGen(c => +{ + // Include XML comments from your assembly + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + c.IncludeXmlComments(xmlPath); +}); builder.Services.AddScoped(); builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); //4/30 builder.Services.AddDbContext(option => diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs index a86a151..11cec22 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs @@ -19,7 +19,10 @@ namespace DamageAssesment.Api.Attachments.Controllers this.AttachmentProvider = AttachmentsProvider; this.UploadService = uploadService; } - //get all Attachments + /// + /// Get all attachments. + /// + [HttpGet("Attachments")] public async Task GetAttachmentsAsync() { @@ -32,7 +35,9 @@ namespace DamageAssesment.Api.Attachments.Controllers return NoContent(); } - //get all Attachment by Id + /// + /// Get all attachments by attachmentId. + /// [HttpGet("Attachments/{id}")] public async Task GetAttachmentbyIdAsync(int id) { @@ -73,7 +78,10 @@ namespace DamageAssesment.Api.Attachments.Controllers // } //} - //Save new Attachment + /// + /// Save new Attachment(s) + /// + [HttpPost("Attachments"), DisableRequestSizeLimit] public async Task UploadAttachmentAsync(AttachmentInfo attachmentInfo) { @@ -97,8 +105,10 @@ namespace DamageAssesment.Api.Attachments.Controllers return BadRequest($"Internal server error: {ex}"); } } + /// + /// Modify an new attachment. + /// - //Save new Attachment [HttpPut("Attachments"), DisableRequestSizeLimit] public async Task UpdateAttachmentAsync(AttachmentInfo attachmentInfo) { @@ -126,7 +136,9 @@ namespace DamageAssesment.Api.Attachments.Controllers return BadRequest($"Internal server error: {ex}"); } } - //delete existing Attachment + /// + /// Delete an existing attachment. + /// [HttpDelete("Delete")] public async Task DeleteAttachment(int Id) { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/DamageAssesment.Api.Attachments.csproj b/DamageAssesmentApi/DamageAssesment.Api.Attachments/DamageAssesment.Api.Attachments.csproj index 3454bff..846a5c2 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/DamageAssesment.Api.Attachments.csproj +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/DamageAssesment.Api.Attachments.csproj @@ -4,6 +4,7 @@ net6.0 enable enable + True diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Program.cs index d661ef6..61ce1c5 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Program.cs @@ -4,6 +4,7 @@ using DamageAssesment.Api.Attachments.Providers; using Microsoft.AspNetCore.Http.Features; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.FileProviders; +using System.Reflection; var builder = WebApplication.CreateBuilder(args); @@ -12,7 +13,14 @@ var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); +//builder.Services.AddSwaggerGen(); +builder.Services.AddSwaggerGen(c => +{ + // Include XML comments from your assembly + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + c.IncludeXmlComments(xmlPath); +}); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Controllers/EmployeesController.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Controllers/EmployeesController.cs index 192a9d0..a074f21 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Controllers/EmployeesController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Controllers/EmployeesController.cs @@ -15,7 +15,11 @@ namespace DamageAssesment.Api.Employees.Controllers { this.EmployeeProvider = EmployeesProvider; } - //get all Employees + + /// + /// GET request for retrieving employees. + /// + [HttpGet("Employees")] public async Task GetEmployeesAsync() { @@ -28,7 +32,11 @@ namespace DamageAssesment.Api.Employees.Controllers return NoContent(); } - //get Employee based on Employeeid + + /// + /// GET request for retrieving an employee by ID. + /// + [HttpGet("Employees/{Id}")] public async Task GetEmployeeByIdAsync(string Id) { @@ -41,8 +49,11 @@ namespace DamageAssesment.Api.Employees.Controllers return NotFound(); } - //update existing Employee - + + /// + /// PUT request for updating an existing employee. + /// + /// The updated employee object. [HttpPut("Employees")] public async Task UpdateEmployee(Db.Employee Employee) { @@ -60,7 +71,11 @@ namespace DamageAssesment.Api.Employees.Controllers } return NotFound(); } - //save new Employee + + /// + /// POST request for creating a new employee. + /// + /// The employee information for creating a new employee. [HttpPost("Employees")] public async Task CreateEmployee(Db.Employee Employee) { @@ -75,7 +90,10 @@ namespace DamageAssesment.Api.Employees.Controllers } return CreatedAtRoute("DefaultApi", new { id = Employee.Id }, Employee); } - //delete existing Employee + /// + /// DELETE request for deleting an existing employee. + /// + /// The ID of the employee to be deleted. [HttpDelete("Employees/{id}")] public async Task DeleteEmployee(string id) { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/DamageAssesment.Api.Employees.csproj b/DamageAssesmentApi/DamageAssesment.Api.Employees/DamageAssesment.Api.Employees.csproj index 53e8700..7f05c71 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/DamageAssesment.Api.Employees.csproj +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/DamageAssesment.Api.Employees.csproj @@ -1,9 +1,10 @@ - + net6.0 enable enable + True diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Program.cs index 29b91fa..7d5dbff 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Program.cs @@ -2,6 +2,7 @@ using DamageAssesment.Api.Employees.Db; using DamageAssesment.Api.Employees.Interfaces; using DamageAssesment.Api.Employees.Providers; using Microsoft.EntityFrameworkCore; +using System.Reflection; var builder = WebApplication.CreateBuilder(args); @@ -10,7 +11,15 @@ var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); +//builder.Services.AddSwaggerGen(); +builder.Services.AddSwaggerGen(c => +{ + // Include XML comments from your assembly + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + c.IncludeXmlComments(xmlPath); +}); + builder.Services.AddScoped(); builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); //4/30 builder.Services.AddDbContext(option => diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs index c1df10f..040bd93 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs @@ -14,7 +14,10 @@ namespace DamageAssesment.Api.Locations.Controllers { this.LocationProvider = LocationsProvider; } - // Get all Locations + /// + /// Get all locations. + /// + [HttpGet("Locations")] public async Task GetLocationsAsync() { @@ -27,7 +30,10 @@ namespace DamageAssesment.Api.Locations.Controllers return NotFound(); } - // Get all Location based on Id + /// + /// Get all locations based on locationdId. + /// + [HttpGet("Locations/{id}")] public async Task GetLocationByIdAsync(string id) { @@ -40,7 +46,10 @@ namespace DamageAssesment.Api.Locations.Controllers return NotFound(); } - // Update Location entity + /// + /// Update a Location. + /// + [HttpPut("Locations")] public async Task UpdateLocation(Db.Location Location) { @@ -55,7 +64,10 @@ namespace DamageAssesment.Api.Locations.Controllers } return NotFound(); } - //save new location + /// + /// Save a new location. + /// + [HttpPost("Locations")] public async Task CreateLocation(Db.Location Location) { @@ -70,7 +82,10 @@ namespace DamageAssesment.Api.Locations.Controllers } return CreatedAtRoute("DefaultApi", new { id = Location.Id }, Location); } - //delete existing location + /// + /// Delete an existing location. + /// + [HttpDelete("Locations/{id}")] public async Task DeleteLocation(string id) { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/RegionsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/RegionsController.cs index 64a9bc7..81725e4 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/RegionsController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/RegionsController.cs @@ -13,8 +13,10 @@ namespace DamageAssesment.Api.Locations.Controllers { this.regionProvider = regionProvider; } + /// + /// Get all regions. + /// - // Get all Regions [HttpGet] public async Task GetRegionsAsync() { @@ -25,6 +27,9 @@ namespace DamageAssesment.Api.Locations.Controllers } return NoContent(); } + /// + /// GET request for retrieving a region by its ID. + /// [HttpGet("{Id}")] public async Task GetRegionAsync(string Id) @@ -36,6 +41,9 @@ namespace DamageAssesment.Api.Locations.Controllers } return NotFound(); } + /// + /// POST request for creating a new region. + /// [HttpPost] public async Task PostRegionAsync(Models.Region region) @@ -47,6 +55,9 @@ namespace DamageAssesment.Api.Locations.Controllers } return BadRequest(result.ErrorMessage); } + /// + /// PUT request for updating an existing region. + /// [HttpPut] public async Task PutRegionAsync(Models.Region region) @@ -61,6 +72,10 @@ namespace DamageAssesment.Api.Locations.Controllers return BadRequest(result.ErrorMessage); } + /// + /// DELETE request for deleting a region based on ID. + /// + [HttpDelete("{Id}")] public async Task DeleteRegionAsync(string Id) diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/DamageAssesment.Api.Locations.csproj b/DamageAssesmentApi/DamageAssesment.Api.Locations/DamageAssesment.Api.Locations.csproj index 47751c7..7f05c71 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/DamageAssesment.Api.Locations.csproj +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/DamageAssesment.Api.Locations.csproj @@ -4,6 +4,7 @@ net6.0 enable enable + True diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Program.cs index a2e3149..c152e61 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Program.cs @@ -2,6 +2,7 @@ using DamageAssesment.Api.Locations.Db; using DamageAssesment.Api.Locations.Interfaces; using DamageAssesment.Api.Locations.Providers; using Microsoft.EntityFrameworkCore; +using System.Reflection; var builder = WebApplication.CreateBuilder(args); @@ -10,8 +11,14 @@ var builder = WebApplication.CreateBuilder(args); builder.Services.AddControllers(); // Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); - +//builder.Services.AddSwaggerGen(); +builder.Services.AddSwaggerGen(c => +{ + // Include XML comments from your assembly + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + c.IncludeXmlComments(xmlPath); +}); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); //4/30 diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs index 0184d72..2519941 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs @@ -19,7 +19,10 @@ namespace DamageAssesment.Api.Questions.Controllers this.questionsProvider = questionsProvider; } - // get all questions + /// + /// GET request for retrieving questions. + /// + [HttpGet("Questions")] public async Task GetQuestionsAsync() { @@ -30,7 +33,10 @@ namespace DamageAssesment.Api.Questions.Controllers } return NoContent(); } - //Get questions based on question id + /// + /// GET request for retrieving a question by ID. + /// + [HttpGet("Questions/{id}")] public async Task GetQuestionAsync(int id) { @@ -41,7 +47,11 @@ namespace DamageAssesment.Api.Questions.Controllers } return NotFound(); } - //get all questions based on survey id + /// + /// GET request for retrieving survey questions based on a survey ID. + /// Uri: {Optional language}/GetSurveyQuestions/{surveyId} :Default returns question in all languages + /// + [HttpGet("GetSurveyQuestions/{surveyId}")] public async Task GetSurveyQuestions(int surveyId,string? Language) { @@ -53,7 +63,10 @@ namespace DamageAssesment.Api.Questions.Controllers } return NotFound(); } - //update existing question + /// + /// PUT request for updating a question (multilingual). + /// + [HttpPut("Questions")] public async Task UpdateQuestion(Models.Question question) { @@ -71,7 +84,10 @@ namespace DamageAssesment.Api.Questions.Controllers } return CreatedAtRoute("DefaultApi", new { id = question.Id }, question); } - //save new question + /// + /// POST request for creating a new question (multilingual). + /// + [HttpPost("Questions")] public async Task CreateQuestion(Models.Question question) { @@ -86,7 +102,10 @@ namespace DamageAssesment.Api.Questions.Controllers } return CreatedAtRoute("DefaultApi", new { id = question.Id }, question); } - // delete existing question + /// + /// DELETE request for deleting a question based on ID. + /// + [HttpDelete("Questions/{id}")] public async Task DeleteQuestion(int id) { @@ -99,7 +118,10 @@ namespace DamageAssesment.Api.Questions.Controllers } - // get all questions + /// + /// GET request for retrieving question categories. + /// + [HttpGet("QuestionCategories")] public async Task GetQuestionCategoriesAsync() { @@ -110,7 +132,10 @@ namespace DamageAssesment.Api.Questions.Controllers } return NoContent(); } - //Get questions based on question id + /// + /// GET request for retrieving a question category by ID. + /// + [HttpGet("QuestionCategories/{id}")] public async Task GetQuestionCategoryAsync(int id) { @@ -123,7 +148,10 @@ namespace DamageAssesment.Api.Questions.Controllers } - //update existing question + /// + /// PUT request for updating a question category. + /// + [HttpPut("QuestionCategories")] public async Task UpdateQuestionCategory(Models.QuestionCategory questionCategory) { @@ -141,7 +169,10 @@ namespace DamageAssesment.Api.Questions.Controllers } return CreatedAtRoute("DefaultApi", new { id = questionCategory.Id }, questionCategory); } - //save new question + /// + /// POST request for creating a new question category. + /// + [HttpPost("QuestionCategories")] public async Task CreateQuestionCategory(Models.QuestionCategory questionCategory) { @@ -156,7 +187,10 @@ namespace DamageAssesment.Api.Questions.Controllers } return CreatedAtRoute("DefaultApi", new { id = questionCategory.Id }, questionCategory); } - // delete existing question + /// + /// DELETE request for deleting a question category based on ID. + /// + [HttpDelete("QuestionCategories/{id}")] public async Task DeleteQuestionCategory(int id) { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/DamageAssesment.Api.Questions.csproj b/DamageAssesmentApi/DamageAssesment.Api.Questions/DamageAssesment.Api.Questions.csproj index 53e8700..7f05c71 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/DamageAssesment.Api.Questions.csproj +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/DamageAssesment.Api.Questions.csproj @@ -1,9 +1,10 @@ - + net6.0 enable enable + True diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Program.cs index 3774b0b..321c989 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Program.cs @@ -3,6 +3,7 @@ using DamageAssesment.Api.Questions.Interfaces; using DamageAssesment.Api.Questions.Providers; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.Options; +using System.Reflection; var builder = WebApplication.CreateBuilder(args); @@ -17,7 +18,14 @@ builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); +//builder.Services.AddSwaggerGen(); +builder.Services.AddSwaggerGen(c => +{ + // Include XML comments from your assembly + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + c.IncludeXmlComments(xmlPath); +}); builder.Services.AddDbContext(option => { option.UseInMemoryDatabase("Questions"); diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Controllers/SurveyResponsesController.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Controllers/SurveyResponsesController.cs index 42b29dc..b3ff885 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Controllers/SurveyResponsesController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Controllers/SurveyResponsesController.cs @@ -16,6 +16,9 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers { this.surveyResponseProvider = surveyResponseProvider; } + /// + /// GET request for retrieving survey responses. + /// [HttpGet("SurveyResponses")] public async Task GetSurveyResponsesAsync() @@ -31,7 +34,10 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers return BadRequest(result.ErrorMessage); } - + /// + /// GET request for retrieving survey responses by survey ID. + /// + [HttpGet("SurveyResponses/{surveyId}")] public async Task GetSurveyResponsesAsync(int surveyId) { @@ -42,6 +48,11 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers } return NoContent(); } + /// + /// GET request for retrieving survey responses by survey and location IDs. + /// + /// The ID of the survey for which responses are to be retrieved. + /// The ID of the location for which responses are to be retrieved. [HttpGet("Responses/{surveyId}/{locationId}")] public async Task GetSurveyResponsesBySurveyAndLocationAsync(int surveyId, string locationId) @@ -54,6 +65,12 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers return NoContent(); } + /// + /// GET request for retrieving survey responses by survey, question, and answer. + /// + /// The ID of the survey for which responses are to be retrieved. + /// The ID of the question for which responses are to be retrieved. + /// The answer for which responses are to be retrieved. [HttpGet("ResponsesByAnswer/{surveyId}/{questionId}/{answer}")] public async Task GetSurveyResponsesByAnswerAsyncAsync(int surveyId, int questionId, string answer) @@ -66,6 +83,10 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers return NoContent(); } + /// + /// GET request for retrieving answers from survey responses by survey ID and region. + /// + /// The ID of the survey for which answers are to be retrieved. [HttpGet("AnswersByRegion/{surveyId}")] public async Task GetAnswersByRegionAsync(int surveyId) @@ -77,6 +98,10 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers } return NoContent(); } + /// + /// GET request for retrieving survey responses by survey ID and maintenance center. + /// + /// The ID of the survey for which responses are to be retrieved. [HttpGet("AnswersByMaintenanceCenter/{surveyId}")] public async Task GetAnswersByMaintenaceCentersync(int surveyId) @@ -88,6 +113,10 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers } return NoContent(); } + /// + /// GET request for retrieving a survey response by response ID. + /// + /// The ID of the survey response to be retrieved. [HttpGet("SurveyResponse/{responseId}")] public async Task GetSurveyResponseByIdAsync(int responseId) @@ -100,6 +129,10 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers return NoContent(); } + /// + /// POST request for creating a new survey response. + /// + /// The survey response object to be created. [HttpPost("SurveyResponses")] public async Task PostSurveysAsync(Models.SurveyResponse surveyResponse) @@ -111,6 +144,11 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers } return BadRequest(result.ErrorMessage); } + /// + /// PUT request for updating an existing survey response. + /// + /// The ID of the survey response to be updated. + /// The updated survey response object. [HttpPut("SurveyResponses/{Id}")] public async Task PutSurveyResponseAsync(int Id, Models.SurveyResponse surveyResponse) @@ -125,7 +163,10 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers return BadRequest(result.ErrorMessage); } - + /// + /// DELETE request for deleting an existing survey response. + /// + [HttpDelete("SurveyResponses/{Id}")] public async Task DeleteSurveyResponseAsync(int Id) { @@ -136,6 +177,10 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers } return NotFound(); } + /// + /// POST request for submitting survey with multiple answers. + /// + /// The answers to be submitted for the survey. [HttpPost("SurveyResponses/Answers")] public async Task PostSurveyAnswersAsync(AnswerRequest answers) diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/DamageAssesment.Api.SurveyResponses.csproj b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/DamageAssesment.Api.SurveyResponses.csproj index a2383fa..aae62bb 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/DamageAssesment.Api.SurveyResponses.csproj +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/DamageAssesment.Api.SurveyResponses.csproj @@ -4,6 +4,7 @@ net6.0 enable enable + True diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Program.cs index b94d753..a4f585f 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Program.cs @@ -4,6 +4,7 @@ using DamageAssesment.Api.SurveyResponses.Providers; using Microsoft.AspNetCore.DataProtection.XmlEncryption; using Microsoft.EntityFrameworkCore; using Polly; +using System.Reflection; var builder = WebApplication.CreateBuilder(args); const int maxApiCallRetries = 3; @@ -50,7 +51,14 @@ builder.Services.AddHttpClient(). builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); +//builder.Services.AddSwaggerGen(); +builder.Services.AddSwaggerGen(c => +{ + // Include XML comments from your assembly + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + c.IncludeXmlComments(xmlPath); +}); builder.Services.AddDbContext(option => { option.UseInMemoryDatabase("SurveyResponses"); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs index 56f2e29..7644a69 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs @@ -14,6 +14,9 @@ namespace DamageAssesment.Api.Surveys.Controllers { this.surveyProvider = surveyProvider; } + /// + /// GET request for retrieving surveys. + /// [HttpGet] public async Task GetSurveysAsync() @@ -25,6 +28,10 @@ namespace DamageAssesment.Api.Surveys.Controllers } return NoContent(); } + /// + /// GET request for retrieving surveys by ID. + /// + [HttpGet("{Id}")] public async Task GetSurveysAsync(int Id) { @@ -35,6 +42,9 @@ namespace DamageAssesment.Api.Surveys.Controllers } return NotFound(); } + /// + /// POST request for creating a new survey. + /// [HttpPost] public async Task PostSurveysAsync(Models.Survey survey) @@ -46,6 +56,10 @@ namespace DamageAssesment.Api.Surveys.Controllers } return BadRequest(result.ErrorMessage); } + /// + /// PUT request for updating an existing survey (surveyId,Updated Survey data). + /// + [HttpPut("{Id}")] public async Task PutSurveysAsync(int Id, Models.Survey survey) @@ -60,7 +74,10 @@ namespace DamageAssesment.Api.Surveys.Controllers return BadRequest(result.ErrorMessage); } - + /// + /// DELETE request for deleting a survey by ID. + /// + [HttpDelete("{Id}")] public async Task DeleteSurveysAsync(int Id) { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/DamageAssesment.Api.Survey.csproj b/DamageAssesmentApi/DamageAssesment.Api.Surveys/DamageAssesment.Api.Survey.csproj index 53e8700..7f05c71 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/DamageAssesment.Api.Survey.csproj +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/DamageAssesment.Api.Survey.csproj @@ -1,9 +1,10 @@ - + net6.0 enable enable + True diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Program.cs index ebb638f..f59b686 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Program.cs @@ -2,6 +2,7 @@ using DamageAssesment.Api.Surveys.Db; using DamageAssesment.Api.Surveys.Interfaces; using DamageAssesment.Api.Surveys.Providers; using Microsoft.EntityFrameworkCore; +using System.Reflection; var builder = WebApplication.CreateBuilder(args); @@ -12,7 +13,14 @@ builder.Services.AddControllers(); builder.Services.AddScoped(); builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); +//builder.Services.AddSwaggerGen(); +builder.Services.AddSwaggerGen(c => +{ + // Include XML comments from your assembly + var xmlFile = $"{Assembly.GetExecutingAssembly().GetName().Name}.xml"; + var xmlPath = Path.Combine(AppContext.BaseDirectory, xmlFile); + c.IncludeXmlComments(xmlPath); +}); builder.Services.AddDbContext(option => { option.UseInMemoryDatabase("Surveys"); From cf3a04891b7b50d0a02ac9c8b9a78ccb9436c35c Mon Sep 17 00:00:00 2001 From: uppuv Date: Fri, 25 Aug 2023 07:20:37 -0400 Subject: [PATCH 04/19] Completed sync call for answer and attachment put and post methods --- .../Controllers/AnswersController.cs | 8 ++++---- .../Interfaces/IAnswersProvider.cs | 4 ++-- .../Providers/AnswerProvider.cs | 4 ++-- .../Controllers/AttachmentsController.cs | 12 ++++++------ .../Interfaces/IAttachmentsProvider.cs | 8 ++++---- .../Providers/AttachmentsProvider.cs | 8 ++++---- 6 files changed, 22 insertions(+), 22 deletions(-) diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs index a8fefff..95b2aab 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs @@ -78,11 +78,11 @@ namespace DamageAssesment.Api.Answers.Controllers /// [HttpPut("Answers")] - public async Task UpdateAnswer(Db.Answer answer) + public IActionResult UpdateAnswer(Db.Answer answer) { if (answer != null) { - var result = await this.answerProvider.UpdateAnswerAsync(answer); + var result = this.answerProvider.UpdateAnswerAsync(answer); if (result.IsSuccess) { return Ok(result.Answer); @@ -99,11 +99,11 @@ namespace DamageAssesment.Api.Answers.Controllers /// [HttpPost("Answers")] - public async Task CreateAnswer(Db.Answer answer) + public IActionResult CreateAnswer(Db.Answer answer) { if (answer != null) { - var result = await this.answerProvider.PostAnswerAsync(answer); + var result = this.answerProvider.PostAnswerAsync(answer); if (result.IsSuccess) { return Ok(result.Answer); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Interfaces/IAnswersProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Interfaces/IAnswersProvider.cs index 4a202f1..4b5fcc1 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Interfaces/IAnswersProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Interfaces/IAnswersProvider.cs @@ -6,8 +6,8 @@ Task<(bool IsSuccess, IEnumerable Answers, string ErrorMessage)> GetAnswersByQuestionAsync(int questionId); Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> GetAnswerByIdAsync(int Id); Task<(bool IsSuccess, IEnumerable Answers, string ErrorMessage)> GetAnswersAsync(int responseId); - Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> PostAnswerAsync(Db.Answer Answer); - Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> UpdateAnswerAsync(Db.Answer Answer); + (bool IsSuccess, Models.Answer Answer, string ErrorMessage) PostAnswerAsync(Db.Answer Answer); + (bool IsSuccess, Models.Answer Answer, string ErrorMessage) UpdateAnswerAsync(Db.Answer Answer); Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> DeleteAnswerAsync(int Id); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs index b1851d8..f7f2268 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs @@ -108,7 +108,7 @@ namespace DamageAssesment.Api.Answers.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> PostAnswerAsync(Db.Answer Answer) + public (bool IsSuccess, Models.Answer Answer, string ErrorMessage) PostAnswerAsync(Db.Answer Answer) { try { @@ -128,7 +128,7 @@ namespace DamageAssesment.Api.Answers.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> UpdateAnswerAsync(Db.Answer Answer) + public (bool IsSuccess, Models.Answer Answer, string ErrorMessage) UpdateAnswerAsync(Db.Answer Answer) { try { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs index 11cec22..745db41 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs @@ -83,15 +83,15 @@ namespace DamageAssesment.Api.Attachments.Controllers /// [HttpPost("Attachments"), DisableRequestSizeLimit] - public async Task UploadAttachmentAsync(AttachmentInfo attachmentInfo) + public IActionResult UploadAttachmentAsync(AttachmentInfo attachmentInfo) { try { if (attachmentInfo.Answers.Count > 0) { - var Attachments = await this.AttachmentProvider.GetAttachmentCounter(); + var Attachments = this.AttachmentProvider.GetAttachmentCounter(); List attachments = UploadService.UploadAttachment(attachmentInfo.ResponseId, Attachments.counter, attachmentInfo.Answers); - var result = await this.AttachmentProvider.PostAttachmentAsync(attachments); + var result = this.AttachmentProvider.PostAttachmentAsync(attachments); if (result.IsSuccess) { return Ok(result.Attachments); @@ -110,17 +110,17 @@ namespace DamageAssesment.Api.Attachments.Controllers /// [HttpPut("Attachments"), DisableRequestSizeLimit] - public async Task UpdateAttachmentAsync(AttachmentInfo attachmentInfo) + public IActionResult UpdateAttachmentAsync(AttachmentInfo attachmentInfo) { try { if (attachmentInfo.Answers.Count > 0) { - var res = await this.AttachmentProvider.GetAttachmentInfo(attachmentInfo.Answers); + var res = this.AttachmentProvider.GetAttachmentInfo(attachmentInfo.Answers); if (res.IsSuccess) { List attachments = UploadService.UpdateAttachments(attachmentInfo.ResponseId, attachmentInfo.Answers, res.Attachments); - var result = await this.AttachmentProvider.PutAttachmentAsync(attachments); + var result = this.AttachmentProvider.PutAttachmentAsync(attachments); if (result.IsSuccess) { return Ok(result.Attachments); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IAttachmentsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IAttachmentsProvider.cs index f193e11..81bc749 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IAttachmentsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IAttachmentsProvider.cs @@ -6,12 +6,12 @@ namespace DamageAssesment.Api.Attachments.Interfaces { Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> GetAttachmentsAsync(); Task<(bool IsSuccess, Models.Attachment Attachment, string ErrorMessage)> GetAttachmentByIdAsync(int Id); - Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> PostAttachmentAsync(List Attachments); - Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> PutAttachmentAsync(List Attachments); + (bool IsSuccess, IEnumerable Attachments, string ErrorMessage) PostAttachmentAsync(List Attachments); + (bool IsSuccess, IEnumerable Attachments, string ErrorMessage) PutAttachmentAsync(List Attachments); Task<(bool IsSuccess, Models.Attachment Attachment, string Path)> DeleteAttachmentAsync(int Id); Task<(bool IsSuccess, int counter, string Path)> DeleteAttachmentsAsync(int responseId, int answerId); Task<(bool IsSuccess, int counter, string Path)> DeleteBulkAttachmentsAsync(int responseId, List answerIds); - Task<(bool IsSuccess, int counter, string message)> GetAttachmentCounter(); - Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> GetAttachmentInfo(List answers); + (bool IsSuccess, int counter, string message) GetAttachmentCounter(); + (bool IsSuccess, IEnumerable Attachments, string ErrorMessage) GetAttachmentInfo(List answers); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/AttachmentsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/AttachmentsProvider.cs index 6a3cc63..aa42d93 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/AttachmentsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/AttachmentsProvider.cs @@ -65,7 +65,7 @@ namespace DamageAssesment.Api.Attachments.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> PostAttachmentAsync(List Attachments) + public (bool IsSuccess, IEnumerable Attachments, string ErrorMessage) PostAttachmentAsync(List Attachments) { try { @@ -82,7 +82,7 @@ namespace DamageAssesment.Api.Attachments.Providers } } - public async Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> PutAttachmentAsync(List Attachments) + public (bool IsSuccess, IEnumerable Attachments, string ErrorMessage) PutAttachmentAsync(List Attachments) { try { @@ -119,7 +119,7 @@ namespace DamageAssesment.Api.Attachments.Providers return (false, AttachmentId, ""); } } - public async Task<(bool IsSuccess,int counter,string message)> GetAttachmentCounter() + public (bool IsSuccess,int counter,string message) GetAttachmentCounter() { try { @@ -152,7 +152,7 @@ namespace DamageAssesment.Api.Attachments.Providers return (false, AttachmentId, ""); } } - public async Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)>GetAttachmentInfo(List answers) + public (bool IsSuccess, IEnumerable Attachments, string ErrorMessage) GetAttachmentInfo(List answers) { try { From 47b0c7b202264fba2c88bdc5bef7966d9fe54e6b Mon Sep 17 00:00:00 2001 From: Reginald Cherenfant Jasmin Date: Fri, 25 Aug 2023 08:55:11 -0400 Subject: [PATCH 05/19] Update Question and Survey to support multilingual functionnality and Make language optional in URL --- .../Controllers/QuestionsController.cs | 27 +-- .../Interfaces/IQuestionsProvider.cs | 4 +- .../Providers/QuestionsProvider.cs | 76 +++++--- .../QuestionsServiceTest.cs | 25 +-- .../Models/Survey.cs | 18 +- .../Models/SurveyTranslation.cs | 13 ++ .../MockData.cs | 4 +- .../SurveyServiceTest.cs | 16 +- .../Controllers/SurveysController.cs | 27 +-- .../DamageAssesment.Api.Surveys/Db/Survey.cs | 16 +- .../Db/SurveyTranslation.cs | 23 +++ .../Db/SurveysDbContext.cs | 2 +- .../Interfaces/ISurveyProvider.cs | 4 +- .../Models/Survey.cs | 18 +- .../Models/SurveyTranslation.cs | 13 ++ .../Providers/SurveysProvider.cs | 169 ++++++++++++++++-- 16 files changed, 321 insertions(+), 134 deletions(-) create mode 100644 DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/SurveyTranslation.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/SurveyTranslation.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/SurveyTranslation.cs diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs index 0184d72..d376c20 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs @@ -1,8 +1,4 @@ -using DamageAssesment.Api.Questions.Db; -using DamageAssesment.Api.Questions.Interfaces; -using DamageAssesment.Api.Questions.Models; -using DamageAssesment.Api.Questions.Providers; -using Microsoft.AspNetCore.Http; +using DamageAssesment.Api.Questions.Interfaces; using Microsoft.AspNetCore.Mvc; namespace DamageAssesment.Api.Questions.Controllers @@ -20,10 +16,12 @@ namespace DamageAssesment.Api.Questions.Controllers } // get all questions - [HttpGet("Questions")] - public async Task GetQuestionsAsync() + [Route("{Language}/Questions")] + [Route("Questions")] + [HttpGet] + public async Task GetQuestionsAsync(string? Language) { - var result = await this.questionsProvider.GetQuestionsAsync(); + var result = await this.questionsProvider.GetQuestionsAsync(Language); if (result.IsSuccess) { return Ok(result.Questions); @@ -31,10 +29,12 @@ namespace DamageAssesment.Api.Questions.Controllers return NoContent(); } //Get questions based on question id - [HttpGet("Questions/{id}")] - public async Task GetQuestionAsync(int id) + [Route("{Language}/Questions/{id}")] + [Route("Questions/{id}")] + [HttpGet] + public async Task GetQuestionAsync(int id, string? Language) { - var result = await this.questionsProvider.GetQuestionAsync(id); + var result = await this.questionsProvider.GetQuestionAsync(id,Language); if (result.IsSuccess) { return Ok(result.Question); @@ -42,10 +42,11 @@ namespace DamageAssesment.Api.Questions.Controllers return NotFound(); } //get all questions based on survey id - [HttpGet("GetSurveyQuestions/{surveyId}")] + [Route("{Language}/GetSurveyQuestions/{surveyId}")] + [Route("GetSurveyQuestions/{surveyId}")] + [HttpGet] public async Task GetSurveyQuestions(int surveyId,string? Language) { - if (string.IsNullOrEmpty(Language)) Language = "en"; var result = await this.questionsProvider.GetSurveyQuestionAsync(surveyId, Language); if (result.IsSuccess) { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Interfaces/IQuestionsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Interfaces/IQuestionsProvider.cs index 0f62339..43aa2e3 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Interfaces/IQuestionsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Interfaces/IQuestionsProvider.cs @@ -4,8 +4,8 @@ namespace DamageAssesment.Api.Questions.Interfaces { public interface IQuestionsProvider : IQuestionTypesProvider { - Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> GetQuestionAsync(int Id); - Task<(bool IsSuccess, IEnumerable Questions, string ErrorMessage)> GetQuestionsAsync(); + Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> GetQuestionAsync(int Id, string Language); + Task<(bool IsSuccess, IEnumerable Questions, string ErrorMessage)> GetQuestionsAsync(string Language); Task<(bool IsSuccess, List SurveyQuestions, string ErrorMessage)> GetSurveyQuestionAsync(int surveyId,string Language); Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> PostQuestionAsync(Models.Question Question); Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs index 647f640..f684a9f 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs @@ -31,7 +31,7 @@ namespace DamageAssesment.Api.Questions.Providers if (!questionDbContext.QuestionsTranslations.Any()) { - questionDbContext.QuestionsTranslations.Add(new Db.QuestionsTranslation() {Id=1, QuestionId = 1, QuestionText = "Can You Open ?",Language="en" }); + questionDbContext.QuestionsTranslations.Add(new Db.QuestionsTranslation() { Id = 1, QuestionId = 1, QuestionText = "Can You Open ?", Language = "en" }); questionDbContext.QuestionsTranslations.Add(new Db.QuestionsTranslation() { Id = 2, QuestionId = 1, QuestionText = "Peux-tu ouvrir ?", Language = "fr" }); questionDbContext.QuestionsTranslations.Add(new Db.QuestionsTranslation() { Id = 3, QuestionId = 2, QuestionText = "Are the grounds flodded ?", Language = "en" }); questionDbContext.QuestionsTranslations.Add(new Db.QuestionsTranslation() { Id = 4, QuestionId = 2, QuestionText = "Les terrains sont-ils inondés ?", Language = "fr" }); @@ -44,9 +44,9 @@ namespace DamageAssesment.Api.Questions.Providers } if (!questionDbContext.Questions.Any()) { - questionDbContext.Questions.Add(new Db.Question() { Id = 1, QuestionTypeId = 2, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, QuestionGroup = "group1",CategoryId=1 }); - questionDbContext.Questions.Add(new Db.Question() { Id = 2, QuestionTypeId = 1, SurveyId = 1, QuestionNumber = 2, IsRequired = false, Comment = true, Key = false, QuestionGroup = "group1", CategoryId = 1 }); - questionDbContext.Questions.Add(new Db.Question() { Id = 3, QuestionTypeId = 1, SurveyId = 1, QuestionNumber = 3, IsRequired = true, Comment = false, Key = true, QuestionGroup = "group1", CategoryId = 2 }); + questionDbContext.Questions.Add(new Db.Question() { Id = 1, QuestionTypeId = 2, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, QuestionGroup = "group1", CategoryId = 1 }); + questionDbContext.Questions.Add(new Db.Question() { Id = 2, QuestionTypeId = 1, SurveyId = 1, QuestionNumber = 2, IsRequired = false, Comment = true, Key = false, QuestionGroup = "group1", CategoryId = 1 }); + questionDbContext.Questions.Add(new Db.Question() { Id = 3, QuestionTypeId = 1, SurveyId = 1, QuestionNumber = 3, IsRequired = true, Comment = false, Key = true, QuestionGroup = "group1", CategoryId = 2 }); questionDbContext.SaveChanges(); } if (!questionDbContext.QuestionTypes.Any()) @@ -61,17 +61,17 @@ namespace DamageAssesment.Api.Questions.Providers if (!questionDbContext.QuestionCategories.Any()) { - questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 1, CategoryName = "Category 1", CategoryImage="img1" }); + questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 1, CategoryName = "Category 1", CategoryImage = "img1" }); questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 2, CategoryName = "Category 2", CategoryImage = "img1" }); questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 3, CategoryName = "Category 3", CategoryImage = "img1" }); questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 4, CategoryName = "Category 4", CategoryImage = "img1" }); - questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 5, CategoryName = "Category 5", CategoryImage = "img1" }); + questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 5, CategoryName = "Category 5", CategoryImage = "img1" }); questionDbContext.SaveChanges(); } } - public async Task<(bool IsSuccess, IEnumerable Questions, string ErrorMessage)> GetQuestionsAsync() + public async Task<(bool IsSuccess, IEnumerable Questions, string ErrorMessage)> GetQuestionsAsync(string Language) { try { @@ -82,10 +82,20 @@ namespace DamageAssesment.Api.Questions.Providers //logger?.LogInformation($"{question} customer(s) found"); var result = mapper.Map, IEnumerable>(questions); + + foreach (var question in result) { - question.Questions=mapper.Map,List>( - questionDbContext.QuestionsTranslations.Where(a=>a.QuestionId==question.Id).ToList()); + if (string.IsNullOrEmpty(Language)) + { + question.Questions = mapper.Map, List>( + questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == question.Id).ToList()); + } + else + { + question.Questions = mapper.Map, List>( + questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == question.Id && a.Language == Language).ToList()); + } } return (true, result, null); } @@ -97,7 +107,7 @@ namespace DamageAssesment.Api.Questions.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> GetQuestionAsync(int Id) + public async Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> GetQuestionAsync(int Id, string Language) { try { @@ -107,8 +117,17 @@ namespace DamageAssesment.Api.Questions.Providers { logger?.LogInformation($"{question} customer(s) found"); var result = mapper.Map(question); - result.Questions = mapper.Map, List>( - questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == result.Id).ToList()); + + if (string.IsNullOrEmpty(Language)) + { + result.Questions = mapper.Map, List>( + questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == result.Id).ToList()); + } + else + { + result.Questions = mapper.Map, List>( + questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == result.Id && a.Language == Language).ToList()); + } return (true, result, null); } return (false, null, "Not found"); @@ -119,12 +138,23 @@ namespace DamageAssesment.Api.Questions.Providers return (false, null, ex.Message); } } - public List GetSurveyQuestion(List questions,string Language) + public List GetSurveyQuestion(List questions, string Language) { - foreach (var item in questions) + if (string.IsNullOrEmpty(Language)) { - item.Questions= mapper.Map, List>( - questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == item.Id && a.Language== Language).ToList()); + foreach (var item in questions) + { + item.Questions = mapper.Map, List>( + questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == item.Id).ToList()); + } + } + else + { + foreach (var item in questions) + { + item.Questions = mapper.Map, List>( + questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == item.Id && a.Language == Language).ToList()); + } } return questions; } @@ -133,12 +163,12 @@ namespace DamageAssesment.Api.Questions.Providers try { logger?.LogInformation("Query Question"); - var questions = await questionDbContext.Questions.Include("QuestionType").Where(a=>a.SurveyId==SurveyId).AsNoTracking().ToListAsync(); + var questions = await questionDbContext.Questions.Include("QuestionType").Where(a => a.SurveyId == SurveyId).AsNoTracking().ToListAsync(); if (questions != null) { List surveyQuestionsList = new List(); - List CategoryIds=questions.Select(a=>a.CategoryId).Distinct().ToList(); - var questioncategories = await questionDbContext.QuestionCategories.Where(a =>CategoryIds.Contains(a.Id)).ToListAsync(); + List CategoryIds = questions.Select(a => a.CategoryId).Distinct().ToList(); + var questioncategories = await questionDbContext.QuestionCategories.Where(a => CategoryIds.Contains(a.Id)).ToListAsync(); //logger?.LogInformation($"{question} customer(s) found"); foreach (var item in questioncategories) { @@ -169,11 +199,11 @@ namespace DamageAssesment.Api.Questions.Providers logger?.LogInformation("Query Question"); var dbquestion = mapper.Map(Question); var dbquestiontranslation = mapper.Map, List>(Question.Questions); - dbquestion.QuestionTypeId=questionDbContext.QuestionTypes.Where(a=>a.TypeText==Question.TypeText).Select(a=>a.Id).FirstOrDefault(); + dbquestion.QuestionTypeId = questionDbContext.QuestionTypes.Where(a => a.TypeText == Question.TypeText).Select(a => a.Id).FirstOrDefault(); questionDbContext.Questions.Add(dbquestion); dbquestiontranslation.ForEach(i => i.QuestionId = dbquestion.Id); questionDbContext.QuestionsTranslations.AddRange(dbquestiontranslation); - questionDbContext.SaveChanges(); + questionDbContext.SaveChanges(); Question.Id = dbquestion.Id; return (true, Question, null); } @@ -192,7 +222,7 @@ namespace DamageAssesment.Api.Questions.Providers dbquestion.QuestionTypeId = questionDbContext.QuestionTypes.Where(a => a.TypeText == Question.TypeText).Select(a => a.Id).FirstOrDefault(); questionDbContext.Entry(dbquestion).State = EntityState.Modified; var oldquestions = questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == dbquestion.Id).ToList(); - if(oldquestions!=null) + if (oldquestions != null) questionDbContext.QuestionsTranslations.RemoveRange(oldquestions); dbquestiontranslation.ForEach(i => i.QuestionId = dbquestion.Id); questionDbContext.QuestionsTranslations.AddRange(dbquestiontranslation); @@ -284,7 +314,7 @@ namespace DamageAssesment.Api.Questions.Providers // Question.QuestionType = GetQuestionType(Question.QuestionTypeId); questionDbContext.QuestionCategories.Add(dbQuestionCategory); questionDbContext.SaveChanges(); - QuestionCategory.Id=dbQuestionCategory.Id; + QuestionCategory.Id = dbQuestionCategory.Id; return (true, QuestionCategory, null); } catch (Exception ex) diff --git a/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/QuestionsServiceTest.cs b/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/QuestionsServiceTest.cs index b21fa9c..17797c6 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/QuestionsServiceTest.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/QuestionsServiceTest.cs @@ -1,16 +1,7 @@ - -using AutoMapper; using DamageAssesment.Api.Questions.Controllers; -using DamageAssesment.Api.Questions.Db; using DamageAssesment.Api.Questions.Interfaces; -using DamageAssesment.Api.Questions.Models; -using DamageAssesment.Api.Questions.Profiles; -using DamageAssesment.Api.Questions.Providers; using Microsoft.AspNetCore.Mvc; -using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Internal; using Moq; -using Newtonsoft.Json; using Xunit; namespace DamageAssesment.Api.Questions.Test @@ -22,10 +13,10 @@ namespace DamageAssesment.Api.Questions.Test { var mockQuestionService = new Mock(); var mockResponse = await MockData.getOkResponse(); - mockQuestionService.Setup(service => service.GetQuestionsAsync()).ReturnsAsync(mockResponse); + mockQuestionService.Setup(service => service.GetQuestionsAsync(null)).ReturnsAsync(mockResponse); var QuestionProvider = new QuestionsController(mockQuestionService.Object); - var result = (OkObjectResult)await QuestionProvider.GetQuestionsAsync(); + var result = (OkObjectResult)await QuestionProvider.GetQuestionsAsync(null); Assert.Equal(200, result.StatusCode); } @@ -35,10 +26,10 @@ namespace DamageAssesment.Api.Questions.Test { var mockQuestionService = new Mock(); var mockResponse = await MockData.getNoContentResponse(); - mockQuestionService.Setup(service => service.GetQuestionsAsync()).ReturnsAsync(mockResponse); + mockQuestionService.Setup(service => service.GetQuestionsAsync(null)).ReturnsAsync(mockResponse); var QuestionProvider = new QuestionsController(mockQuestionService.Object); - var result = (NoContentResult)await QuestionProvider.GetQuestionsAsync(); + var result = (NoContentResult)await QuestionProvider.GetQuestionsAsync(null); Assert.Equal(204, result.StatusCode); } @@ -48,10 +39,10 @@ namespace DamageAssesment.Api.Questions.Test { var mockQuestionService = new Mock(); var mockResponse = await MockData.getOkResponse(1); - mockQuestionService.Setup(service => service.GetQuestionAsync(1)).ReturnsAsync(mockResponse); + mockQuestionService.Setup(service => service.GetQuestionAsync(1,null)).ReturnsAsync(mockResponse); var QuestionProvider = new QuestionsController(mockQuestionService.Object); - var result = (OkObjectResult)await QuestionProvider.GetQuestionAsync(1); + var result = (OkObjectResult)await QuestionProvider.GetQuestionAsync(1,null); Assert.Equal(200, result.StatusCode); } @@ -61,10 +52,10 @@ namespace DamageAssesment.Api.Questions.Test { var mockQuestionService = new Mock(); var mockResponse = await MockData.getNotFoundResponse(); - mockQuestionService.Setup(service => service.GetQuestionAsync(99)).ReturnsAsync(mockResponse); + mockQuestionService.Setup(service => service.GetQuestionAsync(99,null)).ReturnsAsync(mockResponse); var QuestionProvider = new QuestionsController(mockQuestionService.Object); - var result = (NotFoundResult)await QuestionProvider.GetQuestionAsync(99); + var result = (NotFoundResult)await QuestionProvider.GetQuestionAsync(99,null); Assert.Equal(404, result.StatusCode); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Survey.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Survey.cs index 04b60e5..506a2f4 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Survey.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Survey.cs @@ -4,25 +4,11 @@ namespace DamageAssesment.Api.SurveyResponses.Models { public class Survey { - [Key] public int Id { get; set; } - - [StringLength(100)] - public string Title { get; set; } - - //[StringLength(1000)] - //public string Description { get; set; } - public bool IsEnabled { get; set; } - public DateTime? StartDate { get; set; } - public DateTime? EndDate { get; set; } - - //public DateTime CreatedDate { get; set; } - - //[StringLength(6)] - //public string EmployeeID { get; set; } - + public DateTime CreatedDate { get; set; } + public IEnumerable Titles { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/SurveyTranslation.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/SurveyTranslation.cs new file mode 100644 index 0000000..29a1b7c --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/SurveyTranslation.cs @@ -0,0 +1,13 @@ +namespace DamageAssesment.Api.SurveyResponses.Models +{ + public class SurveyTranslation + { + public string Title { get; set; } + public string Language { get; set; } + } +} + + + + + diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys.Test/MockData.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys.Test/MockData.cs index 6936c04..01972e3 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys.Test/MockData.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys.Test/MockData.cs @@ -15,7 +15,7 @@ namespace DamageAssesment.Api.Survey.Test for (int i = 0; i < 10; i++) { - list.Append(new Surveys.Models.Survey { Id = i, Title = "Survey Title - " + i }); + list.Append(new Surveys.Models.Survey { Id = i, /*Title = "Survey Title - " + i */}); } return (true, list, null); } @@ -45,7 +45,7 @@ namespace DamageAssesment.Api.Survey.Test public static async Task getInputSurveyData() { - return new Surveys.Models.Survey { Id = 100, Title = "Mock survey", IsEnabled= true, StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(90) }; + return new Surveys.Models.Survey { Id = 100, /*Title = "Mock survey",*/ IsEnabled= true, StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(90) }; } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys.Test/SurveyServiceTest.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys.Test/SurveyServiceTest.cs index 1aaf4a6..44f1f6e 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys.Test/SurveyServiceTest.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys.Test/SurveyServiceTest.cs @@ -14,10 +14,10 @@ namespace DamageAssesment.Api.Surveys.Test { var mockSurveyService = new Mock(); var mockResponse = await MockData.getOkResponse(); - mockSurveyService.Setup(service => service.GetSurveysAsync()).ReturnsAsync(mockResponse); + mockSurveyService.Setup(service => service.GetSurveysAsync(null)).ReturnsAsync(mockResponse); var surveyProvider = new SurveysController(mockSurveyService.Object); - var result = (OkObjectResult) await surveyProvider.GetSurveysAsync(); + var result = (OkObjectResult) await surveyProvider.GetSurveysAsync(null); Assert.Equal(200, result.StatusCode); } @@ -27,10 +27,10 @@ namespace DamageAssesment.Api.Surveys.Test { var mockSurveyService = new Mock(); var mockResponse = await MockData.getNoContentResponse(); - mockSurveyService.Setup(service => service.GetSurveysAsync()).ReturnsAsync(mockResponse); + mockSurveyService.Setup(service => service.GetSurveysAsync(null)).ReturnsAsync(mockResponse); var surveyProvider = new SurveysController(mockSurveyService.Object); - var result = (NoContentResult)await surveyProvider.GetSurveysAsync(); + var result = (NoContentResult)await surveyProvider.GetSurveysAsync(null); Assert.Equal(204, result.StatusCode); } @@ -40,10 +40,10 @@ namespace DamageAssesment.Api.Surveys.Test { var mockSurveyService = new Mock(); var mockResponse = await MockData.getOkResponse(1); - mockSurveyService.Setup(service => service.GetSurveysAsync(1)).ReturnsAsync(mockResponse); + mockSurveyService.Setup(service => service.GetSurveysAsync(1,null)).ReturnsAsync(mockResponse); var surveyProvider = new SurveysController(mockSurveyService.Object); - var result = (OkObjectResult)await surveyProvider.GetSurveysAsync(1); + var result = (OkObjectResult)await surveyProvider.GetSurveysAsync(1,null); Assert.Equal(200, result.StatusCode); } @@ -53,10 +53,10 @@ namespace DamageAssesment.Api.Surveys.Test { var mockSurveyService = new Mock(); var mockResponse = await MockData.getNotFoundResponse(); - mockSurveyService.Setup(service => service.GetSurveysAsync(99)).ReturnsAsync(mockResponse); + mockSurveyService.Setup(service => service.GetSurveysAsync(99,null)).ReturnsAsync(mockResponse); var surveyProvider = new SurveysController(mockSurveyService.Object); - var result = (NotFoundResult)await surveyProvider.GetSurveysAsync(99); + var result = (NotFoundResult)await surveyProvider.GetSurveysAsync(99,null); Assert.Equal(404, result.StatusCode); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs index a68fd9f..3115228 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs @@ -5,7 +5,7 @@ using Microsoft.AspNetCore.Mvc; namespace DamageAssesment.Api.Surveys.Controllers { - [Route("api/[controller]")] + [Route("api")] [ApiController] public class SurveysController : ControllerBase { @@ -16,10 +16,13 @@ namespace DamageAssesment.Api.Surveys.Controllers this.surveyProvider = surveyProvider; } + + [Route("Surveys")] + [Route("{Language}/Surveys")] [HttpGet] - public async Task GetSurveysAsync() + public async Task GetSurveysAsync(string? Language) { - var result = await this.surveyProvider.GetSurveysAsync(); + var result = await this.surveyProvider.GetSurveysAsync(Language); if (result.IsSuccess) { return Ok(result.Surveys); @@ -27,10 +30,12 @@ namespace DamageAssesment.Api.Surveys.Controllers return NoContent(); } - [HttpGet("{Id}")] - public async Task GetSurveysAsync(int Id) + [Route("Surveys/{Id}")] + [Route("{Language}/Surveys/{Id}")] + [HttpGet] + public async Task GetSurveysAsync(int Id, string? Language) { - var result = await this.surveyProvider.GetSurveysAsync(Id); + var result = await this.surveyProvider.GetSurveysAsync(Id, Language); if (result.IsSuccess) { return Ok(result.Surveys); @@ -38,7 +43,7 @@ namespace DamageAssesment.Api.Surveys.Controllers return NotFound(); } - [HttpPost] + [HttpPost("Surveys")] public async Task PostSurveysAsync(Models.Survey survey) { var result = await this.surveyProvider.PostSurveyAsync(survey); @@ -49,21 +54,21 @@ namespace DamageAssesment.Api.Surveys.Controllers return BadRequest(result.ErrorMessage); } - [HttpPut("{Id}")] + [HttpPut("Surveys/{Id}")] public async Task PutSurveysAsync(int Id, Models.Survey survey) { - var result = await this.surveyProvider.PutSurveyAsync(Id,survey); + var result = await this.surveyProvider.PutSurveyAsync(Id, survey); if (result.IsSuccess) { return Ok(result.Survey); } if (result.ErrorMessage == "Not Found") return NotFound(result.ErrorMessage); - + return BadRequest(result.ErrorMessage); } - [HttpDelete("{Id}")] + [HttpDelete("Surveys/{Id}")] public async Task DeleteSurveysAsync(int Id) { var result = await this.surveyProvider.DeleteSurveyAsync(Id); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/Survey.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/Survey.cs index bff0339..36983bd 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/Survey.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/Survey.cs @@ -1,4 +1,5 @@ using System.ComponentModel.DataAnnotations; +using System.ComponentModel.DataAnnotations.Schema; namespace DamageAssesment.Api.Surveys.Db { @@ -6,11 +7,6 @@ namespace DamageAssesment.Api.Surveys.Db { [Key] public int Id { get; set; } - - [StringLength(100)] - [Required] - public string Title { get; set; } - //[StringLength(1000)] //public string Description { get; set; } @@ -20,9 +16,11 @@ namespace DamageAssesment.Api.Surveys.Db public DateTime? EndDate { get; set; } - //public DateTime CreatedDate { get; set; } - - //[StringLength(6)] - //public string EmployeeID { get; set; } + public DateTime CreatedDate { get; set; } = DateTime.Now; + /* + [StringLength(10)] + [ForeignKey("Employee")] + public string EmployeeId { get; set; } + */ } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/SurveyTranslation.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/SurveyTranslation.cs new file mode 100644 index 0000000..340bf12 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/SurveyTranslation.cs @@ -0,0 +1,23 @@ +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; + +namespace DamageAssesment.Api.Surveys.Db +{ + public class SurveyTranslation + { + [Key] + public int Id { get; set; } + [ForeignKey("Survey")] + public int SurveyId { get; set; } + + [StringLength(200)] + [Required] + public string Title { get; set; } + public string Language { get; set; } + } +} + + + + + diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/SurveysDbContext.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/SurveysDbContext.cs index 9ff36cf..e912e96 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/SurveysDbContext.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/SurveysDbContext.cs @@ -9,6 +9,6 @@ namespace DamageAssesment.Api.Surveys.Db } public DbSet Surveys { get; set; } - + public DbSet SurveysTranslation { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Interfaces/ISurveyProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Interfaces/ISurveyProvider.cs index 42c488e..5cfded9 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Interfaces/ISurveyProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Interfaces/ISurveyProvider.cs @@ -2,8 +2,8 @@ { public interface ISurveyProvider { - Task<(bool IsSuccess, IEnumerable< Models.Survey> Surveys, string ErrorMessage)> GetSurveysAsync(); - Task<(bool IsSuccess, Models.Survey Surveys, string ErrorMessage)> GetSurveysAsync(int Id); + Task<(bool IsSuccess, IEnumerable< Models.Survey> Surveys, string ErrorMessage)> GetSurveysAsync(string Language); + Task<(bool IsSuccess, Models.Survey Surveys, string ErrorMessage)> GetSurveysAsync(int Id, string Language); 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); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/Survey.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/Survey.cs index cd5691b..ab741b5 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/Survey.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/Survey.cs @@ -4,25 +4,11 @@ namespace DamageAssesment.Api.Surveys.Models { public class Survey { - [Key] public int Id { get; set; } - - [StringLength(100)] - public string Title { get; set; } - - //[StringLength(1000)] - // public string? Description { get; set; } - public bool IsEnabled { get; set; } - public DateTime? StartDate { get; set; } - public DateTime? EndDate { get; set; } - - //public DateTime CreatedDate { get; set; } - - //[StringLength(6)] - //public string EmployeeID { get; set; } - + public DateTime CreatedDate { get; set; } + public IEnumerable Titles { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/SurveyTranslation.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/SurveyTranslation.cs new file mode 100644 index 0000000..64671ee --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/SurveyTranslation.cs @@ -0,0 +1,13 @@ +namespace DamageAssesment.Api.Surveys.Models +{ + public class SurveyTranslation + { + public string Title { get; set; } + public string Language { get; set; } + } +} + + + + + diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs index 3eb111c..abec85a 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs @@ -1,7 +1,9 @@ using AutoMapper; using DamageAssesment.Api.Surveys.Db; using DamageAssesment.Api.Surveys.Interfaces; +using DamageAssesment.Api.Surveys.Models; using Microsoft.EntityFrameworkCore; +using System.Collections.Generic; namespace DamageAssesment.Api.Surveys.Providers { @@ -23,24 +25,88 @@ namespace DamageAssesment.Api.Surveys.Providers { if (!surveyDbContext.Surveys.Any()) { - surveyDbContext.Surveys.Add(new Db.Survey { Id = 1, Title = "Sample Survey Title:Damage Assesment 2014", IsEnabled = true, StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(90) }); - surveyDbContext.Surveys.Add(new Db.Survey { Id = 2, Title = "Sample Survey Title: Damage Assesment 2016", IsEnabled = true, StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(90) }); - surveyDbContext.Surveys.Add(new Db.Survey { Id = 3, Title = "Sample Survey Title: Damage Assesment 2018", IsEnabled = true, StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(90) }); + surveyDbContext.Surveys.Add(new Db.Survey { Id = 1, IsEnabled = true, StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(90), CreatedDate = DateTime.Now }); + surveyDbContext.Surveys.Add(new Db.Survey { Id = 2, IsEnabled = true, StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(90), CreatedDate = DateTime.Now }); + surveyDbContext.Surveys.Add(new Db.Survey { Id = 3, IsEnabled = true, StartDate = DateTime.Now, EndDate = DateTime.Now.AddDays(90), CreatedDate = DateTime.Now }); + surveyDbContext.SaveChangesAsync(); + } + + if (!surveyDbContext.SurveysTranslation.Any()) + { + surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation { Id = 1, SurveyId = 1, Language = "en", Title = "Impact of Tropical Storm Emily on Florida's Economy" }); + surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation { Id = 2, SurveyId = 1, Language = "es", Title = "Impacto de la tormenta tropical Emily en la economía de Florida" }); + surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation { Id = 3, SurveyId = 1, Language = "fr", Title = "Impact de la tempête tropicale Emily sur l'économie de la Floride" }); + + surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation { Id = 4, SurveyId = 2, Language = "en", Title = "Hurricane Andrew Aftermath Survey" }); + surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation { Id = 5, SurveyId = 2, Language = "es", Title = "Encuesta sobre las secuelas del huracán Andrew" }); + surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation { Id = 6, SurveyId = 2, Language = "fr", Title = "Enquête sur les conséquences de l'ouragan Andrew" }); + + surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation { Id = 7, SurveyId = 3, Language = "en", Title = "Public Perception of Hurricane Michael's Response" }); + surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation { Id = 8, SurveyId = 3, Language = "es", Title = "Percepción pública de la respuesta del huracán Michael" }); + surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation { Id = 9, SurveyId = 3, Language = "fr", Title = "Perception du public de la réponse de l'ouragan Michael" }); + surveyDbContext.SaveChangesAsync(); } } - public async Task<(bool IsSuccess, IEnumerable Surveys, string ErrorMessage)> GetSurveysAsync() + public async Task<(bool IsSuccess, IEnumerable Surveys, string ErrorMessage)> GetSurveysAsync(string Language) { + IEnumerable surveysList = null; try { logger?.LogInformation("Gell all Surveys from DB"); - var surveys = await surveyDbContext.Surveys.ToListAsync(); + var surveys = await surveyDbContext.Surveys.Where(s => s.IsEnabled == true).ToListAsync(); + var surveyTranslations = await surveyDbContext.SurveysTranslation.ToListAsync(); + if (surveys != null) { + + if (string.IsNullOrEmpty(Language)) + { + surveysList = from s in surveys + select new + Models.Survey + { + Id = s.Id, + StartDate = s.StartDate, + EndDate = s.EndDate, + IsEnabled = s.IsEnabled, + CreatedDate = s.CreatedDate, + Titles = from t in surveyTranslations + where t.SurveyId == s.Id + select new Models.SurveyTranslation + { + Title = t.Title, + Language = t.Language + } + + }; + } + else + { + surveysList = from s in surveys + select new + Models.Survey + { + Id = s.Id, + StartDate = s.StartDate, + EndDate = s.EndDate, + IsEnabled = s.IsEnabled, + CreatedDate = s.CreatedDate, + Titles = from t in surveyTranslations + where t.SurveyId == s.Id + && t.Language == Language + select new Models.SurveyTranslation + { + Title = t.Title, + Language = t.Language + } + + }; + } + logger?.LogInformation($"{surveys.Count} Items(s) found"); - var result = mapper.Map, IEnumerable>(surveys); - return (true, result, null); + return (true, surveysList, null); } return (false, null, "Not found"); } @@ -50,16 +116,55 @@ namespace DamageAssesment.Api.Surveys.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Survey Surveys, string ErrorMessage)> GetSurveysAsync(int Id) + public async Task<(bool IsSuccess, Models.Survey Surveys, string ErrorMessage)> GetSurveysAsync(int Id, string Language) { try { logger?.LogInformation("Query Survey"); - var survey = await surveyDbContext.Surveys.SingleOrDefaultAsync(s => s.Id == Id); + var survey = await surveyDbContext.Surveys.SingleOrDefaultAsync(s => s.Id == Id && s.IsEnabled == true); if (survey != null) { + Models.Survey result = null; + var surveyTranslations = await surveyDbContext.SurveysTranslation.Where(s => s.SurveyId == survey.Id).ToListAsync(); + + if (string.IsNullOrEmpty(Language)) + { + result = new Models.Survey + { + Id = survey.Id, + StartDate = survey.StartDate, + EndDate = survey.EndDate, + IsEnabled = survey.IsEnabled, + CreatedDate = survey.CreatedDate, + Titles = from t in surveyTranslations + select new Models.SurveyTranslation + { + Title = t.Title, + Language = t.Language + } + + }; + } + else + { + result = new Models.Survey + { + Id = survey.Id, + StartDate = survey.StartDate, + EndDate = survey.EndDate, + IsEnabled = survey.IsEnabled, + CreatedDate = survey.CreatedDate, + Titles = from t in surveyTranslations + where t.Language == Language + select new Models.SurveyTranslation + { + Title = t.Title, + Language = t.Language + } + + }; + } logger?.LogInformation($"Survey Id: {Id} found"); - var result = mapper.Map(survey); return (true, result, null); } return (false, null, "Not found"); @@ -78,8 +183,16 @@ namespace DamageAssesment.Api.Surveys.Providers if (survey != null) { var surveys = await surveyDbContext.Surveys.ToListAsync(); - survey.Id = surveys.Count + 1; - surveyDbContext.Surveys.Add(mapper.Map(survey)); + + int Id = surveys.Count + 1; + surveyDbContext.Surveys.Add(new Db.Survey { Id = Id, IsEnabled = survey.IsEnabled, StartDate = survey.StartDate, EndDate = survey.EndDate, CreatedDate = DateTime.Now }); + var surveyTranslations = await surveyDbContext.SurveysTranslation.ToListAsync(); + int count = surveyTranslations.Count; + foreach (var title in survey.Titles) + { + count++; + surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation { Id = count, SurveyId = Id, Language = title.Language, Title = title.Title }); + } await surveyDbContext.SaveChangesAsync(); return (true, survey, "Successful"); } @@ -106,12 +219,40 @@ namespace DamageAssesment.Api.Surveys.Providers if (_survey != null) { - _survey.Title = survey.Title; + var surveysTranslation = await surveyDbContext.SurveysTranslation.Where(s => s.SurveyId == Id).ToListAsync(); + surveyDbContext.SurveysTranslation.RemoveRange(surveysTranslation); + await surveyDbContext.SaveChangesAsync(); + _survey.IsEnabled = survey.IsEnabled; _survey.StartDate = survey.StartDate; _survey.EndDate = survey.EndDate; await surveyDbContext.SaveChangesAsync(); - return (true, mapper.Map(_survey), "Successful"); + + List listSurveyTranslation = new List(); + Random random = new Random(); + foreach (var title in survey.Titles) + { + listSurveyTranslation.Add(new Db.SurveyTranslation { Id = random.Next(), SurveyId = _survey.Id, Language = title.Language, Title = title.Title }); + } + surveyDbContext.SurveysTranslation.AddRange(listSurveyTranslation); + await surveyDbContext.SaveChangesAsync(); + + var result = new Models.Survey + { + Id = Id, + StartDate = survey.StartDate, + EndDate = survey.EndDate, + IsEnabled = survey.IsEnabled, + CreatedDate = survey.CreatedDate, + Titles = from t in listSurveyTranslation + select new Models.SurveyTranslation + { + Title = t.Title, + Language = t.Language + } + + }; + return (true, result, "Successful"); } else { From fe1614fee327b52f8e37e336213e7aba5a1b5d18 Mon Sep 17 00:00:00 2001 From: Reginald Cherenfant Jasmin Date: Fri, 25 Aug 2023 11:36:31 -0400 Subject: [PATCH 06/19] Multi Language support --- .../AnswersServiceTest.cs | 20 +++++----- .../AttachmentsServiceTest.cs | 16 ++++---- .../Controllers/QuestionsController.cs | 40 ++++++------------- .../Providers/QuestionsProvider.cs | 19 --------- .../MockData.cs | 11 +---- .../Controllers/SurveysController.cs | 24 +++-------- .../DamageAssesment.Api.Surveys/Db/Survey.cs | 4 +- .../Models/Survey.cs | 4 +- .../DamageAssesment.Api.Surveys/Program.cs | 3 -- 9 files changed, 42 insertions(+), 99 deletions(-) diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers.Test/AnswersServiceTest.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers.Test/AnswersServiceTest.cs index 3b114f7..ad6ec72 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers.Test/AnswersServiceTest.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers.Test/AnswersServiceTest.cs @@ -95,10 +95,10 @@ namespace DamageAssesment.Api.Answers.Test var mockAnswerService = new Mock(); var mockResponse = await MockData.getOkResponse(1); var mockInputAnswer = await MockData.getInputAnswerData(); - mockAnswerService.Setup(service => service.PostAnswerAsync(mockInputAnswer)).ReturnsAsync(mockResponse); + mockAnswerService.Setup(service => service.PostAnswerAsync(mockInputAnswer)).Returns(mockResponse); var AnswerProvider = new AnswersController(mockAnswerService.Object); - var result = (OkObjectResult)await AnswerProvider.CreateAnswer(mockInputAnswer); + var result = (OkObjectResult) AnswerProvider.CreateAnswer(mockInputAnswer); Assert.Equal(200, result.StatusCode); } @@ -109,10 +109,10 @@ namespace DamageAssesment.Api.Answers.Test var mockAnswerService = new Mock(); var mockInputAnswer = await MockData.getInputAnswerData(); var mockResponse = await MockData.getBadRequestResponse(); - mockAnswerService.Setup(service => service.PostAnswerAsync(mockInputAnswer)).ReturnsAsync(mockResponse); + mockAnswerService.Setup(service => service.PostAnswerAsync(mockInputAnswer)).Returns(mockResponse); var AnswerProvider = new AnswersController(mockAnswerService.Object); - var result = (BadRequestObjectResult)await AnswerProvider.CreateAnswer(mockInputAnswer); + var result = (BadRequestObjectResult) AnswerProvider.CreateAnswer(mockInputAnswer); Assert.Equal(400, result.StatusCode); } @@ -123,10 +123,10 @@ namespace DamageAssesment.Api.Answers.Test var mockAnswerService = new Mock(); var mockResponse = await MockData.getOkResponse(1); var mockInputAnswer = await MockData.getInputAnswerData(); - mockAnswerService.Setup(service => service.UpdateAnswerAsync(mockInputAnswer)).ReturnsAsync(mockResponse); + mockAnswerService.Setup(service => service.UpdateAnswerAsync(mockInputAnswer)).Returns(mockResponse); var AnswerProvider = new AnswersController(mockAnswerService.Object); - var result = (OkObjectResult)await AnswerProvider.UpdateAnswer(mockInputAnswer); + var result = (OkObjectResult) AnswerProvider.UpdateAnswer(mockInputAnswer); Assert.Equal(200, result.StatusCode); } @@ -137,10 +137,10 @@ namespace DamageAssesment.Api.Answers.Test var mockAnswerService = new Mock(); var mockResponse = await MockData.getNotFoundResponse(); var mockInputAnswer = await MockData.getInputAnswerData(); - mockAnswerService.Setup(service => service.UpdateAnswerAsync(mockInputAnswer)).ReturnsAsync(mockResponse); + mockAnswerService.Setup(service => service.UpdateAnswerAsync(mockInputAnswer)).Returns(mockResponse); var AnswerProvider = new AnswersController(mockAnswerService.Object); - var result = (NotFoundObjectResult)await AnswerProvider.UpdateAnswer(mockInputAnswer); + var result = (NotFoundObjectResult) AnswerProvider.UpdateAnswer(mockInputAnswer); Assert.Equal(404, result.StatusCode); } @@ -151,10 +151,10 @@ namespace DamageAssesment.Api.Answers.Test var mockAnswerService = new Mock(); var mockResponse = await MockData.getBadRequestResponse(); var mockInputAnswer = await MockData.getInputAnswerData(); - mockAnswerService.Setup(service => service.UpdateAnswerAsync(mockInputAnswer)).ReturnsAsync(mockResponse); + mockAnswerService.Setup(service => service.UpdateAnswerAsync(mockInputAnswer)).Returns(mockResponse); var AnswerProvider = new AnswersController(mockAnswerService.Object); - var result = (BadRequestObjectResult)await AnswerProvider.UpdateAnswer(mockInputAnswer); + var result = (BadRequestObjectResult) AnswerProvider.UpdateAnswer(mockInputAnswer); Assert.Equal(400, result.StatusCode); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments.Test/AttachmentsServiceTest.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments.Test/AttachmentsServiceTest.cs index 5bf695c..6b65c79 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments.Test/AttachmentsServiceTest.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments.Test/AttachmentsServiceTest.cs @@ -77,10 +77,10 @@ namespace DamageAssesment.Api.Attachments.Test var mockResponse = await MockData.getOkResponse(); var AttachmentResponse = await MockData.GetAttachmentInfo(0); var mockInputAttachment = await MockData.getInputAttachmentData(); - mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).ReturnsAsync(mockResponse); + mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).Returns(mockResponse); var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object); - var result = (NoContentResult)await AttachmentProvider.UploadAttachmentAsync(AttachmentResponse); + var result = (NoContentResult) AttachmentProvider.UploadAttachmentAsync(AttachmentResponse); Assert.Equal(204, result.StatusCode); } @@ -92,11 +92,11 @@ namespace DamageAssesment.Api.Attachments.Test var mockUploadService = new Mock(); var mockInputAttachment = await MockData.getInputAttachmentData(); var mockResponse = await MockData.getBadRequestResponse(); - mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).ReturnsAsync(mockResponse); + mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).Returns(mockResponse); var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object); AttachmentInfo attachmentInfo=new AttachmentInfo(); - var result = (BadRequestObjectResult)await AttachmentProvider.UploadAttachmentAsync(attachmentInfo); + var result = (BadRequestObjectResult) AttachmentProvider.UploadAttachmentAsync(attachmentInfo); Assert.Equal(400, result.StatusCode); } @@ -109,10 +109,10 @@ namespace DamageAssesment.Api.Attachments.Test var mockResponse = await MockData.getOkResponse(); var AttachmentResponse = await MockData.GetAttachmentInfo(1); var mockInputAttachment = await MockData.getInputAttachmentData(); - mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).ReturnsAsync(mockResponse); + mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).Returns(mockResponse); var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object); - var result = (NoContentResult)await AttachmentProvider.UpdateAttachmentAsync(AttachmentResponse); + var result = (NoContentResult) AttachmentProvider.UpdateAttachmentAsync(AttachmentResponse); Assert.Equal(204, result.StatusCode); } @@ -124,11 +124,11 @@ namespace DamageAssesment.Api.Attachments.Test var mockUploadService = new Mock(); var mockInputAttachment = await MockData.getInputAttachmentData(); var mockResponse = await MockData.getBadRequestResponse(); - mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).ReturnsAsync(mockResponse); + mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).Returns(mockResponse); var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object); AttachmentInfo attachmentInfo = new AttachmentInfo(); - var result = (BadRequestObjectResult)await AttachmentProvider.UpdateAttachmentAsync(attachmentInfo); + var result = (BadRequestObjectResult) AttachmentProvider.UpdateAttachmentAsync(attachmentInfo); Assert.Equal(400, result.StatusCode); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs index 7c0ba52..ae98924 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs @@ -15,20 +15,16 @@ namespace DamageAssesment.Api.Questions.Controllers this.questionsProvider = questionsProvider; } -<<<<<<< HEAD + + /// + /// GET request for retrieving questions. + /// + // get all questions [Route("{Language}/Questions")] [Route("Questions")] [HttpGet] public async Task GetQuestionsAsync(string? Language) -======= - /// - /// GET request for retrieving questions. - /// - - [HttpGet("Questions")] - public async Task GetQuestionsAsync() ->>>>>>> cf3a04891b7b50d0a02ac9c8b9a78ccb9436c35c { var result = await this.questionsProvider.GetQuestionsAsync(Language); if (result.IsSuccess) @@ -37,20 +33,15 @@ namespace DamageAssesment.Api.Questions.Controllers } return NoContent(); } -<<<<<<< HEAD + //Get questions based on question id + /// + /// GET request for retrieving a question by ID. + /// [Route("{Language}/Questions/{id}")] [Route("Questions/{id}")] [HttpGet] public async Task GetQuestionAsync(int id, string? Language) -======= - /// - /// GET request for retrieving a question by ID. - /// - - [HttpGet("Questions/{id}")] - public async Task GetQuestionAsync(int id) ->>>>>>> cf3a04891b7b50d0a02ac9c8b9a78ccb9436c35c { var result = await this.questionsProvider.GetQuestionAsync(id,Language); if (result.IsSuccess) @@ -59,19 +50,15 @@ namespace DamageAssesment.Api.Questions.Controllers } return NotFound(); } -<<<<<<< HEAD + //get all questions based on survey id - [Route("{Language}/GetSurveyQuestions/{surveyId}")] - [Route("GetSurveyQuestions/{surveyId}")] - [HttpGet] -======= /// /// GET request for retrieving survey questions based on a survey ID. /// Uri: {Optional language}/GetSurveyQuestions/{surveyId} :Default returns question in all languages /// - - [HttpGet("GetSurveyQuestions/{surveyId}")] ->>>>>>> cf3a04891b7b50d0a02ac9c8b9a78ccb9436c35c + [Route("{Language}/GetSurveyQuestions/{surveyId}")] + [Route("GetSurveyQuestions/{surveyId}")] + [HttpGet] public async Task GetSurveyQuestions(int surveyId,string? Language) { var result = await this.questionsProvider.GetSurveyQuestionAsync(surveyId, Language); @@ -135,7 +122,6 @@ namespace DamageAssesment.Api.Questions.Controllers return NotFound(); } - /// /// GET request for retrieving question categories. /// diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs index 7baea60..719fb5f 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs @@ -24,8 +24,6 @@ namespace DamageAssesment.Api.Questions.Providers SeedData(); } - - private void SeedData() { @@ -44,15 +42,9 @@ namespace DamageAssesment.Api.Questions.Providers } if (!questionDbContext.Questions.Any()) { -<<<<<<< HEAD - questionDbContext.Questions.Add(new Db.Question() { Id = 1, QuestionTypeId = 2, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, QuestionGroup = "group1", CategoryId = 1 }); - questionDbContext.Questions.Add(new Db.Question() { Id = 2, QuestionTypeId = 1, SurveyId = 1, QuestionNumber = 2, IsRequired = false, Comment = true, Key = false, QuestionGroup = "group1", CategoryId = 1 }); - questionDbContext.Questions.Add(new Db.Question() { Id = 3, QuestionTypeId = 1, SurveyId = 1, QuestionNumber = 3, IsRequired = true, Comment = false, Key = true, QuestionGroup = "group1", CategoryId = 2 }); -======= questionDbContext.Questions.Add(new Db.Question() { Id = 1, QuestionTypeId = 2, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId=1 }); questionDbContext.Questions.Add(new Db.Question() { Id = 2, QuestionTypeId = 1, SurveyId = 1, QuestionNumber = 2, IsRequired = false, Comment = true, Key = false, CategoryId = 1 }); questionDbContext.Questions.Add(new Db.Question() { Id = 3, QuestionTypeId = 1, SurveyId = 1, QuestionNumber = 3, IsRequired = true, Comment = false, Key = true, CategoryId = 2 }); ->>>>>>> cf3a04891b7b50d0a02ac9c8b9a78ccb9436c35c questionDbContext.SaveChanges(); } if (!questionDbContext.QuestionTypes.Any()) @@ -65,22 +57,13 @@ namespace DamageAssesment.Api.Questions.Providers if (!questionDbContext.QuestionCategories.Any()) { -<<<<<<< HEAD - questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 1, CategoryName = "Category 1", CategoryImage = "img1" }); - questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 2, CategoryName = "Category 2", CategoryImage = "img1" }); - questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 3, CategoryName = "Category 3", CategoryImage = "img1" }); - questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 4, CategoryName = "Category 4", CategoryImage = "img1" }); - questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 5, CategoryName = "Category 5", CategoryImage = "img1" }); -======= questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 1, CategoryName = "Flooding", CategoryImage= "https://example.com/images/img1.png" }); questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 2, CategoryName = "Electrical", CategoryImage = "https://example.com/images/img2.png" }); questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 3, CategoryName = "Structural", CategoryImage = "https://example.com/images/img3.png" }); questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 4, CategoryName = "Utility", CategoryImage = "https://example.com/images/img4.png" }); questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 5, CategoryName = "Debris", CategoryImage = "https://example.com/images/img5.png" }); ->>>>>>> cf3a04891b7b50d0a02ac9c8b9a78ccb9436c35c questionDbContext.SaveChanges(); } - } public async Task<(bool IsSuccess, IEnumerable Questions, string ErrorMessage)> GetQuestionsAsync(string Language) @@ -273,8 +256,6 @@ namespace DamageAssesment.Api.Questions.Providers } } - - //Question Category Logic public async Task<(bool IsSuccess, IEnumerable QuestionCategories, string ErrorMessage)> GetQuestionCategoriesAsync() diff --git a/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/MockData.cs b/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/MockData.cs index be919ed..1991128 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/MockData.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/MockData.cs @@ -1,11 +1,4 @@ -using DamageAssesment.Api.Questions.Db; -using Microsoft.EntityFrameworkCore.Metadata.Internal; -using Newtonsoft.Json; -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Text; namespace DamageAssesment.Api.Questions.Test { @@ -31,7 +24,7 @@ namespace DamageAssesment.Api.Questions.Test for (int i = 0; i < 10; i++) { List question = new List(); - question.Add(new Models.Question { Id = i, TypeText = "Text" + i, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, QuestionGroup = "group1", CategoryId = i }); + question.Add(new Models.Question { Id = i, TypeText = "Text" + i, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId = i }); list.Append(new Questions.Models.SurveyQuestions { CategoryId = i, diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs index f98a3e0..e360e53 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs @@ -1,6 +1,4 @@ using DamageAssesment.Api.Surveys.Interfaces; -using Microsoft.AspNetCore.Authorization; -using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; namespace DamageAssesment.Api.Surveys.Controllers @@ -19,7 +17,6 @@ namespace DamageAssesment.Api.Surveys.Controllers /// GET request for retrieving surveys. /// - [Route("Surveys")] [Route("{Language}/Surveys")] [HttpGet] @@ -32,20 +29,14 @@ namespace DamageAssesment.Api.Surveys.Controllers } return NoContent(); } -<<<<<<< HEAD + /// + /// GET request for retrieving surveys by ID. + /// [Route("Surveys/{Id}")] [Route("{Language}/Surveys/{Id}")] [HttpGet] public async Task GetSurveysAsync(int Id, string? Language) -======= - /// - /// GET request for retrieving surveys by ID. - /// - - [HttpGet("{Id}")] - public async Task GetSurveysAsync(int Id) ->>>>>>> cf3a04891b7b50d0a02ac9c8b9a78ccb9436c35c { var result = await this.surveyProvider.GetSurveysAsync(Id, Language); if (result.IsSuccess) @@ -71,7 +62,7 @@ namespace DamageAssesment.Api.Surveys.Controllers /// /// PUT request for updating an existing survey (surveyId,Updated Survey data). /// - + [HttpPut("Surveys/{Id}")] public async Task PutSurveysAsync(int Id, Models.Survey survey) @@ -86,16 +77,11 @@ namespace DamageAssesment.Api.Surveys.Controllers return BadRequest(result.ErrorMessage); } -<<<<<<< HEAD - [HttpDelete("Surveys/{Id}")] -======= /// /// DELETE request for deleting a survey by ID. /// - - [HttpDelete("{Id}")] ->>>>>>> cf3a04891b7b50d0a02ac9c8b9a78ccb9436c35c + [HttpDelete("Surveys/{Id}")] public async Task DeleteSurveysAsync(int Id) { var result = await this.surveyProvider.DeleteSurveyAsync(Id); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/Survey.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/Survey.cs index 36983bd..c031f57 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/Survey.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/Survey.cs @@ -12,9 +12,9 @@ namespace DamageAssesment.Api.Surveys.Db public bool IsEnabled { get; set; } - public DateTime? StartDate { get; set; } + public DateTime StartDate { get; set; } - public DateTime? EndDate { get; set; } + public DateTime EndDate { get; set; } public DateTime CreatedDate { get; set; } = DateTime.Now; /* diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/Survey.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/Survey.cs index ab741b5..7fa898d 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/Survey.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/Survey.cs @@ -6,8 +6,8 @@ namespace DamageAssesment.Api.Surveys.Models { public int Id { get; set; } public bool IsEnabled { get; set; } - public DateTime? StartDate { get; set; } - public DateTime? EndDate { get; set; } + public DateTime StartDate { get; set; } + public DateTime EndDate { get; set; } public DateTime CreatedDate { get; set; } public IEnumerable Titles { get; set; } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Program.cs index 7368a72..98fa8a3 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Program.cs @@ -3,12 +3,9 @@ using DamageAssesment.Api.Surveys.Interfaces; using DamageAssesment.Api.Surveys.Providers; using Microsoft.AspNetCore.Authentication.JwtBearer; using Microsoft.EntityFrameworkCore; -<<<<<<< HEAD using Microsoft.IdentityModel.Tokens; using System.Text; -======= using System.Reflection; ->>>>>>> cf3a04891b7b50d0a02ac9c8b9a78ccb9436c35c var builder = WebApplication.CreateBuilder(args); From 099055d0883dfa73c574c49b2f289c92205fa8eb Mon Sep 17 00:00:00 2001 From: Reginald Cherenfant Jasmin Date: Fri, 25 Aug 2023 17:51:07 -0400 Subject: [PATCH 07/19] Conflict resolved in Questions, Surveys --- .../Providers/AnswerProvider.cs | 2 +- .../Models/Employee.cs | 8 -------- .../Providers/SurveyResponsesProvider.cs | 13 +++++++------ .../Db/SurveysDbContext.cs | 18 +++++++++++++++--- .../Providers/SurveysProvider.cs | 18 ++++++++++-------- 5 files changed, 33 insertions(+), 26 deletions(-) diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs index f7f2268..6249712 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs @@ -108,7 +108,7 @@ namespace DamageAssesment.Api.Answers.Providers return (false, null, ex.Message); } } - public (bool IsSuccess, Models.Answer Answer, string ErrorMessage) PostAnswerAsync(Db.Answer Answer) + public (bool IsSuccess, Models.Answer Answer, string ErrorMessage) PostAnswerAsync(Db.Answer Answer) { try { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Models/Employee.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Models/Employee.cs index 37afe32..5defc90 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Models/Employee.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Models/Employee.cs @@ -4,18 +4,10 @@ namespace DamageAssesment.Api.Employees.Models { public class Employee { - [Key] public string Id { get; set; } - - [StringLength(50)] public string Name { get; set; } - public DateTime BirthDate { get; set; } - - [StringLength(50)] public string OfficePhoneNumber { get; set; } - - [StringLength(50)] public string Email { get; set; } public bool IsActive { get; set; } public string? PreferredLanguage { get; set; } = "en"; diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyResponsesProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyResponsesProvider.cs index 48a6a1a..2615cfd 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyResponsesProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyResponsesProvider.cs @@ -709,16 +709,16 @@ namespace DamageAssesment.Api.SurveyResponses.Providers } - async Task ProcessAnswers(QuestionRequest questionRequest, int surveyResponseId) + bool ProcessAnswers(QuestionRequest questionRequest, int surveyResponseId) { if (questionRequest != null) { - var answer = await answerServiceProvider.PostAnswersAsync(new Answer { Id = 0, QuestionId = questionRequest.QuestionId, AnswerText = questionRequest.AnswerText, Comment = questionRequest.Comment, SurveyResponseId = surveyResponseId }); + var answer = answerServiceProvider.PostAnswersAsync(new Answer {QuestionId = questionRequest.QuestionId, AnswerText = questionRequest.AnswerText, Comment = questionRequest.Comment, SurveyResponseId = surveyResponseId }); if (answer != null) { List listAnswerInfo = new List(); listAnswerInfo.Add(new AnswerInfo { AnswerId = answer.Id, postedFiles = questionRequest.PostedFiles }); - var attachments = await attachmentServiceProvider.PostAttachmentsAsync(new AttachmentInfo { ResponseId = surveyResponseId, Answers = listAnswerInfo }); + var attachments = attachmentServiceProvider.PostAttachmentsAsync(new AttachmentInfo { ResponseId = surveyResponseId, Answers = listAnswerInfo }); string message = $"Answer for question {questionRequest.QuestionId} saved to the database"; logger?.LogInformation(message); @@ -757,18 +757,19 @@ namespace DamageAssesment.Api.SurveyResponses.Providers //var tasks = answers.Answers.Select(x => ProcessAnswers(x,surveyResponse.SurveyResponseID)); foreach (QuestionRequest ans in answers.Answers) { + ProcessAnswers(ans, surveyResponse.Id); //var stopwatch = new Stopwatch(); //stopwatch.Start(); - var task = Task.Run(() => ProcessAnswers(ans, surveyResponse.Id)); + // var task = Task.Run(() => ProcessAnswers(ans, surveyResponse.Id)); //var task = await ProcessAnswers(ans, surveyResponse.Id); - answerTasks.Add(task); + //answerTasks.Add(task); //stopwatch.Stop(); //answerTasks.Add(ProcessAnswers(ans, surveyResponse.Id)); } - await Task.WhenAll(answerTasks); + //await Task.WhenAll(answerTasks); return (true, surveyResponse, null); } else diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/SurveysDbContext.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/SurveysDbContext.cs index e912e96..95c73b0 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/SurveysDbContext.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Db/SurveysDbContext.cs @@ -2,13 +2,25 @@ namespace DamageAssesment.Api.Surveys.Db { - public class SurveysDbContext:DbContext + public class SurveysDbContext : DbContext { + public DbSet Surveys { get; set; } + public DbSet SurveysTranslation { get; set; } public SurveysDbContext(DbContextOptions options) : base(options) { } - public DbSet Surveys { get; set; } - public DbSet SurveysTranslation { get; set; } + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs index abec85a..6070d78 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs @@ -60,7 +60,6 @@ namespace DamageAssesment.Api.Surveys.Providers if (surveys != null) { - if (string.IsNullOrEmpty(Language)) { surveysList = from s in surveys @@ -184,17 +183,20 @@ namespace DamageAssesment.Api.Surveys.Providers { var surveys = await surveyDbContext.Surveys.ToListAsync(); - int Id = surveys.Count + 1; - surveyDbContext.Surveys.Add(new Db.Survey { Id = Id, IsEnabled = survey.IsEnabled, StartDate = survey.StartDate, EndDate = survey.EndDate, CreatedDate = DateTime.Now }); - var surveyTranslations = await surveyDbContext.SurveysTranslation.ToListAsync(); - int count = surveyTranslations.Count; + Db.Survey _survey = new Db.Survey { IsEnabled = survey.IsEnabled, StartDate = survey.StartDate, EndDate = survey.EndDate, CreatedDate = DateTime.Now }; + + surveyDbContext.Surveys.Add(_survey); + await surveyDbContext.SaveChangesAsync(); + + //var surveyTranslations = await surveyDbContext.SurveysTranslation.ToListAsync(); + foreach (var title in survey.Titles) { - count++; - surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation { Id = count, SurveyId = Id, Language = title.Language, Title = title.Title }); + surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation {SurveyId = _survey.Id, Language = title.Language, Title = title.Title }); } await surveyDbContext.SaveChangesAsync(); - return (true, survey, "Successful"); + survey.Id = _survey.Id; + return (true,survey, "Successful"); } else { From 82f2ae265a69eaeb1edbecb722a76c90e67dd163 Mon Sep 17 00:00:00 2001 From: uppuv Date: Fri, 25 Aug 2023 18:24:46 -0400 Subject: [PATCH 08/19] Db context changes for auto insertion --- .../MocData.cs | 4 ++-- .../Controllers/AnswersController.cs | 4 ++-- .../Db/AnswerDbContext.cs | 8 ++++++- .../Interfaces/IAnswersProvider.cs | 4 ++-- .../Profiles/AnswersProfile.cs | 1 + .../Providers/AnswerProvider.cs | 14 ++++++----- .../MockData.cs | 8 +++---- .../Controllers/AttachmentsController.cs | 4 ++-- .../Db/AttachmentsDbContext.cs | 7 ++++++ .../Interfaces/IAttachmentsProvider.cs | 4 ++-- .../Interfaces/IUploadService.cs | 6 ++--- .../Models/Attachment.cs | 10 ++++---- .../Profiles/AttachmentsProfiles.cs | 1 + .../Providers/AttachmentsProvider.cs | 19 ++++++++------- .../Providers/UploadService.cs | 20 ++++++++-------- .../Db/QuestionDbContext.cs | 23 +++++++++++++------ 16 files changed, 83 insertions(+), 54 deletions(-) diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers.Test/MocData.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers.Test/MocData.cs index e65d4f4..02466b6 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers.Test/MocData.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers.Test/MocData.cs @@ -43,9 +43,9 @@ namespace DamageAssesment.Api.Answers.Test return (false, list, null); } - public static async Task getInputAnswerData() + public static async Task getInputAnswerData() { - return new Answers.Db.Answer { Id = 1, AnswerText = "Yes", Comment = "", QuestionId = 1, SurveyResponseId = 1 }; + return new Answers.Models.Answer { Id = 1, AnswerText = "Yes", Comment = "", QuestionId = 1, SurveyResponseId = 1 }; } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs index 95b2aab..241b357 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs @@ -78,7 +78,7 @@ namespace DamageAssesment.Api.Answers.Controllers /// [HttpPut("Answers")] - public IActionResult UpdateAnswer(Db.Answer answer) + public IActionResult UpdateAnswer(Models.Answer answer) { if (answer != null) { @@ -99,7 +99,7 @@ namespace DamageAssesment.Api.Answers.Controllers /// [HttpPost("Answers")] - public IActionResult CreateAnswer(Db.Answer answer) + public IActionResult CreateAnswer(Models.Answer answer) { if (answer != null) { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Db/AnswerDbContext.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Db/AnswerDbContext.cs index 8d3a8ef..1f3c996 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Db/AnswerDbContext.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Db/AnswerDbContext.cs @@ -10,7 +10,13 @@ namespace DamageAssesment.Api.Answers.Db } public DbSet Answers { get; set; } - + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Interfaces/IAnswersProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Interfaces/IAnswersProvider.cs index 4b5fcc1..d948124 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Interfaces/IAnswersProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Interfaces/IAnswersProvider.cs @@ -6,8 +6,8 @@ Task<(bool IsSuccess, IEnumerable Answers, string ErrorMessage)> GetAnswersByQuestionAsync(int questionId); Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> GetAnswerByIdAsync(int Id); Task<(bool IsSuccess, IEnumerable Answers, string ErrorMessage)> GetAnswersAsync(int responseId); - (bool IsSuccess, Models.Answer Answer, string ErrorMessage) PostAnswerAsync(Db.Answer Answer); - (bool IsSuccess, Models.Answer Answer, string ErrorMessage) UpdateAnswerAsync(Db.Answer Answer); + (bool IsSuccess, Models.Answer Answer, string ErrorMessage) PostAnswerAsync(Models.Answer Answer); + (bool IsSuccess, Models.Answer Answer, string ErrorMessage) UpdateAnswerAsync(Models.Answer Answer); Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> DeleteAnswerAsync(int Id); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Profiles/AnswersProfile.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Profiles/AnswersProfile.cs index 0a5e6ae..ce01163 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Profiles/AnswersProfile.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Profiles/AnswersProfile.cs @@ -7,6 +7,7 @@ namespace DamageAssesment.Api.Answers.Profiles public AnswersProfile() { CreateMap(); + CreateMap(); } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs index 6249712..e9720d1 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs @@ -108,16 +108,17 @@ namespace DamageAssesment.Api.Answers.Providers return (false, null, ex.Message); } } - public (bool IsSuccess, Models.Answer Answer, string ErrorMessage) PostAnswerAsync(Db.Answer Answer) + public (bool IsSuccess, Models.Answer Answer, string ErrorMessage) PostAnswerAsync(Models.Answer Answer) { try { logger?.LogInformation("Query Answer"); if (!AnswerExists(Answer.Id)) { - answerDbContext.Answers.Add(Answer); + Db.Answer answer = mapper.Map(Answer); + answerDbContext.Answers.Add(answer); answerDbContext.SaveChanges(); - var result = mapper.Map(Answer); + var result = mapper.Map(answer); return (true, result, null); } return (false, null, "Answer is already exits"); @@ -128,7 +129,7 @@ namespace DamageAssesment.Api.Answers.Providers return (false, null, ex.Message); } } - public (bool IsSuccess, Models.Answer Answer, string ErrorMessage) UpdateAnswerAsync(Db.Answer Answer) + public (bool IsSuccess, Models.Answer Answer, string ErrorMessage) UpdateAnswerAsync(Models.Answer Answer) { try { @@ -137,9 +138,10 @@ namespace DamageAssesment.Api.Answers.Providers var existing = answerDbContext.Answers.AsNoTracking().FirstOrDefault(x => x.Id == Answer.Id); if (existing != null) { - answerDbContext.Answers.Update(Answer); + Db.Answer answer = mapper.Map(Answer); + answerDbContext.Answers.Update(answer); answerDbContext.SaveChanges(); - return (true, mapper.Map(Answer), "Successful"); + return (true, mapper.Map(answer), "Successful"); } else { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments.Test/MockData.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments.Test/MockData.cs index 284830d..c097902 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments.Test/MockData.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments.Test/MockData.cs @@ -17,7 +17,7 @@ namespace DamageAssesment.Api.Attachments.Test for (int i = 0; i < 10; i++) { - list.Add(new Attachments.Models.Attachment(i, Guid.NewGuid().ToString() + "@gmail.com") + list.Add(new Attachments.Models.Attachment() { Id = i, AnswerId = i, @@ -73,10 +73,10 @@ namespace DamageAssesment.Api.Attachments.Test return (false, list, null); } - public static async Task> getInputAttachmentData() + public static async Task> getInputAttachmentData() { - List Attachments=new List(); - Attachments.Add(new Db.Attachment{ Id = 0, AnswerId = 10, ResponseId = 10, URI = "sample", IsDeleted = false,FileName="sample1" }) ; + List Attachments=new List(); + Attachments.Add(new Models.Attachment{ Id = 0, AnswerId = 10, ResponseId = 10, URI = "sample", IsDeleted = false,FileName="sample1" }) ; return Attachments; } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs index 745db41..f4f0785 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs @@ -90,7 +90,7 @@ namespace DamageAssesment.Api.Attachments.Controllers if (attachmentInfo.Answers.Count > 0) { var Attachments = this.AttachmentProvider.GetAttachmentCounter(); - List attachments = UploadService.UploadAttachment(attachmentInfo.ResponseId, Attachments.counter, attachmentInfo.Answers); + List attachments = UploadService.UploadAttachment(attachmentInfo.ResponseId, Attachments.counter, attachmentInfo.Answers); var result = this.AttachmentProvider.PostAttachmentAsync(attachments); if (result.IsSuccess) { @@ -119,7 +119,7 @@ namespace DamageAssesment.Api.Attachments.Controllers var res = this.AttachmentProvider.GetAttachmentInfo(attachmentInfo.Answers); if (res.IsSuccess) { - List attachments = UploadService.UpdateAttachments(attachmentInfo.ResponseId, attachmentInfo.Answers, res.Attachments); + List attachments = UploadService.UpdateAttachments(attachmentInfo.ResponseId, attachmentInfo.Answers, res.Attachments); var result = this.AttachmentProvider.PutAttachmentAsync(attachments); if (result.IsSuccess) { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Db/AttachmentsDbContext.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Db/AttachmentsDbContext.cs index 561377d..b4e8d0c 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Db/AttachmentsDbContext.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Db/AttachmentsDbContext.cs @@ -8,5 +8,12 @@ namespace DamageAssesment.Api.Attachments.Db { } public DbSet Attachments { get; set; } + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IAttachmentsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IAttachmentsProvider.cs index 81bc749..5af5c60 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IAttachmentsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IAttachmentsProvider.cs @@ -6,8 +6,8 @@ namespace DamageAssesment.Api.Attachments.Interfaces { Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> GetAttachmentsAsync(); Task<(bool IsSuccess, Models.Attachment Attachment, string ErrorMessage)> GetAttachmentByIdAsync(int Id); - (bool IsSuccess, IEnumerable Attachments, string ErrorMessage) PostAttachmentAsync(List Attachments); - (bool IsSuccess, IEnumerable Attachments, string ErrorMessage) PutAttachmentAsync(List Attachments); + (bool IsSuccess, IEnumerable Attachments, string ErrorMessage) PostAttachmentAsync(List Attachments); + (bool IsSuccess, IEnumerable Attachments, string ErrorMessage) PutAttachmentAsync(List Attachments); Task<(bool IsSuccess, Models.Attachment Attachment, string Path)> DeleteAttachmentAsync(int Id); Task<(bool IsSuccess, int counter, string Path)> DeleteAttachmentsAsync(int responseId, int answerId); Task<(bool IsSuccess, int counter, string Path)> DeleteBulkAttachmentsAsync(int responseId, List answerIds); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IUploadService.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IUploadService.cs index 121d411..f645593 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IUploadService.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IUploadService.cs @@ -4,9 +4,9 @@ namespace DamageAssesment.Api.Attachments.Interfaces { public interface IUploadService { - List UploadAttachment(int responseId,int answerId, int counter, List postedFile); - List UploadAttachment(int responseId, int counter, List answers); - public List UpdateAttachments(int responseId, List answers, IEnumerable attachments); + List UploadAttachment(int responseId,int answerId, int counter, List postedFile); + List UploadAttachment(int responseId, int counter, List answers); + public List UpdateAttachments(int responseId, List answers, IEnumerable attachments); void Deletefile(string path); void Movefile(string path); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Models/Attachment.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Models/Attachment.cs index 8f2ba66..b364727 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Models/Attachment.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Models/Attachment.cs @@ -13,10 +13,10 @@ namespace DamageAssesment.Api.Attachments.Models public bool IsDeleted { get; set; } public string FileName { get; set; } - public Attachment(int answerId, string uri) - { - this.AnswerId = answerId; - this.URI = uri; - } + //public Attachment(int answerId, string uri) + //{ + // this.AnswerId = answerId; + // this.URI = uri; + //} } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Profiles/AttachmentsProfiles.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Profiles/AttachmentsProfiles.cs index 44ee69f..2dca91e 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Profiles/AttachmentsProfiles.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Profiles/AttachmentsProfiles.cs @@ -5,6 +5,7 @@ public AttachmentsProfiles() { CreateMap(); + CreateMap(); } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/AttachmentsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/AttachmentsProvider.cs index aa42d93..46356db 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/AttachmentsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/AttachmentsProvider.cs @@ -65,14 +65,15 @@ namespace DamageAssesment.Api.Attachments.Providers return (false, null, ex.Message); } } - public (bool IsSuccess, IEnumerable Attachments, string ErrorMessage) PostAttachmentAsync(List Attachments) + public (bool IsSuccess, IEnumerable Attachments, string ErrorMessage) PostAttachmentAsync(List Attachments) { try { logger?.LogInformation("Query Attachment"); - AttachmentDbContext.Attachments.AddRange(Attachments); + List attachments = mapper.Map, List>(Attachments); + AttachmentDbContext.Attachments.AddRange(attachments); AttachmentDbContext.SaveChanges(); - var result = mapper.Map, IEnumerable>(Attachments); + var result = mapper.Map, IEnumerable>(attachments); return (true, result, null); } catch (Exception ex) @@ -82,14 +83,15 @@ namespace DamageAssesment.Api.Attachments.Providers } } - public (bool IsSuccess, IEnumerable Attachments, string ErrorMessage) PutAttachmentAsync(List Attachments) + public (bool IsSuccess, IEnumerable Attachments, string ErrorMessage) PutAttachmentAsync(List Attachments) { try { logger?.LogInformation("Query Attachment"); - AttachmentDbContext.Attachments.UpdateRange(Attachments); + List attachments = mapper.Map, List>(Attachments); + AttachmentDbContext.Attachments.UpdateRange(attachments); AttachmentDbContext.SaveChanges(); - var result = mapper.Map, IEnumerable>(Attachments); + var result = mapper.Map, IEnumerable>(attachments); return (true, result, null); } catch (Exception ex) @@ -204,10 +206,11 @@ namespace DamageAssesment.Api.Attachments.Providers FileModel fileModel= new FileModel(){AttachmentId=0,FileName="Sample",FileContent= "c2FtcGxl",FileExtension=".txt"}; List answerInfos=new List(); answerInfos.Add(new AnswerInfo(){ AnswerId = 1,postedFiles=new List { fileModel }}); - List attachments = uploadservice.UploadAttachment(1, 0, answerInfos); + List attachments = uploadservice.UploadAttachment(1, 0, answerInfos); if (attachments.Count > 0) { - AttachmentDbContext.Attachments.AddRange(attachments); + List Attachments = mapper.Map, List>(attachments); + AttachmentDbContext.Attachments.AddRange(Attachments); AttachmentDbContext.SaveChanges(); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/UploadService.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/UploadService.cs index 3c0f21f..8c9045c 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/UploadService.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/UploadService.cs @@ -24,7 +24,7 @@ namespace DamageAssesment.Api.Attachments.Providers uploadpath = configuration.GetValue("Fileupload:folderpath"); Deletepath = configuration.GetValue("Fileupload:Deletepath"); } - public List UploadAttachment(int responseId,int answerId,int counter, List postedFile) + public List UploadAttachment(int responseId,int answerId,int counter, List postedFile) { var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), uploadpath); String responseDirectory = "Response-" + responseId; @@ -42,7 +42,7 @@ namespace DamageAssesment.Api.Attachments.Providers Deletefile(searchFile); } } - List attachments = new List(); + List attachments = new List(); foreach (IFormFile item in postedFile) { @@ -55,15 +55,15 @@ namespace DamageAssesment.Api.Attachments.Providers { item.CopyTo(stream); } - attachments.Add(new Db.Attachment { AnswerId = answerId, ResponseId = responseId, IsDeleted = false, FileName = UserfileName, URI = dbPath }); + attachments.Add(new Models.Attachment { AnswerId = answerId, ResponseId = responseId, IsDeleted = false, FileName = UserfileName, URI = dbPath }); } return attachments; } - public List UploadAttachment(int responseId, int counter,List answers) + public List UploadAttachment(int responseId, int counter,List answers) { - List attachments = new List(); + List attachments = new List(); try { foreach (var item in answers) @@ -94,20 +94,20 @@ namespace DamageAssesment.Api.Attachments.Providers var dbPath = Path.Combine(fullDirectoryPath, fileName); File.WriteAllBytes(dbPath, Convert.FromBase64String(file.FileContent)); - attachments.Add(new Db.Attachment { AnswerId = answerId, ResponseId = responseId, IsDeleted = false, FileName = UserfileName, URI = dbPath }); + attachments.Add(new Models.Attachment { AnswerId = answerId, ResponseId = responseId, IsDeleted = false, FileName = UserfileName, URI = dbPath }); } } return attachments; } catch (Exception ex) { - return new List(); + return new List(); } } - public List UpdateAttachments(int responseId,List answers,IEnumerable attachments) + public List UpdateAttachments(int responseId,List answers,IEnumerable attachments) { - List Dbattachments = new List(); + List Dbattachments = new List(); foreach (Models.Attachment searchFile in attachments) { Deletefile(searchFile.URI); @@ -131,7 +131,7 @@ namespace DamageAssesment.Api.Attachments.Providers var dbPath = Path.Combine(fullDirectoryPath, fileName); File.WriteAllBytes(dbPath, Convert.FromBase64String(file.FileContent)); - Dbattachments.Add(new Db.Attachment { Id=attachment.Id, AnswerId = answerId, ResponseId = responseId, IsDeleted = false, FileName = UserfileName, URI = dbPath }); + Dbattachments.Add(new Models.Attachment { Id=attachment.Id, AnswerId = answerId, ResponseId = responseId, IsDeleted = false, FileName = UserfileName, URI = dbPath }); } } return Dbattachments; diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/QuestionDbContext.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/QuestionDbContext.cs index a784abf..a62485e 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/QuestionDbContext.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/QuestionDbContext.cs @@ -14,12 +14,21 @@ namespace DamageAssesment.Api.Questions.Db { } - //protected override void OnModelCreating(ModelBuilder modelBuilder) - //{ - // modelBuilder.Entity() - // .HasOne(a => a.QuestionType) - // .WithOne(b => b.Question) - // .HasForeignKey(b => b.QuestionTypeID); - //} + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + } } } From 7a50089f6a67496e41426c6254f862b118fde918 Mon Sep 17 00:00:00 2001 From: Reginald Cherenfant Jasmin Date: Fri, 25 Aug 2023 18:44:04 -0400 Subject: [PATCH 09/19] Update DbContext Changes --- .../Controllers/EmployeesController.cs | 6 +++--- .../Db/EmployeeDbContext.cs | 2 -- .../Interfaces/IEmployeesProvider.cs | 4 ++-- .../Providers/EmployeesProvider.cs | 18 ++++++++++-------- .../Interfaces/ILocationsProvider.cs | 4 ++-- .../Providers/LocationsProvider.cs | 13 +++++++------ .../Providers/SurveysProvider.cs | 9 +++------ 7 files changed, 27 insertions(+), 29 deletions(-) diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Controllers/EmployeesController.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Controllers/EmployeesController.cs index a074f21..8d004e6 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Controllers/EmployeesController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Controllers/EmployeesController.cs @@ -55,11 +55,11 @@ namespace DamageAssesment.Api.Employees.Controllers /// /// The updated employee object. [HttpPut("Employees")] - public async Task UpdateEmployee(Db.Employee Employee) + public async Task UpdateEmployee(string Id, Models.Employee Employee) { if (Employee != null) { - var result = await this.EmployeeProvider.UpdateEmployeeAsync(Employee); + var result = await this.EmployeeProvider.UpdateEmployeeAsync(Id,Employee); if (result.IsSuccess) { return Ok(result.Employee); @@ -77,7 +77,7 @@ namespace DamageAssesment.Api.Employees.Controllers /// /// The employee information for creating a new employee. [HttpPost("Employees")] - public async Task CreateEmployee(Db.Employee Employee) + public async Task CreateEmployee(Models.Employee Employee) { if (Employee != null) { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Db/EmployeeDbContext.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Db/EmployeeDbContext.cs index 64234cd..0d7bc5e 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Db/EmployeeDbContext.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Db/EmployeeDbContext.cs @@ -7,8 +7,6 @@ namespace DamageAssesment.Api.Employees.Db public DbSet Employees { get; set; } public EmployeeDbContext(DbContextOptions options) : base(options) { - - } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Interfaces/IEmployeesProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Interfaces/IEmployeesProvider.cs index 059483d..529141c 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Interfaces/IEmployeesProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Interfaces/IEmployeesProvider.cs @@ -4,8 +4,8 @@ { Task<(bool IsSuccess, IEnumerable Employees, string ErrorMessage)> GetEmployeesAsync(); Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> GetEmployeeByIdAsync(string Id); - Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> PostEmployeeAsync(Db.Employee Employee); - Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> UpdateEmployeeAsync(Db.Employee Employee); + 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); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Providers/EmployeesProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Providers/EmployeesProvider.cs index 8e31e82..67ca1eb 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Providers/EmployeesProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Providers/EmployeesProvider.cs @@ -65,17 +65,18 @@ namespace DamageAssesment.Api.Employees.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> PostEmployeeAsync(Db.Employee Employee) + public async Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> PostEmployeeAsync(Models.Employee Employee) { try { + Db.Employee _employee = mapper.Map(Employee); + logger?.LogInformation("Query Employee"); if (!EmployeeExists(Employee.Id)) { - EmployeeDbContext.Employees.Add(Employee); + EmployeeDbContext.Employees.Add(_employee); EmployeeDbContext.SaveChanges(); - var result = mapper.Map(Employee); - return (true, result, null); + return (true, Employee, null); } return (false, null, "Employee is already exits"); } @@ -85,19 +86,20 @@ namespace DamageAssesment.Api.Employees.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> UpdateEmployeeAsync(Db.Employee Employee) + public async Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> UpdateEmployeeAsync(string Id , Models.Employee Employee) { try { if (Employee != null) { - var _employee = await EmployeeDbContext.Employees.AsNoTracking().Where(s => s.Id.ToLower() == Employee.Id.ToLower()).FirstOrDefaultAsync(); + var _employee = await EmployeeDbContext.Employees.AsNoTracking().Where(s => s.Id.ToLower() == Id.ToLower()).FirstOrDefaultAsync(); if (_employee != null) { - EmployeeDbContext.Employees.Update(Employee); + Db.Employee vEmployee = mapper.Map(Employee); + EmployeeDbContext.Employees.Update(vEmployee); EmployeeDbContext.SaveChanges(); - return (true, mapper.Map(Employee), "Successful"); + return (true, Employee, "Successful"); } else { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/ILocationsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/ILocationsProvider.cs index 8e85496..ff0ee55 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/ILocationsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/ILocationsProvider.cs @@ -6,8 +6,8 @@ namespace DamageAssesment.Api.Locations.Interfaces { Task<(bool IsSuccess, IEnumerable locations, string ErrorMessage)> GetLocationsAsync(); Task<(bool IsSuccess, Models.Location Location, string ErrorMessage)> GetLocationByIdAsync(string Id); - Task<(bool IsSuccess, Models.Location Question, string ErrorMessage)> PostLocationAsync(Db.Location Location); - Task<(bool IsSuccess, string ErrorMessage)> UpdateLocationAsync(Db.Location Location); + 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); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/LocationsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/LocationsProvider.cs index fcba375..cf0e978 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/LocationsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/LocationsProvider.cs @@ -63,17 +63,17 @@ namespace DamageAssesment.Api.Locations.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Location Question, string ErrorMessage)> PostLocationAsync(Db.Location Location) + public async Task<(bool IsSuccess, Models.Location Question, string ErrorMessage)> PostLocationAsync(Models.Location Location) { try { logger?.LogInformation("Query Location"); if (!LocationExists(Location.Id)) { - locationDbContext.Locations.Add(Location); + Db.Location _location = mapper.Map(Location); + locationDbContext.Locations.Add(_location); locationDbContext.SaveChanges(); - var result = mapper.Map(Location); - return (true, result, null); + return (true, Location, null); } else { @@ -86,11 +86,12 @@ namespace DamageAssesment.Api.Locations.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, string ErrorMessage)> UpdateLocationAsync(Db.Location Location) + public async Task<(bool IsSuccess, string ErrorMessage)> UpdateLocationAsync(Models.Location Location) { try { - locationDbContext.Entry(Location).State = EntityState.Modified; + Db.Location _location = mapper.Map(Location); + locationDbContext.Entry(_location).State = EntityState.Modified; locationDbContext.SaveChanges(); return (true, "Record updated successfully"); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs index 6070d78..38ea756 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs @@ -181,15 +181,12 @@ namespace DamageAssesment.Api.Surveys.Providers { if (survey != null) { - var surveys = await surveyDbContext.Surveys.ToListAsync(); + survey.CreatedDate = DateTime.Now; + Db.Survey _survey = mapper.Map(survey); - Db.Survey _survey = new Db.Survey { IsEnabled = survey.IsEnabled, StartDate = survey.StartDate, EndDate = survey.EndDate, CreatedDate = DateTime.Now }; - surveyDbContext.Surveys.Add(_survey); await surveyDbContext.SaveChangesAsync(); - - //var surveyTranslations = await surveyDbContext.SurveysTranslation.ToListAsync(); - + foreach (var title in survey.Titles) { surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation {SurveyId = _survey.Id, Language = title.Language, Title = title.Title }); From 5a641ff3aa5aa3e120e6930c0f810074a0c6e45f Mon Sep 17 00:00:00 2001 From: Reginald Cherenfant Jasmin Date: Fri, 25 Aug 2023 18:51:50 -0400 Subject: [PATCH 10/19] Update controller in Location for Models Class --- .../Controllers/LocationsController.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs index 040bd93..0ee489a 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs @@ -51,7 +51,7 @@ namespace DamageAssesment.Api.Locations.Controllers /// [HttpPut("Locations")] - public async Task UpdateLocation(Db.Location Location) + public async Task UpdateLocation(Models.Location Location) { if (Location != null) { @@ -69,7 +69,7 @@ namespace DamageAssesment.Api.Locations.Controllers /// [HttpPost("Locations")] - public async Task CreateLocation(Db.Location Location) + public async Task CreateLocation(Models.Location Location) { if (Location != null) { From 96ccb96bf1d0015ae1816e4a496cc18eba7f1587 Mon Sep 17 00:00:00 2001 From: Reginald Cherenfant Jasmin Date: Sun, 27 Aug 2023 11:55:58 -0400 Subject: [PATCH 11/19] Update to Async Attachement, Answer and Update Multiple Answers submission - backlog #288 --- .../AnswersServiceTest.cs | 20 +- .../Controllers/AnswersController.cs | 8 +- .../Interfaces/IAnswersProvider.cs | 4 +- .../Providers/AnswerProvider.cs | 13 +- .../AttachmentsServiceTest.cs | 16 +- .../Controllers/AttachmentsController.cs | 12 +- .../Response-1/Answer-1/Attachment_1.txt | 1 - .../Interfaces/IAttachmentsProvider.cs | 8 +- .../Providers/AttachmentsProvider.cs | 18 +- .../EmployeeServiceTest.cs | 12 +- .../MockData.cs | 8 +- .../LocationsServiceTest.cs | 4 +- .../Controllers/SurveyResponsesController.cs | 6 +- .../Db/SurveyResponseDbContext.cs | 8 + .../Interfaces/ISurveysResponse.cs | 2 +- .../Models/AnswerRequest.cs | 8 +- .../Models/Question.cs | 2 +- .../Models/QuestionRequest.cs | 10 - .../Models/Request.cs | 10 + .../Program.cs | 1 + .../Providers/AnswerServiceProvider.cs | 23 +- .../Providers/AttachmentServiceProvider.cs | 13 +- .../Providers/SurveyResponsesProvider.cs | 97 ++--- .../Bases/ServiceProviderBase.cs | 21 -- .../Controllers/UsersAccessController.cs | 97 ----- .../DamageAssesment.Api.UsersAccess.csproj | 19 - .../Db/Role.cs | 21 -- .../Db/Token.cs | 17 - .../Db/User.cs | 27 -- .../Db/UsersAccessDbContext.cs | 17 - .../Interfaces/IEmployeeServiceProvider.cs | 10 - .../Interfaces/IRoleProvider.cs | 12 - .../Interfaces/ITokenServiceProvider.cs | 11 - .../Interfaces/IUsersAccessProvider.cs | 16 - .../Models/Employee.cs | 21 -- .../Models/JwtSettings.cs | 9 - .../Models/Role.cs | 9 - .../Models/Token.cs | 10 - .../Models/TokenResponse.cs | 8 - .../Models/User.cs | 12 - .../Models/UserCredentials.cs | 5 - .../Profiles/UsersAccessProfile.cs | 14 - .../Program.cs | 77 ---- .../Properties/launchSettings.json | 31 -- .../Providers/EmployeeServiceProvider.cs | 58 --- .../Providers/TokenServiceProvider.cs | 57 --- .../Providers/UserAccessProvider.cs | 341 ------------------ .../appsettings.Development.json | 8 - .../appsettings.json | 15 - DamageAssesmentApi/DamageAssesment.sln | 6 - 50 files changed, 166 insertions(+), 1087 deletions(-) delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.Attachments/DMS_Attachments/Active/Response-1/Answer-1/Attachment_1.txt delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/QuestionRequest.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Request.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Bases/ServiceProviderBase.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Controllers/UsersAccessController.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/DamageAssesment.Api.UsersAccess.csproj delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/Role.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/Token.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/User.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/UsersAccessDbContext.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IEmployeeServiceProvider.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IRoleProvider.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/ITokenServiceProvider.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IUsersAccessProvider.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Employee.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/JwtSettings.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Role.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Token.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/TokenResponse.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/User.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/UserCredentials.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Profiles/UsersAccessProfile.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Program.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Properties/launchSettings.json delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/EmployeeServiceProvider.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/TokenServiceProvider.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/UserAccessProvider.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/appsettings.Development.json delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.UsersAccess/appsettings.json diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers.Test/AnswersServiceTest.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers.Test/AnswersServiceTest.cs index ad6ec72..0969153 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers.Test/AnswersServiceTest.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers.Test/AnswersServiceTest.cs @@ -95,10 +95,10 @@ namespace DamageAssesment.Api.Answers.Test var mockAnswerService = new Mock(); var mockResponse = await MockData.getOkResponse(1); var mockInputAnswer = await MockData.getInputAnswerData(); - mockAnswerService.Setup(service => service.PostAnswerAsync(mockInputAnswer)).Returns(mockResponse); + mockAnswerService.Setup(service => service.PostAnswerAsync(mockInputAnswer)).ReturnsAsync(mockResponse); var AnswerProvider = new AnswersController(mockAnswerService.Object); - var result = (OkObjectResult) AnswerProvider.CreateAnswer(mockInputAnswer); + var result = (OkObjectResult) await AnswerProvider.CreateAnswer(mockInputAnswer); Assert.Equal(200, result.StatusCode); } @@ -109,10 +109,10 @@ namespace DamageAssesment.Api.Answers.Test var mockAnswerService = new Mock(); var mockInputAnswer = await MockData.getInputAnswerData(); var mockResponse = await MockData.getBadRequestResponse(); - mockAnswerService.Setup(service => service.PostAnswerAsync(mockInputAnswer)).Returns(mockResponse); + mockAnswerService.Setup(service => service.PostAnswerAsync(mockInputAnswer)).ReturnsAsync(mockResponse); var AnswerProvider = new AnswersController(mockAnswerService.Object); - var result = (BadRequestObjectResult) AnswerProvider.CreateAnswer(mockInputAnswer); + var result = (BadRequestObjectResult) await AnswerProvider.CreateAnswer(mockInputAnswer); Assert.Equal(400, result.StatusCode); } @@ -123,10 +123,10 @@ namespace DamageAssesment.Api.Answers.Test var mockAnswerService = new Mock(); var mockResponse = await MockData.getOkResponse(1); var mockInputAnswer = await MockData.getInputAnswerData(); - mockAnswerService.Setup(service => service.UpdateAnswerAsync(mockInputAnswer)).Returns(mockResponse); + mockAnswerService.Setup(service => service.UpdateAnswerAsync(mockInputAnswer)).ReturnsAsync(mockResponse); var AnswerProvider = new AnswersController(mockAnswerService.Object); - var result = (OkObjectResult) AnswerProvider.UpdateAnswer(mockInputAnswer); + var result = (OkObjectResult) await AnswerProvider.UpdateAnswer(mockInputAnswer); Assert.Equal(200, result.StatusCode); } @@ -137,10 +137,10 @@ namespace DamageAssesment.Api.Answers.Test var mockAnswerService = new Mock(); var mockResponse = await MockData.getNotFoundResponse(); var mockInputAnswer = await MockData.getInputAnswerData(); - mockAnswerService.Setup(service => service.UpdateAnswerAsync(mockInputAnswer)).Returns(mockResponse); + mockAnswerService.Setup(service => service.UpdateAnswerAsync(mockInputAnswer)).ReturnsAsync(mockResponse); var AnswerProvider = new AnswersController(mockAnswerService.Object); - var result = (NotFoundObjectResult) AnswerProvider.UpdateAnswer(mockInputAnswer); + var result = (NotFoundObjectResult) await AnswerProvider.UpdateAnswer(mockInputAnswer); Assert.Equal(404, result.StatusCode); } @@ -151,10 +151,10 @@ namespace DamageAssesment.Api.Answers.Test var mockAnswerService = new Mock(); var mockResponse = await MockData.getBadRequestResponse(); var mockInputAnswer = await MockData.getInputAnswerData(); - mockAnswerService.Setup(service => service.UpdateAnswerAsync(mockInputAnswer)).Returns(mockResponse); + mockAnswerService.Setup(service => service.UpdateAnswerAsync(mockInputAnswer)).ReturnsAsync(mockResponse); var AnswerProvider = new AnswersController(mockAnswerService.Object); - var result = (BadRequestObjectResult) AnswerProvider.UpdateAnswer(mockInputAnswer); + var result = (BadRequestObjectResult) await AnswerProvider.UpdateAnswer(mockInputAnswer); Assert.Equal(400, result.StatusCode); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs index 241b357..bbfc323 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs @@ -78,11 +78,11 @@ namespace DamageAssesment.Api.Answers.Controllers /// [HttpPut("Answers")] - public IActionResult UpdateAnswer(Models.Answer answer) + public async Task UpdateAnswer(Models.Answer answer) { if (answer != null) { - var result = this.answerProvider.UpdateAnswerAsync(answer); + var result = await this.answerProvider.UpdateAnswerAsync(answer); if (result.IsSuccess) { return Ok(result.Answer); @@ -99,11 +99,11 @@ namespace DamageAssesment.Api.Answers.Controllers /// [HttpPost("Answers")] - public IActionResult CreateAnswer(Models.Answer answer) + public async Task CreateAnswer(Models.Answer answer) { if (answer != null) { - var result = this.answerProvider.PostAnswerAsync(answer); + var result = await this.answerProvider.PostAnswerAsync(answer); if (result.IsSuccess) { return Ok(result.Answer); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Interfaces/IAnswersProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Interfaces/IAnswersProvider.cs index d948124..fa76fcf 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Interfaces/IAnswersProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Interfaces/IAnswersProvider.cs @@ -6,8 +6,8 @@ Task<(bool IsSuccess, IEnumerable Answers, string ErrorMessage)> GetAnswersByQuestionAsync(int questionId); Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> GetAnswerByIdAsync(int Id); Task<(bool IsSuccess, IEnumerable Answers, string ErrorMessage)> GetAnswersAsync(int responseId); - (bool IsSuccess, Models.Answer Answer, string ErrorMessage) PostAnswerAsync(Models.Answer Answer); - (bool IsSuccess, Models.Answer Answer, string ErrorMessage) UpdateAnswerAsync(Models.Answer Answer); + 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); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs index e9720d1..37a80a7 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Providers/AnswerProvider.cs @@ -108,7 +108,7 @@ namespace DamageAssesment.Api.Answers.Providers return (false, null, ex.Message); } } - public (bool IsSuccess, Models.Answer Answer, string ErrorMessage) PostAnswerAsync(Models.Answer Answer) + public async Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> PostAnswerAsync(Models.Answer Answer) { try { @@ -117,7 +117,7 @@ namespace DamageAssesment.Api.Answers.Providers { Db.Answer answer = mapper.Map(Answer); answerDbContext.Answers.Add(answer); - answerDbContext.SaveChanges(); + await answerDbContext.SaveChangesAsync(); var result = mapper.Map(answer); return (true, result, null); } @@ -129,7 +129,7 @@ namespace DamageAssesment.Api.Answers.Providers return (false, null, ex.Message); } } - public (bool IsSuccess, Models.Answer Answer, string ErrorMessage) UpdateAnswerAsync(Models.Answer Answer) + public async Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> UpdateAnswerAsync(Models.Answer Answer) { try { @@ -140,7 +140,7 @@ namespace DamageAssesment.Api.Answers.Providers { Db.Answer answer = mapper.Map(Answer); answerDbContext.Answers.Update(answer); - answerDbContext.SaveChanges(); + await answerDbContext.SaveChangesAsync(); return (true, mapper.Map(answer), "Successful"); } else @@ -154,7 +154,6 @@ namespace DamageAssesment.Api.Answers.Providers logger?.LogInformation($"{Answer} Bad Request"); return (false, null, "Bad request"); } - } catch (Exception ex) { @@ -201,10 +200,6 @@ namespace DamageAssesment.Api.Answers.Providers answerDbContext.Answers.Add(new Db.Answer() { Id = 6, AnswerText = "No", Comment = "No Comment", QuestionId = 3, SurveyResponseId = 2 }); answerDbContext.SaveChanges(); } - } - - - } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments.Test/AttachmentsServiceTest.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments.Test/AttachmentsServiceTest.cs index 6b65c79..1b3ff31 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments.Test/AttachmentsServiceTest.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments.Test/AttachmentsServiceTest.cs @@ -77,10 +77,10 @@ namespace DamageAssesment.Api.Attachments.Test var mockResponse = await MockData.getOkResponse(); var AttachmentResponse = await MockData.GetAttachmentInfo(0); var mockInputAttachment = await MockData.getInputAttachmentData(); - mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).Returns(mockResponse); + mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).ReturnsAsync(mockResponse); var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object); - var result = (NoContentResult) AttachmentProvider.UploadAttachmentAsync(AttachmentResponse); + var result = (NoContentResult) await AttachmentProvider.UploadAttachmentAsync(AttachmentResponse); Assert.Equal(204, result.StatusCode); } @@ -92,11 +92,11 @@ namespace DamageAssesment.Api.Attachments.Test var mockUploadService = new Mock(); var mockInputAttachment = await MockData.getInputAttachmentData(); var mockResponse = await MockData.getBadRequestResponse(); - mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).Returns(mockResponse); + mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).ReturnsAsync(mockResponse); var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object); AttachmentInfo attachmentInfo=new AttachmentInfo(); - var result = (BadRequestObjectResult) AttachmentProvider.UploadAttachmentAsync(attachmentInfo); + var result = (BadRequestObjectResult) await AttachmentProvider.UploadAttachmentAsync(attachmentInfo); Assert.Equal(400, result.StatusCode); } @@ -109,10 +109,10 @@ namespace DamageAssesment.Api.Attachments.Test var mockResponse = await MockData.getOkResponse(); var AttachmentResponse = await MockData.GetAttachmentInfo(1); var mockInputAttachment = await MockData.getInputAttachmentData(); - mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).Returns(mockResponse); + mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).ReturnsAsync(mockResponse); var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object); - var result = (NoContentResult) AttachmentProvider.UpdateAttachmentAsync(AttachmentResponse); + var result = (NoContentResult) await AttachmentProvider.UpdateAttachmentAsync(AttachmentResponse); Assert.Equal(204, result.StatusCode); } @@ -124,11 +124,11 @@ namespace DamageAssesment.Api.Attachments.Test var mockUploadService = new Mock(); var mockInputAttachment = await MockData.getInputAttachmentData(); var mockResponse = await MockData.getBadRequestResponse(); - mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).Returns(mockResponse); + mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).ReturnsAsync(mockResponse); var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object); AttachmentInfo attachmentInfo = new AttachmentInfo(); - var result = (BadRequestObjectResult) AttachmentProvider.UpdateAttachmentAsync(attachmentInfo); + var result = (BadRequestObjectResult) await AttachmentProvider.UpdateAttachmentAsync(attachmentInfo); Assert.Equal(400, result.StatusCode); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs index f4f0785..8050515 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs @@ -83,15 +83,15 @@ namespace DamageAssesment.Api.Attachments.Controllers /// [HttpPost("Attachments"), DisableRequestSizeLimit] - public IActionResult UploadAttachmentAsync(AttachmentInfo attachmentInfo) + public async Task UploadAttachmentAsync(AttachmentInfo attachmentInfo) { try { if (attachmentInfo.Answers.Count > 0) { - var Attachments = this.AttachmentProvider.GetAttachmentCounter(); + var Attachments = await this.AttachmentProvider.GetAttachmentCounter(); List attachments = UploadService.UploadAttachment(attachmentInfo.ResponseId, Attachments.counter, attachmentInfo.Answers); - var result = this.AttachmentProvider.PostAttachmentAsync(attachments); + var result = await this.AttachmentProvider.PostAttachmentAsync(attachments); if (result.IsSuccess) { return Ok(result.Attachments); @@ -110,17 +110,17 @@ namespace DamageAssesment.Api.Attachments.Controllers /// [HttpPut("Attachments"), DisableRequestSizeLimit] - public IActionResult UpdateAttachmentAsync(AttachmentInfo attachmentInfo) + public async Task UpdateAttachmentAsync(AttachmentInfo attachmentInfo) { try { if (attachmentInfo.Answers.Count > 0) { - var res = this.AttachmentProvider.GetAttachmentInfo(attachmentInfo.Answers); + var res = await this.AttachmentProvider.GetAttachmentInfo(attachmentInfo.Answers); if (res.IsSuccess) { List attachments = UploadService.UpdateAttachments(attachmentInfo.ResponseId, attachmentInfo.Answers, res.Attachments); - var result = this.AttachmentProvider.PutAttachmentAsync(attachments); + var result = await this.AttachmentProvider.PutAttachmentAsync(attachments); if (result.IsSuccess) { return Ok(result.Attachments); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/DMS_Attachments/Active/Response-1/Answer-1/Attachment_1.txt b/DamageAssesmentApi/DamageAssesment.Api.Attachments/DMS_Attachments/Active/Response-1/Answer-1/Attachment_1.txt deleted file mode 100644 index eed7e79..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/DMS_Attachments/Active/Response-1/Answer-1/Attachment_1.txt +++ /dev/null @@ -1 +0,0 @@ -sample \ No newline at end of file diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IAttachmentsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IAttachmentsProvider.cs index 5af5c60..5e56dbb 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IAttachmentsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Interfaces/IAttachmentsProvider.cs @@ -6,12 +6,12 @@ namespace DamageAssesment.Api.Attachments.Interfaces { Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> GetAttachmentsAsync(); Task<(bool IsSuccess, Models.Attachment Attachment, string ErrorMessage)> GetAttachmentByIdAsync(int Id); - (bool IsSuccess, IEnumerable Attachments, string ErrorMessage) PostAttachmentAsync(List Attachments); - (bool IsSuccess, IEnumerable Attachments, string ErrorMessage) PutAttachmentAsync(List Attachments); + Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> PostAttachmentAsync(List Attachments); + Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> PutAttachmentAsync(List Attachments); Task<(bool IsSuccess, Models.Attachment Attachment, string Path)> DeleteAttachmentAsync(int Id); Task<(bool IsSuccess, int counter, string Path)> DeleteAttachmentsAsync(int responseId, int answerId); Task<(bool IsSuccess, int counter, string Path)> DeleteBulkAttachmentsAsync(int responseId, List answerIds); - (bool IsSuccess, int counter, string message) GetAttachmentCounter(); - (bool IsSuccess, IEnumerable Attachments, string ErrorMessage) GetAttachmentInfo(List answers); + Task<(bool IsSuccess, int counter, string message)> GetAttachmentCounter(); + Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> GetAttachmentInfo(List answers); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/AttachmentsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/AttachmentsProvider.cs index 46356db..c18cd05 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/AttachmentsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Providers/AttachmentsProvider.cs @@ -65,14 +65,14 @@ namespace DamageAssesment.Api.Attachments.Providers return (false, null, ex.Message); } } - public (bool IsSuccess, IEnumerable Attachments, string ErrorMessage) PostAttachmentAsync(List Attachments) + public async Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> PostAttachmentAsync(List Attachments) { try { logger?.LogInformation("Query Attachment"); List attachments = mapper.Map, List>(Attachments); AttachmentDbContext.Attachments.AddRange(attachments); - AttachmentDbContext.SaveChanges(); + await AttachmentDbContext.SaveChangesAsync(); var result = mapper.Map, IEnumerable>(attachments); return (true, result, null); } @@ -83,14 +83,14 @@ namespace DamageAssesment.Api.Attachments.Providers } } - public (bool IsSuccess, IEnumerable Attachments, string ErrorMessage) PutAttachmentAsync(List Attachments) + public async Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> PutAttachmentAsync(List Attachments) { try { logger?.LogInformation("Query Attachment"); List attachments = mapper.Map, List>(Attachments); AttachmentDbContext.Attachments.UpdateRange(attachments); - AttachmentDbContext.SaveChanges(); + await AttachmentDbContext.SaveChangesAsync(); var result = mapper.Map, IEnumerable>(attachments); return (true, result, null); } @@ -110,7 +110,7 @@ namespace DamageAssesment.Api.Attachments.Providers if (Attachments.Count > 0) { AttachmentDbContext.Attachments.RemoveRange(Attachments); - AttachmentDbContext.SaveChanges(); + await AttachmentDbContext.SaveChangesAsync(); } return (true, AttachmentId, ""); } @@ -121,7 +121,7 @@ namespace DamageAssesment.Api.Attachments.Providers return (false, AttachmentId, ""); } } - public (bool IsSuccess,int counter,string message) GetAttachmentCounter() + public async Task<(bool IsSuccess,int counter,string message)> GetAttachmentCounter() { try { @@ -143,7 +143,7 @@ namespace DamageAssesment.Api.Attachments.Providers if (Attachments.Count > 0) { AttachmentDbContext.Attachments.RemoveRange(Attachments); - AttachmentDbContext.SaveChanges(); + await AttachmentDbContext.SaveChangesAsync(); } return (true, AttachmentId, ""); } @@ -154,7 +154,7 @@ namespace DamageAssesment.Api.Attachments.Providers return (false, AttachmentId, ""); } } - public (bool IsSuccess, IEnumerable Attachments, string ErrorMessage) GetAttachmentInfo(List answers) + public async Task<(bool IsSuccess, IEnumerable Attachments, string ErrorMessage)> GetAttachmentInfo(List answers) { try { @@ -183,7 +183,7 @@ namespace DamageAssesment.Api.Attachments.Providers } Attachment.IsDeleted = true; AttachmentDbContext.Attachments.Update(Attachment); - AttachmentDbContext.SaveChanges(); + await AttachmentDbContext.SaveChangesAsync(); return (true, mapper.Map(Attachment), $"Attachment {Id} is deleted"); } catch (Exception ex) diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/EmployeeServiceTest.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/EmployeeServiceTest.cs index 7c45f0d..aa30faf 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/EmployeeServiceTest.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/EmployeeServiceTest.cs @@ -98,10 +98,10 @@ namespace DamageAssesment.Api.Employees.Test var mockEmployeeService = new Mock(); var mockResponse = await MockData.getOkResponse("Emp1"); var mockInputEmployee = await MockData.getInputEmployeeData(); - mockEmployeeService.Setup(service => service.UpdateEmployeeAsync(mockInputEmployee)).ReturnsAsync(mockResponse); + mockEmployeeService.Setup(service => service.UpdateEmployeeAsync("Emp1",mockInputEmployee)).ReturnsAsync(mockResponse); var EmployeeProvider = new EmployeesController(mockEmployeeService.Object); - var result = (OkObjectResult)await EmployeeProvider.UpdateEmployee(mockInputEmployee); + var result = (OkObjectResult)await EmployeeProvider.UpdateEmployee("Emp1",mockInputEmployee); Assert.Equal(200, result.StatusCode); } @@ -112,10 +112,10 @@ namespace DamageAssesment.Api.Employees.Test var mockEmployeeService = new Mock(); var mockResponse = await MockData.getNotFoundResponse(); var mockInputEmployee = await MockData.getInputEmployeeData(); - mockEmployeeService.Setup(service => service.UpdateEmployeeAsync(mockInputEmployee)).ReturnsAsync(mockResponse); + mockEmployeeService.Setup(service => service.UpdateEmployeeAsync("Emp1", mockInputEmployee)).ReturnsAsync(mockResponse); var EmployeeProvider = new EmployeesController(mockEmployeeService.Object); - var result = (NotFoundObjectResult)await EmployeeProvider.UpdateEmployee(mockInputEmployee); + var result = (NotFoundObjectResult)await EmployeeProvider.UpdateEmployee("Emp1", mockInputEmployee); Assert.Equal(404, result.StatusCode); } @@ -126,10 +126,10 @@ namespace DamageAssesment.Api.Employees.Test var mockEmployeeService = new Mock(); var mockResponse = await MockData.getBadRequestResponse(); var mockInputEmployee = await MockData.getInputEmployeeData(); - mockEmployeeService.Setup(service => service.UpdateEmployeeAsync(mockInputEmployee)).ReturnsAsync(mockResponse); + mockEmployeeService.Setup(service => service.UpdateEmployeeAsync("Emp1", mockInputEmployee)).ReturnsAsync(mockResponse); var EmployeeProvider = new EmployeesController(mockEmployeeService.Object); - var result = (BadRequestObjectResult)await EmployeeProvider.UpdateEmployee(mockInputEmployee); + var result = (BadRequestObjectResult)await EmployeeProvider.UpdateEmployee("Emp1", mockInputEmployee); Assert.Equal(400, result.StatusCode); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/MockData.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/MockData.cs index cd5206e..91c8b84 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/MockData.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/MockData.cs @@ -33,19 +33,19 @@ namespace DamageAssesment.Api.Employees.Test return (false, null, "Bad Request"); } - public static async Task<(bool, Employees.Models.Employee, string)> getNotFoundResponse() + public static async Task<(bool, Models.Employee, string)> getNotFoundResponse() { return (false, null, "Not Found"); } - public static async Task<(bool, IEnumerable, string)> getNoContentResponse() + public static async Task<(bool, IEnumerable, string)> getNoContentResponse() { IEnumerable list = new List(); return (false, list, null); } - public static async Task getInputEmployeeData() + public static async Task getInputEmployeeData() { - return new Employees.Db.Employee { Id = "Emp1", Name = "ABC1", Email = "abc1@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-18), IsActive = true, PreferredLanguage = "en" }; + return new Models.Employee { Id = "Emp1", Name = "ABC1", Email = "abc1@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-18), IsActive = true, PreferredLanguage = "en" }; } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/LocationsServiceTest.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/LocationsServiceTest.cs index 270c638..2d15662 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/LocationsServiceTest.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/LocationsServiceTest.cs @@ -93,7 +93,7 @@ namespace DamageAssesment.Api.Locations.Test var mapper = new Mapper(configuration); var LocationsProvider = new LocationsProvider(dbContext, null, mapper); //Testmethode - Db.Location newLocation = new Db.Location() { Id = "Loc9", RegionId = "1", Name = "Test 1", MaintenanceCenter = "1", SchoolType = "US" }; + Models.Location newLocation = new Models.Location() { Id = "Loc9", RegionId = "1", Name = "Test 1", MaintenanceCenter = "1", SchoolType = "US" }; var Location = await LocationsProvider.PostLocationAsync(newLocation); Assert.True(Location.IsSuccess); @@ -113,7 +113,7 @@ namespace DamageAssesment.Api.Locations.Test var mapper = new Mapper(configuration); var LocationsProvider = new LocationsProvider(dbContext, null, mapper); //Testmethode - Db.Location updateLocation = new Db.Location() { Id = "Loc1", RegionId = "1", Name = "Tampa", MaintenanceCenter = "1", SchoolType = "NA" }; + Models.Location updateLocation = new Models.Location() { Id = "Loc1", RegionId = "1", Name = "Tampa", MaintenanceCenter = "1", SchoolType = "NA" }; var Location = await LocationsProvider.UpdateLocationAsync(updateLocation); var modified = dbContext.Locations.FirstOrDefault(a => a.Id == updateLocation.Id); Assert.True(Location.IsSuccess); diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Controllers/SurveyResponsesController.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Controllers/SurveyResponsesController.cs index b3ff885..c650d1d 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Controllers/SurveyResponsesController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Controllers/SurveyResponsesController.cs @@ -180,10 +180,10 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers /// /// POST request for submitting survey with multiple answers. /// - /// The answers to be submitted for the survey. + /// The answers to be submitted for the survey. [HttpPost("SurveyResponses/Answers")] - public async Task PostSurveyAnswersAsync(AnswerRequest answers) + public async Task PostSurveyAnswersAsync(Request request) { /* var result = await this.surveyResponseProvider.PostSurveyAnswersAsync(surveyAnswers); if (result.IsSuccess) @@ -191,7 +191,7 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers return Ok(result.SurveyResponse); } return BadRequest(result.ErrorMessage);*/ - var result = await this.surveyResponseProvider.PostSurveyAnswersAsync(answers); + var result = await this.surveyResponseProvider.PostSurveyAnswersAsync(request); if (result.IsSuccess) return Ok(result.SurveyResponse); diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Db/SurveyResponseDbContext.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Db/SurveyResponseDbContext.cs index bb8a2a2..61726ad 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Db/SurveyResponseDbContext.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Db/SurveyResponseDbContext.cs @@ -10,5 +10,13 @@ namespace DamageAssesment.Api.SurveyResponses.Db { } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/ISurveysResponse.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/ISurveysResponse.cs index 79ca1ad..5cdd198 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/ISurveysResponse.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/ISurveysResponse.cs @@ -17,7 +17,7 @@ namespace DamageAssesment.Api.SurveyResponses.Interfaces Task<(bool IsSuccess, dynamic SurveyResponses, string ErrorMessage)> GetSurveyResponsesByMaintenanceCenterAsync(int surveyId); Task<(bool IsSuccess, dynamic SurveyResponses, string ErrorMessage)> GetResponsesByAnswerAsync(int surveyId, int questionId, string answer); - Task<(bool IsSuccess, Models.SurveyResponse SurveyResponse, string ErrorMessage)> PostSurveyAnswersAsync(Models.AnswerRequest answers); + Task<(bool IsSuccess, Models.SurveyResponse SurveyResponse, string ErrorMessage)> PostSurveyAnswersAsync(Request request); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AnswerRequest.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AnswerRequest.cs index 68a217a..3d86488 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AnswerRequest.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AnswerRequest.cs @@ -2,9 +2,9 @@ { public class AnswerRequest { - public int SurveyId { get; set; } - public string LocationId { get; set; } - public string EmployeeId { get; set; } - public List Answers { get; set; } + public int QuestionId { get; set; } + public string AnswerText { get; set; } + public string Comment { get; set; } + public List PostedFiles { get; set; } = new List(); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Question.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Question.cs index 5dba504..ad18bf1 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Question.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Question.cs @@ -17,7 +17,7 @@ namespace DamageAssesment.Api.SurveyResponses.Models public bool Key { get; set; } public int? SurveyId { get; set; } - public string QuestionGroup { get; set; } + //public string QuestionGroup { get; set; } public int CategoryId { get; set; } // public int? Survey_SurveyID { get; set; } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/QuestionRequest.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/QuestionRequest.cs deleted file mode 100644 index d0930ab..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/QuestionRequest.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace DamageAssesment.Api.SurveyResponses.Models -{ - public class QuestionRequest - { - public int QuestionId { get; set; } - public string AnswerText { get; set; } - public string Comment { get; set; } - public List PostedFiles { get; set; } = new List(); - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Request.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Request.cs new file mode 100644 index 0000000..53b3044 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Request.cs @@ -0,0 +1,10 @@ +namespace DamageAssesment.Api.SurveyResponses.Models +{ + public class Request + { + public int SurveyId { get; set; } + public string LocationId { get; set; } + public string EmployeeId { get; set; } + public List Answers { get; set; } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Program.cs index a4f585f..cf41624 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Program.cs @@ -4,6 +4,7 @@ using DamageAssesment.Api.SurveyResponses.Providers; using Microsoft.AspNetCore.DataProtection.XmlEncryption; using Microsoft.EntityFrameworkCore; using Polly; +using System.Net.Http; using System.Reflection; var builder = WebApplication.CreateBuilder(args); diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AnswerServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AnswerServiceProvider.cs index 5796eff..cb638bc 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AnswerServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AnswerServiceProvider.cs @@ -7,6 +7,8 @@ using System.Data.Common; using System.Security.Cryptography; using System.Text.Json.Nodes; using System.Text; +using System.Net.Http.Headers; +using System; namespace DamageAssesment.Api.SurveyResponses.Providers { @@ -42,8 +44,8 @@ namespace DamageAssesment.Api.SurveyResponses.Providers try { httpClient.BaseAddress = new Uri(urlBase); - - var response = await httpClient.GetAsync("/api/AnswersByResponse/"+ responseId); + + var response = await httpClient.GetAsync("/api/AnswersByResponse/" + responseId); response.EnsureSuccessStatusCode(); var responseString = await response.Content.ReadAsStringAsync(); var answers = JsonConvert.DeserializeObject>(responseString); @@ -63,19 +65,26 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { try { - httpClient.BaseAddress = new Uri(urlBase); + 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); - var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json"); - var response = await httpClient.PostAsync(ressource,content); + 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); - if (answers == null) { + if (answers == null) + { logger?.LogError($"Answer 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 3e46c84..04f8121 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AttachmentServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AttachmentServiceProvider.cs @@ -4,6 +4,7 @@ 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; @@ -40,10 +41,16 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { try { - httpClient.BaseAddress = new Uri(urlBase); + + 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); - var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json"); - var response = await httpClient.PostAsync(ressource, content); + 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); diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyResponsesProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyResponsesProvider.cs index 2615cfd..98c138d 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyResponsesProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyResponsesProvider.cs @@ -4,7 +4,9 @@ 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 @@ -251,7 +253,6 @@ namespace DamageAssesment.Api.SurveyResponses.Providers answers = new List(); return (true, answers, "Empty object returned"); } - } catch (Exception ex) { @@ -266,16 +267,16 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { if (surveyResponse != null) { - var surveyResponses = await surveyResponseDbContext.SurveyResponses.ToListAsync(); - surveyResponse.Id = surveyResponses.Count + 1; - surveyResponseDbContext.SurveyResponses.Add(mapper.Map(surveyResponse)); - surveyResponseDbContext.SaveChanges(); + var _surveyResponse = mapper.Map(surveyResponse); + surveyResponseDbContext.SurveyResponses.Add(_surveyResponse); + await surveyResponseDbContext.SaveChangesAsync(); + surveyResponse.Id = _surveyResponse.Id; return (true, surveyResponse, "Request Successful"); } else { - logger?.LogInformation($"SurveyResponseID={surveyResponse.Id} cannot be added"); - return (false, null, "Survey cannot be added"); + logger?.LogInformation($"SurveyResponse cannot be added"); + return (false, null, "SurveyResponse cannot be added"); } } catch (Exception ex) @@ -299,7 +300,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers _SurveyResponse.SurveyId = SurveyResponse.SurveyId; _SurveyResponse.EmployeeId = SurveyResponse.EmployeeId; _SurveyResponse.LocationId = SurveyResponse.LocationId; - surveyResponseDbContext.SaveChanges(); + await surveyResponseDbContext.SaveChangesAsync(); return (true, mapper.Map(_SurveyResponse), "Successful"); } else @@ -331,7 +332,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers if (_SurveyResponse != null) { surveyResponseDbContext.Remove(_SurveyResponse); - surveyResponseDbContext.SaveChanges(); + await surveyResponseDbContext.SaveChangesAsync(); return (true, mapper.Map(_SurveyResponse), "Successful"); } else @@ -458,7 +459,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers ans.Id, ans.AnswerText, ans.Comment, - Questions = (from q in questions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.QuestionGroup, q.Questions }).SingleOrDefault(), + 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 } } }; @@ -503,7 +504,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers ans.QuestionId, ans.AnswerText, ans.Comment, - Questions = (from q in surveyQuestions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.QuestionGroup, q.Questions }).SingleOrDefault(), + Questions = (from q in surveyQuestions 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 } } @@ -546,7 +547,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers ans.QuestionId, ans.AnswerText, ans.Comment, - Questions = (from q in questions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.QuestionGroup, q.Questions }).SingleOrDefault(), + 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 } } }; @@ -650,7 +651,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers ans.Id, ans.AnswerText, ans.Comment, - Questions = (from q in surveyQuestions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.QuestionGroup, q.Questions }).SingleOrDefault(), + Questions = (from q in surveyQuestions 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 } } }; @@ -709,67 +710,75 @@ namespace DamageAssesment.Api.SurveyResponses.Providers } - bool ProcessAnswers(QuestionRequest questionRequest, int surveyResponseId) + async Task ProcessAnswers(AnswerRequest answerRequest, int surveyResponseId) { - if (questionRequest != null) + if (answerRequest != null) { - var answer = answerServiceProvider.PostAnswersAsync(new Answer {QuestionId = questionRequest.QuestionId, AnswerText = questionRequest.AnswerText, Comment = questionRequest.Comment, SurveyResponseId = surveyResponseId }); - if (answer != null) - { - List listAnswerInfo = new List(); - listAnswerInfo.Add(new AnswerInfo { AnswerId = answer.Id, postedFiles = questionRequest.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 {questionRequest.QuestionId} saved to the database"; - logger?.LogInformation(message); - return (true); - } - else - { - string message = $"Answer for question {questionRequest.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 { - var message = $"Answer for question {questionRequest.QuestionId} cannot be saved to the database - questionRequest object is null"; + var message = $"Answer for question {answerRequest.QuestionId} cannot be saved to the database - answerRequest object is null"; logger?.LogInformation(message); return (false); } } - public async Task<(bool IsSuccess, Models.SurveyResponse SurveyResponse, string ErrorMessage)> PostSurveyAnswersAsync(Models.AnswerRequest answers) + public async Task<(bool IsSuccess, Models.SurveyResponse SurveyResponse, string ErrorMessage)> PostSurveyAnswersAsync(Models.Request request) { try { - if (answers != null) + if (request != null) { - var response = await PostSurveyResponseAsync(new Models.SurveyResponse { Id = 0, SurveyId = answers.SurveyId, EmployeeId = answers.EmployeeId, LocationId = answers.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)); - var answerTasks = new List(); //new List(); - - //var tasks = answers.Answers.Select(x => ProcessAnswers(x,surveyResponse.SurveyResponseID)); - foreach (QuestionRequest ans in answers.Answers) - { - ProcessAnswers(ans, 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)); - } - //await Task.WhenAll(answerTasks); + // } + await Task.WhenAll(tasks); return (true, surveyResponse, null); } else diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Bases/ServiceProviderBase.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Bases/ServiceProviderBase.cs deleted file mode 100644 index 799f082..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Bases/ServiceProviderBase.cs +++ /dev/null @@ -1,21 +0,0 @@ -namespace DamageAssesment.Api.UsersAccess.Bases -{ - public class ServiceProviderBase - { - protected readonly IConfiguration configuration; - protected readonly HttpClient httpClient; - protected private readonly ILogger logger; - protected string ressource; - protected string urlBase; - - - public ServiceProviderBase(IConfiguration configuration, HttpClient httpClient, ILogger logger, string ressource, string urlBase) - { - this.configuration = configuration; - this.httpClient = httpClient; - this.logger = logger; - this.ressource = ressource; - this.urlBase = urlBase; - } - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Controllers/UsersAccessController.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Controllers/UsersAccessController.cs deleted file mode 100644 index 5e16362..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Controllers/UsersAccessController.cs +++ /dev/null @@ -1,97 +0,0 @@ -using DamageAssesment.Api.UsersAccess.Interfaces; -using DamageAssesment.Api.UsersAccess.Models; -using Microsoft.AspNetCore.Mvc; - -namespace DamageAssesment.Api.UsersAccess.Controllers -{ - [Route("api")] - [ApiController] - public class UsersAccessController : ControllerBase - { - private IUsersAccessProvider userAccessProvider; - - public UsersAccessController(IUsersAccessProvider userAccessProvider) - { - this.userAccessProvider = userAccessProvider; - } - [HttpPost("authenticate")] - public async Task AuthenticateAsync(UserCredentials userCredentials) - { - var result = await userAccessProvider.AuthenticateAsync(userCredentials); - if (result.IsSuccess) - { - return Ok(result.TokenResponse); - } - return Unauthorized(result.ErrorMessage); - } - - [HttpPost("refreshToken")] - public async Task RefreshTokenAsync(TokenResponse tokenResponse) - { - var result = await userAccessProvider.RefreshTokenAsync(tokenResponse); - if (result.IsSuccess) - { - return Ok(result.TokenResponse); - } - return Unauthorized(result.ErrorMessage); - } - - [HttpGet("users")] - public async Task GetUsersAsync() - { - var result = await userAccessProvider.GetUsersAsync(); - if (result.IsSuccess) - { - return Ok(result.Users); - } - return NoContent(); - } - - [HttpGet("users/{Id}")] - public async Task GetUsersAsync(int Id) - { - var result = await userAccessProvider.GetUsersAsync(Id); - if (result.IsSuccess) - { - return Ok(result.User); - } - return NotFound(); - } - - [HttpPost("users")] - public async Task PostUserAsync(User user) - { - var result = await userAccessProvider.PostUserAsync(user); - if (result.IsSuccess) - { - return Ok(result.User); - } - return BadRequest(result.ErrorMessage); - } - - [HttpPut("users/{Id}")] - public async Task PutUserAsync(int Id, User user) - { - var result = await userAccessProvider.PutUserAsync(Id, user); - if (result.IsSuccess) - { - return Ok(result.User); - } - if (result.ErrorMessage == "Not Found") - return NotFound(result.ErrorMessage); - - return BadRequest(result.ErrorMessage); - } - - [HttpDelete("users/{Id}")] - public async Task DeleteSurveysAsync(int Id) - { - var result = await userAccessProvider.DeleteUserAsync(Id); - if (result.IsSuccess) - { - return Ok(result.User); - } - return NotFound(); - } - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/DamageAssesment.Api.UsersAccess.csproj b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/DamageAssesment.Api.UsersAccess.csproj deleted file mode 100644 index d56ba51..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/DamageAssesment.Api.UsersAccess.csproj +++ /dev/null @@ -1,19 +0,0 @@ - - - - net6.0 - enable - enable - - - - - - - - - - - - - diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/Role.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/Role.cs deleted file mode 100644 index 93e522a..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/Role.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; -using System.Text.Json.Serialization; - -namespace DamageAssesment.Api.UsersAccess.Db -{ - public class Role - { - [Key] - public int Id { get; set; } - - [StringLength(100)] - [Required] - public string Name { get; set; } - - // add a status field - - [StringLength(100)] - public string? Description { get; set; } - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/Token.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/Token.cs deleted file mode 100644 index cfea1e2..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/Token.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Microsoft.EntityFrameworkCore.Metadata.Internal; -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; - -namespace DamageAssesment.Api.UsersAccess.Db -{ - public class Token - { - [Key] - public string Id { get; set; } - [Required] - [ForeignKey("User")] - public int UserId { get; set; } - public string? RefreshToken { get; set; } - public bool? IsActive { get; set; } - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/User.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/User.cs deleted file mode 100644 index d5fc4ee..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/User.cs +++ /dev/null @@ -1,27 +0,0 @@ -using System.ComponentModel.DataAnnotations; -using System.ComponentModel.DataAnnotations.Schema; -using System.Text.Json.Serialization; - -namespace DamageAssesment.Api.UsersAccess.Db -{ - public class User - { - [Key] - public int Id { get; set; } - - [ForeignKey("Employee")] - public string EmployeeId { get; set; } - - [ForeignKey("Role")] - [Required] - public int RoleId { get; set; } - [Required] - public bool? IsActive { get; set; } = true; - - [Required] - public DateTime? CreateDate { get; set; } = DateTime.Now; - - public DateTime? UpdateDate { get; set; } - - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/UsersAccessDbContext.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/UsersAccessDbContext.cs deleted file mode 100644 index a46a10d..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Db/UsersAccessDbContext.cs +++ /dev/null @@ -1,17 +0,0 @@ -using Microsoft.EntityFrameworkCore; - -namespace DamageAssesment.Api.UsersAccess.Db -{ - public class UsersAccessDbContext:DbContext - { - public DbSet Users { get; set; } - public DbSet Roles { get; set; } - public DbSet Tokens { get; set; } - public UsersAccessDbContext(DbContextOptions options) : base(options) - { - - } - - - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IEmployeeServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IEmployeeServiceProvider.cs deleted file mode 100644 index fc35b00..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IEmployeeServiceProvider.cs +++ /dev/null @@ -1,10 +0,0 @@ -using DamageAssesment.Api.UsersAccess.Models; - -namespace DamageAssesment.Api.UsersAccess.Interfaces -{ - public interface IEmployeeServiceProvider - { - Task> getEmployeesAsync(); - Task getEmployeeAsync(string employeeID); - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IRoleProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IRoleProvider.cs deleted file mode 100644 index 6ca0209..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IRoleProvider.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace DamageAssesment.Api.UsersAccess.Interfaces -{ - public interface IRoleProvider - { - Task<(bool IsSuccess, IEnumerable< Models.Role> Roles, string ErrorMessage)> GetRolesAsync(); - Task<(bool IsSuccess, Models.Role Roles, string ErrorMessage)> GetRolesAsync(int Id); - Task<(bool IsSuccess, Models.Role Role, string ErrorMessage)> PostRoleAsync(Models.Role Role); - Task<(bool IsSuccess, Models.Role Role, string ErrorMessage)> PutRoleAsync(int Id,Models.Role Role); - Task<(bool IsSuccess, Models.Role Role, string ErrorMessage)> DeleteRoleAsync(int Id); - - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/ITokenServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/ITokenServiceProvider.cs deleted file mode 100644 index 58574b7..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/ITokenServiceProvider.cs +++ /dev/null @@ -1,11 +0,0 @@ -using DamageAssesment.Api.UsersAccess.Models; -using System.Security.Claims; - -namespace DamageAssesment.Api.UsersAccess.Interfaces -{ - public interface ITokenServiceProvider - { - Task GenerateToken(User user); - Task TokenAuthenticate(User user, Claim[] claims); - } -} \ No newline at end of file diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IUsersAccessProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IUsersAccessProvider.cs deleted file mode 100644 index 7e39e11..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Interfaces/IUsersAccessProvider.cs +++ /dev/null @@ -1,16 +0,0 @@ -using DamageAssesment.Api.UsersAccess.Models; - -namespace DamageAssesment.Api.UsersAccess.Interfaces -{ - public interface IUsersAccessProvider - { - public Task<(bool IsSuccess, IEnumerable< Models.User> Users, string ErrorMessage)> GetUsersAsync(); - public Task<(bool IsSuccess, Models.User User, string ErrorMessage)> GetUsersAsync(int Id); - public Task<(bool IsSuccess, Models.User User, string ErrorMessage)> PostUserAsync(Models.User User); - public Task<(bool IsSuccess, Models.User User, string ErrorMessage)> PutUserAsync(int Id,Models.User User); - public Task<(bool IsSuccess, Models.User User, string ErrorMessage)> DeleteUserAsync(int Id); - public Task<(bool IsSuccess, IEnumerable Roles, string ErrorMessage)> GetRolesAsync(); - public Task<(bool IsSuccess, Models.TokenResponse TokenResponse, string ErrorMessage)> AuthenticateAsync(UserCredentials userCredentials); - public Task<(bool IsSuccess, Models.TokenResponse TokenResponse, string ErrorMessage)>RefreshTokenAsync(TokenResponse tokenResponse); - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Employee.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Employee.cs deleted file mode 100644 index e14f27d..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Employee.cs +++ /dev/null @@ -1,21 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace DamageAssesment.Api.UsersAccess.Models -{ - public class Employee - { - public string Id { get; set; } - - [StringLength(50)] - public string Name { get; set; } - - public DateTime BirthDate { get; set; } - - [StringLength(50)] - public string OfficePhoneNumber { get; set; } - - [StringLength(50)] - public string Email { get; set; } - public bool IsActive { get; set; } - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/JwtSettings.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/JwtSettings.cs deleted file mode 100644 index 3f9dadf..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/JwtSettings.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System.ComponentModel.DataAnnotations; -namespace DamageAssesment.Api.UsersAccess.Models -{ - - public class JwtSettings - { - public string securitykey { get; set; } - } -} \ No newline at end of file diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Role.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Role.cs deleted file mode 100644 index 809e677..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Role.cs +++ /dev/null @@ -1,9 +0,0 @@ -using System.ComponentModel.DataAnnotations; -namespace DamageAssesment.Api.UsersAccess.Models -{ - public class Role { - public int Id { get; set; } - public string Name { get; set; } - public string? Description { get; set; } - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Token.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Token.cs deleted file mode 100644 index 9c46d81..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/Token.cs +++ /dev/null @@ -1,10 +0,0 @@ -namespace DamageAssesment.Api.UsersAccess.Models -{ - public class Token - { - public string Id { get; set; } - public int UserId { get; set; } - public string? RefreshToken { get; set; } - public bool? IsActive { get; set; } - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/TokenResponse.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/TokenResponse.cs deleted file mode 100644 index 4d0b6da..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/TokenResponse.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace DamageAssesment.Api.UsersAccess.Models -{ - public class TokenResponse - { - public string? jwttoken { get; set; } - public string? refreshtoken { get; set; } - } -} \ No newline at end of file diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/User.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/User.cs deleted file mode 100644 index f3c9971..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/User.cs +++ /dev/null @@ -1,12 +0,0 @@ -namespace DamageAssesment.Api.UsersAccess.Models -{ - public class User - { - public int Id { get; set; } - public string EmployeeId { get; set; } - public int RoleId { get; set; } - public bool? IsActive { get; set; } - public DateTime? CreateDate { get; set; } - public DateTime? UpdateDate { get; set; } - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/UserCredentials.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/UserCredentials.cs deleted file mode 100644 index a23a43b..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Models/UserCredentials.cs +++ /dev/null @@ -1,5 +0,0 @@ -public class UserCredentials -{ - public string? username { get; set; } - // public string? password { get; set; } -} \ No newline at end of file diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Profiles/UsersAccessProfile.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Profiles/UsersAccessProfile.cs deleted file mode 100644 index bf744eb..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Profiles/UsersAccessProfile.cs +++ /dev/null @@ -1,14 +0,0 @@ -namespace DamageAssesment.Api.UsersAccess.Profiles -{ - public class UsersAccessProfile : AutoMapper.Profile - { - public UsersAccessProfile() - { - CreateMap(); - CreateMap(); - - CreateMap(); - CreateMap(); - } - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Program.cs deleted file mode 100644 index a7fb1ac..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Program.cs +++ /dev/null @@ -1,77 +0,0 @@ -using DamageAssesment.Api.UsersAccess.Db; -using DamageAssesment.Api.UsersAccess.Interfaces; -using DamageAssesment.Api.UsersAccess.Providers; -using DamageAssesment.Api.UsersAccess.Models; -using Microsoft.AspNetCore.Authentication.JwtBearer; -using Microsoft.EntityFrameworkCore; -using Microsoft.IdentityModel.Tokens; -using System.Text; -using Polly; -using DamageAssesment.Api.SurveyResponses.Providers; - -const int maxApiCallRetries = 3; -const int intervalToRetry = 2; //2 seconds -const int maxRetryForCircuitBraker = 5; -const int intervalForCircuitBraker = 5; //5 seconds - -var builder = WebApplication.CreateBuilder(args); - -// Add services to the container. -var authkey = builder.Configuration.GetValue("JwtSettings:securitykey"); -builder.Services.AddAuthentication(item => -{ - item.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; - item.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; -}).AddJwtBearer(item => -{ - item.RequireHttpsMetadata = true; - item.SaveToken = true; - item.TokenValidationParameters = new TokenValidationParameters() - { - ValidateIssuerSigningKey = true, - IssuerSigningKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(authkey)), - ValidateIssuer = false, - ValidateAudience = false, - ClockSkew = TimeSpan.Zero - }; -}); - -var _jwtsettings = builder.Configuration.GetSection("JwtSettings"); -builder.Services.Configure(_jwtsettings); - - - -builder.Services.AddHttpClient(). - AddTransientHttpErrorPolicy(policy => policy.WaitAndRetryAsync(maxApiCallRetries, _ => TimeSpan.FromSeconds(intervalToRetry))). - AddTransientHttpErrorPolicy(policy => policy.CircuitBreakerAsync(maxRetryForCircuitBraker, TimeSpan.FromSeconds(intervalForCircuitBraker))); - -builder.Services.AddControllers(); -// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle -builder.Services.AddScoped(); -builder.Services.AddScoped(); -builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); -builder.Services.AddEndpointsApiExplorer(); -builder.Services.AddSwaggerGen(); -builder.Services.AddDbContext(option => -{ - option.UseInMemoryDatabase("UsersAccess"); -}); - - - - -var app = builder.Build(); - -// Configure the HTTP request pipeline. -if (app.Environment.IsDevelopment()) -{ - app.UseSwagger(); - app.UseSwaggerUI(); -} - -app.UseAuthentication(); -app.UseAuthorization(); - -app.MapControllers(); - -app.Run(); diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Properties/launchSettings.json b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Properties/launchSettings.json deleted file mode 100644 index 859e680..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Properties/launchSettings.json +++ /dev/null @@ -1,31 +0,0 @@ -{ - "$schema": "https://json.schemastore.org/launchsettings.json", - "iisSettings": { - "windowsAuthentication": false, - "anonymousAuthentication": true, - "iisExpress": { - "applicationUrl": "http://localhost:28382", - "sslPort": 0 - } - }, - "profiles": { - "DamageAssesment.Api.Users": { - "commandName": "Project", - "dotnetRunMessages": true, - "launchBrowser": true, - "launchUrl": "swagger", - "applicationUrl": "http://localhost:5027", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - }, - "IIS Express": { - "commandName": "IISExpress", - "launchBrowser": true, - "launchUrl": "swagger", - "environmentVariables": { - "ASPNETCORE_ENVIRONMENT": "Development" - } - } - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/EmployeeServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/EmployeeServiceProvider.cs deleted file mode 100644 index ace59ee..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/EmployeeServiceProvider.cs +++ /dev/null @@ -1,58 +0,0 @@ -using DamageAssesment.Api.UsersAccess.Bases; -using DamageAssesment.Api.UsersAccess.Interfaces; -using DamageAssesment.Api.UsersAccess.Models; -using Newtonsoft.Json; -using System.Reflection; - -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 async Task> getEmployeesAsync() - { - 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); - - if (employees == null || !employees.Any()) - return null; - else return employees; - } - catch (Exception ex) - { - logger?.LogError($"Exception Found : {ex.Message} - Ref: EmployeeServiceProvider.getEmployeesAsync()"); - return null; - } - } - - 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); - - if (employee == null ) - return null; - else return employee; - } - catch (Exception ex) - { - logger?.LogError($"Exception Found : {ex.Message} - Ref: EmployeeServiceProvider.getEmployeeAsync()"); - return null; - } - } - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/TokenServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/TokenServiceProvider.cs deleted file mode 100644 index a77d6bc..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/TokenServiceProvider.cs +++ /dev/null @@ -1,57 +0,0 @@ -using System.IdentityModel.Tokens.Jwt; -using System.Security.Claims; -using System.Security.Cryptography; -using System.Text; -using DamageAssesment.Api.UsersAccess.Db; -using DamageAssesment.Api.UsersAccess.Interfaces; -using DamageAssesment.Api.UsersAccess.Models; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; -using Microsoft.IdentityModel.Tokens; - -public class TokenServiceProvider : ITokenServiceProvider -{ - private readonly UsersAccessDbContext usersAccessDbContext; - private readonly JwtSettings jwtSettings; - public TokenServiceProvider(IOptions options,UsersAccessDbContext usersAccessDbContext) - { - this.usersAccessDbContext = usersAccessDbContext; - this.jwtSettings = options.Value; - } - public async Task GenerateToken(DamageAssesment.Api.UsersAccess.Models.User user) - { - var randomnumber = new byte[32]; - using (var ramdomnumbergenerator = RandomNumberGenerator.Create()) - { - ramdomnumbergenerator.GetBytes(randomnumber); - string refreshtoken = Convert.ToBase64String(randomnumber); - var token = await usersAccessDbContext.Tokens.FirstOrDefaultAsync(item => item.UserId == user.Id); - if (token != null) - { - token.RefreshToken = refreshtoken; - } - else - { - usersAccessDbContext.Tokens.Add(new DamageAssesment.Api.UsersAccess.Db.Token() - { - Id = new Random().Next().ToString(), - UserId = user.Id, - RefreshToken = refreshtoken, - IsActive = true - }); - } - await usersAccessDbContext.SaveChangesAsync(); - - return refreshtoken; - } - } - - public async Task TokenAuthenticate(DamageAssesment.Api.UsersAccess.Models.User user, Claim[] claims) - { - var token = new JwtSecurityToken(claims: claims, expires: DateTime.Now.AddSeconds(20), - signingCredentials: new SigningCredentials(new SymmetricSecurityKey(Encoding.UTF8.GetBytes(jwtSettings.securitykey)), SecurityAlgorithms.HmacSha256) - ); - var jwttoken = new JwtSecurityTokenHandler().WriteToken(token); - return new TokenResponse() { jwttoken = jwttoken, refreshtoken = await GenerateToken(user) }; - } -} \ No newline at end of file diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/UserAccessProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/UserAccessProvider.cs deleted file mode 100644 index 6188d92..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/Providers/UserAccessProvider.cs +++ /dev/null @@ -1,341 +0,0 @@ -using AutoMapper; -using DamageAssesment.Api.UsersAccess.Db; -using DamageAssesment.Api.UsersAccess.Interfaces; -using DamageAssesment.Api.UsersAccess.Models; -using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; -using Microsoft.IdentityModel.Tokens; -using System.Data; -using System.IdentityModel.Tokens.Jwt; -using System.Security.Claims; -using System.Text; - -namespace DamageAssesment.Api.UsersAccess.Providers -{ - public class UsersAccessProvider : IUsersAccessProvider - { - private readonly UsersAccessDbContext userAccessDbContext; - private readonly ILogger logger; - private readonly IMapper mapper; - private readonly IEmployeeServiceProvider employeeServiceProvider; - private readonly JwtSettings jwtSettings; - private readonly ITokenServiceProvider tokenServiceProvider; - - public UsersAccessProvider(IOptions options, ITokenServiceProvider tokenServiceProvider, UsersAccessDbContext userAccessDbContext, IEmployeeServiceProvider employeeServiceProvider, ILogger logger, IMapper mapper) - { - this.userAccessDbContext = userAccessDbContext; - this.employeeServiceProvider = employeeServiceProvider; - this.logger = logger; - this.mapper = mapper; - jwtSettings = options.Value; - this.tokenServiceProvider = tokenServiceProvider; - seedData(); - } - - private void seedData() - { - if (!userAccessDbContext.Users.Any()) - { - userAccessDbContext.Users.Add(new Db.User { Id = 1, EmployeeId = "Emp1", RoleId = 1 }); - userAccessDbContext.Users.Add(new Db.User { Id = 2, EmployeeId = "Emp2", RoleId = 2 }); - userAccessDbContext.Users.Add(new Db.User { Id = 3, EmployeeId = "Emp3", RoleId = 3 }); - userAccessDbContext.SaveChanges(); - } - - if (!userAccessDbContext.Roles.Any()) - { - userAccessDbContext.Roles.Add(new Db.Role { Id = 1, Name = "admin" }); - userAccessDbContext.Roles.Add(new Db.Role { Id = 2, Name = "user" }); - userAccessDbContext.Roles.Add(new Db.Role { Id = 3, Name = "survey" }); - userAccessDbContext.Roles.Add(new Db.Role { Id = 4, Name = "report" }); - userAccessDbContext.Roles.Add(new Db.Role { Id = 5, Name = "document" }); - userAccessDbContext.SaveChanges(); - } - } - - public async Task<(bool IsSuccess, IEnumerable Users, string ErrorMessage)> GetUsersAsync() - { - try - { - logger?.LogInformation("Gell all Users from DB"); - var users = await userAccessDbContext.Users.ToListAsync(); - if (users != null) - { - logger?.LogInformation($"{users.Count} Items(s) found"); - var result = mapper.Map, IEnumerable>(users); - return (true, result, null); - } - return (false, null, "Not found"); - } - catch (Exception ex) - { - logger?.LogError(ex.ToString()); - return (false, null, ex.Message); - } - } - - public async Task<(bool IsSuccess, Models.User User, string ErrorMessage)> GetUsersAsync(int Id) - { - try - { - logger?.LogInformation("Querying Users table"); - var user = await userAccessDbContext.Users.SingleOrDefaultAsync(s => s.Id == Id); - if (user != null) - { - logger?.LogInformation($"User Id: {Id} found"); - var result = mapper.Map(user); - return (true, result, null); - } - return (false, null, "Not found"); - } - catch (Exception ex) - { - logger?.LogError(ex.ToString()); - return (false, null, ex.Message); - } - } - - public async Task<(bool IsSuccess, Models.User User, string ErrorMessage)> PostUserAsync(Models.User user) - { - try - { - if (user != null) - { - var users = await userAccessDbContext.Users.ToListAsync(); - int count = users.Where(u => u.EmployeeId == user.EmployeeId).Count(); - if (count == 0) - { - user.Id = users.Count + 1; - userAccessDbContext.Users.Add(mapper.Map(user)); - await userAccessDbContext.SaveChangesAsync(); - return (true, user, "Successful"); - } - else - { - logger?.LogInformation($"Employee Id: {user.EmployeeId} is already exist"); - return (false, null, $"Employee Id: {user.EmployeeId} is already exist"); - } - } - else - { - logger?.LogInformation($"Employee Id: {user.EmployeeId} cannot be added"); - return (false, null, $"Employee Id: {user.EmployeeId} cannot be added"); - } - } - catch (Exception ex) - { - logger?.LogError(ex.ToString()); - return (false, null, ex.Message); - } - } - - public async Task<(bool IsSuccess, Models.User User, string ErrorMessage)> PutUserAsync(int Id, Models.User user) - { - try - { - if (user != null) - { - var _user = await userAccessDbContext.Users.Where(s => s.Id == Id).SingleOrDefaultAsync(); - - if (_user != null) - { - int count = userAccessDbContext.Users.Where(u => u.Id != user.Id && u.EmployeeId == user.EmployeeId).Count(); - if (count == 0) - { - _user.EmployeeId = user.EmployeeId; - _user.RoleId = user.RoleId; - _user.IsActive = user.IsActive; - _user.UpdateDate = DateTime.Now; - await userAccessDbContext.SaveChangesAsync(); - - - logger?.LogInformation($"Employee Id: {user.EmployeeId} updated successfuly"); - return (true, mapper.Map(_user), $"Employee Id: {_user.EmployeeId} updated successfuly"); - } - else - { - logger?.LogInformation($"Employee Id: {user.EmployeeId} is already exist"); - return (false, null, $"Employee Id: {user.EmployeeId} is already exist"); - } - } - else - { - logger?.LogInformation($"User Id : {Id} Not found"); - return (false, null, "Not Found"); - } - } - else - { - logger?.LogInformation($"User Id: {Id} Bad Request"); - return (false, null, "Bad request"); - } - } - catch (Exception ex) - { - logger?.LogError(ex.ToString()); - return (false, null, ex.Message); - } - } - - public async Task<(bool IsSuccess, Models.User User, string ErrorMessage)> DeleteUserAsync(int Id) - { - try - { - var user = await userAccessDbContext.Users.Where(x => x.Id == Id).SingleOrDefaultAsync(); - - if (user != null) - { - userAccessDbContext.Users.Remove(user); - await userAccessDbContext.SaveChangesAsync(); - logger?.LogInformation($"User Id: {Id} deleted Successfuly"); - return (true, mapper.Map(user), $"User Id: {Id} deleted Successfuly"); - } - else - { - logger?.LogInformation($"User Id : {Id} Not found"); - return (false, null, "Not Found"); - } - } - catch (Exception ex) - { - logger?.LogError(ex.ToString()); - return (false, null, ex.Message); - } - } - - public async Task<(bool IsSuccess, TokenResponse TokenResponse, string ErrorMessage)> AuthenticateAsync(UserCredentials userCredentials) - { - - if (userCredentials != null) - { - //implementation for dadeschools authentication - - var employee = await employeeServiceProvider.getEmployeeAsync(userCredentials.username); - - if (employee != null) - { - var result = await GetUsersAsync(); - - if (result.IsSuccess) - { - var user = result.Users.Where(x => x.IsActive == true && x.EmployeeId.ToLower().Equals(userCredentials.username.ToLower())).SingleOrDefault(); - - if (user != null) - { - - var r = await GetRolesAsync(); - var role = r.Roles.Where(x => x.Id == user.RoleId).SingleOrDefault(); - - var authClaims = new List { - new Claim(ClaimTypes.Name, user.EmployeeId), - new Claim(ClaimTypes.Role, role.Name), - new Claim(JwtRegisteredClaimNames.Jti,Guid.NewGuid().ToString()) - - }; - - /// Generate Token - var tokenhandler = new JwtSecurityTokenHandler(); - var tokenkey = Encoding.UTF8.GetBytes(jwtSettings.securitykey); - var tokendesc = new SecurityTokenDescriptor - { - Audience = "", - NotBefore = DateTime.Now, - Subject = new ClaimsIdentity(authClaims), - Expires = DateTime.Now.AddMinutes(30), - SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(tokenkey), SecurityAlgorithms.HmacSha256) - }; - var token = tokenhandler.CreateToken(tokendesc); - string finaltoken = tokenhandler.WriteToken(token); - - var response = new TokenResponse() { jwttoken = finaltoken, refreshtoken = await tokenServiceProvider.GenerateToken(user) }; - - - return (true, response, "Authentication success and token issued."); - - } - else - { - return (false, null, "user inactive or not exist."); - } - } - else - { - return (false, null, "users list empty."); - } - } - else - { - return (false, null, "Employee not exist."); - } - } - else - { - return (false, null, "Credentials are required to authenticate."); - - } - - } - public async Task<(bool IsSuccess, IEnumerable Roles, string ErrorMessage)> GetRolesAsync() - { - try - { - logger?.LogInformation("Gell all Roles from DB"); - var roles = await userAccessDbContext.Roles.ToListAsync(); - if (roles != null) - { - logger?.LogInformation($"{roles.Count} Items(s) found"); - var result = mapper.Map, IEnumerable>(roles); - return (true, result, null); - } - return (false, null, "Not found"); - } - catch (Exception ex) - { - logger?.LogError(ex.ToString()); - return (false, null, ex.Message); - } - } - - public async Task<(bool IsSuccess, Models.TokenResponse TokenResponse, string ErrorMessage)> RefreshTokenAsync(TokenResponse tokenResponse) - { - //Generate token - var tokenhandler = new JwtSecurityTokenHandler(); - var tokenkey = Encoding.UTF8.GetBytes(this.jwtSettings.securitykey); - SecurityToken securityToken; - var principal = tokenhandler.ValidateToken(tokenResponse.jwttoken, new TokenValidationParameters - { - ValidateIssuerSigningKey = true, - IssuerSigningKey = new SymmetricSecurityKey(tokenkey), - ValidateIssuer = false, - ValidateAudience = false, - - }, out securityToken); - - var token = securityToken as JwtSecurityToken; - if (token != null && !token.Header.Alg.Equals(SecurityAlgorithms.HmacSha256)) - { - return (false, null, "Unauthorized"); - } - var username = principal.Identity?.Name; - - var tokens = await userAccessDbContext.Tokens.ToListAsync(); - var users = await userAccessDbContext.Users.ToListAsync(); - - var user = (from u in users - join t in tokens - on u.Id equals t.UserId - where u.EmployeeId == username - && t.RefreshToken == tokenResponse.refreshtoken - select u).FirstOrDefault(); - - if (user == null) - return (false, null, "Invalid Token Response object provided"); - - var _user = mapper.Map(user); - var response = tokenServiceProvider.TokenAuthenticate(_user, principal.Claims.ToArray()).Result; - return (true, response, "Token authenticated and refreshed."); - } - - - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/appsettings.Development.json b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/appsettings.Development.json deleted file mode 100644 index 0c208ae..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/appsettings.Development.json +++ /dev/null @@ -1,8 +0,0 @@ -{ - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/appsettings.json b/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/appsettings.json deleted file mode 100644 index 4a1b1b5..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.UsersAccess/appsettings.json +++ /dev/null @@ -1,15 +0,0 @@ -{ - "JwtSettings": { - "securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk=" - }, - "Logging": { - "LogLevel": { - "Default": "Information", - "Microsoft.AspNetCore": "Warning" - } - }, - "EndPointSettings": { - "EmployeeUrlBase": "http://localhost:5135" - }, - "AllowedHosts": "*" -} diff --git a/DamageAssesmentApi/DamageAssesment.sln b/DamageAssesmentApi/DamageAssesment.sln index 8deb2aa..101bcec 100644 --- a/DamageAssesmentApi/DamageAssesment.sln +++ b/DamageAssesmentApi/DamageAssesment.sln @@ -37,8 +37,6 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DamageAssesment.Api.Employe EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DamageAssesment.Api.Employees.Test", "DamageAssesment.Api.Employees.Test\DamageAssesment.Api.Employees.Test.csproj", "{D6BF9AE9-72FA-4726-A326-35A35D27FFB8}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DamageAssesment.Api.UsersAccess", "DamageAssesment.Api.UsersAccess\DamageAssesment.Api.UsersAccess.csproj", "{83177BB9-DD23-4A85-A000-D60F843D0835}" -EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -101,10 +99,6 @@ Global {D6BF9AE9-72FA-4726-A326-35A35D27FFB8}.Debug|Any CPU.Build.0 = Debug|Any CPU {D6BF9AE9-72FA-4726-A326-35A35D27FFB8}.Release|Any CPU.ActiveCfg = Release|Any CPU {D6BF9AE9-72FA-4726-A326-35A35D27FFB8}.Release|Any CPU.Build.0 = Release|Any CPU - {83177BB9-DD23-4A85-A000-D60F843D0835}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {83177BB9-DD23-4A85-A000-D60F843D0835}.Debug|Any CPU.Build.0 = Debug|Any CPU - {83177BB9-DD23-4A85-A000-D60F843D0835}.Release|Any CPU.ActiveCfg = Release|Any CPU - {83177BB9-DD23-4A85-A000-D60F843D0835}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE From cd261a55568e2d073689f09f302baeaab118f7ff Mon Sep 17 00:00:00 2001 From: Reginald Cherenfant Jasmin Date: Thu, 31 Aug 2023 01:57:14 -0400 Subject: [PATCH 12/19] Test project for location service updated --- .../LocationsServiceTest.cs | 247 +++++++++--------- .../MockData.cs | 41 ++- 2 files changed, 167 insertions(+), 121 deletions(-) diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/LocationsServiceTest.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/LocationsServiceTest.cs index 2d15662..8be1910 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/LocationsServiceTest.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/LocationsServiceTest.cs @@ -13,131 +13,144 @@ namespace DamageAssesment.Api.Locations.Test { public class LocationsServiceTest { - - [Fact(DisplayName = "Get Location using Location ID")] - public async Task GetLocationsUsingLocationID() + //Test for locations + [Fact(DisplayName = "Get Locations - Ok case")] + public async Task GetLocationsAsync_ShouldReturnStatusCode200() { - var options = new DbContextOptionsBuilder() - .UseInMemoryDatabase(nameof(GetLocationsUsingLocationID)) - .Options; + var mockLocationService = new Mock(); + var mockResponse = await MockData.getOkResponseLocation(); + mockLocationService.Setup(service => service.GetLocationsAsync()).ReturnsAsync(mockResponse); - var dbContext = new LocationDbContext(options); - CreateLocations(dbContext); - //Mapping - var LocationsProfile = new LocationProfile(); - var configuration = new MapperConfiguration(cfg => cfg.AddProfile(LocationsProfile)); - var mapper = new Mapper(configuration); + var locationProvider = new LocationsController(mockLocationService.Object); + var result = (OkObjectResult)await locationProvider.GetLocationsAsync(); - var LocationsProvider = new LocationsProvider(dbContext, null, mapper); - //Testmethode - var Location = await LocationsProvider.GetLocationByIdAsync("Loc3"); - - Assert.True(Location.IsSuccess); - Assert.Null(Location.ErrorMessage); - } - [Fact(DisplayName = "Get Locations")] - public async Task GetAllLocationsTest() - { - var options = new DbContextOptionsBuilder() - .UseInMemoryDatabase(nameof(GetLocationsUsingLocationID)) - .Options; - - var dbContext = new LocationDbContext(options); - CreateLocations(dbContext); - //Mapping - var LocationsProfile = new LocationProfile(); - var configuration = new MapperConfiguration(cfg => cfg.AddProfile(LocationsProfile)); - var mapper = new Mapper(configuration); - - var LocationsProvider = new LocationsProvider(dbContext, null, mapper); - //Testmethode - var Location = await LocationsProvider.GetLocationsAsync(); - - Assert.True(Location.IsSuccess); - Assert.Null(Location.ErrorMessage); + Assert.Equal(200, result.StatusCode); } - [Fact(DisplayName = "Delete Location by Id")] - public async Task DeleteLocationTest() + + [Fact(DisplayName = "Get Locations - NoContent Case")] + public async Task GetLocationsAsync_ShouldReturnStatusCode204() { - var options = new DbContextOptionsBuilder() - .UseInMemoryDatabase(nameof(GetLocationsUsingLocationID)) - .Options; + var mockLocationService = new Mock(); + var mockResponse = await MockData.getNotFoundResponseLocation(); + mockLocationService.Setup(service => service.GetLocationsAsync()).ReturnsAsync(mockResponse); - var dbContext = new LocationDbContext(options); - CreateLocations(dbContext); - //Mapping - var LocationsProfile = new LocationProfile(); - var configuration = new MapperConfiguration(cfg => cfg.AddProfile(LocationsProfile)); - var mapper = new Mapper(configuration); + var locationProvider = new LocationsController(mockLocationService.Object); + var result = (NoContentResult)await locationProvider.GetLocationsAsync(); - var LocationsProvider = new LocationsProvider(dbContext, null, mapper); - //Testmethode - var Location = await LocationsProvider.DeleteLocationAsync("Loc2"); - - Assert.True(Location.IsSuccess); - Assert.NotNull(Location.ErrorMessage); + Assert.Equal(204, result.StatusCode); } - [Fact(DisplayName = "Add Location")] - public async Task AddLocationTest() + + [Fact(DisplayName = "Get Locations by Id- Ok case")] + public async Task GetLocationsByIdAsync_ShouldReturnStatusCode200() { - var options = new DbContextOptionsBuilder() - .UseInMemoryDatabase(nameof(GetLocationsUsingLocationID)) - .Options; + var mockLocationService = new Mock(); + var mockResponse = await MockData.getOkResponseLocation("Loc1"); + mockLocationService.Setup(service => service.GetLocationByIdAsync("Loc1")).ReturnsAsync(mockResponse); - var dbContext = new LocationDbContext(options); - CreateLocations(dbContext); - //Mapping - var LocationsProfile = new LocationProfile(); - var configuration = new MapperConfiguration(cfg => cfg.AddProfile(LocationsProfile)); - var mapper = new Mapper(configuration); - var LocationsProvider = new LocationsProvider(dbContext, null, mapper); - //Testmethode - Models.Location newLocation = new Models.Location() { Id = "Loc9", RegionId = "1", Name = "Test 1", MaintenanceCenter = "1", SchoolType = "US" }; - var Location = await LocationsProvider.PostLocationAsync(newLocation); + var locationProvider = new LocationsController(mockLocationService.Object); + var result = (OkObjectResult)await locationProvider.GetLocationByIdAsync("Loc1"); - Assert.True(Location.IsSuccess); - Assert.Null(Location.ErrorMessage); + Assert.Equal(200, result.StatusCode); } - [Fact(DisplayName = "Update Location")] - public async Task UpdateLocationTest() - { - var options = new DbContextOptionsBuilder() - .UseInMemoryDatabase(nameof(GetLocationsUsingLocationID)) - .Options; - var dbContext = new LocationDbContext(options); - CreateLocations(dbContext); - //Mapping - var LocationsProfile = new LocationProfile(); - var configuration = new MapperConfiguration(cfg => cfg.AddProfile(LocationsProfile)); - var mapper = new Mapper(configuration); - var LocationsProvider = new LocationsProvider(dbContext, null, mapper); - //Testmethode - Models.Location updateLocation = new Models.Location() { Id = "Loc1", RegionId = "1", Name = "Tampa", MaintenanceCenter = "1", SchoolType = "NA" }; - var Location = await LocationsProvider.UpdateLocationAsync(updateLocation); - var modified = dbContext.Locations.FirstOrDefault(a => a.Id == updateLocation.Id); - Assert.True(Location.IsSuccess); - Assert.NotNull(Location.ErrorMessage); - } - private static void CreateLocations(LocationDbContext dbContext) - { - //Create sample data for testing - if (dbContext.Locations.Count() == 0) - { - for (int i = 1; i < 6; i++) - { - dbContext.Locations.Add(new Db.Location() - { - Id = "Loc"+i.ToString(), - RegionId = i.ToString(), - Name = "Test Location" + Guid.NewGuid().ToString(), - MaintenanceCenter = i.ToString(), - SchoolType = "US" - }); - } - dbContext.SaveChanges(); - } + + [Fact(DisplayName = "Get Locations By Id - NoFound Case")] + public async Task GetLocationsByIdAsync_ShouldReturnStatusCode404() + { + var mockLocationService = new Mock(); + var mockResponse = await MockData.getLocationNotFoundResponse(); + mockLocationService.Setup(service => service.GetLocationByIdAsync("Loc1")).ReturnsAsync(mockResponse); + + var locationProvider = new LocationsController(mockLocationService.Object); + var result = (NotFoundResult)await locationProvider.GetLocationByIdAsync("Loc1"); + + Assert.Equal(404, result.StatusCode); + } + + + [Fact(DisplayName = "Post Location - Ok case")] + public async Task PostLocationAsync_ShouldReturnStatusCode200() + { + var mockLocationService = new Mock(); + var mockResponse = await MockData.getOkResponseLocation("Loc1"); + var mockInputLocation = new Models.Location { Id = "Loc1", RegionId = "R1", Name = "Location 1", SchoolType = "US", MaintenanceCenter = "1" }; + mockLocationService.Setup(service => service.PostLocationAsync(mockInputLocation)).ReturnsAsync(mockResponse); + + var locationProvider = new LocationsController(mockLocationService.Object); + var result = (OkObjectResult)await locationProvider.CreateLocation(mockInputLocation); + + Assert.Equal(200, result.StatusCode); + } + + [Fact(DisplayName = "Post Location - BadRequest case")] + public async Task PostLocationAsync_ShouldReturnStatusCode400() + { + var mockLocationService = new Mock(); + var mockResponse = await MockData.getLocationNotFoundResponse(); + var mockInputLocation = new Models.Location { Id = "Loc1", RegionId = "R1", Name = "Location 1", SchoolType = "US", MaintenanceCenter = "1" }; + mockLocationService.Setup(service => service.PostLocationAsync(mockInputLocation)).ReturnsAsync(mockResponse); + + var locationProvider = new LocationsController(mockLocationService.Object); + var result = (BadRequestResult)await locationProvider.CreateLocation(mockInputLocation); + + Assert.Equal(400, result.StatusCode); + } + + + [Fact(DisplayName = "Put Location - Ok case")] + public async Task PutLocationAsync_ShouldReturnStatusCode200() + { + var mockLocationService = new Mock(); + var mockResponse = await MockData.getLocation(true, "update success"); + var mockInputLocation = new Models.Location { Id = "Loc1", RegionId = "R1", Name = "Location 1", SchoolType = "US", MaintenanceCenter = "1" }; + mockLocationService.Setup(service => service.UpdateLocationAsync(mockInputLocation)).ReturnsAsync(mockResponse); + + var locationProvider = new LocationsController(mockLocationService.Object); + var result = (OkObjectResult)await locationProvider.UpdateLocation(mockInputLocation); + + Assert.Equal(200, result.StatusCode); + } + + [Fact(DisplayName = "Put Location - NotFound case")] + public async Task PutLocationAsync_ShouldReturnStatusCode404() + { + var mockLocationService = new Mock(); + var mockResponse = await MockData.getLocation(false, null); + var mockInputLocation = new Models.Location { Id = "Loc1", RegionId = "R1", Name = "Location 1", SchoolType = "US", MaintenanceCenter = "1" }; + mockLocationService.Setup(service => service.UpdateLocationAsync(mockInputLocation)).ReturnsAsync(mockResponse); + + var locationProvider = new LocationsController(mockLocationService.Object); + var result = (NotFoundResult)await locationProvider.UpdateLocation(mockInputLocation); + + Assert.Equal(404, result.StatusCode); + } + + + [Fact(DisplayName = "Delete Location - Ok case")] + public async Task DeleteLocationAsync_ShouldReturnStatusCode200() + { + var mockLocationService = new Mock(); + var mockResponse = await MockData.getLocation(true, "delete success"); + mockLocationService.Setup(service => service.DeleteLocationAsync("Loc1")).ReturnsAsync(mockResponse); + + var locationProvider = new LocationsController(mockLocationService.Object); + var result = (OkObjectResult)await locationProvider.DeleteLocation("Loc1"); + + Assert.Equal(200, result.StatusCode); + } + + [Fact(DisplayName = "Delete Location - NotFound case")] + public async Task DeleteLocationAsync_ShouldReturnStatusCode404() + { + var mockLocationService = new Mock(); + var mockResponse = await MockData.getLocation(false, null); + mockLocationService.Setup(service => service.DeleteLocationAsync("Loc1")).ReturnsAsync(mockResponse); + + var locationProvider = new LocationsController(mockLocationService.Object); + var result = (NotFoundResult)await locationProvider.DeleteLocation("Loc1"); + + Assert.Equal(404, result.StatusCode); } //Tests for regions @@ -194,7 +207,7 @@ namespace DamageAssesment.Api.Locations.Test } [Fact(DisplayName = "Post Region - Ok case")] - public async Task PostSurveyAsync_ShouldReturnStatusCode200() + public async Task PostRegionAsync_ShouldReturnStatusCode200() { var mockRegionService = new Mock(); var mockResponse = await MockData.getOkResponse("1"); @@ -208,7 +221,7 @@ namespace DamageAssesment.Api.Locations.Test } [Fact(DisplayName = "Post Region - BadRequest case")] - public async Task PostSurveyAsync_ShouldReturnStatusCode400() + public async Task PostRegionAsync_ShouldReturnStatusCode400() { var mockRegionService = new Mock(); var mockResponse = await MockData.getBadRequestResponse(); @@ -236,7 +249,7 @@ namespace DamageAssesment.Api.Locations.Test } [Fact(DisplayName = "Put Region - NotFound case")] - public async Task PutSurveyAsync_ShouldReturnStatusCode404() + public async Task PutRegionAsync_ShouldReturnStatusCode404() { var mockRegionService = new Mock(); var mockResponse = await MockData.getNotFoundResponse(); @@ -250,7 +263,7 @@ namespace DamageAssesment.Api.Locations.Test } [Fact(DisplayName = "Put Region - BadRequest case")] - public async Task PutSurveyAsync_ShouldReturnStatusCode400() + public async Task PutRegionyAsync_ShouldReturnStatusCode400() { var mockRegionService = new Mock(); var mockResponse = await MockData.getBadRequestResponse(); @@ -264,7 +277,7 @@ namespace DamageAssesment.Api.Locations.Test } [Fact(DisplayName = "Delete Region - Ok case")] - public async Task DeleteSurveyAsync_ShouldReturnStatusCode200() + public async Task DeleteRegionAsync_ShouldReturnStatusCode200() { var mockRegionService = new Mock(); var mockResponse = await MockData.getOkResponse("1"); @@ -278,7 +291,7 @@ namespace DamageAssesment.Api.Locations.Test } [Fact(DisplayName = "Delete Region - NotFound case")] - public async Task DeleteSurveyAsync_ShouldReturnStatusCode404() + public async Task DeleteRegionAsync_ShouldReturnStatusCode404() { var mockRegionService = new Mock(); var mockResponse = await MockData.getNotFoundResponse(); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/MockData.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/MockData.cs index cd6b85e..dec67b8 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/MockData.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/MockData.cs @@ -17,9 +17,43 @@ namespace DamageAssesment.Api.Locations.Test public static async Task<(bool, Locations.Models.Region, string)> getOkResponse(string Id) { - var surveys = await getOkResponse(); - var survey = surveys.Item2.FirstOrDefault(s => s.Id == Id); - return (true, survey, null); + var regions = await getOkResponse(); + var region = regions.Item2.FirstOrDefault(s => s.Id == Id); + return (true, region, null); + } + + + public static async Task<(bool, IEnumerable, string)> getOkResponseLocation() + { + IEnumerable list = new List(); + + for (int i = 0; i < 10; i++) + { + list.Append(new Locations.Models.Location { Id = "Loc"+ i, RegionId = "R"+i, Name ="Location"}); + } + return (true, list, null); + } + + public static async Task<(bool, IEnumerable, string)> getNotFoundResponseLocation() + { + return (false, null, null); + } + + public static async Task<(bool, Models.Location, string)> getOkResponseLocation(string Id) + { + var locations = await getOkResponseLocation(); + var location = locations.Item2.FirstOrDefault(s => s.Id == Id); + return (true, location, null); + } + + public static async Task<(bool, string)> getLocation(bool value,string message) + { + return (value,message); + } + + public static async Task<(bool, Locations.Models.Location, string)> getLocationNotFoundResponse() + { + return (false, null, "Not Found"); } public static async Task<(bool, Locations.Models.Region, string)> getBadRequestResponse() @@ -41,6 +75,5 @@ namespace DamageAssesment.Api.Locations.Test { return new Locations.Models.Region { Id = "R99", Name = "Region 99", Abbreviation = "A99" }; } - } } From d78d5e0ba444615f924b3cba521462b92f090c9d Mon Sep 17 00:00:00 2001 From: uppuv Date: Thu, 31 Aug 2023 19:12:47 -0400 Subject: [PATCH 13/19] Modified Documents api for InMemory Logic --- .../Db/DocumentDbContext.cs | 9 +-------- .../DamageAssesment.Api.Documents/Program.cs | 2 +- .../Providers/DocumentsProvider.cs | 2 +- .../DamageAssesment.Api.Documents/appsettings.json | 3 --- 4 files changed, 3 insertions(+), 13 deletions(-) diff --git a/DamageAssesmentApi/DamageAssesment.Api.Documents/Db/DocumentDbContext.cs b/DamageAssesmentApi/DamageAssesment.Api.Documents/Db/DocumentDbContext.cs index f0ddc60..4df2f77 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Documents/Db/DocumentDbContext.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Documents/Db/DocumentDbContext.cs @@ -7,19 +7,12 @@ namespace DamageAssesment.Api.Documents.Db { public class DocumentDbContext : DbContext { - private IConfiguration _Configuration { get; set; } - public DocumentDbContext(DbContextOptions options, IConfiguration configuration) : base(options) + public DocumentDbContext(DbContextOptions options) : base(options) { - _Configuration = configuration; } public DbSet Documents { get; set; } public DbSet LinkTypes { get; set; } public DbSet DocumentsTranslations { get; set; } - protected override void OnConfiguring(DbContextOptionsBuilder options) - { - // connect to sql server with connection string from app settings - options.UseSqlServer(_Configuration.GetConnectionString("DocumentConnection")); - } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Documents/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Documents/Program.cs index a1e9361..af38287 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Documents/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Documents/Program.cs @@ -17,7 +17,7 @@ builder.Services.AddScoped(); builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); //4/30 builder.Services.AddDbContext(option => { - option.UseSqlServer("DocumentConnection"); + option.UseInMemoryDatabase("DocumentConnection"); }); var app = builder.Build(); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Documents/Providers/DocumentsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Documents/Providers/DocumentsProvider.cs index 8b6c1ee..4af3174 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Documents/Providers/DocumentsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Documents/Providers/DocumentsProvider.cs @@ -49,7 +49,7 @@ namespace DamageAssesment.Api.Documents.Providers } if (!DocumentDbContext.DocumentsTranslations.Any()) { - Db.DocumentsTranslation documents = new Db.DocumentsTranslation { Id = 0, DocumentId = 1, title = "Test", description = "ss", Language = "en" }; + Db.DocumentsTranslation documents = new Db.DocumentsTranslation { DocumentId = 1, title = "Test", description = "ss", Language = "en" }; DocumentDbContext.DocumentsTranslations.Add(documents); DocumentDbContext.SaveChanges(); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Documents/appsettings.json b/DamageAssesmentApi/DamageAssesment.Api.Documents/appsettings.json index 5006fa8..e38d9fb 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Documents/appsettings.json +++ b/DamageAssesmentApi/DamageAssesment.Api.Documents/appsettings.json @@ -9,8 +9,5 @@ "Fileupload": { "folderpath": "DASA_Documents/Active", "Deletepath": "DASA_Documents/Deleted" - }, - "ConnectionStrings": { - "DocumentConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;" } } From 5a4dda12ff431f433e0637d0baf161260bed62a0 Mon Sep 17 00:00:00 2001 From: Reginald Cherenfant Jasmin Date: Fri, 1 Sep 2023 12:14:25 -0400 Subject: [PATCH 14/19] Update on the controller for NoContent return type --- .../Controllers/LocationsController.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs index 0ee489a..d919c07 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs @@ -27,7 +27,7 @@ namespace DamageAssesment.Api.Locations.Controllers { return Ok(result.locations); } - return NotFound(); + return NoContent(); } /// @@ -78,9 +78,9 @@ namespace DamageAssesment.Api.Locations.Controllers { return Ok(result.Question); } - return NotFound(); + return BadRequest(); } - return CreatedAtRoute("DefaultApi", new { id = Location.Id }, Location); + return BadRequest(); } /// /// Delete an existing location. From a1a9fd1dc51b069eda6cb08808046905472b65b9 Mon Sep 17 00:00:00 2001 From: Reginald Cherenfant Jasmin Date: Mon, 4 Sep 2023 21:31:41 -0400 Subject: [PATCH 15/19] 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()) { From 24a6e6513e023dd391300d957a331d2fb85c8eea Mon Sep 17 00:00:00 2001 From: Reginald Cherenfant Jasmin Date: Mon, 4 Sep 2023 21:59:21 -0400 Subject: [PATCH 16/19] Adding external services to Service folder --- .../DamageAssesment.Api.SurveyResponses/Program.cs | 2 +- .../AnswerServiceProvider.cs | 13 +++---------- .../AttachmentServiceProvider.cs | 7 ++----- .../EmployeeServiceProvider.cs | 7 ++----- .../{Utils => Services}/HttpUtil.cs | 6 +++--- .../LocationServiceProvider.cs | 5 ++--- .../QuestionServiceProvider.cs | 5 ++--- .../RegionServiceProvider.cs | 5 ++--- .../{Bases => Services}/ServiceProviderBase.cs | 2 +- .../SurveyServiceProvider.cs | 6 ++---- 10 files changed, 20 insertions(+), 38 deletions(-) rename DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/{Providers => Services}/AnswerServiceProvider.cs (88%) rename DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/{Providers => Services}/AttachmentServiceProvider.cs (91%) rename DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/{Providers => Services}/EmployeeServiceProvider.cs (88%) rename DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/{Utils => Services}/HttpUtil.cs (90%) rename DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/{Providers => Services}/LocationServiceProvider.cs (88%) rename DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/{Providers => Services}/QuestionServiceProvider.cs (94%) rename DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/{Providers => Services}/RegionServiceProvider.cs (87%) rename DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/{Bases => Services}/ServiceProviderBase.cs (93%) rename DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/{Providers => Services}/SurveyServiceProvider.cs (90%) diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Program.cs index 7b1fe15..8d27911 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Program.cs @@ -1,7 +1,7 @@ using DamageAssesment.Api.SurveyResponses.Db; using DamageAssesment.Api.SurveyResponses.Interfaces; +using DamageAssesment.Api.SurveyResponses.Services; using DamageAssesment.Api.SurveyResponses.Providers; -using DamageAssesment.Api.SurveyResponses.Utils; using Microsoft.EntityFrameworkCore; using Polly; using System.Reflection; diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AnswerServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/AnswerServiceProvider.cs similarity index 88% rename from DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AnswerServiceProvider.cs rename to DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/AnswerServiceProvider.cs index 19ed7eb..921f59c 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AnswerServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/AnswerServiceProvider.cs @@ -1,16 +1,9 @@ -using DamageAssesment.Api.SurveyResponses.Bases; -using DamageAssesment.Api.SurveyResponses.Db; -using DamageAssesment.Api.SurveyResponses.Interfaces; +using DamageAssesment.Api.SurveyResponses.Interfaces; using DamageAssesment.Api.SurveyResponses.Models; using Newtonsoft.Json; -using System.Data.Common; -using System.Security.Cryptography; -using System.Text.Json.Nodes; -using System.Text; -using System.Net.Http.Headers; -using System; -namespace DamageAssesment.Api.SurveyResponses.Providers + +namespace DamageAssesment.Api.SurveyResponses.Services { public class AnswerServiceProvider : ServiceProviderBase, IAnswerServiceProvider { diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AttachmentServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/AttachmentServiceProvider.cs similarity index 91% rename from DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AttachmentServiceProvider.cs rename to DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/AttachmentServiceProvider.cs index ae19cbb..9c45c72 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/AttachmentServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/AttachmentServiceProvider.cs @@ -1,11 +1,8 @@ -using DamageAssesment.Api.SurveyResponses.Bases; -using DamageAssesment.Api.SurveyResponses.Interfaces; +using DamageAssesment.Api.SurveyResponses.Interfaces; using DamageAssesment.Api.SurveyResponses.Models; using Newtonsoft.Json; -using System.Net.Http.Headers; -using System.Text; -namespace DamageAssesment.Api.SurveyResponses.Providers +namespace DamageAssesment.Api.SurveyResponses.Services { public class AttachmentServiceProvider : ServiceProviderBase, IAttachmentServiceProvider { diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/EmployeeServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/EmployeeServiceProvider.cs similarity index 88% rename from DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/EmployeeServiceProvider.cs rename to DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/EmployeeServiceProvider.cs index 56d876e..46288a8 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/EmployeeServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/EmployeeServiceProvider.cs @@ -1,11 +1,8 @@ -using DamageAssesment.Api.SurveyResponses.Bases; -using DamageAssesment.Api.SurveyResponses.Interfaces; +using DamageAssesment.Api.SurveyResponses.Interfaces; using DamageAssesment.Api.SurveyResponses.Models; -using DamageAssesment.Api.SurveyResponses.Utils; using Newtonsoft.Json; -using System.Reflection; -namespace DamageAssesment.Api.SurveyResponses.Providers +namespace DamageAssesment.Api.SurveyResponses.Services { public class EmployeeServiceProvider :ServiceProviderBase, IEmployeeServiceProvider { diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Utils/HttpUtil.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/HttpUtil.cs similarity index 90% rename from DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Utils/HttpUtil.cs rename to DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/HttpUtil.cs index 02dfd3d..8b4755d 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Utils/HttpUtil.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/HttpUtil.cs @@ -1,9 +1,8 @@ -using DamageAssesment.Api.SurveyResponses.Bases; -using DamageAssesment.Api.SurveyResponses.Interfaces; +using DamageAssesment.Api.SurveyResponses.Interfaces; using System.Net.Http.Headers; using System.Text; -namespace DamageAssesment.Api.SurveyResponses.Utils +namespace DamageAssesment.Api.SurveyResponses.Services { public class HttpUtil : IHttpUtil { @@ -22,6 +21,7 @@ namespace DamageAssesment.Api.SurveyResponses.Utils 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) { diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/LocationServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/LocationServiceProvider.cs similarity index 88% rename from DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/LocationServiceProvider.cs rename to DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/LocationServiceProvider.cs index d45e7b4..07e456b 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/LocationServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/LocationServiceProvider.cs @@ -1,9 +1,8 @@ -using DamageAssesment.Api.SurveyResponses.Bases; -using DamageAssesment.Api.SurveyResponses.Interfaces; +using DamageAssesment.Api.SurveyResponses.Interfaces; using DamageAssesment.Api.SurveyResponses.Models; using Newtonsoft.Json; -namespace DamageAssesment.Api.SurveyResponses.Providers +namespace DamageAssesment.Api.SurveyResponses.Services { public class LocationServiceProvider :ServiceProviderBase, ILocationServiceProvider { diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/QuestionServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/QuestionServiceProvider.cs similarity index 94% rename from DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/QuestionServiceProvider.cs rename to DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/QuestionServiceProvider.cs index 2dd90cb..6099141 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/QuestionServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/QuestionServiceProvider.cs @@ -1,9 +1,8 @@ -using DamageAssesment.Api.SurveyResponses.Bases; -using DamageAssesment.Api.SurveyResponses.Interfaces; +using DamageAssesment.Api.SurveyResponses.Interfaces; using DamageAssesment.Api.SurveyResponses.Models; using Newtonsoft.Json; -namespace DamageAssesment.Api.SurveyResponses.Providers +namespace DamageAssesment.Api.SurveyResponses.Services { public class QuestionServiceProvider : ServiceProviderBase, IQuestionServiceProvider { diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/RegionServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/RegionServiceProvider.cs similarity index 87% rename from DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/RegionServiceProvider.cs rename to DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/RegionServiceProvider.cs index 5cbee97..f31a1e1 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/RegionServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/RegionServiceProvider.cs @@ -1,9 +1,8 @@ -using DamageAssesment.Api.SurveyResponses.Bases; -using DamageAssesment.Api.SurveyResponses.Interfaces; +using DamageAssesment.Api.SurveyResponses.Interfaces; using DamageAssesment.Api.SurveyResponses.Models; using Newtonsoft.Json; -namespace DamageAssesment.Api.SurveyResponses.Providers +namespace DamageAssesment.Api.SurveyResponses.Services { public class RegionServiceProvider : ServiceProviderBase, IRegionServiceProvider { diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Bases/ServiceProviderBase.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/ServiceProviderBase.cs similarity index 93% rename from DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Bases/ServiceProviderBase.cs rename to DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/ServiceProviderBase.cs index 7db6371..487975b 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Bases/ServiceProviderBase.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/ServiceProviderBase.cs @@ -1,6 +1,6 @@ using DamageAssesment.Api.SurveyResponses.Interfaces; -namespace DamageAssesment.Api.SurveyResponses.Bases +namespace DamageAssesment.Api.SurveyResponses.Services { public class ServiceProviderBase { diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/SurveyServiceProvider.cs similarity index 90% rename from DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyServiceProvider.cs rename to DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/SurveyServiceProvider.cs index fa65c74..616afb2 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/SurveyServiceProvider.cs @@ -1,10 +1,8 @@ -using DamageAssesment.Api.SurveyResponses.Bases; -using DamageAssesment.Api.SurveyResponses.Interfaces; +using DamageAssesment.Api.SurveyResponses.Interfaces; using DamageAssesment.Api.SurveyResponses.Models; using Newtonsoft.Json; -using System.Reflection; -namespace DamageAssesment.Api.SurveyResponses.Providers +namespace DamageAssesment.Api.SurveyResponses.Services { public class SurveyServiceProvider :ServiceProviderBase, ISurveyServiceProvider { From 4cf7d9f89118ec51a92be7665db15574996a46ec Mon Sep 17 00:00:00 2001 From: uppuv Date: Fri, 8 Sep 2023 15:40:06 -0400 Subject: [PATCH 17/19] Multi language dynamic object changes --- .../Controllers/QuestionsController.cs | 43 ++-- .../Db/CategoryTranslation.cs | 15 ++ .../Db/QuestionCategory.cs | 4 +- .../Db/QuestionDbContext.cs | 4 + .../Interfaces/IQuestionsProvider.cs | 22 +- .../Models/CategoryTranslation.cs | 8 + .../Models/Question.cs | 12 +- .../Models/QuestionCategory.cs | 14 +- .../Models/QuestionsTranslation.cs | 4 + .../Models/SurveyQuestion.cs | 6 +- .../Profiles/QuestionProfile.cs | 6 +- .../Providers/QuestionsProvider.cs | 213 ++++++++++++------ .../CategoryMockData.cs | 18 +- .../MockData.cs | 24 +- .../QuestionsServiceTest.cs | 20 +- .../MockData.cs | 16 +- .../Controllers/SurveysController.cs | 27 ++- .../Interfaces/ISurveyProvider.cs | 10 +- .../Models/Survey.cs | 12 +- .../Profiles/SurveysProfile.cs | 4 +- .../Providers/SurveysProvider.cs | 171 ++++++-------- 21 files changed, 370 insertions(+), 283 deletions(-) create mode 100644 DamageAssesmentApi/DamageAssesment.Api.Questions/Db/CategoryTranslation.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.Questions/Models/CategoryTranslation.cs diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs index ae98924..19c32bc 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs @@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Mvc; namespace DamageAssesment.Api.Questions.Controllers { - [Route("api")] [ApiController] public class QuestionsController : ControllerBase { @@ -21,12 +20,12 @@ namespace DamageAssesment.Api.Questions.Controllers /// // get all questions - [Route("{Language}/Questions")] [Route("Questions")] + [Route("Questions/{language:alpha}")] [HttpGet] - public async Task GetQuestionsAsync(string? Language) + public async Task GetQuestionsAsync(string? language) { - var result = await this.questionsProvider.GetQuestionsAsync(Language); + var result = await this.questionsProvider.GetQuestionsAsync(language); if (result.IsSuccess) { return Ok(result.Questions); @@ -38,12 +37,12 @@ namespace DamageAssesment.Api.Questions.Controllers /// /// GET request for retrieving a question by ID. /// - [Route("{Language}/Questions/{id}")] - [Route("Questions/{id}")] + [Route("Questions/{id}/{language:alpha}")] + [Route("Questions/{id:int}")] [HttpGet] - public async Task GetQuestionAsync(int id, string? Language) + public async Task GetQuestionByIdAsync(string? language,int id) { - var result = await this.questionsProvider.GetQuestionAsync(id,Language); + var result = await this.questionsProvider.GetQuestionAsync(id, language); if (result.IsSuccess) { return Ok(result.Question); @@ -56,12 +55,12 @@ namespace DamageAssesment.Api.Questions.Controllers /// GET request for retrieving survey questions based on a survey ID. /// Uri: {Optional language}/GetSurveyQuestions/{surveyId} :Default returns question in all languages /// - [Route("{Language}/GetSurveyQuestions/{surveyId}")] - [Route("GetSurveyQuestions/{surveyId}")] + [Route("Questions/BySurvey/{surveyId:int}")] + [Route("Questions/BySurvey/{surveyId:int}/{language:alpha}")] [HttpGet] - public async Task GetSurveyQuestions(int surveyId,string? Language) + public async Task GetSurveyQuestions(int surveyId,string? language) { - var result = await this.questionsProvider.GetSurveyQuestionAsync(surveyId, Language); + var result = await this.questionsProvider.GetSurveyQuestionAsync(surveyId, language); if (result.IsSuccess) { return Ok(result.SurveyQuestions); @@ -126,10 +125,11 @@ namespace DamageAssesment.Api.Questions.Controllers /// GET request for retrieving question categories. /// - [HttpGet("QuestionCategories")] - public async Task GetQuestionCategoriesAsync() + [HttpGet("Questions/Categories")] + [HttpGet("Questions/Categories/{language:alpha}")] + public async Task GetQuestionCategoriesAsync(string? language) { - var result = await this.questionsProvider.GetQuestionCategoriesAsync(); + var result = await this.questionsProvider.GetQuestionCategoriesAsync(language); if (result.IsSuccess) { return Ok(result.QuestionCategories); @@ -140,10 +140,11 @@ namespace DamageAssesment.Api.Questions.Controllers /// GET request for retrieving a question category by ID. /// - [HttpGet("QuestionCategories/{id}")] - public async Task GetQuestionCategoryAsync(int id) + [HttpGet("Questions/Categories/{id:int}")] + [HttpGet("Questions/Categories/{id:int}/{language:alpha}")] + public async Task GetQuestionCategoryAsync(int id,string? language) { - var result = await this.questionsProvider.GetQuestionCategoryAsync(id); + var result = await this.questionsProvider.GetQuestionCategoryAsync(id, language); if (result.IsSuccess) { return Ok(result.QuestionCategory); @@ -156,7 +157,7 @@ namespace DamageAssesment.Api.Questions.Controllers /// PUT request for updating a question category. /// - [HttpPut("QuestionCategories")] + [HttpPut("Questions/Categories")] public async Task UpdateQuestionCategory(Models.QuestionCategory questionCategory) { if (questionCategory != null) @@ -177,7 +178,7 @@ namespace DamageAssesment.Api.Questions.Controllers /// POST request for creating a new question category. /// - [HttpPost("QuestionCategories")] + [HttpPost("Questions/Categories")] public async Task CreateQuestionCategory(Models.QuestionCategory questionCategory) { if (questionCategory != null) @@ -195,7 +196,7 @@ namespace DamageAssesment.Api.Questions.Controllers /// DELETE request for deleting a question category based on ID. /// - [HttpDelete("QuestionCategories/{id}")] + [HttpDelete("Questions/Categories/{id}")] public async Task DeleteQuestionCategory(int id) { var result = await this.questionsProvider.DeleteQuestionCategoryAsync(id); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/CategoryTranslation.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/CategoryTranslation.cs new file mode 100644 index 0000000..b6e21fa --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/CategoryTranslation.cs @@ -0,0 +1,15 @@ +using System.ComponentModel.DataAnnotations.Schema; +using System.ComponentModel.DataAnnotations; + +namespace DamageAssesment.Api.Questions.Db +{ + public class CategoryTranslation + { + [Key] + public int Id { get; set; } + [ForeignKey("QuestionCategory")] + public int CategoryId { get; set; } + public string Title { get; set; } + public string Language { get; set; } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/QuestionCategory.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/QuestionCategory.cs index 06fc296..117f770 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/QuestionCategory.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/QuestionCategory.cs @@ -7,8 +7,8 @@ namespace DamageAssesment.Api.Questions.Db { [Key] public int Id { get; set; } - public string CategoryName { get; set; } - public string CategoryImage { get; set; } + public string IconName { get; set; } + public string IconLibrary { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/QuestionDbContext.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/QuestionDbContext.cs index a62485e..01e3c3d 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/QuestionDbContext.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Db/QuestionDbContext.cs @@ -10,6 +10,7 @@ namespace DamageAssesment.Api.Questions.Db public DbSet QuestionTypes { get; set; } public DbSet QuestionsTranslations { get; set; } public DbSet QuestionCategories { get; set; } + public DbSet CategoryTranslations { get; set; } public QuestionDbContext(DbContextOptions options) : base(options) { @@ -29,6 +30,9 @@ namespace DamageAssesment.Api.Questions.Db modelBuilder.Entity() .Property(item => item.Id) .ValueGeneratedOnAdd(); + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Interfaces/IQuestionsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Interfaces/IQuestionsProvider.cs index 58def79..59a805b 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Interfaces/IQuestionsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Interfaces/IQuestionsProvider.cs @@ -4,19 +4,19 @@ namespace DamageAssesment.Api.Questions.Interfaces { public interface IQuestionsProvider : IQuestionTypesProvider { - Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> GetQuestionAsync(int Id, string Language); - Task<(bool IsSuccess, IEnumerable Questions, string ErrorMessage)> GetQuestionsAsync(string Language); - Task<(bool IsSuccess, List SurveyQuestions, string ErrorMessage)> GetSurveyQuestionAsync(int surveyId,string Language); - Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> PostQuestionAsync(Models.Question Question); - Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question); - Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> DeleteQuestionAsync(int Id); + Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> GetQuestionAsync(int id, string language); + Task<(bool IsSuccess, IEnumerable Questions, string ErrorMessage)> GetQuestionsAsync(string language); + Task<(bool IsSuccess, List SurveyQuestions, string ErrorMessage)> GetSurveyQuestionAsync(int surveyId,string language); + Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> PostQuestionAsync(Models.Question Question); + Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question); + Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> DeleteQuestionAsync(int id); - Task<(bool IsSuccess, IEnumerable QuestionCategories, string ErrorMessage)> GetQuestionCategoriesAsync(); - Task<(bool IsSuccess, Models.QuestionCategory QuestionCategory, string ErrorMessage)> GetQuestionCategoryAsync(int Id); - 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); + Task<(bool IsSuccess, IEnumerable QuestionCategories, string ErrorMessage)> GetQuestionCategoriesAsync(string? language); + Task<(bool IsSuccess, Models.MultiLanQuestionCategory QuestionCategory, string ErrorMessage)> GetQuestionCategoryAsync(int id, string? language); + Task<(bool IsSuccess, Models.MultiLanQuestionCategory QuestionCategory, string ErrorMessage)> PostQuestionCategoryAsync(Models.QuestionCategory QuestionCategory); + Task<(bool IsSuccess, Models.MultiLanQuestionCategory QuestionCategory, string ErrorMessage)> UpdateQuestionCategoryAsync(Models.QuestionCategory QuestionCategory); + Task<(bool IsSuccess, Models.MultiLanQuestionCategory QuestionCategory, string ErrorMessage)> DeleteQuestionCategoryAsync(int id); void SeedData(); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/CategoryTranslation.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/CategoryTranslation.cs new file mode 100644 index 0000000..0c60d6b --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/CategoryTranslation.cs @@ -0,0 +1,8 @@ +namespace DamageAssesment.Api.Questions.Models +{ + public class CategoryTranslation + { + public string Title { get; set; } + public string Language { get; set; } + } +} diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/Question.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/Question.cs index b694f5b..7900097 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/Question.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/Question.cs @@ -2,11 +2,17 @@ namespace DamageAssesment.Api.Questions.Models { - public class Question + public class MultiLanQuestion: BaseQuestion + { + public MultiLanguage Questions { get; set; } + } + public class Question: BaseQuestion + { + public List Questions { get; set; } + } + public class BaseQuestion { public int Id { get; set; } - public List Questions { get; set; } - //public int QuestionTypeID { get; set; } public string TypeText { get; set; } = string.Empty; diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/QuestionCategory.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/QuestionCategory.cs index 78a6b52..7c8ccc7 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/QuestionCategory.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/QuestionCategory.cs @@ -1,9 +1,17 @@ namespace DamageAssesment.Api.Questions.Models { - public class QuestionCategory + public class MultiLanQuestionCategory : BaseQuestionCategory + { + public object Titles { get; set; } + } + public class QuestionCategory : BaseQuestionCategory + { + public List Categories { get; set; } + } + public class BaseQuestionCategory { public int Id { get; set; } - public string CategoryName { get; set; } - public string CategoryImage { get; set; } + public string IconName { get; set; } + public string IconLibrary { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/QuestionsTranslation.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/QuestionsTranslation.cs index 6df8219..af39cdd 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/QuestionsTranslation.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/QuestionsTranslation.cs @@ -5,4 +5,8 @@ public string QuestionText { get; set; } public string Language { get; set; } = "En"; } + public class MultiLanguage + { + public object questionText { get; set; } + } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/SurveyQuestion.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/SurveyQuestion.cs index 9736510..a3a5513 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/SurveyQuestion.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/SurveyQuestion.cs @@ -3,8 +3,8 @@ public class SurveyQuestions { public int CategoryId { get; set; } - public string CategoryName { get; set; } - public string CategoryImage { get; set; } - public List Questions { get; set; } + public string IconName { get; set; } + public string IconLibrary { get; set; } + public List Questions { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Profiles/QuestionProfile.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Profiles/QuestionProfile.cs index 015fe0c..5c0f36e 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Profiles/QuestionProfile.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Profiles/QuestionProfile.cs @@ -8,11 +8,15 @@ namespace DamageAssesment.Api.Questions.Profiles { CreateMap().ForMember(dest => dest.TypeText, opt => opt.MapFrom(src => src.QuestionType.TypeText)); + CreateMap().ForMember(dest => dest.TypeText, + opt => opt.MapFrom(src => src.QuestionType.TypeText)); CreateMap(); - CreateMap(); + CreateMap(); CreateMap(); CreateMap(); CreateMap(); + CreateMap(); + CreateMap(); } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs index 7ec55fa..26aa866 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs @@ -5,6 +5,8 @@ using DamageAssesment.Api.Questions.Models; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Internal; +using System.Collections; +using System.Collections.Generic; namespace DamageAssesment.Api.Questions.Providers { @@ -57,16 +59,89 @@ namespace DamageAssesment.Api.Questions.Providers if (!questionDbContext.QuestionCategories.Any()) { - questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 1, CategoryName = "Flooding", CategoryImage= "https://example.com/images/img1.png" }); - questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 2, CategoryName = "Electrical", CategoryImage = "https://example.com/images/img2.png" }); - questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 3, CategoryName = "Structural", CategoryImage = "https://example.com/images/img3.png" }); - questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 4, CategoryName = "Utility", CategoryImage = "https://example.com/images/img4.png" }); - questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 5, CategoryName = "Debris", CategoryImage = "https://example.com/images/img5.png" }); + questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 1, IconName = "Flooding", IconLibrary= "https://example.com/images/img1.png" }); + questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 2, IconName = "Electrical", IconLibrary = "https://example.com/images/img2.png" }); + questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 3, IconName = "Structural", IconLibrary = "https://example.com/images/img3.png" }); + questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 4, IconName = "Utility", IconLibrary = "https://example.com/images/img4.png" }); + questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 5, IconName = "Debris", IconLibrary = "https://example.com/images/img5.png" }); + questionDbContext.SaveChanges(); + } + + if (!questionDbContext.CategoryTranslations.Any()) + { + + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 1, CategoryId = 1, Title = "Flooding", Language = "en" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 2, CategoryId = 2, Title = "Electrical", Language = "en" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 3, CategoryId = 3, Title = "Structural", Language = "en" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 4, CategoryId = 4, Title = "Utility", Language = "en" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 5, CategoryId = 5, Title = "Debris", Language = "en" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 6, CategoryId = 1, Title = "Inondation", Language = "fr" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 7, CategoryId = 2, Title = "Électrique", Language = "fr" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 8, CategoryId = 3, Title = "De construction", Language = "fr" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 9, CategoryId = 4, Title = "Utilitaire", Language = "fr" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 10, CategoryId = 5, Title = "Débris", Language = "fr" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 11, CategoryId = 1, Title = "Inundación", Language = "es" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 12, CategoryId = 2, Title = "Eléctrica", Language = "es" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 13, CategoryId = 3, Title = "Estructural", Language = "es" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 14, CategoryId = 4, Title = "Utilidad", Language = "es" }); + questionDbContext.CategoryTranslations.Add(new Db.CategoryTranslation() { Id = 15, CategoryId = 5, Title = "Escombros", Language = "es" }); questionDbContext.SaveChanges(); } } - public async Task<(bool IsSuccess, IEnumerable Questions, string ErrorMessage)> GetQuestionsAsync(string Language) + public List GetCategoryTranslations(int id, string? language) + { + List categoryTranslations = new List(); + if (string.IsNullOrEmpty(language)) + { + categoryTranslations = mapper.Map, List>( + questionDbContext.CategoryTranslations.AsNoTracking().Where(a => a.CategoryId == id).ToList()); + } + else + { + categoryTranslations = mapper.Map, List>( + questionDbContext.CategoryTranslations.AsNoTracking().Where(a => a.CategoryId == id && a.Language == language).ToList()); + } + return categoryTranslations; + } + public object CreateCategoryMultiLanguageObject(List categoryTranslations) + { + object MultiLanguage = new object(); + Dictionary dict = new Dictionary(); + foreach (Models.CategoryTranslation item in categoryTranslations) + { + dict.Add(item.Language, item.Title); + } + MultiLanguage = dict; + return MultiLanguage; + } + public List GetQuestionsTranslations(int id, string? language) + { + List QuestionTranslations; + if (string.IsNullOrEmpty(language)) + { + QuestionTranslations = mapper.Map, List>( + questionDbContext.QuestionsTranslations.AsNoTracking().Where(a => a.QuestionId == id).ToList()); + } + else + { + QuestionTranslations = mapper.Map, List>( + questionDbContext.QuestionsTranslations.AsNoTracking().Where(a => a.QuestionId == id && a.Language == language).ToList()); + } + return QuestionTranslations; + } + public MultiLanguage CreateMultiLanguageObject(List questions) + { + MultiLanguage MultiLanguage = new MultiLanguage(); + Dictionary dict = new Dictionary(); + foreach (Models.QuestionsTranslation item in questions) + { + dict.Add(item.Language, item.QuestionText); + } + MultiLanguage.questionText = dict; + return MultiLanguage; + } + public async Task<(bool IsSuccess, IEnumerable Questions, string ErrorMessage)> GetQuestionsAsync(string language) { try { @@ -76,21 +151,10 @@ namespace DamageAssesment.Api.Questions.Providers { //logger?.LogInformation($"{question} customer(s) found"); - var result = mapper.Map, IEnumerable>(questions); - - + var result = mapper.Map, IEnumerable>(questions); foreach (var question in result) { - if (string.IsNullOrEmpty(Language)) - { - question.Questions = mapper.Map, List>( - questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == question.Id).ToList()); - } - else - { - question.Questions = mapper.Map, List>( - questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == question.Id && a.Language == Language).ToList()); - } + question.Questions = CreateMultiLanguageObject(GetQuestionsTranslations(question.Id, language)); } return (true, result, null); } @@ -102,27 +166,17 @@ namespace DamageAssesment.Api.Questions.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> GetQuestionAsync(int Id, string Language) + public async Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> GetQuestionAsync(int id, string language) { try { logger?.LogInformation("Query Question"); - var question = await questionDbContext.Questions.Include("QuestionType").AsNoTracking().FirstOrDefaultAsync(q => q.Id == Id); + var question = await questionDbContext.Questions.Include("QuestionType").AsNoTracking().FirstOrDefaultAsync(q => q.Id == id); if (question != null) { logger?.LogInformation($"{question} customer(s) found"); - var result = mapper.Map(question); - - if (string.IsNullOrEmpty(Language)) - { - result.Questions = mapper.Map, List>( - questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == result.Id).ToList()); - } - else - { - result.Questions = mapper.Map, List>( - questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == result.Id && a.Language == Language).ToList()); - } + var result = mapper.Map(question); + result.Questions = CreateMultiLanguageObject(GetQuestionsTranslations(id, language)); return (true, result, null); } return (false, null, "Not found"); @@ -133,27 +187,15 @@ namespace DamageAssesment.Api.Questions.Providers return (false, null, ex.Message); } } - public List GetSurveyQuestion(List questions, string Language) + public List GetSurveyQuestion(List questions, string language) { - if (string.IsNullOrEmpty(Language)) + foreach (var item in questions) { - foreach (var item in questions) - { - item.Questions = mapper.Map, List>( - questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == item.Id).ToList()); - } - } - else - { - foreach (var item in questions) - { - item.Questions = mapper.Map, List>( - questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == item.Id && a.Language == Language).ToList()); - } + item.Questions = CreateMultiLanguageObject(GetQuestionsTranslations(item.Id, language)); } return questions; } - public async Task<(bool IsSuccess, List SurveyQuestions, string ErrorMessage)> GetSurveyQuestionAsync(int SurveyId, string Language) + public async Task<(bool IsSuccess, List SurveyQuestions, string ErrorMessage)> GetSurveyQuestionAsync(int SurveyId, string language) { try { @@ -170,9 +212,9 @@ namespace DamageAssesment.Api.Questions.Providers surveyQuestionsList.Add(new SurveyQuestions() { CategoryId = item.Id, - CategoryImage = item.CategoryImage, - CategoryName = item.CategoryName, - Questions = GetSurveyQuestion(mapper.Map, List>(questions.Where(a => a.CategoryId == item.Id).ToList()), Language) + IconLibrary = item.IconLibrary, + IconName = item.IconName, + Questions = GetSurveyQuestion(mapper.Map, List>(questions.Where(a => a.CategoryId == item.Id).ToList()), language) }); } @@ -187,7 +229,7 @@ namespace DamageAssesment.Api.Questions.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> PostQuestionAsync(Models.Question Question) + public async Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> PostQuestionAsync(Models.Question Question) { try { @@ -200,7 +242,9 @@ namespace DamageAssesment.Api.Questions.Providers questionDbContext.QuestionsTranslations.AddRange(dbquestiontranslation); questionDbContext.SaveChanges(); Question.Id = dbquestion.Id; - return (true, Question, null); + var result = mapper.Map(dbquestion); + result.Questions = CreateMultiLanguageObject(GetQuestionsTranslations(result.Id,"")); + return (true, result, null); } catch (Exception ex) { @@ -208,7 +252,7 @@ namespace DamageAssesment.Api.Questions.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question) + public async Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question) { try { @@ -222,7 +266,9 @@ namespace DamageAssesment.Api.Questions.Providers dbquestiontranslation.ForEach(i => i.QuestionId = dbquestion.Id); questionDbContext.QuestionsTranslations.AddRange(dbquestiontranslation); questionDbContext.SaveChanges(); - return (true, Question, null); + var result = mapper.Map(dbquestion); + result.Questions = CreateMultiLanguageObject(GetQuestionsTranslations(result.Id, "")); + return (true, result, null); } catch (Exception ex) { @@ -231,21 +277,23 @@ namespace DamageAssesment.Api.Questions.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> DeleteQuestionAsync(int Id) + public async Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> DeleteQuestionAsync(int id) { try { - var question = await questionDbContext.Questions.Where(x => x.Id == Id).FirstOrDefaultAsync(); + var question = await questionDbContext.Questions.Where(x => x.Id == id).FirstOrDefaultAsync(); if (question != null) { + var result = mapper.Map(question); + result.Questions = CreateMultiLanguageObject(GetQuestionsTranslations(result.Id, "")); questionDbContext.Questions.Remove(question); questionDbContext.SaveChanges(); - return (true, mapper.Map(question), $"QuestionID {Id} deleted Successfuly"); + return (true, result, $"QuestionID {id} deleted Successfuly"); } else { - logger?.LogInformation($"QuestionID: {Id} Not found"); + logger?.LogInformation($"QuestionID: {id} Not found"); return (false, null, "Not Found"); } } @@ -258,7 +306,7 @@ namespace DamageAssesment.Api.Questions.Providers //Question Category Logic - public async Task<(bool IsSuccess, IEnumerable QuestionCategories, string ErrorMessage)> GetQuestionCategoriesAsync() + public async Task<(bool IsSuccess, IEnumerable QuestionCategories, string ErrorMessage)> GetQuestionCategoriesAsync(string? language) { try { @@ -267,7 +315,11 @@ namespace DamageAssesment.Api.Questions.Providers if (questionCategories != null) { //logger?.LogInformation($"{question} customer(s) found"); - var result = mapper.Map, IEnumerable>(questionCategories); + var result = mapper.Map, IEnumerable>(questionCategories); + foreach (var category in result) + { + category.Titles = CreateCategoryMultiLanguageObject(GetCategoryTranslations(category.Id, language)); + } return (true, result, null); } return (false, null, "Not found"); @@ -278,16 +330,17 @@ namespace DamageAssesment.Api.Questions.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.QuestionCategory QuestionCategory, string ErrorMessage)> GetQuestionCategoryAsync(int Id) + public async Task<(bool IsSuccess, Models.MultiLanQuestionCategory QuestionCategory, string ErrorMessage)> GetQuestionCategoryAsync(int id, string? language) { try { logger?.LogInformation("Query Question"); - var questioncategory = await questionDbContext.QuestionCategories.AsNoTracking().FirstOrDefaultAsync(q => q.Id == Id); + var questioncategory = await questionDbContext.QuestionCategories.AsNoTracking().FirstOrDefaultAsync(q => q.Id == id); if (questioncategory != null) { logger?.LogInformation($"{questioncategory} customer(s) found"); - var result = mapper.Map(questioncategory); + var result = mapper.Map(questioncategory); + result.Titles = CreateCategoryMultiLanguageObject(GetCategoryTranslations(result.Id, language)); return (true, result, null); } return (false, null, "Not found"); @@ -298,17 +351,23 @@ namespace DamageAssesment.Api.Questions.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.QuestionCategory QuestionCategory, string ErrorMessage)> PostQuestionCategoryAsync(Models.QuestionCategory QuestionCategory) + public async Task<(bool IsSuccess, Models.MultiLanQuestionCategory QuestionCategory, string ErrorMessage)> PostQuestionCategoryAsync(Models.QuestionCategory QuestionCategory) { try { logger?.LogInformation("Query Question"); var dbQuestionCategory = mapper.Map(QuestionCategory); + var dbCategorytranslations = mapper.Map, List>(QuestionCategory.Categories); // Question.QuestionType = GetQuestionType(Question.QuestionTypeId); questionDbContext.QuestionCategories.Add(dbQuestionCategory); questionDbContext.SaveChanges(); QuestionCategory.Id = dbQuestionCategory.Id; - return (true, QuestionCategory, null); + dbCategorytranslations.ForEach(i => i.CategoryId = QuestionCategory.Id); + questionDbContext.CategoryTranslations.AddRange(dbCategorytranslations); + questionDbContext.SaveChanges(); + var result = mapper.Map(dbQuestionCategory); + result.Titles = CreateCategoryMultiLanguageObject(GetCategoryTranslations(result.Id, "")); + return (true, result, null); } catch (Exception ex) { @@ -316,15 +375,23 @@ namespace DamageAssesment.Api.Questions.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.QuestionCategory QuestionCategory, string ErrorMessage)> UpdateQuestionCategoryAsync(Models.QuestionCategory QuestionCategory) + public async Task<(bool IsSuccess, Models.MultiLanQuestionCategory QuestionCategory, string ErrorMessage)> UpdateQuestionCategoryAsync(Models.QuestionCategory QuestionCategory) { try { var dbQuestionCategory = mapper.Map(QuestionCategory); + var dbCategorytranslations = mapper.Map, List>(QuestionCategory.Categories); questionDbContext.Entry(dbQuestionCategory).State = EntityState.Modified; - + QuestionCategory.Id = dbQuestionCategory.Id; + var oldcategories = questionDbContext.CategoryTranslations.Where(a => a.CategoryId == dbQuestionCategory.Id).ToList(); + if (oldcategories != null) + questionDbContext.CategoryTranslations.RemoveRange(oldcategories); + dbCategorytranslations.ForEach(i => i.CategoryId = QuestionCategory.Id); + questionDbContext.CategoryTranslations.AddRange(dbCategorytranslations); questionDbContext.SaveChanges(); - return (true, QuestionCategory, null); + var result = mapper.Map(dbQuestionCategory); + result.Titles = CreateCategoryMultiLanguageObject(GetCategoryTranslations(result.Id, "")); + return (true, result, null); } catch (Exception ex) { @@ -333,18 +400,20 @@ namespace DamageAssesment.Api.Questions.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.QuestionCategory QuestionCategory, string ErrorMessage)> DeleteQuestionCategoryAsync(int Id) + public async Task<(bool IsSuccess, Models.MultiLanQuestionCategory QuestionCategory, string ErrorMessage)> DeleteQuestionCategoryAsync(int Id) { try { var questioncategory = await questionDbContext.QuestionCategories.Where(x => x.Id == Id).FirstOrDefaultAsync(); if (questioncategory != null) { + var result = mapper.Map(questioncategory); + result.Titles = CreateCategoryMultiLanguageObject(GetCategoryTranslations(result.Id, "")); var question = await questionDbContext.Questions.Where(x => x.Id == Id).ToListAsync(); questionDbContext.Questions.RemoveRange(question); questionDbContext.QuestionCategories.Remove(questioncategory); questionDbContext.SaveChanges(); - return (true, mapper.Map(questioncategory), $"QuestionID {Id} deleted Successfuly"); + return (true, result, $"QuestionID {Id} deleted Successfuly"); } else { diff --git a/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/CategoryMockData.cs b/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/CategoryMockData.cs index cf0bb04..e09a7c0 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/CategoryMockData.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/CategoryMockData.cs @@ -8,42 +8,42 @@ namespace DamageAssesment.Api.Questions.Test { public class CategoryMockData { - public static async Task<(bool, IEnumerable, string)> getOkResponse() + public static async Task<(bool, IEnumerable, string)> getOkResponse() { - IEnumerable list = new List(); + IEnumerable list = new List(); for (int i = 0; i < 10; i++) { - list.Append(new Questions.Models.QuestionCategory { Id = i, CategoryImage = "img"+i,CategoryName="Category "+i }); + list.Append(new Questions.Models.MultiLanQuestionCategory { Id = i, IconLibrary = "img"+i,IconName="Category "+i }); } return (true, list, null); } - public static async Task<(bool, Questions.Models.QuestionCategory, string)> getOkResponse(int Id) + public static async Task<(bool, Questions.Models.MultiLanQuestionCategory, string)> getOkResponse(int Id) { var Questions = await getOkResponse(); var Question = Questions.Item2.FirstOrDefault(s => s.Id == Id); return (true, Question, null); } - public static async Task<(bool, Questions.Models.QuestionCategory, string)> getBadRequestResponse() + public static async Task<(bool, Questions.Models.MultiLanQuestionCategory, string)> getBadRequestResponse() { return (false, null, "Bad Request"); } - public static async Task<(bool, Questions.Models.QuestionCategory, string)> getNotFoundResponse() + public static async Task<(bool, Questions.Models.MultiLanQuestionCategory, string)> getNotFoundResponse() { return (false, null, "Not Found"); } - public static async Task<(bool, IEnumerable, string)> getNoContentResponse() + public static async Task<(bool, IEnumerable, string)> getNoContentResponse() { - IEnumerable list = new List(); + IEnumerable list = new List(); return (false, list, null); } public static async Task getInputQuestionCategoryData() { - return new Questions.Models.QuestionCategory { Id = 1, CategoryName = "Category 1",CategoryImage="img 1" }; + return new Questions.Models.QuestionCategory { Id = 1, IconName = "Category 1",IconLibrary="img 1" }; } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/MockData.cs b/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/MockData.cs index 1991128..363ed98 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/MockData.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/MockData.cs @@ -5,13 +5,13 @@ namespace DamageAssesment.Api.Questions.Test public class MockData { - public static async Task<(bool, IEnumerable, string)> getOkResponse() + public static async Task<(bool, IEnumerable, string)> getOkResponse() { - IEnumerable list = new List(); + IEnumerable list = new List(); for (int i = 0; i < 10; i++) { - list.Append(new Questions.Models.Question { Id = i, TypeText = "Text" + i, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId=i }); + list.Append(new Questions.Models.MultiLanQuestion { Id = i, TypeText = "Text" + i, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId=i }); } return (true, list, null); } @@ -23,38 +23,38 @@ namespace DamageAssesment.Api.Questions.Test for (int i = 0; i < 10; i++) { - List question = new List(); - question.Add(new Models.Question { Id = i, TypeText = "Text" + i, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId = i }); + List question = new List(); + question.Add(new Models.MultiLanQuestion { Id = i, TypeText = "Text" + i, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId = i }); list.Append(new Questions.Models.SurveyQuestions { CategoryId = i, - CategoryImage = "img" + i, - CategoryName = "Category " + i, + IconLibrary = "img" + i, + IconName = "Category " + i, Questions = question }); } return (true, list, null); } - public static async Task<(bool, Questions.Models.Question, string)> getOkResponse(int Id) + public static async Task<(bool, Questions.Models.MultiLanQuestion, string)> getOkResponse(int Id) { var Questions = await getOkResponse(); var Question = Questions.Item2.FirstOrDefault(s => s.Id == Id); return (true, Question, null); } - public static async Task<(bool, Questions.Models.Question, string)> getBadRequestResponse() + public static async Task<(bool, Questions.Models.MultiLanQuestion, string)> getBadRequestResponse() { return (false, null, "Bad Request"); } - public static async Task<(bool, Questions.Models.Question, string)> getNotFoundResponse() + public static async Task<(bool, Questions.Models.MultiLanQuestion, string)> getNotFoundResponse() { return (false, null, "Not Found"); } - public static async Task<(bool, IEnumerable, string)> getNoContentResponse() + public static async Task<(bool, IEnumerable, string)> getNoContentResponse() { - IEnumerable list = new List(); + IEnumerable list = new List(); return (false, list, null); } public static async Task<(bool, List, string)> getNoSurveyContentResponse() diff --git a/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/QuestionsServiceTest.cs b/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/QuestionsServiceTest.cs index 17797c6..bda9db2 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/QuestionsServiceTest.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/QuestionsServiceTest.cs @@ -42,7 +42,7 @@ namespace DamageAssesment.Api.Questions.Test mockQuestionService.Setup(service => service.GetQuestionAsync(1,null)).ReturnsAsync(mockResponse); var QuestionProvider = new QuestionsController(mockQuestionService.Object); - var result = (OkObjectResult)await QuestionProvider.GetQuestionAsync(1,null); + var result = (OkObjectResult)await QuestionProvider.GetQuestionByIdAsync(1,null); Assert.Equal(200, result.StatusCode); } @@ -55,7 +55,7 @@ namespace DamageAssesment.Api.Questions.Test mockQuestionService.Setup(service => service.GetQuestionAsync(99,null)).ReturnsAsync(mockResponse); var QuestionProvider = new QuestionsController(mockQuestionService.Object); - var result = (NotFoundResult)await QuestionProvider.GetQuestionAsync(99,null); + var result = (NotFoundResult)await QuestionProvider.GetQuestionByIdAsync(99,null); Assert.Equal(404, result.StatusCode); } @@ -188,10 +188,10 @@ namespace DamageAssesment.Api.Questions.Test { var mockQuestionService = new Mock(); var mockResponse = await CategoryMockData.getOkResponse(); - mockQuestionService.Setup(service => service.GetQuestionCategoriesAsync()).ReturnsAsync(mockResponse); + mockQuestionService.Setup(service => service.GetQuestionCategoriesAsync("en")).ReturnsAsync(mockResponse); var QuestionProvider = new QuestionsController(mockQuestionService.Object); - var result = (OkObjectResult)await QuestionProvider.GetQuestionCategoriesAsync(); + var result = (OkObjectResult)await QuestionProvider.GetQuestionCategoriesAsync("en"); Assert.Equal(200, result.StatusCode); } @@ -201,10 +201,10 @@ namespace DamageAssesment.Api.Questions.Test { var mockQuestionService = new Mock(); var mockResponse = await CategoryMockData.getNoContentResponse(); - mockQuestionService.Setup(service => service.GetQuestionCategoriesAsync()).ReturnsAsync(mockResponse); + mockQuestionService.Setup(service => service.GetQuestionCategoriesAsync("en")).ReturnsAsync(mockResponse); var QuestionProvider = new QuestionsController(mockQuestionService.Object); - var result = (NoContentResult)await QuestionProvider.GetQuestionCategoriesAsync(); + var result = (NoContentResult)await QuestionProvider.GetQuestionCategoriesAsync("en"); Assert.Equal(204, result.StatusCode); } @@ -214,10 +214,10 @@ namespace DamageAssesment.Api.Questions.Test { var mockQuestionService = new Mock(); var mockResponse = await CategoryMockData.getOkResponse(1); - mockQuestionService.Setup(service => service.GetQuestionCategoryAsync(1)).ReturnsAsync(mockResponse); + mockQuestionService.Setup(service => service.GetQuestionCategoryAsync(1, "en")).ReturnsAsync(mockResponse); var QuestionProvider = new QuestionsController(mockQuestionService.Object); - var result = (OkObjectResult)await QuestionProvider.GetQuestionCategoryAsync(1); + var result = (OkObjectResult)await QuestionProvider.GetQuestionCategoryAsync(1, "en"); Assert.Equal(200, result.StatusCode); } @@ -227,10 +227,10 @@ namespace DamageAssesment.Api.Questions.Test { var mockQuestionService = new Mock(); var mockResponse = await CategoryMockData.getNotFoundResponse(); - mockQuestionService.Setup(service => service.GetQuestionCategoryAsync(99)).ReturnsAsync(mockResponse); + mockQuestionService.Setup(service => service.GetQuestionCategoryAsync(99, "en")).ReturnsAsync(mockResponse); var QuestionProvider = new QuestionsController(mockQuestionService.Object); - var result = (NotFoundResult)await QuestionProvider.GetQuestionCategoryAsync(99); + var result = (NotFoundResult)await QuestionProvider.GetQuestionCategoryAsync(99, "en"); Assert.Equal(404, result.StatusCode); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys.Test/MockData.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys.Test/MockData.cs index 01972e3..fa4928d 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys.Test/MockData.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys.Test/MockData.cs @@ -9,37 +9,37 @@ namespace DamageAssesment.Api.Survey.Test { public class MockData { - public static async Task<(bool, IEnumerable, string)> getOkResponse() + public static async Task<(bool, IEnumerable, string)> getOkResponse() { - IEnumerable list = new List(); + IEnumerable list = new List(); for (int i = 0; i < 10; i++) { - list.Append(new Surveys.Models.Survey { Id = i, /*Title = "Survey Title - " + i */}); + list.Append(new Surveys.Models.MultiLanSurvey { Id = i, /*Title = "Survey Title - " + i */}); } return (true, list, null); } - public static async Task<(bool, Surveys.Models.Survey, string)> getOkResponse( int Id) + public static async Task<(bool, Surveys.Models.MultiLanSurvey, string)> getOkResponse( int Id) { var surveys = await getOkResponse(); var survey = surveys.Item2.FirstOrDefault(s => s.Id == Id); return (true, survey, null); } - public static async Task<(bool, Surveys.Models.Survey, string)> getBadRequestResponse() + public static async Task<(bool, Surveys.Models.MultiLanSurvey, string)> getBadRequestResponse() { return (false, null,"Bad Request"); } - public static async Task<(bool, Surveys.Models.Survey, string)> getNotFoundResponse() + public static async Task<(bool, Surveys.Models.MultiLanSurvey, string)> getNotFoundResponse() { return (false, null, "Not Found"); } - public static async Task<(bool, IEnumerable, string)> getNoContentResponse() + public static async Task<(bool, IEnumerable, string)> getNoContentResponse() { - IEnumerable list = new List(); + IEnumerable list = new List(); return (false, list, null); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs index e360e53..7853716 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Controllers/SurveysController.cs @@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Mvc; namespace DamageAssesment.Api.Surveys.Controllers { - [Route("api")] [ApiController] public class SurveysController : ControllerBase { @@ -18,11 +17,11 @@ namespace DamageAssesment.Api.Surveys.Controllers /// [Route("Surveys")] - [Route("{Language}/Surveys")] + [Route("Surveys/{language:alpha}")] [HttpGet] - public async Task GetSurveysAsync(string? Language) + public async Task GetSurveysAsync(string? language) { - var result = await this.surveyProvider.GetSurveysAsync(Language); + var result = await this.surveyProvider.GetSurveysAsync(language); if (result.IsSuccess) { return Ok(result.Surveys); @@ -33,12 +32,12 @@ namespace DamageAssesment.Api.Surveys.Controllers /// /// GET request for retrieving surveys by ID. /// - [Route("Surveys/{Id}")] - [Route("{Language}/Surveys/{Id}")] + [Route("Surveys/{id:int}")] + [Route("Surveys/{id:int}/{language:alpha}")] [HttpGet] - public async Task GetSurveysAsync(int Id, string? Language) + public async Task GetSurveysAsync(int id, string? language) { - var result = await this.surveyProvider.GetSurveysAsync(Id, Language); + var result = await this.surveyProvider.GetSurveysAsync(id, language); if (result.IsSuccess) { return Ok(result.Surveys); @@ -64,10 +63,10 @@ namespace DamageAssesment.Api.Surveys.Controllers /// - [HttpPut("Surveys/{Id}")] - public async Task PutSurveysAsync(int Id, Models.Survey survey) + [HttpPut("Surveys/{id}")] + public async Task PutSurveysAsync(int id, Models.Survey survey) { - var result = await this.surveyProvider.PutSurveyAsync(Id, survey); + var result = await this.surveyProvider.PutSurveyAsync(id, survey); if (result.IsSuccess) { return Ok(result.Survey); @@ -81,10 +80,10 @@ namespace DamageAssesment.Api.Surveys.Controllers /// /// DELETE request for deleting a survey by ID. /// - [HttpDelete("Surveys/{Id}")] - public async Task DeleteSurveysAsync(int Id) + [HttpDelete("Surveys/{id}")] + public async Task DeleteSurveysAsync(int id) { - var result = await this.surveyProvider.DeleteSurveyAsync(Id); + var result = await this.surveyProvider.DeleteSurveyAsync(id); if (result.IsSuccess) { return Ok(result.Survey); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Interfaces/ISurveyProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Interfaces/ISurveyProvider.cs index 46743d3..22b2910 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Interfaces/ISurveyProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Interfaces/ISurveyProvider.cs @@ -2,11 +2,11 @@ { public interface ISurveyProvider { - Task<(bool IsSuccess, IEnumerable< Models.Survey> Surveys, string ErrorMessage)> GetSurveysAsync(string Language); - Task<(bool IsSuccess, Models.Survey Surveys, string ErrorMessage)> GetSurveysAsync(int Id, string Language); - 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); + Task<(bool IsSuccess, IEnumerable< Models.MultiLanSurvey> Surveys, string ErrorMessage)> GetSurveysAsync(string language); + Task<(bool IsSuccess, Models.MultiLanSurvey Surveys, string ErrorMessage)> GetSurveysAsync(int id, string language); + Task<(bool IsSuccess, Models.MultiLanSurvey Survey, string ErrorMessage)> PostSurveyAsync(Models.Survey Survey); + Task<(bool IsSuccess, Models.MultiLanSurvey Survey, string ErrorMessage)> PutSurveyAsync(int id, Models.Survey Survey); + Task<(bool IsSuccess, Models.MultiLanSurvey Survey, string ErrorMessage)> DeleteSurveyAsync(int id); void seedData(); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/Survey.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/Survey.cs index 7fa898d..f79158b 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/Survey.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/Survey.cs @@ -2,13 +2,21 @@ namespace DamageAssesment.Api.Surveys.Models { - public class Survey + public class MultiLanSurvey : BaseSurvey + { + public object Titles { get; set; } + } + public class Survey : BaseSurvey + { + public IEnumerable Titles { get; set; } + + } + public class BaseSurvey { public int Id { get; set; } public bool IsEnabled { get; set; } public DateTime StartDate { get; set; } public DateTime EndDate { get; set; } public DateTime CreatedDate { get; set; } - public IEnumerable Titles { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Profiles/SurveysProfile.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Profiles/SurveysProfile.cs index 2cb043c..7b65d99 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Profiles/SurveysProfile.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Profiles/SurveysProfile.cs @@ -3,8 +3,10 @@ public class SurveysProfile:AutoMapper.Profile { public SurveysProfile() { - CreateMap(); + CreateMap(); CreateMap(); + CreateMap(); + CreateMap(); } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs index c756738..f843216 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs @@ -49,60 +49,57 @@ namespace DamageAssesment.Api.Surveys.Providers } } - public async Task<(bool IsSuccess, IEnumerable Surveys, string ErrorMessage)> GetSurveysAsync(string Language) + public IEnumerable GetSurveyTranslations(int id, IEnumerable SurveyTranslation,string? language) { - IEnumerable surveysList = null; + if (SurveyTranslation == null) + { + if (string.IsNullOrEmpty(language)) + { + SurveyTranslation = mapper.Map, IEnumerable>( + surveyDbContext.SurveysTranslation.Where(a => a.SurveyId == id).ToList()); + } + else + { + SurveyTranslation = mapper.Map, IEnumerable>( + surveyDbContext.SurveysTranslation.Where(a => a.SurveyId == id && a.Language == language).ToList()); + } + } + return SurveyTranslation; + } + public object CreateMultiLanguageObject(IEnumerable surveyTranslations) + { + object MultiLanguage = new object(); + Dictionary dict = new Dictionary(); + foreach (Models.SurveyTranslation item in surveyTranslations) + { + dict.Add(item.Language, item.Title); + } + MultiLanguage = dict; + return MultiLanguage; + } + public async Task<(bool IsSuccess, IEnumerable Surveys, string ErrorMessage)> GetSurveysAsync(string language) + { + IEnumerable surveysList = null; try { logger?.LogInformation("Gell all Surveys from DB"); var surveys = await surveyDbContext.Surveys.Where(s => s.IsEnabled == true).ToListAsync(); - var surveyTranslations = await surveyDbContext.SurveysTranslation.ToListAsync(); + //var surveyTranslations = await surveyDbContext.SurveysTranslation.ToListAsync(); if (surveys != null) { - if (string.IsNullOrEmpty(Language)) - { - surveysList = from s in surveys - select new - Models.Survey - { - Id = s.Id, - StartDate = s.StartDate, - EndDate = s.EndDate, - IsEnabled = s.IsEnabled, - CreatedDate = s.CreatedDate, - Titles = from t in surveyTranslations - where t.SurveyId == s.Id - select new Models.SurveyTranslation - { - Title = t.Title, - Language = t.Language - } + surveysList = from s in surveys + select new + Models.MultiLanSurvey + { + Id = s.Id, + StartDate = s.StartDate, + EndDate = s.EndDate, + IsEnabled = s.IsEnabled, + CreatedDate = s.CreatedDate, + Titles = CreateMultiLanguageObject(GetSurveyTranslations(s.Id,null, language)) - }; - } - else - { - surveysList = from s in surveys - select new - Models.Survey - { - Id = s.Id, - StartDate = s.StartDate, - EndDate = s.EndDate, - IsEnabled = s.IsEnabled, - CreatedDate = s.CreatedDate, - Titles = from t in surveyTranslations - where t.SurveyId == s.Id - && t.Language == Language - select new Models.SurveyTranslation - { - Title = t.Title, - Language = t.Language - } - - }; - } + }; logger?.LogInformation($"{surveys.Count} Items(s) found"); return (true, surveysList, null); @@ -115,55 +112,27 @@ namespace DamageAssesment.Api.Surveys.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Survey Surveys, string ErrorMessage)> GetSurveysAsync(int Id, string Language) + public async Task<(bool IsSuccess, Models.MultiLanSurvey Surveys, string ErrorMessage)> GetSurveysAsync(int id, string language) { try { logger?.LogInformation("Query Survey"); - var survey = await surveyDbContext.Surveys.SingleOrDefaultAsync(s => s.Id == Id && s.IsEnabled == true); + var survey = await surveyDbContext.Surveys.SingleOrDefaultAsync(s => s.Id == id && s.IsEnabled == true); if (survey != null) { - Models.Survey result = null; + Models.MultiLanSurvey result = null; var surveyTranslations = await surveyDbContext.SurveysTranslation.Where(s => s.SurveyId == survey.Id).ToListAsync(); - - if (string.IsNullOrEmpty(Language)) + result = new Models.MultiLanSurvey { - result = new Models.Survey - { - Id = survey.Id, - StartDate = survey.StartDate, - EndDate = survey.EndDate, - IsEnabled = survey.IsEnabled, - CreatedDate = survey.CreatedDate, - Titles = from t in surveyTranslations - select new Models.SurveyTranslation - { - Title = t.Title, - Language = t.Language - } + Id = survey.Id, + StartDate = survey.StartDate, + EndDate = survey.EndDate, + IsEnabled = survey.IsEnabled, + CreatedDate = survey.CreatedDate, + Titles = CreateMultiLanguageObject(GetSurveyTranslations(survey.Id,null, language)) - }; - } - else - { - result = new Models.Survey - { - Id = survey.Id, - StartDate = survey.StartDate, - EndDate = survey.EndDate, - IsEnabled = survey.IsEnabled, - CreatedDate = survey.CreatedDate, - Titles = from t in surveyTranslations - where t.Language == Language - select new Models.SurveyTranslation - { - Title = t.Title, - Language = t.Language - } - - }; - } - logger?.LogInformation($"Survey Id: {Id} found"); + }; + logger?.LogInformation($"Survey Id: {id} found"); return (true, result, null); } return (false, null, "Not found"); @@ -175,7 +144,7 @@ namespace DamageAssesment.Api.Surveys.Providers } } - public async Task<(bool IsSuccess, Models.Survey Survey, string ErrorMessage)> PostSurveyAsync(Models.Survey survey) + public async Task<(bool IsSuccess, Models.MultiLanSurvey Survey, string ErrorMessage)> PostSurveyAsync(Models.Survey survey) { try { @@ -192,8 +161,9 @@ namespace DamageAssesment.Api.Surveys.Providers surveyDbContext.SurveysTranslation.Add(new Db.SurveyTranslation {SurveyId = _survey.Id, Language = title.Language, Title = title.Title }); } await surveyDbContext.SaveChangesAsync(); - survey.Id = _survey.Id; - return (true,survey, "Successful"); + var result = mapper.Map(_survey); + result.Titles = CreateMultiLanguageObject(GetSurveyTranslations(_survey.Id, survey.Titles, "")); + return (true, result, "Successful"); } else { @@ -208,7 +178,7 @@ namespace DamageAssesment.Api.Surveys.Providers } } - public async Task<(bool IsSuccess, Models.Survey Survey, string ErrorMessage)> PutSurveyAsync(int Id, Models.Survey survey) + public async Task<(bool IsSuccess, Models.MultiLanSurvey Survey, string ErrorMessage)> PutSurveyAsync(int Id, Models.Survey survey) { try { @@ -236,21 +206,8 @@ namespace DamageAssesment.Api.Surveys.Providers surveyDbContext.SurveysTranslation.AddRange(listSurveyTranslation); await surveyDbContext.SaveChangesAsync(); - var result = new Models.Survey - { - Id = Id, - StartDate = survey.StartDate, - EndDate = survey.EndDate, - IsEnabled = survey.IsEnabled, - CreatedDate = survey.CreatedDate, - Titles = from t in listSurveyTranslation - select new Models.SurveyTranslation - { - Title = t.Title, - Language = t.Language - } - - }; + var result = mapper.Map(_survey); + result.Titles = CreateMultiLanguageObject(GetSurveyTranslations(_survey.Id, survey.Titles, "")); return (true, result, "Successful"); } else @@ -272,7 +229,7 @@ namespace DamageAssesment.Api.Surveys.Providers } } - public async Task<(bool IsSuccess, Models.Survey Survey, string ErrorMessage)> DeleteSurveyAsync(int Id) + public async Task<(bool IsSuccess, Models.MultiLanSurvey Survey, string ErrorMessage)> DeleteSurveyAsync(int Id) { try { @@ -280,9 +237,11 @@ namespace DamageAssesment.Api.Surveys.Providers if (survey != null) { + var result = mapper.Map(survey); + result.Titles = CreateMultiLanguageObject(GetSurveyTranslations(survey.Id, null, "")); surveyDbContext.Surveys.Remove(survey); await surveyDbContext.SaveChangesAsync(); - return (true, mapper.Map(survey), $"Survey Id: {Id} deleted Successfuly"); + return (true, result, $"Survey Id: {Id} deleted Successfuly"); } else { From b878cd706c150d98edfc8f06651df48fb2f0b845 Mon Sep 17 00:00:00 2001 From: uppuv Date: Mon, 11 Sep 2023 13:23:50 -0400 Subject: [PATCH 18/19] 314: updated document multi language output format --- ...DamageAssesment.Api.DocuLinks.Test.csproj} | 2 +- .../DocumentsServiceTest.cs | 30 ++--- .../MockData.cs | 23 ++-- .../Controllers/DocumentsController.cs | 74 ++++++------ ...j => DamageAssesment.Api.DocuLinks.csproj} | 0 .../Interfaces/IDocumentsProvider.cs | 13 +- .../Models/Document.cs | 12 +- .../Profiles/DocumentProfile.cs | 1 + .../Providers/DocumentsProvider.cs | 114 ++++++++++++++---- DamageAssesmentApi/DamageAssesment.sln | 4 +- 10 files changed, 176 insertions(+), 97 deletions(-) rename DamageAssesmentApi/DamageAssesment.Api.Documents.Test/{DamageAssesment.Api.Documents.Test.csproj => DamageAssesment.Api.DocuLinks.Test.csproj} (95%) rename DamageAssesmentApi/DamageAssesment.Api.Documents/{DamageAssesment.Api.Documents.csproj => DamageAssesment.Api.DocuLinks.csproj} (100%) diff --git a/DamageAssesmentApi/DamageAssesment.Api.Documents.Test/DamageAssesment.Api.Documents.Test.csproj b/DamageAssesmentApi/DamageAssesment.Api.Documents.Test/DamageAssesment.Api.DocuLinks.Test.csproj similarity index 95% rename from DamageAssesmentApi/DamageAssesment.Api.Documents.Test/DamageAssesment.Api.Documents.Test.csproj rename to DamageAssesmentApi/DamageAssesment.Api.Documents.Test/DamageAssesment.Api.DocuLinks.Test.csproj index 725bea6..e990a2c 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Documents.Test/DamageAssesment.Api.Documents.Test.csproj +++ b/DamageAssesmentApi/DamageAssesment.Api.Documents.Test/DamageAssesment.Api.DocuLinks.Test.csproj @@ -21,7 +21,7 @@ - + diff --git a/DamageAssesmentApi/DamageAssesment.Api.Documents.Test/DocumentsServiceTest.cs b/DamageAssesmentApi/DamageAssesment.Api.Documents.Test/DocumentsServiceTest.cs index 9d63289..3490c42 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Documents.Test/DocumentsServiceTest.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Documents.Test/DocumentsServiceTest.cs @@ -17,7 +17,7 @@ namespace DamageAssesment.Api.Documents.Test var mockDocumentService = new Mock(); var mockUploadService = new Mock(); var mockResponse = await MockData.getNoContentResponse(); - mockDocumentService.Setup(service => service.GetDocumnetsAsync()).ReturnsAsync(mockResponse); + mockDocumentService.Setup(service => service.GetDocumnetsAsync("en")).ReturnsAsync(mockResponse); var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object); var result = (NoContentResult)await DocumentProvider.GetDocumentsbyFormsandLanguageAsync("", ""); @@ -31,7 +31,7 @@ namespace DamageAssesment.Api.Documents.Test var mockDocumentService = new Mock(); var mockUploadService = new Mock(); var mockResponse = await MockData.getNoContentResponse(); - mockDocumentService.Setup(service => service.GetDocumnetsAsync()).ReturnsAsync(mockResponse); + mockDocumentService.Setup(service => service.GetDocumnetsAsync("en")).ReturnsAsync(mockResponse); var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object); var result = (NoContentResult)await DocumentProvider.GetDocumentsbyFormsandLanguageAsync("", ""); @@ -44,10 +44,10 @@ namespace DamageAssesment.Api.Documents.Test var mockDocumentService = new Mock(); var mockUploadService = new Mock(); var mockResponse = await MockData.getOkResponse(); - mockDocumentService.Setup(service => service.GetDocumnetsAsync()).ReturnsAsync(mockResponse); + mockDocumentService.Setup(service => service.GetDocumnetsAsync("en")).ReturnsAsync(mockResponse); var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object); - var result = (OkObjectResult)await DocumentProvider.GetDocumentsAsync(); + var result = (OkObjectResult)await DocumentProvider.GetDocumentsAsync("en"); Assert.Equal(200, result.StatusCode); } @@ -58,10 +58,10 @@ namespace DamageAssesment.Api.Documents.Test var mockDocumentService = new Mock(); var mockUploadService = new Mock(); var mockResponse = await MockData.getNoContentResponse(); - mockDocumentService.Setup(service => service.GetDocumnetsAsync()).ReturnsAsync(mockResponse); + mockDocumentService.Setup(service => service.GetDocumnetsAsync("en")).ReturnsAsync(mockResponse); var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object); - var result = (NoContentResult)await DocumentProvider.GetDocumentsAsync(); + var result = (NoContentResult)await DocumentProvider.GetDocumentsAsync("en"); Assert.Equal(204, result.StatusCode); } @@ -72,10 +72,10 @@ namespace DamageAssesment.Api.Documents.Test var mockDocumentService = new Mock(); var mockUploadService = new Mock(); var mockResponse = await MockData.getOkResponse(1); - mockDocumentService.Setup(service => service.GetDocumentAsync(1)).ReturnsAsync(mockResponse); + mockDocumentService.Setup(service => service.GetDocumentAsync(1,"en")).ReturnsAsync(mockResponse); var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object); - var result = (OkObjectResult)await DocumentProvider.GetDocumentAsync(1); + var result = (OkObjectResult)await DocumentProvider.GetDocumentAsync(1,"en"); Assert.Equal(200, result.StatusCode); } @@ -86,9 +86,9 @@ namespace DamageAssesment.Api.Documents.Test var mockDocumentService = new Mock(); var mockUploadService = new Mock(); var mockResponse = await MockData.getNotFoundResponse(); - mockDocumentService.Setup(service => service.GetDocumentAsync(99)).ReturnsAsync(mockResponse); + mockDocumentService.Setup(service => service.GetDocumentAsync(99, "en")).ReturnsAsync(mockResponse); var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object); - var result = (NotFoundResult)await DocumentProvider.GetDocumentAsync(99); + var result = (NotFoundResult)await DocumentProvider.GetDocumentAsync(99, "en"); Assert.Equal(404, result.StatusCode); } [Fact(DisplayName = "Post Document - Ok case")] @@ -129,11 +129,11 @@ namespace DamageAssesment.Api.Documents.Test var mockResponse = await MockData.getOkResponse(1); var mockInputDocument = await MockData.getInputDocumentData(); var DocumentResponse = await MockData.GetDocumentsInfo(1); - mockDocumentService.Setup(service => service.UpdateDocumentAsync(mockInputDocument)).ReturnsAsync(mockResponse); + mockDocumentService.Setup(service => service.UpdateDocumentAsync(1,mockInputDocument)).ReturnsAsync(mockResponse); var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object); - var result = (NoContentResult)await DocumentProvider.UpdateDocument(DocumentResponse); + var result = (NotFoundResult)await DocumentProvider.UpdateDocument(1,DocumentResponse); - Assert.Equal(204, result.StatusCode); + Assert.Equal(404, result.StatusCode); } [Fact(DisplayName = "Put Document - BadRequest case")] @@ -143,9 +143,9 @@ namespace DamageAssesment.Api.Documents.Test var mockUploadService = new Mock(); var mockResponse = await MockData.getBadRequestResponse(); var mockInputDocument = await MockData.getInputDocumentData(); - mockDocumentService.Setup(service => service.UpdateDocumentAsync(mockInputDocument)).ReturnsAsync(mockResponse); + mockDocumentService.Setup(service => service.UpdateDocumentAsync(99,mockInputDocument)).ReturnsAsync(mockResponse); var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object); - var result = (BadRequestObjectResult)await DocumentProvider.UpdateDocument(null); + var result = (BadRequestObjectResult)await DocumentProvider.UpdateDocument(99,null); Assert.Equal(400, result.StatusCode); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Documents.Test/MockData.cs b/DamageAssesmentApi/DamageAssesment.Api.Documents.Test/MockData.cs index 374a929..e1d3f65 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Documents.Test/MockData.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Documents.Test/MockData.cs @@ -11,12 +11,16 @@ namespace DamageAssesment.Api.Documents.Test public class MockData { - public static async Task<(bool, List, string)> getOkResponse() + public static async Task<(bool, List, string)> getOkResponse() { - List list = new List(); + List list = new List(); for (int i = 1; i < 4; i++) { + Dictionary dicttitle = new Dictionary(); + Dictionary dictdesc = new Dictionary(); + dicttitle.Add("en", "test"); dicttitle.Add("fr", "tester"); + dictdesc.Add("en", "test"); dictdesc.Add("fr", "tester"); List documentsTranslations = new List(); documentsTranslations.Add(new DocumentsTranslation() { @@ -24,7 +28,7 @@ namespace DamageAssesment.Api.Documents.Test title = "tel"+i, description = "Sample"+i }); - list.Add(new Documents.Models.Document() + list.Add(new Documents.Models.MultiLanDocument() { Id = i, @@ -33,32 +37,33 @@ namespace DamageAssesment.Api.Documents.Test url = "testurl" + i, Path = "testpath" + i, IsActive = true, - documentsTranslations= documentsTranslations, + titles= dicttitle, + description=dictdesc, dateCreated = DateTime.Now, dateUpdated = DateTime.Now }); } return (true, list, null); } - public static async Task<(bool, Documents.Models.Document, string)> getOkResponse(int Id) + public static async Task<(bool, Documents.Models.MultiLanDocument, string)> getOkResponse(int Id) { var Documents = await getOkResponse(); var Document = Documents.Item2.FirstOrDefault(s => s.Id == Id); return (true, Document, null); } - public static async Task<(bool, Documents.Models.Document, string)> getBadRequestResponse() + public static async Task<(bool, Documents.Models.MultiLanDocument, string)> getBadRequestResponse() { return (false, null, "Bad Request"); } - public static async Task<(bool, Documents.Models.Document, string)> getNotFoundResponse() + public static async Task<(bool, Documents.Models.MultiLanDocument, string)> getNotFoundResponse() { return (false, null, "Not Found"); } - public static async Task<(bool, IEnumerable, string)> getNoContentResponse() + public static async Task<(bool, IEnumerable, string)> getNoContentResponse() { - IEnumerable list = new List(); + IEnumerable list = new List(); return (false, list, null); } public static async Task GetDocumentsInfo(int id) diff --git a/DamageAssesmentApi/DamageAssesment.Api.Documents/Controllers/DocumentsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Documents/Controllers/DocumentsController.cs index 38d8ee5..bdb0437 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Documents/Controllers/DocumentsController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Documents/Controllers/DocumentsController.cs @@ -7,7 +7,6 @@ using Microsoft.AspNetCore.Mvc; namespace DamageAssesment.Api.Documents.Controllers { - [Route("api")] [ApiController] public class DocumentsController : ControllerBase { @@ -25,10 +24,13 @@ namespace DamageAssesment.Api.Documents.Controllers /// /// Get all documnets. /// - [HttpGet("{language}/{LinkType}/documents")] - public async Task GetDocumentsbyFormsandLanguageAsync(string language,string LinkType) + /// + [Route("doculinks/{linktype:alpha}")] + [Route("doculinks/{linktype:alpha}/{language:alpha}")] + [HttpGet] + public async Task GetDocumentsbyFormsandLanguageAsync(string linktype, string? language) { - var result = await this.documentsProvider.GetDocumnetsByLinkAsync(language, LinkType); + var result = await this.documentsProvider.GetDocumnetsByLinkAsync(language, linktype); if (result.IsSuccess) { return Ok(result.documents); @@ -38,23 +40,13 @@ namespace DamageAssesment.Api.Documents.Controllers /// /// Get all documnets. /// - [HttpGet("{LinkType}/documents")] - public async Task GetDocumentsbyFormAsync(string LinkType) + /// + //[Route("doculinks/{language:alpha}")] + [Route("doculinks")] + [HttpGet] + public async Task GetDocumentsAsync(string? language) { - var result = await this.documentsProvider.GetDocumnetsByLinkAsync(null, LinkType); - if (result.IsSuccess) - { - return Ok(result.documents); - } - return NoContent(); - } - /// - /// Get all documnets. - /// - [HttpGet("documents")] - public async Task GetDocumentsAsync() - { - var result = await this.documentsProvider.GetDocumnetsAsync(); + var result = await this.documentsProvider.GetDocumnetsAsync(language); if (result.IsSuccess) { return Ok(result.documents); @@ -65,10 +57,12 @@ namespace DamageAssesment.Api.Documents.Controllers /// /// Get a documnet by id. /// - [HttpGet("documents/{id}")] - public async Task GetDocumentAsync(int id) + [HttpGet] + [Route("doculinks/{id}")] + [Route("doculinks/{id}/{language:alpha}")] + public async Task GetDocumentAsync(int id,string? language) { - var result = await this.documentsProvider.GetDocumentAsync(id); + var result = await this.documentsProvider.GetDocumentAsync(id,language); if (result.IsSuccess) { return Ok(result.Document); @@ -78,30 +72,32 @@ namespace DamageAssesment.Api.Documents.Controllers /// /// Upload new document. /// - [HttpPut("documents")] - public async Task UpdateDocument(DocumentInfo documentInfo) + [HttpPut] + [Route("doculinks/{id}")] + public async Task UpdateDocument(int id,DocumentInfo documentInfo) { if (documentInfo != null) { - var dbdoc = await this.documentsProvider.GetDocumentAsync(documentInfo.Id); + var dbdoc = await this.documentsProvider.GetDocumentByidAsync(id); if (dbdoc.IsSuccess) { Models.Document document = uploadService.UpdateDocuments(dbdoc.Document, documentInfo); - var result = await this.documentsProvider.UpdateDocumentAsync(document); + var result = await this.documentsProvider.UpdateDocumentAsync(id,document); if (result.IsSuccess) { return Ok(result.Document); } return NoContent(); } - return NoContent(); + return NotFound(); } return BadRequest(documentInfo); } /// /// update existing document. /// - [HttpPost("documents")] + [HttpPost] + [Route("doculinks")] public async Task CreateDocument(DocumentInfo documentInfo) { try @@ -127,7 +123,8 @@ namespace DamageAssesment.Api.Documents.Controllers /// /// Delete documnet by id. /// - [HttpDelete("documents/{id}")] + [HttpDelete] + [Route("doculinks/{id}")] public async Task DeleteDocument(int id) { // database soft delete @@ -143,7 +140,8 @@ namespace DamageAssesment.Api.Documents.Controllers /// /// Get all document link type. /// - [HttpGet("LinkTypes")] + [HttpGet] + [Route("doculinks/types")] public async Task GetLinkTypesAsync() { var result = await this.documentsProvider.GetLinkTypesAsync(); @@ -156,7 +154,8 @@ namespace DamageAssesment.Api.Documents.Controllers /// /// Get a document link type by id. /// - [HttpGet("LinkTypes/{id}")] + [HttpGet] + [Route("doculinks/types/{id}")] public async Task GetLinkTypeAsync(int id) { var result = await this.documentsProvider.GetLinkTypeAsync(id); @@ -169,7 +168,8 @@ namespace DamageAssesment.Api.Documents.Controllers /// /// Update a existing document link type. /// - [HttpPut("LinkTypes")] + [HttpPut] + [Route("doculinks/types")] public async Task UpdateLinkType(Models.LinkType linkType) { if (linkType != null) @@ -189,7 +189,8 @@ namespace DamageAssesment.Api.Documents.Controllers /// /// Create a new document link type. /// - [HttpPost("LinkTypes")] + [HttpPost] + [Route("doculinks/types")] public async Task CreateLinkType(Models.LinkType linkType) { if (linkType != null) @@ -206,7 +207,8 @@ namespace DamageAssesment.Api.Documents.Controllers /// /// Delete a existing document link type by id. /// - [HttpDelete("LinkTypes/{id}")] + [HttpDelete] + [Route("doculinks/types/{id}")] public async Task DeleteLinkType(int id) { var result = await this.documentsProvider.DeleteLinkTypeAsync(id); @@ -216,7 +218,5 @@ namespace DamageAssesment.Api.Documents.Controllers } return NotFound(); } - - } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Documents/DamageAssesment.Api.Documents.csproj b/DamageAssesmentApi/DamageAssesment.Api.Documents/DamageAssesment.Api.DocuLinks.csproj similarity index 100% rename from DamageAssesmentApi/DamageAssesment.Api.Documents/DamageAssesment.Api.Documents.csproj rename to DamageAssesmentApi/DamageAssesment.Api.Documents/DamageAssesment.Api.DocuLinks.csproj diff --git a/DamageAssesmentApi/DamageAssesment.Api.Documents/Interfaces/IDocumentsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Documents/Interfaces/IDocumentsProvider.cs index 845a51f..7cb4e79 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Documents/Interfaces/IDocumentsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Documents/Interfaces/IDocumentsProvider.cs @@ -4,12 +4,13 @@ namespace DamageAssesment.Api.Documents.Interfaces { public interface IDocumentsProvider : ILinkTypesProvider { - Task<(bool IsSuccess, Models.Document Document, string ErrorMessage)> GetDocumentAsync(int Id); - Task<(bool IsSuccess, IEnumerable documents, string ErrorMessage)> GetDocumnetsAsync(); - Task<(bool IsSuccess, IEnumerable documents, string ErrorMessage)> GetDocumnetsByLinkAsync(string Language,string LinkType); - Task<(bool IsSuccess, Models.Document Document, string ErrorMessage)> PostDocumentAsync(Models.Document Document); - Task<(bool IsSuccess, Models.Document Document, string ErrorMessage)> UpdateDocumentAsync(Models.Document Document); - Task<(bool IsSuccess, Models.Document Document, string ErrorMessage)> DeleteDocumentAsync(int Id); + Task<(bool IsSuccess, Models.MultiLanDocument Document, string ErrorMessage)> GetDocumentAsync(int id,string? language); + Task<(bool IsSuccess, Models.Document Document, string ErrorMessage)> GetDocumentByidAsync(int id); + Task<(bool IsSuccess, IEnumerable documents, string ErrorMessage)> GetDocumnetsAsync(string? language); + Task<(bool IsSuccess, IEnumerable documents, string ErrorMessage)> GetDocumnetsByLinkAsync(string? Language,string LinkType); + Task<(bool IsSuccess, Models.MultiLanDocument Document, string ErrorMessage)> PostDocumentAsync(Models.Document Document); + Task<(bool IsSuccess, Models.MultiLanDocument Document, string ErrorMessage)> UpdateDocumentAsync(int id,Models.Document Document); + Task<(bool IsSuccess, Models.MultiLanDocument Document, string ErrorMessage)> DeleteDocumentAsync(int id); Task<(bool IsSuccess, int counter, string message)> GetDocumentCounter(); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Documents/Models/Document.cs b/DamageAssesmentApi/DamageAssesment.Api.Documents/Models/Document.cs index 1652dca..7ad6c0f 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Documents/Models/Document.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Documents/Models/Document.cs @@ -2,7 +2,16 @@ namespace DamageAssesment.Api.Documents.Models { - public class Document + public class Document : BaseDocument + { + public List documentsTranslations { get; set; } + } + public class MultiLanDocument:BaseDocument + { + public object titles { get; set; } + public object description { get; set; } + } + public class BaseDocument { public int Id { get; set; } @@ -14,6 +23,5 @@ namespace DamageAssesment.Api.Documents.Models public bool IsActive { get; set; } public DateTime dateCreated { get; set; } public DateTime dateUpdated { get; set; } - public List documentsTranslations { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Documents/Profiles/DocumentProfile.cs b/DamageAssesmentApi/DamageAssesment.Api.Documents/Profiles/DocumentProfile.cs index f9a2570..755a59b 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Documents/Profiles/DocumentProfile.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Documents/Profiles/DocumentProfile.cs @@ -6,6 +6,7 @@ namespace DamageAssesment.Api.Documents.Profiles { public DocumentProfile() { + CreateMap(); CreateMap(); CreateMap(); CreateMap(); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Documents/Providers/DocumentsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Documents/Providers/DocumentsProvider.cs index 4af3174..9286b97 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Documents/Providers/DocumentsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Documents/Providers/DocumentsProvider.cs @@ -7,6 +7,7 @@ using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Internal; using System; using System.Diagnostics.Eventing.Reader; +using System.Reflection.Metadata; namespace DamageAssesment.Api.Documents.Providers { @@ -54,7 +55,36 @@ namespace DamageAssesment.Api.Documents.Providers DocumentDbContext.SaveChanges(); } } - public async Task<(bool IsSuccess, IEnumerable documents, string ErrorMessage)> GetDocumnetsByLinkAsync(string Language, string LinkType) + public List GetDocumentTranslations(int id, string? language) + { + List QuestionTranslations; + if (string.IsNullOrEmpty(language)) + { + QuestionTranslations = mapper.Map, List>( + DocumentDbContext.DocumentsTranslations.AsNoTracking().Where(a => a.DocumentId == id).ToList()); + } + else + { + QuestionTranslations = mapper.Map, List>( + DocumentDbContext.DocumentsTranslations.AsNoTracking().Where(a => a.DocumentId == id && a.Language == language).ToList()); + } + return QuestionTranslations; + } + public MultiLanDocument CreateMultiLanguageObject(List questions) + { + MultiLanDocument MultiLanguage = new MultiLanDocument(); + Dictionary dicttitle = new Dictionary(); + Dictionary dictdesc = new Dictionary(); + foreach (Models.DocumentsTranslation item in questions) + { + dicttitle.Add(item.Language, item.title); + dictdesc.Add(item.Language, item.description); + } + MultiLanguage.titles = dicttitle; + MultiLanguage.description = dictdesc; + return MultiLanguage; + } + public async Task<(bool IsSuccess, IEnumerable documents, string ErrorMessage)> GetDocumnetsByLinkAsync(string? language, string? LinkType) { try @@ -68,15 +98,12 @@ namespace DamageAssesment.Api.Documents.Providers q.linkTypeId == (DocumentDbContext.LinkTypes.AsNoTracking().Where(a => a.TypeText.ToLower() == LinkType.ToLower()).Select(a => a.Id).FirstOrDefault())).ToListAsync(); if (documents != null) { - var result = mapper.Map, IEnumerable>(documents); + var result = mapper.Map, List>(documents); foreach (var item in result) { - if(!String.IsNullOrEmpty(Language)) - item.documentsTranslations = mapper.Map, List>( - DocumentDbContext.DocumentsTranslations.Where(a => a.DocumentId == item.Id && (a.Language.ToLower() == Language.ToLower())).ToList()); - else - item.documentsTranslations = mapper.Map, List>( - DocumentDbContext.DocumentsTranslations.Where(a => a.DocumentId == item.Id).ToList()); + var multilan = CreateMultiLanguageObject(GetDocumentTranslations(item.Id, language)); + item.titles = multilan.titles; + item.description = multilan.description; } return (true, result, null); } @@ -89,7 +116,7 @@ namespace DamageAssesment.Api.Documents.Providers } } - public async Task<(bool IsSuccess, IEnumerable documents, string ErrorMessage)> GetDocumnetsAsync() + public async Task<(bool IsSuccess, IEnumerable documents, string ErrorMessage)> GetDocumnetsAsync(string? language) { try @@ -99,11 +126,12 @@ namespace DamageAssesment.Api.Documents.Providers if (documents != null) { logger?.LogInformation($"{documents.Count} Document(s) found"); - var result = mapper.Map, IEnumerable>(documents); + var result = mapper.Map, List>(documents); foreach (var item in result) { - item.documentsTranslations = mapper.Map, List>( - DocumentDbContext.DocumentsTranslations.Where(a => a.DocumentId == item.Id).ToList()); + var multilan = CreateMultiLanguageObject(GetDocumentTranslations(item.Id, language)); + item.titles = multilan.titles; + item.description = multilan.description; } return (true, result, null); } @@ -116,16 +144,16 @@ namespace DamageAssesment.Api.Documents.Providers } } - public async Task<(bool IsSuccess, Models.Document Document, string ErrorMessage)> GetDocumentAsync(int Id) + public async Task<(bool IsSuccess, Models.Document Document, string ErrorMessage)> GetDocumentByidAsync(int id) { try { logger?.LogInformation("Query LinkType"); - var Document = await DocumentDbContext.Documents.AsNoTracking().FirstOrDefaultAsync(q => q.Id == Id && q.IsActive); + var Document = await DocumentDbContext.Documents.AsNoTracking().FirstOrDefaultAsync(q => q.Id == id && q.IsActive); if (Document != null) { logger?.LogInformation($"{Document} customer(s) found"); - var result = mapper.Map(Document); + var result = mapper.Map(Document); result.documentsTranslations = mapper.Map, List>( DocumentDbContext.DocumentsTranslations.Where(a => a.DocumentId == result.Id).ToList()); return (true, result, null); @@ -138,7 +166,30 @@ namespace DamageAssesment.Api.Documents.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Document Document, string ErrorMessage)> PostDocumentAsync(Models.Document Document) + public async Task<(bool IsSuccess, Models.MultiLanDocument Document, string ErrorMessage)> GetDocumentAsync(int id,string? language) + { + try + { + logger?.LogInformation("Query LinkType"); + var Document = await DocumentDbContext.Documents.AsNoTracking().FirstOrDefaultAsync(q => q.Id == id && q.IsActive); + if (Document != null) + { + logger?.LogInformation($"{Document} customer(s) found"); + var result = mapper.Map(Document); + var multilan = CreateMultiLanguageObject(GetDocumentTranslations(result.Id, language)); + result.titles = multilan.titles; + result.description = multilan.description; + return (true, result, null); + } + return (false, null, "Not found"); + } + catch (Exception ex) + { + logger?.LogError(ex.ToString()); + return (false, null, ex.Message); + } + } + public async Task<(bool IsSuccess, Models.MultiLanDocument Document, string ErrorMessage)> PostDocumentAsync(Models.Document Document) { try { @@ -149,8 +200,11 @@ namespace DamageAssesment.Api.Documents.Providers dbtranslation.ForEach(i => i.DocumentId = document.Id); DocumentDbContext.DocumentsTranslations.AddRange(dbtranslation); DocumentDbContext.SaveChanges(); - Document.Id = document.Id; - return (true, Document, null); + var result = mapper.Map(document); + var multilan = CreateMultiLanguageObject(GetDocumentTranslations(document.Id, "")); + result.titles = multilan.titles; + result.description = multilan.description; + return (true, result, null); } catch (Exception ex) { @@ -159,15 +213,16 @@ namespace DamageAssesment.Api.Documents.Providers } } - public async Task<(bool IsSuccess, Models.Document Document, string ErrorMessage)> UpdateDocumentAsync(Models.Document Document) + public async Task<(bool IsSuccess, Models.MultiLanDocument Document, string ErrorMessage)> UpdateDocumentAsync(int id,Models.Document Document) { try { if (Document != null) { - var existing = DocumentDbContext.Documents.AsNoTracking().FirstOrDefault(x => x.Id == Document.Id); + var existing = DocumentDbContext.Documents.AsNoTracking().FirstOrDefault(x => x.Id == id); if (existing != null) { + Document.Id = existing.Id; var document = mapper.Map(Document); DocumentDbContext.Documents.Update(document); DocumentDbContext.SaveChanges(); @@ -176,7 +231,13 @@ namespace DamageAssesment.Api.Documents.Providers DocumentDbContext.DocumentsTranslations.RemoveRange(oldtranslations); var dbtranslation = mapper.Map, List>(Document.documentsTranslations); dbtranslation.ForEach(i => i.DocumentId = Document.Id); - return (true, Document, "Successful"); + DocumentDbContext.DocumentsTranslations.AddRange(dbtranslation); + DocumentDbContext.SaveChanges(); + var result = mapper.Map(document); + var multilan = CreateMultiLanguageObject(GetDocumentTranslations(document.Id, "")); + result.titles = multilan.titles; + result.description = multilan.description; + return (true, result, "Successful"); } else { @@ -198,20 +259,24 @@ namespace DamageAssesment.Api.Documents.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Document Document, string ErrorMessage)> DeleteDocumentAsync(int Id) + public async Task<(bool IsSuccess, Models.MultiLanDocument Document, string ErrorMessage)> DeleteDocumentAsync(int id) { try { - Db.Document Document = DocumentDbContext.Documents.AsNoTracking().Where(a => a.Id == Id).FirstOrDefault(); + Db.Document Document = DocumentDbContext.Documents.AsNoTracking().Where(a => a.Id == id).FirstOrDefault(); if (Document == null) { return (false, null, "Not Found"); } + var result = mapper.Map(Document); + var multilan = CreateMultiLanguageObject(GetDocumentTranslations(Document.Id, "")); + result.titles = multilan.titles; + result.description = multilan.description; Document.IsActive = false; DocumentDbContext.Documents.Update(Document); DocumentDbContext.SaveChanges(); - return (true, mapper.Map(Document), $"DocumentId {Id} deleted Successfuly"); + return (true, result, $"DocumentId {id} deleted Successfuly"); } catch (Exception ex) { @@ -257,7 +322,6 @@ namespace DamageAssesment.Api.Documents.Providers } } - public async Task<(bool IsSuccess, Models.LinkType LinkType, string ErrorMessage)> GetLinkTypeAsync(int Id) { try diff --git a/DamageAssesmentApi/DamageAssesment.sln b/DamageAssesmentApi/DamageAssesment.sln index 2871442..20b7b6d 100644 --- a/DamageAssesmentApi/DamageAssesment.sln +++ b/DamageAssesmentApi/DamageAssesment.sln @@ -37,9 +37,9 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DamageAssesment.Api.Employe EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DamageAssesment.Api.Employees.Test", "DamageAssesment.Api.Employees.Test\DamageAssesment.Api.Employees.Test.csproj", "{D6BF9AE9-72FA-4726-A326-35A35D27FFB8}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DamageAssesment.Api.Documents", "DamageAssesment.Api.Documents\DamageAssesment.Api.Documents.csproj", "{977C1053-9D63-4153-B61B-C3D2F1010F9F}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DamageAssesment.Api.DocuLinks", "DamageAssesment.Api.Documents\DamageAssesment.Api.DocuLinks.csproj", "{977C1053-9D63-4153-B61B-C3D2F1010F9F}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DamageAssesment.Api.Documents.Test", "DamageAssesment.Api.Documents.Test\DamageAssesment.Api.Documents.Test.csproj", "{884BA4AC-9170-49B1-BD6B-850B350C95C0}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "DamageAssesment.Api.DocuLinks.Test", "DamageAssesment.Api.Documents.Test\DamageAssesment.Api.DocuLinks.Test.csproj", "{884BA4AC-9170-49B1-BD6B-850B350C95C0}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution From 9109d0d79392fd276d19df3207df79ffaa33b963 Mon Sep 17 00:00:00 2001 From: Reginald Cherenfant Jasmin Date: Wed, 13 Sep 2023 01:28:24 -0400 Subject: [PATCH 19/19] Update survey response, adding EmployeeId , Location Id as int, adjust end point for ansers submission in batch --- .../Controllers/AnswersController.cs | 13 +- .../Controllers/AttachmentsController.cs | 7 +- .../EmployeeServiceTest.cs | 36 ++--- .../MockData.cs | 12 +- .../Controllers/EmployeesController.cs | 17 +-- .../Db/Employee.cs | 6 +- .../Db/EmployeeDbContext.cs | 9 ++ .../Interfaces/IEmployeesProvider.cs | 6 +- .../Models/Employee.cs | 3 +- .../Profiles/EmployeesProfile.cs | 1 + .../Providers/EmployeesProvider.cs | 43 +++--- .../LocationsServiceTest.cs | 74 ++++----- .../MockData.cs | 15 +- .../Controllers/LocationsController.cs | 22 ++- .../Controllers/RegionsController.cs | 25 ++-- .../Db/Location.cs | 10 +- .../Db/LocationDbContext.cs | 14 +- .../Db/Region.cs | 7 +- .../Interfaces/ILocationsProvider.cs | 10 +- .../Interfaces/IRegionsProvider.cs | 8 +- .../Models/Location.cs | 15 +- .../Models/Region.cs | 8 +- .../Profiles/LocationProfile.cs | 1 + .../Providers/LocationsProvider.cs | 140 +++++++++--------- .../Providers/RegionsProvider.cs | 48 +++--- .../Controllers/QuestionsController.cs | 2 +- .../Interfaces/IQuestionsProvider.cs | 10 +- .../Models/Question.cs | 15 +- .../Models/QuestionsTranslation.cs | 6 +- .../Models/SurveyQuestion.cs | 2 +- .../Profiles/QuestionProfile.cs | 2 +- .../DamageAssesment.Api.Questions/Program.cs | 2 - .../Providers/QuestionsProvider.cs | 48 +++--- .../MockData.cs | 22 +-- .../Controllers/SurveyResponsesController.cs | 59 ++++---- .../Db/SurveyResponse.cs | 6 +- .../Interfaces/IEmployeeServiceProvider.cs | 2 +- .../Interfaces/ISurveysResponse.cs | 2 +- .../Models/AggregateAnswer.cs | 11 -- .../Models/AggregateResult.cs | 11 -- .../Models/Answer.cs | 6 +- .../Models/AnswerData.cs | 13 -- .../Models/Employee.cs | 11 +- .../Models/Location.cs | 4 +- .../Models/Question.cs | 17 +-- .../Models/QuestionsTranslation.cs | 8 - .../Models/Region.cs | 2 +- .../Models/Request.cs | 9 +- .../Models/ResultData.cs | 10 -- .../Models/Survey.cs | 6 +- .../Models/SurveyResponse.cs | 14 +- .../Providers/SurveyResponsesProvider.cs | 105 +++++++------ .../Services/AnswerServiceProvider.cs | 6 +- .../Services/AttachmentServiceProvider.cs | 4 +- .../Services/EmployeeServiceProvider.cs | 12 +- .../Services/LocationServiceProvider.cs | 3 +- .../Services/QuestionServiceProvider.cs | 7 +- .../Services/RegionServiceProvider.cs | 3 +- .../Services/ServiceProviderBase.cs | 2 + .../Services/SurveyServiceProvider.cs | 6 +- .../appsettings.Development.json | 24 +++ .../appsettings.Production.json | 5 + .../appsettings.Test.json | 5 + .../appsettings.json | 14 ++ .../Models/Survey.cs | 1 - .../Providers/SurveysProvider.cs | 8 +- .../MockData.cs | 2 +- .../SurveyResponsesServiceTest.cs | 8 +- 68 files changed, 525 insertions(+), 540 deletions(-) delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AggregateAnswer.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AggregateResult.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AnswerData.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/QuestionsTranslation.cs delete mode 100644 DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/ResultData.cs create mode 100644 DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.Production.json create mode 100644 DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.Test.json diff --git a/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs b/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs index bbfc323..a86cbf1 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Answers/Controllers/AnswersController.cs @@ -5,7 +5,6 @@ using Microsoft.OpenApi.Any; namespace DamageAssesment.Api.Answers.Controllers { - [Route("api")] [ApiController] public class AnswersController: ControllerBase { @@ -49,10 +48,10 @@ namespace DamageAssesment.Api.Answers.Controllers /// /// Get all answers based on responseId. /// - [HttpGet("AnswersByResponse/{ResponseId}")] - public async Task GetAnswersByResponseId(int ResponseId) + [HttpGet("Answers/ByResponse/{responseid}")] + public async Task GetAnswersByResponseId(int responseid) { - var result = await this.answerProvider.GetAnswersAsync(ResponseId); + var result = await this.answerProvider.GetAnswersAsync(responseid); if(result.IsSuccess) { return Ok(result.Answers); @@ -63,10 +62,10 @@ namespace DamageAssesment.Api.Answers.Controllers /// Get all answers based on questionId. /// - [HttpGet("AnswersByQuestion/{QuestionId}")] - public async Task AnswersByQuestionId(int QuestionId) + [HttpGet("Answers/ByQuestion/{questionid}")] + public async Task AnswersByQuestionId(int questionid) { - var result = await this.answerProvider.GetAnswersByQuestionAsync(QuestionId); + var result = await this.answerProvider.GetAnswersByQuestionAsync(questionid); if (result.IsSuccess) { return Ok(result.Answers); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs index 8050515..0fcec65 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Attachments/Controllers/AttachmentsController.cs @@ -7,7 +7,6 @@ using System.Net.Http.Headers; namespace DamageAssesment.Api.Attachments.Controllers { - [Route("api")] [ApiController] public class AttachmentsController : ControllerBase { @@ -139,11 +138,11 @@ namespace DamageAssesment.Api.Attachments.Controllers /// /// Delete an existing attachment. /// - [HttpDelete("Delete")] - public async Task DeleteAttachment(int Id) + [HttpDelete("Attachments/{id}")] + public async Task DeleteAttachment(int id) { // database soft delete - var result = await this.AttachmentProvider.DeleteAttachmentAsync(Id); + var result = await this.AttachmentProvider.DeleteAttachmentAsync(id); if (result.IsSuccess) { // deleting file from folder diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/EmployeeServiceTest.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/EmployeeServiceTest.cs index aa30faf..4fcecad 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/EmployeeServiceTest.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/EmployeeServiceTest.cs @@ -43,11 +43,11 @@ namespace DamageAssesment.Api.Employees.Test public async Task GetEmployeeAsync_ShouldReturnStatusCode200() { var mockEmployeeService = new Mock(); - var mockResponse = await MockData.getOkResponse("Emp1"); - mockEmployeeService.Setup(service => service.GetEmployeeByIdAsync("Emp1")).ReturnsAsync(mockResponse); + var mockResponse = await MockData.getOkResponse(1); + mockEmployeeService.Setup(service => service.GetEmployeeByIdAsync(1)).ReturnsAsync(mockResponse); var EmployeeProvider = new EmployeesController(mockEmployeeService.Object); - var result = (OkObjectResult)await EmployeeProvider.GetEmployeeByIdAsync("Emp1"); + var result = (OkObjectResult)await EmployeeProvider.GetEmployeeByIdAsync(1); Assert.Equal(200, result.StatusCode); } @@ -57,10 +57,10 @@ namespace DamageAssesment.Api.Employees.Test { var mockEmployeeService = new Mock(); var mockResponse = await MockData.getNotFoundResponse(); - mockEmployeeService.Setup(service => service.GetEmployeeByIdAsync("Emp99")).ReturnsAsync(mockResponse); + mockEmployeeService.Setup(service => service.GetEmployeeByIdAsync(99999)).ReturnsAsync(mockResponse); var EmployeeProvider = new EmployeesController(mockEmployeeService.Object); - var result = (NotFoundResult)await EmployeeProvider.GetEmployeeByIdAsync("Emp99"); + var result = (NotFoundResult)await EmployeeProvider.GetEmployeeByIdAsync(99999); Assert.Equal(404, result.StatusCode); } @@ -68,7 +68,7 @@ namespace DamageAssesment.Api.Employees.Test public async Task PostEmployeeAsync_ShouldReturnStatusCode200() { var mockEmployeeService = new Mock(); - var mockResponse = await MockData.getOkResponse("Emp1"); + var mockResponse = await MockData.getOkResponse(1); var mockInputEmployee = await MockData.getInputEmployeeData(); mockEmployeeService.Setup(service => service.PostEmployeeAsync(mockInputEmployee)).ReturnsAsync(mockResponse); @@ -96,12 +96,12 @@ namespace DamageAssesment.Api.Employees.Test public async Task PutEmployeeAsync_ShouldReturnStatusCode200() { var mockEmployeeService = new Mock(); - var mockResponse = await MockData.getOkResponse("Emp1"); + var mockResponse = await MockData.getOkResponse(1); var mockInputEmployee = await MockData.getInputEmployeeData(); - mockEmployeeService.Setup(service => service.UpdateEmployeeAsync("Emp1",mockInputEmployee)).ReturnsAsync(mockResponse); + mockEmployeeService.Setup(service => service.UpdateEmployeeAsync(1,mockInputEmployee)).ReturnsAsync(mockResponse); var EmployeeProvider = new EmployeesController(mockEmployeeService.Object); - var result = (OkObjectResult)await EmployeeProvider.UpdateEmployee("Emp1",mockInputEmployee); + var result = (OkObjectResult)await EmployeeProvider.UpdateEmployee(1,mockInputEmployee); Assert.Equal(200, result.StatusCode); } @@ -112,10 +112,10 @@ namespace DamageAssesment.Api.Employees.Test var mockEmployeeService = new Mock(); var mockResponse = await MockData.getNotFoundResponse(); var mockInputEmployee = await MockData.getInputEmployeeData(); - mockEmployeeService.Setup(service => service.UpdateEmployeeAsync("Emp1", mockInputEmployee)).ReturnsAsync(mockResponse); + mockEmployeeService.Setup(service => service.UpdateEmployeeAsync(1, mockInputEmployee)).ReturnsAsync(mockResponse); var EmployeeProvider = new EmployeesController(mockEmployeeService.Object); - var result = (NotFoundObjectResult)await EmployeeProvider.UpdateEmployee("Emp1", mockInputEmployee); + var result = (NotFoundObjectResult)await EmployeeProvider.UpdateEmployee(1, mockInputEmployee); Assert.Equal(404, result.StatusCode); } @@ -126,10 +126,10 @@ namespace DamageAssesment.Api.Employees.Test var mockEmployeeService = new Mock(); var mockResponse = await MockData.getBadRequestResponse(); var mockInputEmployee = await MockData.getInputEmployeeData(); - mockEmployeeService.Setup(service => service.UpdateEmployeeAsync("Emp1", mockInputEmployee)).ReturnsAsync(mockResponse); + mockEmployeeService.Setup(service => service.UpdateEmployeeAsync(1, mockInputEmployee)).ReturnsAsync(mockResponse); var EmployeeProvider = new EmployeesController(mockEmployeeService.Object); - var result = (BadRequestObjectResult)await EmployeeProvider.UpdateEmployee("Emp1", mockInputEmployee); + var result = (BadRequestObjectResult)await EmployeeProvider.UpdateEmployee(1, mockInputEmployee); Assert.Equal(400, result.StatusCode); } @@ -138,12 +138,12 @@ namespace DamageAssesment.Api.Employees.Test public async Task DeleteEmployeeAsync_ShouldReturnStatusCode200() { var mockEmployeeService = new Mock(); - var mockResponse = await MockData.getOkResponse("Emp1"); + var mockResponse = await MockData.getOkResponse(1); - mockEmployeeService.Setup(service => service.DeleteEmployeeAsync("Emp1")).ReturnsAsync(mockResponse); + mockEmployeeService.Setup(service => service.DeleteEmployeeAsync(1)).ReturnsAsync(mockResponse); var EmployeeProvider = new EmployeesController(mockEmployeeService.Object); - var result = (OkObjectResult)await EmployeeProvider.DeleteEmployee("Emp1"); + var result = (OkObjectResult)await EmployeeProvider.DeleteEmployee(1); Assert.Equal(200, result.StatusCode); } @@ -153,10 +153,10 @@ namespace DamageAssesment.Api.Employees.Test { var mockEmployeeService = new Mock(); var mockResponse = await MockData.getNotFoundResponse(); - mockEmployeeService.Setup(service => service.DeleteEmployeeAsync("Emp1")).ReturnsAsync(mockResponse); + mockEmployeeService.Setup(service => service.DeleteEmployeeAsync(1)).ReturnsAsync(mockResponse); var EmployeeProvider = new EmployeesController(mockEmployeeService.Object); - var result = (NotFoundResult)await EmployeeProvider.DeleteEmployee("Emp1"); + var result = (NotFoundResult)await EmployeeProvider.DeleteEmployee(1); Assert.Equal(404, result.StatusCode); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/MockData.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/MockData.cs index 91c8b84..19768fc 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/MockData.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees.Test/MockData.cs @@ -1,8 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Linq; -using System.Text; -using System.Threading.Tasks; +using System.Text; namespace DamageAssesment.Api.Employees.Test { @@ -15,13 +11,13 @@ namespace DamageAssesment.Api.Employees.Test for (int i = 0; i < 10; i++) { - list.Append(new Employees.Models.Employee { Id = "Emp"+i, Name = "Emoployee"+i, Email = "abc"+i+"@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-18-i), IsActive = true, PreferredLanguage = "en" }); + list.Append(new Employees.Models.Employee { Id = i, Name = "Emoployee"+i, Email = "abc"+i+"@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-18-i), IsActive = true, PreferredLanguage = "en" }); } return (true, list, null); } - public static async Task<(bool, Employees.Models.Employee, string)> getOkResponse(string Id) + public static async Task<(bool, Employees.Models.Employee, string)> getOkResponse(int Id) { var Employees = await getOkResponse(); var Employee = Employees.Item2.FirstOrDefault(s => s.Id == Id); @@ -45,7 +41,7 @@ namespace DamageAssesment.Api.Employees.Test public static async Task getInputEmployeeData() { - return new Models.Employee { Id = "Emp1", Name = "ABC1", Email = "abc1@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-18), IsActive = true, PreferredLanguage = "en" }; + return new Models.Employee { Id = 1, Name = "ABC1", Email = "abc1@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-18), IsActive = true, PreferredLanguage = "en" }; } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Controllers/EmployeesController.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Controllers/EmployeesController.cs index 8d004e6..f5e0d88 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Controllers/EmployeesController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Controllers/EmployeesController.cs @@ -4,7 +4,6 @@ using Microsoft.AspNetCore.Mvc; namespace DamageAssesment.Api.Employees.Controllers { - [Route("api")] [ApiController] public class EmployeesController : ControllerBase { @@ -37,11 +36,11 @@ namespace DamageAssesment.Api.Employees.Controllers /// GET request for retrieving an employee by ID. /// - [HttpGet("Employees/{Id}")] - public async Task GetEmployeeByIdAsync(string Id) + [HttpGet("Employees/{id}")] + public async Task GetEmployeeByIdAsync(int id) { - var result = await EmployeeProvider.GetEmployeeByIdAsync(Id); + var result = await EmployeeProvider.GetEmployeeByIdAsync(id); if (result.IsSuccess) { return Ok(result.Employee); @@ -54,12 +53,12 @@ namespace DamageAssesment.Api.Employees.Controllers /// PUT request for updating an existing employee. /// /// The updated employee object. - [HttpPut("Employees")] - public async Task UpdateEmployee(string Id, Models.Employee Employee) + [HttpPut("Employees/{id}")] + public async Task UpdateEmployee(int id, Models.Employee Employee) { if (Employee != null) { - var result = await this.EmployeeProvider.UpdateEmployeeAsync(Id,Employee); + var result = await this.EmployeeProvider.UpdateEmployeeAsync(id,Employee); if (result.IsSuccess) { return Ok(result.Employee); @@ -88,14 +87,14 @@ namespace DamageAssesment.Api.Employees.Controllers } return BadRequest(result.ErrorMessage); } - return CreatedAtRoute("DefaultApi", new { id = Employee.Id }, Employee); + return CreatedAtRoute("DefaultApi", new { Id = Employee.Id }, Employee); } /// /// DELETE request for deleting an existing employee. /// /// The ID of the employee to be deleted. [HttpDelete("Employees/{id}")] - public async Task DeleteEmployee(string id) + public async Task DeleteEmployee(int id) { var result = await this.EmployeeProvider.DeleteEmployeeAsync(id); if (result.IsSuccess) diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Db/Employee.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Db/Employee.cs index 2b3202a..45ab57e 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Db/Employee.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Db/Employee.cs @@ -5,7 +5,9 @@ namespace DamageAssesment.Api.Employees.Db public class Employee { [Key] - public string Id { get; set; } + public int Id { get; set; } + [StringLength(50)] + public string EmployeeCode { get; set; } [StringLength(50)] public string Name { get; set; } @@ -17,7 +19,7 @@ namespace DamageAssesment.Api.Employees.Db [StringLength(50)] public string Email { get; set; } - public bool IsActive {get;set;} + public bool IsActive { get; set; } public string? PreferredLanguage { get; set; } = "en"; } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Db/EmployeeDbContext.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Db/EmployeeDbContext.cs index 0d7bc5e..ec7b0f0 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Db/EmployeeDbContext.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Db/EmployeeDbContext.cs @@ -8,5 +8,14 @@ namespace DamageAssesment.Api.Employees.Db public EmployeeDbContext(DbContextOptions options) : base(options) { } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Interfaces/IEmployeesProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Interfaces/IEmployeesProvider.cs index 8083d2c..91da039 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Interfaces/IEmployeesProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Interfaces/IEmployeesProvider.cs @@ -3,10 +3,10 @@ public interface IEmployeesProvider { Task<(bool IsSuccess, IEnumerable Employees, string ErrorMessage)> GetEmployeesAsync(); - Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> GetEmployeeByIdAsync(string Id); + Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> GetEmployeeByIdAsync(int Id); 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); + Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> UpdateEmployeeAsync(int Id, Models.Employee Employee); + Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> DeleteEmployeeAsync(int Id); void SeedData(); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Models/Employee.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Models/Employee.cs index 5defc90..0d5638c 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Models/Employee.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Models/Employee.cs @@ -4,7 +4,8 @@ namespace DamageAssesment.Api.Employees.Models { public class Employee { - public string Id { get; set; } + public int Id { get; set; } + public string EmployeeCode { get; set; } public string Name { get; set; } public DateTime BirthDate { get; set; } public string OfficePhoneNumber { get; set; } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Profiles/EmployeesProfile.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Profiles/EmployeesProfile.cs index 444752b..e46d15f 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Employees/Profiles/EmployeesProfile.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Employees/Profiles/EmployeesProfile.cs @@ -7,6 +7,7 @@ namespace DamageAssesment.Api.Employees.Profiles public EmployeesProfile() { CreateMap(); + CreateMap(); } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Employees/Providers/EmployeesProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Employees/Providers/EmployeesProvider.cs index 533763f..75cefed 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() @@ -45,12 +45,12 @@ namespace DamageAssesment.Api.Employees.Providers } - public async Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> GetEmployeeByIdAsync(string Id) + public async Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> GetEmployeeByIdAsync(int Id) { try { logger?.LogInformation("Query Employee"); - var Employee = await EmployeeDbContext.Employees.AsNoTracking().FirstOrDefaultAsync(q => q.Id.ToLower() == Id.ToLower()); + var Employee = await EmployeeDbContext.Employees.AsNoTracking().FirstOrDefaultAsync(q => q.Id == Id); if (Employee != null) { logger?.LogInformation($"{Employee} customer(s) found"); @@ -72,13 +72,14 @@ namespace DamageAssesment.Api.Employees.Providers Db.Employee _employee = mapper.Map(Employee); logger?.LogInformation("Query Employee"); - if (!EmployeeExists(Employee.Id)) + if (!EmployeeCodeExists(Employee.EmployeeCode)) { EmployeeDbContext.Employees.Add(_employee); + Employee.Id = _employee.Id; EmployeeDbContext.SaveChanges(); return (true, Employee, null); } - return (false, null, "Employee is already exits"); + return (false, null, "Employee code is already exits"); } catch (Exception ex) { @@ -86,19 +87,20 @@ namespace DamageAssesment.Api.Employees.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> UpdateEmployeeAsync(string Id , Models.Employee Employee) + public async Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> UpdateEmployeeAsync(int Id, Models.Employee Employee) { try { if (Employee != null) { - var _employee = await EmployeeDbContext.Employees.AsNoTracking().Where(s => s.Id.ToLower() == Id.ToLower()).FirstOrDefaultAsync(); + var _employee = await EmployeeDbContext.Employees.AsNoTracking().Where(s => s.Id == Id).FirstOrDefaultAsync(); if (_employee != null) { Db.Employee vEmployee = mapper.Map(Employee); EmployeeDbContext.Employees.Update(vEmployee); EmployeeDbContext.SaveChanges(); + Employee.Id = Id; return (true, Employee, "Successful"); } else @@ -120,11 +122,11 @@ namespace DamageAssesment.Api.Employees.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> DeleteEmployeeAsync(string Id) + public async Task<(bool IsSuccess, Models.Employee Employee, string ErrorMessage)> DeleteEmployeeAsync(int Id) { try { - Db.Employee Employee = EmployeeDbContext.Employees.AsNoTracking().Where(a => a.Id.ToLower() == Id.ToLower()).FirstOrDefault(); + Db.Employee Employee = EmployeeDbContext.Employees.AsNoTracking().Where(a => a.Id == Id).FirstOrDefault(); if (Employee == null) { return (false, null, "Not Found"); @@ -137,24 +139,29 @@ namespace DamageAssesment.Api.Employees.Providers { logger?.LogError(ex.ToString()); - return (false,null, ex.Message); + return (false, null, ex.Message); } } - private bool EmployeeExists(string id) + private bool EmployeeExists(int id) { - return EmployeeDbContext.Employees.AsNoTracking().Count(e => e.Id.ToLower() == id.ToLower()) > 0; + return EmployeeDbContext.Employees.AsNoTracking().Count(e => e.Id == id) > 0; + } + + private bool EmployeeCodeExists(string employeeCode) + { + return EmployeeDbContext.Employees.AsNoTracking().Count(e => e.EmployeeCode.ToLower() == employeeCode.ToLower()) > 0; } public void SeedData() { if (!EmployeeDbContext.Employees.Any()) { - EmployeeDbContext.Employees.Add(new Db.Employee() { Id = "Emp1", Name = "ABC1", Email = "abc1@gmail.com", OfficePhoneNumber = "12345678",BirthDate=DateTime.Now.AddYears(-18), IsActive = true,PreferredLanguage="en" }); - EmployeeDbContext.Employees.Add(new Db.Employee() { Id = "Emp2", Name = "ABC2", Email = "abc2@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-22), IsActive = true, PreferredLanguage = "fr" }); - EmployeeDbContext.Employees.Add(new Db.Employee() { Id = "Emp3", Name = "ABC3", Email = "abc3@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-30) ,IsActive = true, PreferredLanguage = "fr" }); - EmployeeDbContext.Employees.Add(new Db.Employee() { Id = "Emp4", Name = "ABC4", Email = "abc4@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-20) ,IsActive = true, PreferredLanguage = "en" }); - EmployeeDbContext.Employees.Add(new Db.Employee() { Id = "Emp5", Name = "ABC5", Email = "abc5@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-23) ,IsActive = true, PreferredLanguage = "es" }); - EmployeeDbContext.Employees.Add(new Db.Employee() { Id = "Emp6", Name = "ABC6", Email = "abc6@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-32) ,IsActive = true, PreferredLanguage = "es" }); + EmployeeDbContext.Employees.Add(new Db.Employee() { Id = 1, EmployeeCode = "Emp1", Name = "ABC1", Email = "abc1@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-18), IsActive = true, PreferredLanguage = "en" }); + EmployeeDbContext.Employees.Add(new Db.Employee() { Id = 2, EmployeeCode = "Emp2", Name = "ABC2", Email = "abc2@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-22), IsActive = true, PreferredLanguage = "fr" }); + EmployeeDbContext.Employees.Add(new Db.Employee() { Id = 3, EmployeeCode = "Emp3", Name = "ABC3", Email = "abc3@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-30), IsActive = true, PreferredLanguage = "fr" }); + EmployeeDbContext.Employees.Add(new Db.Employee() { Id = 4, EmployeeCode = "Emp4", Name = "ABC4", Email = "abc4@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-20), IsActive = true, PreferredLanguage = "en" }); + EmployeeDbContext.Employees.Add(new Db.Employee() { Id = 5, EmployeeCode = "Emp5", Name = "ABC5", Email = "abc5@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-23), IsActive = true, PreferredLanguage = "es" }); + EmployeeDbContext.Employees.Add(new Db.Employee() { Id = 6, EmployeeCode = "Emp6", Name = "ABC6", Email = "abc6@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-32), IsActive = true, PreferredLanguage = "es" }); EmployeeDbContext.SaveChanges(); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/LocationsServiceTest.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/LocationsServiceTest.cs index 94e518d..cc0ad45 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/LocationsServiceTest.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/LocationsServiceTest.cs @@ -40,11 +40,11 @@ namespace DamageAssesment.Api.Locations.Test public async Task GetLocationsByIdAsync_ShouldReturnStatusCode200() { var mockLocationService = new Mock(); - var mockResponse = await MockData.getOkResponseLocation("Loc1"); - mockLocationService.Setup(service => service.GetLocationByIdAsync("Loc1")).ReturnsAsync(mockResponse); + var mockResponse = await MockData.getOkResponseLocation(1); + mockLocationService.Setup(service => service.GetLocationByIdAsync(1)).ReturnsAsync(mockResponse); var locationProvider = new LocationsController(mockLocationService.Object); - var result = (OkObjectResult)await locationProvider.GetLocationByIdAsync("Loc1"); + var result = (OkObjectResult)await locationProvider.GetLocationByIdAsync(1); Assert.Equal(200, result.StatusCode); } @@ -55,10 +55,10 @@ namespace DamageAssesment.Api.Locations.Test { var mockLocationService = new Mock(); var mockResponse = await MockData.getLocationNotFoundResponse(); - mockLocationService.Setup(service => service.GetLocationByIdAsync("Loc1")).ReturnsAsync(mockResponse); + mockLocationService.Setup(service => service.GetLocationByIdAsync(1)).ReturnsAsync(mockResponse); var locationProvider = new LocationsController(mockLocationService.Object); - var result = (NotFoundResult)await locationProvider.GetLocationByIdAsync("Loc1"); + var result = (NotFoundResult)await locationProvider.GetLocationByIdAsync(1); Assert.Equal(404, result.StatusCode); } @@ -68,8 +68,8 @@ namespace DamageAssesment.Api.Locations.Test public async Task PostLocationAsync_ShouldReturnStatusCode200() { var mockLocationService = new Mock(); - var mockResponse = await MockData.getOkResponseLocation("Loc1"); - var mockInputLocation = new Models.Location { Id = "Loc1", RegionId = "R1", Name = "Location 1", SchoolType = "US", MaintenanceCenter = "1" }; + var mockResponse = await MockData.getOkResponseLocation(1); + var mockInputLocation = new Models.Location { Id = 1, RegionId = 1, Name = "Location 1", SchoolType = "US", MaintenanceCenter = "1" }; mockLocationService.Setup(service => service.PostLocationAsync(mockInputLocation)).ReturnsAsync(mockResponse); var locationProvider = new LocationsController(mockLocationService.Object); @@ -83,11 +83,11 @@ namespace DamageAssesment.Api.Locations.Test { var mockLocationService = new Mock(); var mockResponse = await MockData.getLocationNotFoundResponse(); - var mockInputLocation = new Models.Location { Id = "Loc1", RegionId = "R1", Name = "Location 1", SchoolType = "US", MaintenanceCenter = "1" }; + var mockInputLocation = new Models.Location { Id = 1, RegionId = 1, Name = "Location 1", SchoolType = "US", MaintenanceCenter = "1" }; mockLocationService.Setup(service => service.PostLocationAsync(mockInputLocation)).ReturnsAsync(mockResponse); var locationProvider = new LocationsController(mockLocationService.Object); - var result = (BadRequestResult)await locationProvider.CreateLocation(mockInputLocation); + var result = (BadRequestObjectResult)await locationProvider.CreateLocation(mockInputLocation); Assert.Equal(400, result.StatusCode); } @@ -98,11 +98,11 @@ namespace DamageAssesment.Api.Locations.Test { var mockLocationService = new Mock(); var mockResponse = await MockData.getLocation(true, "update success"); - var mockInputLocation = new Models.Location { Id = "Loc1", RegionId = "R1", Name = "Location 1", SchoolType = "US", MaintenanceCenter = "1" }; - mockLocationService.Setup(service => service.UpdateLocationAsync(mockInputLocation)).ReturnsAsync(mockResponse); + var mockInputLocation = new Models.Location { Id = 1, LocationCode ="Loc1", RegionId = 1, Name = "Location 1", SchoolType = "US", MaintenanceCenter = "1" }; + mockLocationService.Setup(service => service.UpdateLocationAsync(1,mockInputLocation)).ReturnsAsync(mockResponse); var locationProvider = new LocationsController(mockLocationService.Object); - var result = (OkObjectResult)await locationProvider.UpdateLocation(mockInputLocation); + var result = (OkObjectResult)await locationProvider.UpdateLocation(1,mockInputLocation); Assert.Equal(200, result.StatusCode); } @@ -112,11 +112,11 @@ namespace DamageAssesment.Api.Locations.Test { var mockLocationService = new Mock(); var mockResponse = await MockData.getLocation(false, null); - var mockInputLocation = new Models.Location { Id = "Loc1", RegionId = "R1", Name = "Location 1", SchoolType = "US", MaintenanceCenter = "1" }; - mockLocationService.Setup(service => service.UpdateLocationAsync(mockInputLocation)).ReturnsAsync(mockResponse); + var mockInputLocation = new Models.Location { Id = 1, RegionId = 1, Name = "Location 1", SchoolType = "US", MaintenanceCenter = "1" }; + mockLocationService.Setup(service => service.UpdateLocationAsync(1,mockInputLocation)).ReturnsAsync(mockResponse); var locationProvider = new LocationsController(mockLocationService.Object); - var result = (NotFoundResult)await locationProvider.UpdateLocation(mockInputLocation); + var result = (NotFoundResult)await locationProvider.UpdateLocation(1,mockInputLocation); Assert.Equal(404, result.StatusCode); } @@ -127,10 +127,10 @@ namespace DamageAssesment.Api.Locations.Test { var mockLocationService = new Mock(); var mockResponse = await MockData.getLocation(true, "delete success"); - mockLocationService.Setup(service => service.DeleteLocationAsync("Loc1")).ReturnsAsync(mockResponse); + mockLocationService.Setup(service => service.DeleteLocationAsync(1)).ReturnsAsync(mockResponse); var locationProvider = new LocationsController(mockLocationService.Object); - var result = (OkObjectResult)await locationProvider.DeleteLocation("Loc1"); + var result = (OkObjectResult)await locationProvider.DeleteLocation(1); Assert.Equal(200, result.StatusCode); } @@ -140,10 +140,10 @@ namespace DamageAssesment.Api.Locations.Test { var mockLocationService = new Mock(); var mockResponse = await MockData.getLocation(false, null); - mockLocationService.Setup(service => service.DeleteLocationAsync("Loc1")).ReturnsAsync(mockResponse); + mockLocationService.Setup(service => service.DeleteLocationAsync(1)).ReturnsAsync(mockResponse); var locationProvider = new LocationsController(mockLocationService.Object); - var result = (NotFoundResult)await locationProvider.DeleteLocation("Loc1"); + var result = (NotFoundResult)await locationProvider.DeleteLocation(1); Assert.Equal(404, result.StatusCode); } @@ -180,11 +180,11 @@ namespace DamageAssesment.Api.Locations.Test public async Task GetRegionAsync_ShouldReturnStatusCode200() { var mockRegionService = new Mock(); - var mockResponse = await MockData.getOkResponse("1"); - mockRegionService.Setup(service => service.GetRegionByIdAsync("1")).ReturnsAsync(mockResponse); + var mockResponse = await MockData.getOkResponse(1); + mockRegionService.Setup(service => service.GetRegionByIdAsync(1)).ReturnsAsync(mockResponse); var regionProvider = new RegionsController(mockRegionService.Object); - var result = (OkObjectResult)await regionProvider.GetRegionAsync("1"); + var result = (OkObjectResult)await regionProvider.GetRegionAsync(1); Assert.Equal(200, result.StatusCode); } @@ -194,10 +194,10 @@ namespace DamageAssesment.Api.Locations.Test { var mockRegionService = new Mock(); var mockResponse = await MockData.getNotFoundResponse(); - mockRegionService.Setup(service => service.GetRegionByIdAsync("99")).ReturnsAsync(mockResponse); + mockRegionService.Setup(service => service.GetRegionByIdAsync(99999)).ReturnsAsync(mockResponse); var regionProvider = new RegionsController(mockRegionService.Object); - var result = (NotFoundResult)await regionProvider.GetRegionAsync("99"); + var result = (NotFoundResult)await regionProvider.GetRegionAsync(99); Assert.Equal(404, result.StatusCode); } @@ -205,7 +205,7 @@ namespace DamageAssesment.Api.Locations.Test public async Task PostRegionAsync_ShouldReturnStatusCode200() { var mockRegionService = new Mock(); - var mockResponse = await MockData.getOkResponse("1"); + var mockResponse = await MockData.getOkResponse(1); var mockInputRegion = await MockData.getInputRegionData(); mockRegionService.Setup(service => service.PostRegionAsync(mockInputRegion)).ReturnsAsync(mockResponse); @@ -233,12 +233,12 @@ namespace DamageAssesment.Api.Locations.Test public async Task PutRegionAsync_ShouldReturnStatusCode200() { var mockRegionService = new Mock(); - var mockResponse = await MockData.getOkResponse("1"); + var mockResponse = await MockData.getOkResponse(1); var mockInputRegion = await MockData.getInputRegionData(); - mockRegionService.Setup(service => service.PutRegionAsync(mockInputRegion)).ReturnsAsync(mockResponse); + mockRegionService.Setup(service => service.PutRegionAsync(1,mockInputRegion)).ReturnsAsync(mockResponse); var regionProvider = new RegionsController(mockRegionService.Object); - var result = (OkObjectResult)await regionProvider.PutRegionAsync(mockInputRegion); + var result = (OkObjectResult)await regionProvider.PutRegionAsync(1,mockInputRegion); Assert.Equal(200, result.StatusCode); } @@ -249,10 +249,10 @@ namespace DamageAssesment.Api.Locations.Test var mockRegionService = new Mock(); var mockResponse = await MockData.getNotFoundResponse(); var mockInputRegion = await MockData.getInputRegionData(); - mockRegionService.Setup(service => service.PutRegionAsync(mockInputRegion)).ReturnsAsync(mockResponse); + mockRegionService.Setup(service => service.PutRegionAsync(1, mockInputRegion)).ReturnsAsync(mockResponse); var regionProvider = new RegionsController(mockRegionService.Object); - var result = (NotFoundObjectResult)await regionProvider.PutRegionAsync(mockInputRegion); + var result = (NotFoundObjectResult)await regionProvider.PutRegionAsync(1,mockInputRegion); Assert.Equal(404, result.StatusCode); } @@ -263,10 +263,10 @@ namespace DamageAssesment.Api.Locations.Test var mockRegionService = new Mock(); var mockResponse = await MockData.getBadRequestResponse(); var mockInputRegion = await MockData.getInputRegionData(); - mockRegionService.Setup(service => service.PutRegionAsync(mockInputRegion)).ReturnsAsync(mockResponse); + mockRegionService.Setup(service => service.PutRegionAsync(1, mockInputRegion)).ReturnsAsync(mockResponse); var regionProvider = new RegionsController(mockRegionService.Object); - var result = (BadRequestObjectResult)await regionProvider.PutRegionAsync(mockInputRegion); + var result = (BadRequestObjectResult)await regionProvider.PutRegionAsync(1, mockInputRegion); Assert.Equal(400, result.StatusCode); } @@ -275,12 +275,12 @@ namespace DamageAssesment.Api.Locations.Test public async Task DeleteRegionAsync_ShouldReturnStatusCode200() { var mockRegionService = new Mock(); - var mockResponse = await MockData.getOkResponse("1"); + var mockResponse = await MockData.getOkResponse(1); - mockRegionService.Setup(service => service.DeleteRegionAsync("1")).ReturnsAsync(mockResponse); + mockRegionService.Setup(service => service.DeleteRegionAsync(1)).ReturnsAsync(mockResponse); var regionProvider = new RegionsController(mockRegionService.Object); - var result = (OkObjectResult)await regionProvider.DeleteRegionAsync("1"); + var result = (OkObjectResult)await regionProvider.DeleteRegionAsync(1); Assert.Equal(200, result.StatusCode); } @@ -291,10 +291,10 @@ namespace DamageAssesment.Api.Locations.Test var mockRegionService = new Mock(); var mockResponse = await MockData.getNotFoundResponse(); - mockRegionService.Setup(service => service.DeleteRegionAsync("1")).ReturnsAsync(mockResponse); + mockRegionService.Setup(service => service.DeleteRegionAsync(1)).ReturnsAsync(mockResponse); var regionProvider = new RegionsController(mockRegionService.Object); - var result = (NotFoundResult)await regionProvider.DeleteRegionAsync("1"); + var result = (NotFoundResult)await regionProvider.DeleteRegionAsync(1); Assert.Equal(404, result.StatusCode); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/MockData.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/MockData.cs index dec67b8..50d1c8c 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/MockData.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations.Test/MockData.cs @@ -9,13 +9,13 @@ namespace DamageAssesment.Api.Locations.Test for (int i = 0; i < 10; i++) { - list.Append(new Locations.Models.Region { Id = "R" + i, Abbreviation = "AB" + i, Name = "Region " + i }); + list.Append(new Locations.Models.Region { Id = i, Abbreviation = "AB" + i, Name = "Region " + i }); } return (true, list, null); } - public static async Task<(bool, Locations.Models.Region, string)> getOkResponse(string Id) + public static async Task<(bool, Locations.Models.Region, string)> getOkResponse(int Id) { var regions = await getOkResponse(); var region = regions.Item2.FirstOrDefault(s => s.Id == Id); @@ -29,7 +29,7 @@ namespace DamageAssesment.Api.Locations.Test for (int i = 0; i < 10; i++) { - list.Append(new Locations.Models.Location { Id = "Loc"+ i, RegionId = "R"+i, Name ="Location"}); + list.Append(new Locations.Models.Location { Id = i, RegionId = i, Name = "Location" }); } return (true, list, null); } @@ -39,16 +39,17 @@ namespace DamageAssesment.Api.Locations.Test return (false, null, null); } - public static async Task<(bool, Models.Location, string)> getOkResponseLocation(string Id) + public static async Task<(bool, Models.Location, string)> getOkResponseLocation(int Id) { var locations = await getOkResponseLocation(); var location = locations.Item2.FirstOrDefault(s => s.Id == Id); return (true, location, null); } - public static async Task<(bool, string)> getLocation(bool value,string message) + public static async Task<(bool, Models.Location, string)> getLocation(bool value, string message) { - return (value,message); + var location = new Models.Location { Id = 1, LocationCode = "Loc1", RegionId = 1, Name = "Location 1", SchoolType = "US", MaintenanceCenter = "1" }; + return (value, location, message); } public static async Task<(bool, Locations.Models.Location, string)> getLocationNotFoundResponse() @@ -73,7 +74,7 @@ namespace DamageAssesment.Api.Locations.Test public static async Task getInputRegionData() { - return new Locations.Models.Region { Id = "R99", Name = "Region 99", Abbreviation = "A99" }; + return new Locations.Models.Region { Id = 99999, Name = "Region 99", Abbreviation = "A99" }; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs index d919c07..d9bbea3 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/LocationsController.cs @@ -4,12 +4,10 @@ using Microsoft.AspNetCore.Mvc; namespace DamageAssesment.Api.Locations.Controllers { - [Route("api")] [ApiController] public class LocationsController : ControllerBase { private ILocationsProvider LocationProvider; - public LocationsController(ILocationsProvider LocationsProvider) { this.LocationProvider = LocationsProvider; @@ -25,7 +23,7 @@ namespace DamageAssesment.Api.Locations.Controllers var result = await LocationProvider.GetLocationsAsync(); if (result.IsSuccess) { - return Ok(result.locations); + return Ok(result.Locations); } return NoContent(); @@ -35,7 +33,7 @@ namespace DamageAssesment.Api.Locations.Controllers /// [HttpGet("Locations/{id}")] - public async Task GetLocationByIdAsync(string id) + public async Task GetLocationByIdAsync(int id) { var result = await LocationProvider.GetLocationByIdAsync(id); @@ -50,15 +48,15 @@ namespace DamageAssesment.Api.Locations.Controllers /// Update a Location. /// - [HttpPut("Locations")] - public async Task UpdateLocation(Models.Location Location) + [HttpPut("Locations/{id}")] + public async Task UpdateLocation(int id, Models.Location Location) { if (Location != null) { - var result = await this.LocationProvider.UpdateLocationAsync(Location); + var result = await this.LocationProvider.UpdateLocationAsync(id, Location); if (result.IsSuccess) { - return Ok(result.ErrorMessage); + return Ok(result.Location); } return NotFound(); } @@ -76,9 +74,9 @@ namespace DamageAssesment.Api.Locations.Controllers var result = await this.LocationProvider.PostLocationAsync(Location); if (result.IsSuccess) { - return Ok(result.Question); + return Ok(result.Location); } - return BadRequest(); + return BadRequest(result.ErrorMessage); } return BadRequest(); } @@ -87,12 +85,12 @@ namespace DamageAssesment.Api.Locations.Controllers /// [HttpDelete("Locations/{id}")] - public async Task DeleteLocation(string id) + public async Task DeleteLocation(int id) { var result = await this.LocationProvider.DeleteLocationAsync(id); if (result.IsSuccess) { - return Ok(result.ErrorMessage); + return Ok(result.Location); } return NotFound(); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/RegionsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/RegionsController.cs index f69e7ce..172043c 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/RegionsController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Controllers/RegionsController.cs @@ -3,7 +3,6 @@ using Microsoft.AspNetCore.Mvc; namespace DamageAssesment.Api.Locations.Controllers { - [Route("api/[controller]")] [ApiController] public class RegionsController : ControllerBase { @@ -17,13 +16,13 @@ namespace DamageAssesment.Api.Locations.Controllers /// Get all regions.2 /// - [HttpGet] + [HttpGet("regions")] public async Task GetRegionsAsync() { var result = await regionProvider.GetRegionsAsync(); if (result.IsSuccess) { - return Ok(result.regions); + return Ok(result.Regions); } return NoContent(); } @@ -31,10 +30,10 @@ namespace DamageAssesment.Api.Locations.Controllers /// GET request for retrieving a region by its ID. /// - [HttpGet("{Id}")] - public async Task GetRegionAsync(string Id) + [HttpGet("regions/{id}")] + public async Task GetRegionAsync(int id) { - var result = await this.regionProvider.GetRegionByIdAsync(Id); + var result = await this.regionProvider.GetRegionByIdAsync(id); if (result.IsSuccess) { return Ok(result.Region); @@ -45,7 +44,7 @@ namespace DamageAssesment.Api.Locations.Controllers /// POST request for creating a new region. /// - [HttpPost] + [HttpPost("regions")] public async Task PostRegionAsync(Models.Region region) { var result = await this.regionProvider.PostRegionAsync(region); @@ -59,10 +58,10 @@ namespace DamageAssesment.Api.Locations.Controllers /// PUT request for updating an existing region. /// - [HttpPut] - public async Task PutRegionAsync(Models.Region region) + [HttpPut("regions/{id}")] + public async Task PutRegionAsync(int id, Models.Region region) { - var result = await this.regionProvider.PutRegionAsync(region); + var result = await this.regionProvider.PutRegionAsync(id,region); if (result.IsSuccess) { return Ok(result.Region); @@ -77,10 +76,10 @@ namespace DamageAssesment.Api.Locations.Controllers /// - [HttpDelete("{Id}")] - public async Task DeleteRegionAsync(string Id) + [HttpDelete("regions/{id}")] + public async Task DeleteRegionAsync(int id) { - var result = await this.regionProvider.DeleteRegionAsync(Id); + var result = await this.regionProvider.DeleteRegionAsync(id); if (result.IsSuccess) { return Ok(result.Region); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/Location.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/Location.cs index 98afcf2..1774c9f 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/Location.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/Location.cs @@ -6,18 +6,20 @@ namespace DamageAssesment.Api.Locations.Db public class Location { [Key] + public int Id { get; set; } + [ForeignKey("Region")] + public int RegionId { get; set; } [StringLength(4)] - public string Id { get; set; } + public string LocationCode { get; set; } [StringLength(50)] public string Name { get; set; } - [StringLength(1)] + [StringLength(4)] public string MaintenanceCenter { get; set; } [StringLength(2)] public string SchoolType { get; set; } - [ForeignKey("Region")] - public string RegionId { get; set; } + } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/LocationDbContext.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/LocationDbContext.cs index 407faca..48f0543 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/LocationDbContext.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/LocationDbContext.cs @@ -2,7 +2,7 @@ namespace DamageAssesment.Api.Locations.Db { - public class LocationDbContext:DbContext + public class LocationDbContext : DbContext { public DbSet Locations { get; set; } public DbSet Regions { get; set; } @@ -10,5 +10,17 @@ namespace DamageAssesment.Api.Locations.Db { } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + modelBuilder.Entity() + .Property(item => item.Id) + .ValueGeneratedOnAdd(); + + } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/Region.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/Region.cs index 7c03858..c0b64bb 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/Region.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Db/Region.cs @@ -5,15 +5,12 @@ namespace DamageAssesment.Api.Locations.Db public class Region { [Key] - [StringLength(2)] - public string Id { get; set; } - + public int Id { get; set; } + [StringLength(50)] public string Name { get; set; } [StringLength(5)] public string Abbreviation { get; set; } - - // public ICollection Locations { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/ILocationsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/ILocationsProvider.cs index 55b847b..cd1de0c 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/ILocationsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/ILocationsProvider.cs @@ -4,11 +4,11 @@ namespace DamageAssesment.Api.Locations.Interfaces { public interface ILocationsProvider { - Task<(bool IsSuccess, IEnumerable locations, string ErrorMessage)> GetLocationsAsync(); - Task<(bool IsSuccess, Models.Location Location, string ErrorMessage)> GetLocationByIdAsync(string Id); - 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); + Task<(bool IsSuccess, IEnumerable Locations, string ErrorMessage)> GetLocationsAsync(); + Task<(bool IsSuccess, Models.Location Location, string ErrorMessage)> GetLocationByIdAsync(int Id); + Task<(bool IsSuccess, Models.Location Location, string ErrorMessage)> PostLocationAsync(Models.Location Location); + Task<(bool IsSuccess, Models.Location Location, string ErrorMessage)> UpdateLocationAsync(int Id, Models.Location Location); + Task<(bool IsSuccess, Models.Location Location, string ErrorMessage)> DeleteLocationAsync(int Id); void SeedData(); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/IRegionsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/IRegionsProvider.cs index 65f8d0b..22ef8b8 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/IRegionsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Interfaces/IRegionsProvider.cs @@ -2,11 +2,11 @@ { public interface IRegionsProvider { - Task<(bool IsSuccess, IEnumerable regions, string ErrorMessage)> GetRegionsAsync(); - Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> GetRegionByIdAsync(string Id); + Task<(bool IsSuccess, IEnumerable Regions, string ErrorMessage)> GetRegionsAsync(); + Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> GetRegionByIdAsync(int Id); 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); + Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> PutRegionAsync(int Id, Models.Region region); + Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> DeleteRegionAsync(int Id); void SeedData(); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Models/Location.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Models/Location.cs index 1fdad6a..eafbea6 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Models/Location.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Models/Location.cs @@ -4,19 +4,12 @@ namespace DamageAssesment.Api.Locations.Models { public class Location { - [StringLength(4)] - public string Id { get; set; } - - [StringLength(1)] - public string RegionId { get; set; } - - [StringLength(50)] + [Key] + public int Id { get; set; } + public int RegionId { get; set; } + public string LocationCode { get; set; } public string Name { get; set; } - - [StringLength(1)] public string MaintenanceCenter { get; set; } - - [StringLength(2)] public string SchoolType { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Models/Region.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Models/Region.cs index ebcabeb..e2481a9 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Models/Region.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Models/Region.cs @@ -4,14 +4,8 @@ namespace DamageAssesment.Api.Locations.Models { public class Region { - - [StringLength(1)] - public string Id { get; set; } - - [StringLength(50)] + public int Id { get; set; } public string Name { get; set; } - - [StringLength(5)] public string Abbreviation { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Profiles/LocationProfile.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Profiles/LocationProfile.cs index ca91e6a..dce65b3 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Profiles/LocationProfile.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Profiles/LocationProfile.cs @@ -5,6 +5,7 @@ public LocationProfile() { CreateMap(); + CreateMap(); } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/LocationsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/LocationsProvider.cs index 85da34c..5f1d057 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/LocationsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/LocationsProvider.cs @@ -20,39 +20,16 @@ namespace DamageAssesment.Api.Locations.Providers //SeedData(); } - public async Task<(bool IsSuccess, IEnumerable locations, string ErrorMessage)> GetLocationsAsync() - { - - try - { - logger?.LogInformation("Query Question"); - var Location = await locationDbContext.Locations.AsNoTracking().ToListAsync(); - if (Location != null) - { - logger?.LogInformation($"{Location.Count} Locations(s) found"); - var result = mapper.Map, IEnumerable>(Location); - return (true, result, null); - } - return (false, null, "Not found"); - } - catch (Exception ex) - { - logger?.LogError(ex.ToString()); - return (false, null, ex.Message); - } - - } - - public async Task<(bool IsSuccess, Models.Location Location, string ErrorMessage)> GetLocationByIdAsync(string Id) + public async Task<(bool IsSuccess, IEnumerable Locations, string ErrorMessage)> GetLocationsAsync() { try { logger?.LogInformation("Query Location"); - var Location = await locationDbContext.Locations.AsNoTracking().FirstOrDefaultAsync(q => q.Id == Id); - if (Location != null) + var locations = await locationDbContext.Locations.AsNoTracking().ToListAsync(); + if (locations != null) { - logger?.LogInformation($"{Location} customer(s) found"); - var result = mapper.Map(Location); + logger?.LogInformation($"{locations.Count} Locations(s) found"); + var result = mapper.Map, IEnumerable>(locations); return (true, result, null); } return (false, null, "Not found"); @@ -63,21 +40,42 @@ namespace DamageAssesment.Api.Locations.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.Location Question, string ErrorMessage)> PostLocationAsync(Models.Location Location) + + public async Task<(bool IsSuccess, Models.Location Location, string ErrorMessage)> GetLocationByIdAsync(int Id) { try { logger?.LogInformation("Query Location"); - if (!LocationExists(Location.Id)) + var location = await locationDbContext.Locations.AsNoTracking().FirstOrDefaultAsync(q => q.Id == Id); + if (location != null) { - Db.Location _location = mapper.Map(Location); + logger?.LogInformation($"{location} found"); + var result = mapper.Map(location); + return (true, result, null); + } + return (false, null, "Not found"); + } + catch (Exception ex) + { + logger?.LogError(ex.ToString()); + return (false, null, ex.Message); + } + } + public async Task<(bool IsSuccess, Models.Location Location, string ErrorMessage)> PostLocationAsync(Models.Location location) + { + try + { + if (!LocationCodeExists(location.LocationCode)) + { + Db.Location _location = mapper.Map(location); locationDbContext.Locations.Add(_location); - locationDbContext.SaveChanges(); - return (true, Location, null); + await locationDbContext.SaveChangesAsync(); + location.Id = _location.Id; + return (true, location, null); } else { - return (false, null, "Location is Already exists"); + return (false, null, "Location code is already exists"); } } catch (Exception ex) @@ -86,57 +84,67 @@ namespace DamageAssesment.Api.Locations.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, string ErrorMessage)> UpdateLocationAsync(Models.Location Location) + public async Task<(bool IsSuccess, Models.Location Location, string ErrorMessage)> UpdateLocationAsync(int Id, Models.Location location) { try { - Db.Location _location = mapper.Map(Location); - locationDbContext.Entry(_location).State = EntityState.Modified; - locationDbContext.SaveChanges(); - return (true, "Record updated successfully"); - } - catch (Exception ex) - { - - logger?.LogError(ex.ToString()); - return (false, ex.Message); - } - } - public async Task<(bool IsSuccess, string ErrorMessage)> DeleteLocationAsync(string Id) - { - try - { - Db.Location Location = locationDbContext.Locations.AsNoTracking().Where(a => a.Id == Id).FirstOrDefault(); - if (Location == null) + if (LocationExists(Id)) { - return (false, "record not found"); + Db.Location _location = mapper.Map(location); + locationDbContext.Entry(_location).State = EntityState.Modified; + await locationDbContext.SaveChangesAsync(); + return (true, location, "Record updated successfully"); + } + else + { + return (false, null, "Location is not exists"); } - locationDbContext.Locations.Remove(Location); - locationDbContext.SaveChanges(); - return (true, "Record deleted successfully"); } catch (Exception ex) { - logger?.LogError(ex.ToString()); - return (false, ex.Message); + return (false, null, ex.Message); + } + } + public async Task<(bool IsSuccess, Models.Location Location, string ErrorMessage)> DeleteLocationAsync(int Id) + { + try + { + Db.Location location = locationDbContext.Locations.AsNoTracking().Where(a => a.Id == Id).FirstOrDefault(); + if (location == null) + { + return (false, null, "record not found"); + } + locationDbContext.Locations.Remove(location); + await locationDbContext.SaveChangesAsync(); + return (true, mapper.Map(location), "Record deleted successfully"); + } + catch (Exception ex) + { + logger?.LogError(ex.ToString()); + return (false, null, ex.Message); } } - private bool LocationExists(string id) + private bool LocationExists(int id) { return locationDbContext.Locations.AsNoTracking().Count(e => e.Id == id) > 0; } + + private bool LocationCodeExists(string locationCode) + { + return locationDbContext.Locations.AsNoTracking().Count(e => e.LocationCode.ToLower() == locationCode.ToLower()) > 0; + } public void SeedData() { if (!locationDbContext.Locations.Any()) { - locationDbContext.Locations.Add(new Db.Location() { Id = "Loc1", RegionId = "1", Name = "BOB GRAHAM EDUCATION CENTER 1", MaintenanceCenter = "1", SchoolType = "US" }); - locationDbContext.Locations.Add(new Db.Location() { Id = "Loc2", RegionId = "2", Name = "BOB GRAHAM EDUCATION CENTER 2", MaintenanceCenter = "1", SchoolType = "US" }); - locationDbContext.Locations.Add(new Db.Location() { Id = "Loc3", RegionId = "3", Name = "BOB GRAHAM EDUCATION CENTER 3", MaintenanceCenter = "1", SchoolType = "US" }); - locationDbContext.Locations.Add(new Db.Location() { Id = "Loc4", RegionId = "1", Name = "BOB GRAHAM EDUCATION CENTER 4", MaintenanceCenter = "1", SchoolType = "US" }); - locationDbContext.Locations.Add(new Db.Location() { Id = "Loc5", RegionId = "2", Name = "BOB GRAHAM EDUCATION CENTER 5", MaintenanceCenter = "1", SchoolType = "US" }); - locationDbContext.Locations.Add(new Db.Location() { Id = "Loc6", RegionId = "3", Name = "BOB GRAHAM EDUCATION CENTER 6", MaintenanceCenter = "1", SchoolType = "US" }); + locationDbContext.Locations.Add(new Db.Location() { Id = 1, LocationCode = "Loc1", RegionId = 1, Name = "BOB GRAHAM EDUCATION CENTER 1", MaintenanceCenter = "1", SchoolType = "US" }); + locationDbContext.Locations.Add(new Db.Location() { Id = 2, LocationCode = "Loc2", RegionId = 2, Name = "BOB GRAHAM EDUCATION CENTER 2", MaintenanceCenter = "1", SchoolType = "US" }); + locationDbContext.Locations.Add(new Db.Location() { Id = 3, LocationCode = "Loc3", RegionId = 3, Name = "BOB GRAHAM EDUCATION CENTER 3", MaintenanceCenter = "1", SchoolType = "US" }); + locationDbContext.Locations.Add(new Db.Location() { Id = 4, LocationCode = "Loc4", RegionId = 1, Name = "BOB GRAHAM EDUCATION CENTER 4", MaintenanceCenter = "1", SchoolType = "US" }); + locationDbContext.Locations.Add(new Db.Location() { Id = 5, LocationCode = "Loc5", RegionId = 2, Name = "BOB GRAHAM EDUCATION CENTER 5", MaintenanceCenter = "1", SchoolType = "US" }); + locationDbContext.Locations.Add(new Db.Location() { Id = 6, LocationCode = "Loc6", RegionId = 3, Name = "BOB GRAHAM EDUCATION CENTER 6", MaintenanceCenter = "1", SchoolType = "US" }); locationDbContext.SaveChanges(); } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/RegionsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/RegionsProvider.cs index 0ea0b3f..4f33fee 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/RegionsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Locations/Providers/RegionsProvider.cs @@ -19,7 +19,7 @@ namespace DamageAssesment.Api.Locations.Providers //SeedData(); } - public async Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> GetRegionByIdAsync(string Id) + public async Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> GetRegionByIdAsync(int Id) { try { @@ -41,7 +41,7 @@ namespace DamageAssesment.Api.Locations.Providers } } - public async Task<(bool IsSuccess, IEnumerable regions, string ErrorMessage)> GetRegionsAsync() + public async Task<(bool IsSuccess, IEnumerable Regions, string ErrorMessage)> GetRegionsAsync() { try { @@ -69,11 +69,10 @@ namespace DamageAssesment.Api.Locations.Providers { if (region != null) { - var regions = await locationDbContext.Regions.AsNoTracking().ToListAsync(); - - region.Id = Convert.ToString(regions.Count + 1); - locationDbContext.Regions.Add(mapper.Map(region)); - locationDbContext.SaveChanges(); + var _region = mapper.Map(region); + locationDbContext.Regions.Add(_region); + await locationDbContext.SaveChangesAsync(); + region.Id = _region.Id; logger?.LogInformation($"{region} added successfuly"); return (true, region, "Successful"); } @@ -90,30 +89,38 @@ namespace DamageAssesment.Api.Locations.Providers } } - public async Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> PutRegionAsync(Models.Region region) + public async Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> PutRegionAsync(int Id, Models.Region region) { try { if (region != null) { - var _region = await locationDbContext.Regions.AsNoTracking().Where(s => s.Id == region.Id).FirstOrDefaultAsync(); + var _region = await locationDbContext.Regions.AsNoTracking().Where(s => s.Id == Id).FirstOrDefaultAsync(); if (_region != null) { - locationDbContext.Regions.Update(mapper.Map(region)); - locationDbContext.SaveChanges(); - return (true, region, "Region updated Successfuly"); + if (RegionExists(region.Id)) + { + locationDbContext.Regions.Update(mapper.Map(region)); + locationDbContext.SaveChanges(); + return (true, region, "Region updated Successfuly"); + } + else + { + logger?.LogInformation($"RegionID: {Id} Not exists"); + return (false, null, "Region not exists"); + } } else { - logger?.LogInformation($"RegionID: {region.Id} Not found"); + logger?.LogInformation($"RegionID: {Id} Not found"); return (false, null, "Not Found"); } } else { - logger?.LogInformation($"RegionID: {region.Id} Bad Request"); + logger?.LogInformation($"RegionID: {Id} Bad Request"); return (false, null, "Bad request"); } } @@ -124,7 +131,7 @@ namespace DamageAssesment.Api.Locations.Providers } } - public async Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> DeleteRegionAsync(string Id) + public async Task<(bool IsSuccess, Models.Region Region, string ErrorMessage)> DeleteRegionAsync(int Id) { try { @@ -149,13 +156,18 @@ namespace DamageAssesment.Api.Locations.Providers } } + private bool RegionExists(int id) + { + return locationDbContext.Regions.AsNoTracking().Count(e => e.Id == id) > 0; + } + public void SeedData() { if (!locationDbContext.Regions.Any()) { - locationDbContext.Regions.Add(new Db.Region() { Id = "1", Name = "North", Abbreviation = "N" }); - locationDbContext.Regions.Add(new Db.Region() { Id = "2", Name = "South", Abbreviation = "S" }); - locationDbContext.Regions.Add(new Db.Region() { Id = "3", Name = "Central", Abbreviation = "C" }); + locationDbContext.Regions.Add(new Db.Region() { Id = 1, Name = "North", Abbreviation = "N" }); + locationDbContext.Regions.Add(new Db.Region() { Id = 2, Name = "South", Abbreviation = "S" }); + locationDbContext.Regions.Add(new Db.Region() { Id = 3, Name = "Central", Abbreviation = "C" }); locationDbContext.SaveChanges(); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs index 19c32bc..17024eb 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Controllers/QuestionsController.cs @@ -40,7 +40,7 @@ namespace DamageAssesment.Api.Questions.Controllers [Route("Questions/{id}/{language:alpha}")] [Route("Questions/{id:int}")] [HttpGet] - public async Task GetQuestionByIdAsync(string? language,int id) + public async Task GetQuestionByIdAsync(int id, string? language) { var result = await this.questionsProvider.GetQuestionAsync(id, language); if (result.IsSuccess) diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Interfaces/IQuestionsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Interfaces/IQuestionsProvider.cs index 59a805b..f8e13c8 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Interfaces/IQuestionsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Interfaces/IQuestionsProvider.cs @@ -4,12 +4,12 @@ namespace DamageAssesment.Api.Questions.Interfaces { public interface IQuestionsProvider : IQuestionTypesProvider { - Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> GetQuestionAsync(int id, string language); - Task<(bool IsSuccess, IEnumerable Questions, string ErrorMessage)> GetQuestionsAsync(string language); + Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> GetQuestionAsync(int id, string language); + Task<(bool IsSuccess, IEnumerable Questions, string ErrorMessage)> GetQuestionsAsync(string language); Task<(bool IsSuccess, List SurveyQuestions, string ErrorMessage)> GetSurveyQuestionAsync(int surveyId,string language); - Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> PostQuestionAsync(Models.Question Question); - Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question); - Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> DeleteQuestionAsync(int id); + Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> PostQuestionAsync(Models.Question Question); + Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question); + Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> DeleteQuestionAsync(int id); Task<(bool IsSuccess, IEnumerable QuestionCategories, string ErrorMessage)> GetQuestionCategoriesAsync(string? language); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/Question.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/Question.cs index 7900097..b6c1668 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/Question.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/Question.cs @@ -1,29 +1,18 @@ -using System.ComponentModel.DataAnnotations; - -namespace DamageAssesment.Api.Questions.Models +namespace DamageAssesment.Api.Questions.Models { - public class MultiLanQuestion: BaseQuestion - { - public MultiLanguage Questions { get; set; } - } - public class Question: BaseQuestion + public class Question: BaseQuestion { public List Questions { get; set; } } public class BaseQuestion { public int Id { get; set; } - //public int QuestionTypeID { get; set; } - public string TypeText { get; set; } = string.Empty; - public int QuestionNumber { get; set; } public bool IsRequired { get; set; } public bool Comment { get; set; } - public bool Key { get; set; } public int? SurveyId { get; set; } public int CategoryId { get; set; } - // public int? Survey_SurveyID { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/QuestionsTranslation.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/QuestionsTranslation.cs index af39cdd..28548f1 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/QuestionsTranslation.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/QuestionsTranslation.cs @@ -3,10 +3,10 @@ public class QuestionsTranslation { public string QuestionText { get; set; } - public string Language { get; set; } = "En"; + public string Language { get; set; } = "en"; } - public class MultiLanguage + public class MultiLanguage : BaseQuestion { - public object questionText { get; set; } + public Dictionary Text { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/SurveyQuestion.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/SurveyQuestion.cs index a3a5513..8f4fd7b 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/SurveyQuestion.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Models/SurveyQuestion.cs @@ -5,6 +5,6 @@ public int CategoryId { get; set; } public string IconName { get; set; } public string IconLibrary { get; set; } - public List Questions { get; set; } + public List QuestionsText { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Profiles/QuestionProfile.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Profiles/QuestionProfile.cs index 5c0f36e..59b402a 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Profiles/QuestionProfile.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Profiles/QuestionProfile.cs @@ -8,7 +8,7 @@ namespace DamageAssesment.Api.Questions.Profiles { CreateMap().ForMember(dest => dest.TypeText, opt => opt.MapFrom(src => src.QuestionType.TypeText)); - CreateMap().ForMember(dest => dest.TypeText, + CreateMap().ForMember(dest => dest.TypeText, opt => opt.MapFrom(src => src.QuestionType.TypeText)); CreateMap(); CreateMap(); diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Program.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Program.cs index b978465..073cb10 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Program.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Program.cs @@ -2,7 +2,6 @@ using DamageAssesment.Api.Questions.Db; using DamageAssesment.Api.Questions.Interfaces; using DamageAssesment.Api.Questions.Providers; using Microsoft.EntityFrameworkCore; -using Microsoft.Extensions.Options; using System.Reflection; var builder = WebApplication.CreateBuilder(args); @@ -16,7 +15,6 @@ builder.Services.AddControllers(); builder.Services.AddScoped(); builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); - builder.Services.AddEndpointsApiExplorer(); //builder.Services.AddSwaggerGen(); builder.Services.AddSwaggerGen(c => diff --git a/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs index 26aa866..0b140e0 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Questions/Providers/QuestionsProvider.cs @@ -2,11 +2,7 @@ using DamageAssesment.Api.Questions.Db; using DamageAssesment.Api.Questions.Interfaces; using DamageAssesment.Api.Questions.Models; -using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; -using Microsoft.EntityFrameworkCore.Metadata.Internal; -using System.Collections; -using System.Collections.Generic; namespace DamageAssesment.Api.Questions.Providers { @@ -130,7 +126,7 @@ namespace DamageAssesment.Api.Questions.Providers } return QuestionTranslations; } - public MultiLanguage CreateMultiLanguageObject(List questions) + public Dictionary CreateMultiLanguageObject(List questions) { MultiLanguage MultiLanguage = new MultiLanguage(); Dictionary dict = new Dictionary(); @@ -138,10 +134,10 @@ namespace DamageAssesment.Api.Questions.Providers { dict.Add(item.Language, item.QuestionText); } - MultiLanguage.questionText = dict; - return MultiLanguage; + //MultiLanguage.questionText = dict; + return dict; } - public async Task<(bool IsSuccess, IEnumerable Questions, string ErrorMessage)> GetQuestionsAsync(string language) + public async Task<(bool IsSuccess, IEnumerable Questions, string ErrorMessage)> GetQuestionsAsync(string language) { try { @@ -151,10 +147,10 @@ namespace DamageAssesment.Api.Questions.Providers { //logger?.LogInformation($"{question} customer(s) found"); - var result = mapper.Map, IEnumerable>(questions); - foreach (var question in result) + var result = mapper.Map, IEnumerable>(questions); + foreach (var item in result) { - question.Questions = CreateMultiLanguageObject(GetQuestionsTranslations(question.Id, language)); + item.Text = CreateMultiLanguageObject(GetQuestionsTranslations(item.Id, language)); } return (true, result, null); } @@ -166,7 +162,7 @@ namespace DamageAssesment.Api.Questions.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> GetQuestionAsync(int id, string language) + public async Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> GetQuestionAsync(int id, string language) { try { @@ -175,8 +171,8 @@ namespace DamageAssesment.Api.Questions.Providers if (question != null) { logger?.LogInformation($"{question} customer(s) found"); - var result = mapper.Map(question); - result.Questions = CreateMultiLanguageObject(GetQuestionsTranslations(id, language)); + var result = mapper.Map(question); + result.Text = CreateMultiLanguageObject(GetQuestionsTranslations(id, language)); return (true, result, null); } return (false, null, "Not found"); @@ -187,11 +183,11 @@ namespace DamageAssesment.Api.Questions.Providers return (false, null, ex.Message); } } - public List GetSurveyQuestion(List questions, string language) + public List GetSurveyQuestion(List questions, string language) { foreach (var item in questions) { - item.Questions = CreateMultiLanguageObject(GetQuestionsTranslations(item.Id, language)); + item.Text = CreateMultiLanguageObject(GetQuestionsTranslations(item.Id, language)); } return questions; } @@ -214,7 +210,7 @@ namespace DamageAssesment.Api.Questions.Providers CategoryId = item.Id, IconLibrary = item.IconLibrary, IconName = item.IconName, - Questions = GetSurveyQuestion(mapper.Map, List>(questions.Where(a => a.CategoryId == item.Id).ToList()), language) + QuestionsText = GetSurveyQuestion(mapper.Map, List>(questions.Where(a => a.CategoryId == item.Id).ToList()), language) }); } @@ -229,7 +225,7 @@ namespace DamageAssesment.Api.Questions.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> PostQuestionAsync(Models.Question Question) + public async Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> PostQuestionAsync(Models.Question Question) { try { @@ -242,8 +238,8 @@ namespace DamageAssesment.Api.Questions.Providers questionDbContext.QuestionsTranslations.AddRange(dbquestiontranslation); questionDbContext.SaveChanges(); Question.Id = dbquestion.Id; - var result = mapper.Map(dbquestion); - result.Questions = CreateMultiLanguageObject(GetQuestionsTranslations(result.Id,"")); + var result = mapper.Map(dbquestion); + result.Text = CreateMultiLanguageObject(GetQuestionsTranslations(result.Id,"")); return (true, result, null); } catch (Exception ex) @@ -252,7 +248,7 @@ namespace DamageAssesment.Api.Questions.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question) + public async Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question) { try { @@ -266,8 +262,8 @@ namespace DamageAssesment.Api.Questions.Providers dbquestiontranslation.ForEach(i => i.QuestionId = dbquestion.Id); questionDbContext.QuestionsTranslations.AddRange(dbquestiontranslation); questionDbContext.SaveChanges(); - var result = mapper.Map(dbquestion); - result.Questions = CreateMultiLanguageObject(GetQuestionsTranslations(result.Id, "")); + var result = mapper.Map(dbquestion); + result.Text = CreateMultiLanguageObject(GetQuestionsTranslations(result.Id, "")); return (true, result, null); } catch (Exception ex) @@ -277,7 +273,7 @@ namespace DamageAssesment.Api.Questions.Providers return (false, null, ex.Message); } } - public async Task<(bool IsSuccess, Models.MultiLanQuestion Question, string ErrorMessage)> DeleteQuestionAsync(int id) + public async Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> DeleteQuestionAsync(int id) { try { @@ -285,8 +281,8 @@ namespace DamageAssesment.Api.Questions.Providers if (question != null) { - var result = mapper.Map(question); - result.Questions = CreateMultiLanguageObject(GetQuestionsTranslations(result.Id, "")); + var result = mapper.Map(question); + result.Text = CreateMultiLanguageObject(GetQuestionsTranslations(result.Id, "")); questionDbContext.Questions.Remove(question); questionDbContext.SaveChanges(); return (true, result, $"QuestionID {id} deleted Successfuly"); diff --git a/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/MockData.cs b/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/MockData.cs index 363ed98..8b13b70 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/MockData.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.QuestionsTest/MockData.cs @@ -5,13 +5,13 @@ namespace DamageAssesment.Api.Questions.Test public class MockData { - public static async Task<(bool, IEnumerable, string)> getOkResponse() + public static async Task<(bool, IEnumerable, string)> getOkResponse() { - IEnumerable list = new List(); + IEnumerable list = new List(); for (int i = 0; i < 10; i++) { - list.Append(new Questions.Models.MultiLanQuestion { Id = i, TypeText = "Text" + i, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId=i }); + list.Append(new Questions.Models.MultiLanguage { Id = i, TypeText = "Text" + i, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId=i }); } return (true, list, null); } @@ -23,38 +23,38 @@ namespace DamageAssesment.Api.Questions.Test for (int i = 0; i < 10; i++) { - List question = new List(); - question.Add(new Models.MultiLanQuestion { Id = i, TypeText = "Text" + i, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId = i }); + List question = new List(); + question.Add(new Models.MultiLanguage { Id = i, TypeText = "Text" + i, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId = i }); list.Append(new Questions.Models.SurveyQuestions { CategoryId = i, IconLibrary = "img" + i, IconName = "Category " + i, - Questions = question + QuestionsText = question }); } return (true, list, null); } - public static async Task<(bool, Questions.Models.MultiLanQuestion, string)> getOkResponse(int Id) + public static async Task<(bool, Questions.Models.MultiLanguage, string)> getOkResponse(int Id) { var Questions = await getOkResponse(); var Question = Questions.Item2.FirstOrDefault(s => s.Id == Id); return (true, Question, null); } - public static async Task<(bool, Questions.Models.MultiLanQuestion, string)> getBadRequestResponse() + public static async Task<(bool, Questions.Models.MultiLanguage, string)> getBadRequestResponse() { return (false, null, "Bad Request"); } - public static async Task<(bool, Questions.Models.MultiLanQuestion, string)> getNotFoundResponse() + public static async Task<(bool, Questions.Models.MultiLanguage, string)> getNotFoundResponse() { return (false, null, "Not Found"); } - public static async Task<(bool, IEnumerable, string)> getNoContentResponse() + public static async Task<(bool, IEnumerable, string)> getNoContentResponse() { - IEnumerable list = new List(); + IEnumerable list = new List(); return (false, list, null); } public static async Task<(bool, List, string)> getNoSurveyContentResponse() diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Controllers/SurveyResponsesController.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Controllers/SurveyResponsesController.cs index 5b141a8..e5f3917 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Controllers/SurveyResponsesController.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Controllers/SurveyResponsesController.cs @@ -6,7 +6,6 @@ using Microsoft.Extensions.Configuration; namespace DamageAssesment.Api.SurveyResponses.Controllers { - [Route("api")] [ApiController] public class SurveyResponsesController : ControllerBase { @@ -20,7 +19,7 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers /// GET request for retrieving survey responses. /// - [HttpGet("SurveyResponses")] + [HttpGet("Responses")] public async Task GetSurveyResponsesAsync() { var result = await this.surveyResponseProvider.GetSurveyResponsesAsync(); @@ -38,10 +37,10 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers /// GET request for retrieving survey responses by survey ID. /// - [HttpGet("SurveyResponses/{surveyId}")] - public async Task GetSurveyResponsesAsync(int surveyId) + [HttpGet("Responses/BySurvey/{surveyid}")] + public async Task GetSurveyResponsesAsync(int surveyid) { - var result = await this.surveyResponseProvider.GetSurveyResponsesBySurveyAsync(surveyId); + var result = await this.surveyResponseProvider.GetSurveyResponsesBySurveyAsync(surveyid); if (result.IsSuccess) { return Ok(result.SurveyResponses); @@ -51,13 +50,13 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers /// /// GET request for retrieving survey responses by survey and location IDs. /// - /// The ID of the survey for which responses are to be retrieved. - /// The ID of the location for which responses are to be retrieved. + /// The ID of the survey for which responses are to be retrieved. + /// The ID of the location for which responses are to be retrieved. - [HttpGet("Responses/{surveyId}/{locationId}")] - public async Task GetSurveyResponsesBySurveyAndLocationAsync(int surveyId, string locationId) + [HttpGet("Responses/{surveyid}/{locationid}")] + public async Task GetSurveyResponsesBySurveyAndLocationAsync(int surveyid, int locationid) { - var result = await this.surveyResponseProvider.GetSurveyResponsesBySurveyAndLocationAsync(surveyId, locationId); + var result = await this.surveyResponseProvider.GetSurveyResponsesBySurveyAndLocationAsync(surveyid, locationid); if (result.IsSuccess) { return Ok(result.SurveyResponses); @@ -72,10 +71,10 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers /// The ID of the question for which responses are to be retrieved. /// The answer for which responses are to be retrieved. - [HttpGet("ResponsesByAnswer/{surveyId}/{questionId}/{answer}")] - public async Task GetSurveyResponsesByAnswerAsyncAsync(int surveyId, int questionId, string answer) + [HttpGet("Responses/ByAnswer/{surveyid}/{questionid}/{answer}")] + public async Task GetSurveyResponsesByAnswerAsyncAsync(int surveyid, int questionid, string answer) { - var result = await surveyResponseProvider.GetResponsesByAnswerAsync(surveyId, questionId, answer); + var result = await surveyResponseProvider.GetResponsesByAnswerAsync(surveyid, questionid, answer); if (result.IsSuccess) { return Ok(result.SurveyResponses); @@ -88,10 +87,10 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers /// /// The ID of the survey for which answers are to be retrieved. - [HttpGet("AnswersByRegion/{surveyId}")] - public async Task GetAnswersByRegionAsync(int surveyId) + [HttpGet("Responses/ByRegion/{surveyid}")] + public async Task GetAnswersByRegionAsync(int surveyid) { - var result = await this.surveyResponseProvider.GetAnswersByRegionAsync(surveyId); + var result = await this.surveyResponseProvider.GetAnswersByRegionAsync(surveyid); if (result.IsSuccess) { return Ok(result.Answers); @@ -103,10 +102,10 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers /// /// The ID of the survey for which responses are to be retrieved. - [HttpGet("AnswersByMaintenanceCenter/{surveyId}")] - public async Task GetAnswersByMaintenaceCentersync(int surveyId) + [HttpGet("Responses/ByMaintenanceCenter/{surveyid}")] + public async Task GetAnswersByMaintenaceCentersync(int surveyid) { - var result = await this.surveyResponseProvider.GetSurveyResponsesByMaintenanceCenterAsync(surveyId); + var result = await this.surveyResponseProvider.GetSurveyResponsesByMaintenanceCenterAsync(surveyid); if (result.IsSuccess) { return Ok(result.SurveyResponses); @@ -118,10 +117,10 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers /// /// The ID of the survey response to be retrieved. - [HttpGet("SurveyResponse/{Id}")] - public async Task GetSurveyResponseByIdAsync(int Id) + [HttpGet("Responses/{id}")] + public async Task GetSurveyResponseByIdAsync(int id) { - var result = await this.surveyResponseProvider.GetSurveyResponseByIdAsync(Id); + var result = await this.surveyResponseProvider.GetSurveyResponseByIdAsync(id); if (result.IsSuccess) { return Ok(result.SurveyResponse); @@ -134,7 +133,7 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers /// /// The survey response object to be created. - [HttpPost("SurveyResponses")] + [HttpPost("Responses")] public async Task PostSurveysAsync(Models.SurveyResponse surveyResponse) { var result = await this.surveyResponseProvider.PostSurveyResponseAsync(surveyResponse); @@ -150,10 +149,10 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers /// The ID of the survey response to be updated. /// The updated survey response object. - [HttpPut("SurveyResponses/{Id}")] - public async Task PutSurveyResponseAsync(int Id, Models.SurveyResponse surveyResponse) + [HttpPut("Responses/{id}")] + public async Task PutSurveyResponseAsync(int id, Models.SurveyResponse surveyResponse) { - var result = await this.surveyResponseProvider.PutSurveyResponseAsync(Id, surveyResponse); + var result = await this.surveyResponseProvider.PutSurveyResponseAsync(id, surveyResponse); if (result.IsSuccess) { return Ok(result.SurveyResponse); @@ -167,10 +166,10 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers /// DELETE request for deleting an existing survey response. /// - [HttpDelete("SurveyResponses/{Id}")] - public async Task DeleteSurveyResponseAsync(int Id) + [HttpDelete("Responses/{id}")] + public async Task DeleteSurveyResponseAsync(int id) { - var result = await this.surveyResponseProvider.DeleteSurveyResponseAsync(Id); + var result = await this.surveyResponseProvider.DeleteSurveyResponseAsync(id); if (result.IsSuccess) { return Ok(result.SurveyResponse); @@ -182,7 +181,7 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers /// /// The answers to be submitted for the survey. - [HttpPost("SurveyResponses/Answers")] + [HttpPost("Responses/Answers")] public async Task PostSurveyAnswersAsync(Request request) { var result = await this.surveyResponseProvider.PostSurveyAnswersAsync(request); diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Db/SurveyResponse.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Db/SurveyResponse.cs index ea9ed5e..2169097 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Db/SurveyResponse.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Db/SurveyResponse.cs @@ -10,14 +10,12 @@ namespace DamageAssesment.Api.SurveyResponses.Db [ForeignKey("Survey")] public int SurveyId { get; set; } - - [StringLength(4)] [ForeignKey("Location")] - public string LocationId { get; set; } + public int LocationId { get; set; } [StringLength(6)] [ForeignKey("Employee")] - public string EmployeeId { get; set; } + public int EmployeeId { get; set; } public DateTime? CreatedDate { get; set; } = DateTime.Now; diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/IEmployeeServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/IEmployeeServiceProvider.cs index a402c30..62031d5 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/IEmployeeServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/IEmployeeServiceProvider.cs @@ -5,6 +5,6 @@ namespace DamageAssesment.Api.SurveyResponses.Interfaces public interface IEmployeeServiceProvider { Task> getEmployeesAsync(); - Task getEmployeeAsync(string employeeID); + Task getEmployeeAsync(int employeeId); } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/ISurveysResponse.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/ISurveysResponse.cs index 5cdd198..536353c 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/ISurveysResponse.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Interfaces/ISurveysResponse.cs @@ -13,7 +13,7 @@ namespace DamageAssesment.Api.SurveyResponses.Interfaces Task<(bool IsSuccess, Models.SurveyResponse SurveyResponse, string ErrorMessage)> DeleteSurveyResponseAsync(int Id); Task<(bool IsSuccess, dynamic SurveyResponse, string ErrorMessage)> GetSurveyResponseByIdAsync(int responseId); Task<(bool IsSuccess, dynamic SurveyResponses, string ErrorMessage)> GetSurveyResponsesBySurveyAsync(int surveyId); - Task<(bool IsSuccess, dynamic SurveyResponses, string ErrorMessage)> GetSurveyResponsesBySurveyAndLocationAsync(int surveyId, string location); + Task<(bool IsSuccess, dynamic SurveyResponses, string ErrorMessage)> GetSurveyResponsesBySurveyAndLocationAsync(int surveyId, int locationId); Task<(bool IsSuccess, dynamic SurveyResponses, string ErrorMessage)> GetSurveyResponsesByMaintenanceCenterAsync(int surveyId); Task<(bool IsSuccess, dynamic SurveyResponses, string ErrorMessage)> GetResponsesByAnswerAsync(int surveyId, int questionId, string answer); diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AggregateAnswer.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AggregateAnswer.cs deleted file mode 100644 index d728e1d..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AggregateAnswer.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace DamageAssesment.Api.SurveyResponses.Models -{ - public class AggregateAnswer - { - public string? Answer { get; set; } - public int Counter { get; set; } - - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AggregateResult.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AggregateResult.cs deleted file mode 100644 index ef8d174..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AggregateResult.cs +++ /dev/null @@ -1,11 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace DamageAssesment.Api.SurveyResponses.Models -{ - public class AggregateResult - { - public string RegionId { get; set; } - public AggregateAnswer Answers { get; set; } - - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Answer.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Answer.cs index cab6f5b..d607a2f 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Answer.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Answer.cs @@ -6,11 +6,11 @@ namespace DamageAssesment.Api.SurveyResponses.Models { public int Id { get; set; } public int QuestionId { get; set; } - public string? LocationId { get; set; } + public int LocationId { get; set; } public string AnswerText { get; set; } - public string? Comment { get; set; } + public string Comment { get; set; } public int SurveyResponseId { get; set; } - public string? RegionId { get; set; } + public int RegionId { get; set; } // public string? Name { get; set; } // public string? Abbreviation { get; set; } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AnswerData.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AnswerData.cs deleted file mode 100644 index cee0699..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/AnswerData.cs +++ /dev/null @@ -1,13 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace DamageAssesment.Api.SurveyResponses.Models -{ - public class AnswerData - { - public string RegionId { get; set; } - public string Name { get; set; } - public string Abbreviation { get; set; } - public List Answers { get; set; } - - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Employee.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Employee.cs index c1fb576..9a06020 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Employee.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Employee.cs @@ -4,18 +4,13 @@ namespace DamageAssesment.Api.SurveyResponses.Models { public class Employee { - public string Id { get; set; } - - [StringLength(50)] + public int Id { get; set; } + public string EmployeeCode { get; set; } public string Name { get; set; } - public DateTime BirthDate { get; set; } - - [StringLength(50)] public string OfficePhoneNumber { get; set; } - - [StringLength(50)] public string Email { get; set; } public bool IsActive { get; set; } + public string? PreferredLanguage { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Location.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Location.cs index 4c7f846..078a5ef 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Location.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Location.cs @@ -2,8 +2,8 @@ { public class Location { - public string Id { get; set; } - public string RegionId { get; set; } + public int Id { get; set; } + public int RegionId { get; set; } public string Name { get; set; } public string MaintenanceCenter { get; set; } public string SchoolType { get; set; } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Question.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Question.cs index ad18bf1..37abb4b 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Question.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Question.cs @@ -1,24 +1,17 @@ -using System.ComponentModel.DataAnnotations; +using System.Collections.Generic; namespace DamageAssesment.Api.SurveyResponses.Models { - public class Question + public class Question { public int Id { get; set; } - public List Questions { get; set; } - - //public int QuestionTypeID { get; set; } - - public string TypeText { get; set; } = string.Empty; - + public string TypeText { get; set; } public int QuestionNumber { get; set; } public bool IsRequired { get; set; } public bool Comment { get; set; } - public bool Key { get; set; } - public int? SurveyId { get; set; } - //public string QuestionGroup { get; set; } + public int SurveyId { get; set; } public int CategoryId { get; set; } - // public int? Survey_SurveyID { get; set; } + public Dictionary Text { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/QuestionsTranslation.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/QuestionsTranslation.cs deleted file mode 100644 index e347a5c..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/QuestionsTranslation.cs +++ /dev/null @@ -1,8 +0,0 @@ -namespace DamageAssesment.Api.SurveyResponses.Models -{ - public class QuestionsTranslation - { - public string QuestionText { get; set; } - public string Language { get; set; } = "En"; - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Region.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Region.cs index b1941d2..3fc5ad7 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Region.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Region.cs @@ -4,7 +4,7 @@ namespace DamageAssesment.Api.SurveyResponses.Models { public class Region { - public string Id { get; set; } + public int Id { get; set; } public string Name { get; set; } public string Abbreviation { get; set; } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Request.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Request.cs index 53b3044..5060914 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Request.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Request.cs @@ -3,8 +3,13 @@ public class Request { public int SurveyId { get; set; } - public string LocationId { get; set; } - public string EmployeeId { get; set; } + public int LocationId { get; set; } + public int EmployeeId { get; set; } + public string? ClientDevice { get; set; } + public string? KeyAnswerResult { get; set; } + public double? Longitute { get; set; } + public double? Latitude { get; set; } + public DateTime? CreatedDate { get; set; } = DateTime.Now; public List Answers { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/ResultData.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/ResultData.cs deleted file mode 100644 index 4df1631..0000000 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/ResultData.cs +++ /dev/null @@ -1,10 +0,0 @@ -using System.ComponentModel.DataAnnotations; - -namespace DamageAssesment.Api.SurveyResponses.Models -{ - public class ResultData - { - public List Regions { get; set; } - - } -} diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Survey.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Survey.cs index 506a2f4..b47193e 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Survey.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/Survey.cs @@ -6,9 +6,9 @@ namespace DamageAssesment.Api.SurveyResponses.Models { public int Id { get; set; } public bool IsEnabled { get; set; } - public DateTime? StartDate { get; set; } - public DateTime? EndDate { get; set; } + public DateTime StartDate { get; set; } + public DateTime EndDate { get; set; } public DateTime CreatedDate { get; set; } - public IEnumerable Titles { get; set; } + public Dictionary Titles { get; set; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/SurveyResponse.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/SurveyResponse.cs index ccaffdc..37862ca 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/SurveyResponse.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Models/SurveyResponse.cs @@ -7,12 +7,12 @@ namespace DamageAssesment.Api.SurveyResponses.Models { public int Id { get; set; } public int SurveyId { get; set; } - public string LocationId { get; set; } - public string EmployeeId { 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; } + public int LocationId { get; set; } + public int EmployeeId { 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/Providers/SurveyResponsesProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyResponsesProvider.cs index ec5bcc3..1f82d8c 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyResponsesProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Providers/SurveyResponsesProvider.cs @@ -31,19 +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", 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.SurveyResponses.Add(new Db.SurveyResponse { Id = 1, SurveyId = 1, EmployeeId = 1, LocationId = 1, ClientDevice = "Mobile", Latitude = 98.8767, Longitute = -129.9897, KeyAnswerResult = "true", CreatedDate = DateTime.Now }); + surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { Id = 2, SurveyId = 1, EmployeeId = 2, LocationId = 2, ClientDevice = "Desktop", Latitude = 98.8767, Longitute = -129.9897, KeyAnswerResult = "true", CreatedDate = DateTime.Now }); + surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { Id = 3, SurveyId = 3, EmployeeId = 4, LocationId = 1, ClientDevice = "Mobile", Latitude = 98.8767, Longitute = -129.9897, KeyAnswerResult = "true", CreatedDate = DateTime.Now }); + surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { Id = 4, SurveyId = 4, EmployeeId = 1, LocationId = 2, ClientDevice = "Desktop", Latitude = 98.8767, Longitute = -129.9897, KeyAnswerResult = "false", CreatedDate = DateTime.Now }); + surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { Id = 6, SurveyId = 1, EmployeeId = 4, LocationId = 2, ClientDevice = "Desktop", Latitude = 98.8767, Longitute = -129.9897, KeyAnswerResult = "true", CreatedDate = DateTime.Now }); + surveyResponseDbContext.SurveyResponses.Add(new Db.SurveyResponse { Id = 7, SurveyId = 1, EmployeeId = 4, LocationId = 3, ClientDevice = "Desktop", Latitude = 98.8767, Longitute = -129.9897, KeyAnswerResult = "false", CreatedDate = DateTime.Now }); surveyResponseDbContext.SaveChanges(); } } @@ -136,7 +136,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers } } - public async Task<(bool IsSuccess, dynamic SurveyResponses, string ErrorMessage)> GetSurveyResponsesBySurveyAndLocationAsync(int surveyId, string locationId) + public async Task<(bool IsSuccess, dynamic SurveyResponses, string ErrorMessage)> GetSurveyResponsesBySurveyAndLocationAsync(int surveyId, int locationId) { try { @@ -286,19 +286,14 @@ namespace DamageAssesment.Api.SurveyResponses.Providers { if (SurveyResponse != null) { - var _SurveyResponse = await surveyResponseDbContext.SurveyResponses.Where(s => s.Id == Id).FirstOrDefaultAsync(); + var _SurveyResponse = await surveyResponseDbContext.SurveyResponses.AsNoTracking().Where(s => s.Id == Id).FirstOrDefaultAsync(); if (_SurveyResponse != null) { - _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; + var response = mapper.Map(SurveyResponse); + surveyResponseDbContext.Update(response); await surveyResponseDbContext.SaveChangesAsync(); - return (true, mapper.Map(_SurveyResponse), "Successful"); + return (true, SurveyResponse, "Successful"); } else { @@ -360,13 +355,13 @@ namespace DamageAssesment.Api.SurveyResponses.Providers answer => answer.SurveyResponseId, surveyResponse => surveyResponse.Id, (answer, surveyResponse) => new - Answer + { - Id = answer.Id, - QuestionId = answer.QuestionId, - AnswerText = answer.AnswerText, - Comment = answer.Comment, - LocationId = surveyResponse.LocationId, + answer.Id, + answer.QuestionId, + answer.AnswerText, + answer.Comment, + surveyResponse.LocationId, SurveyResponseId = surveyResponse.Id }); @@ -383,41 +378,46 @@ namespace DamageAssesment.Api.SurveyResponses.Providers //get all the answers based on the locations var result = from answer in surveyAnswers from location in locations - where answer.LocationId == location.Id - select new Answer + where answer.LocationId.Equals(location.Id) + select new { - Id = answer.Id, - QuestionId = answer.QuestionId, - AnswerText = answer.AnswerText, - Comment = answer.Comment, - RegionId = location.RegionId, - LocationId = location.Id, - SurveyResponseId = answer.SurveyResponseId + answer.Id, + answer.QuestionId, + answer.AnswerText, + answer.Comment, + location.RegionId, + LocationId = location.Id, + answer.SurveyResponseId }; + + //group records by answer and region var q = from e in result group e by (e.RegionId, e.AnswerText) into g - select new AggregateResult + select new { - RegionId = g.Key.RegionId, - Answers = new AggregateAnswer + g.Key.RegionId, + Answers = new { - Answer = g.Key.AnswerText, + g.Key.AnswerText, Counter = g.Count() } }; - + //build the result - List resultList = new List(); + + List resultList = new List(); foreach (Region region in regions) { - var answers = q.Where(x => x.RegionId.Equals(region.Id)).Select(x => x.Answers).ToList(); - resultList.Add(new AnswerData { RegionId = region.Id, Name = region.Name, Abbreviation = region.Abbreviation, Answers = answers }); + var answers = from u in q.ToList() + where u.RegionId.Equals(region.Id) + select u.Answers; + + resultList.Add(new { RegionId = region.Id, region.Name, region.Abbreviation, Answers = answers}); } - //return the object result - return new ResultData { Regions = resultList }; + return new { Regions = resultList }; } catch (Exception ex) { @@ -455,7 +455,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers 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(), + Questions = (from q in questions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Text }).SingleOrDefault(), Attachments = from att in attachments where att.AnswerId == ans.Id select new { att.Id, att.URI } } }; @@ -504,7 +504,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers ans.QuestionId, ans.AnswerText, ans.Comment, - Questions = (from q in surveyQuestions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Questions }).SingleOrDefault(), + Questions = (from q in surveyQuestions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Text }).SingleOrDefault(), Attachments = from att in attachments where att.AnswerId == ans.Id select new { att.Id, att.URI } } @@ -531,8 +531,6 @@ namespace DamageAssesment.Api.SurveyResponses.Providers var questions = await questionServiceProvider.getQuestionsAsync(); var attachments = await attachmentServiceProvider.getAttachmentsAsync(); - - var result = from r in surveyResonses select new { @@ -553,7 +551,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers ans.QuestionId, 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(), + Questions = (from q in questions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Text }).SingleOrDefault(), Attachments = from att in attachments where att.AnswerId == ans.Id select new { att.Id, att.URI } } }; @@ -594,7 +592,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers //get all the answers with location var surveyAnswersLocations = from surveyAns in surveyAnswers from location in locations - where surveyAns.LocationId == location.Id + where surveyAns.LocationId.Equals(location.Id) select new { surveyAns, location.MaintenanceCenter }; //aggreting the answers @@ -603,9 +601,9 @@ namespace DamageAssesment.Api.SurveyResponses.Providers select new { g.Key.MaintenanceCenter, - Answers = new AggregateAnswer + Answers = new { - Answer = g.Key.AnswerText, + g.Key.AnswerText, Counter = g.Count() } }; @@ -628,7 +626,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers } //Method to get Survey Responses by surveyId and LocationId - private async Task getSurveyResponsesBySurveyIdLocationIdAsync(int surveyId, string locationId) + private async Task getSurveyResponsesBySurveyIdLocationIdAsync(int surveyId, int locationId) { try { @@ -661,7 +659,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers ans.Id, ans.AnswerText, ans.Comment, - Questions = (from q in surveyQuestions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Questions }).SingleOrDefault(), + Questions = (from q in surveyQuestions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Text }).SingleOrDefault(), Attachments = from att in attachments where att.AnswerId == ans.Id select new { att.Id, att.URI } } }; @@ -759,8 +757,7 @@ 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, ClientDevice = request.ClientDevice, KeyAnswerResult = request.KeyAnswerResult, Latitude = Convert.ToDouble(request.Latitude), Longitute = Convert.ToDouble(request.Longitute), CreatedDate=DateTime.Now }); if (response.IsSuccess) { var surveyResponse = response.SurveyResponse; diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/AnswerServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/AnswerServiceProvider.cs index 921f59c..695ad3e 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/AnswerServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/AnswerServiceProvider.cs @@ -7,14 +7,13 @@ namespace DamageAssesment.Api.SurveyResponses.Services { public class AnswerServiceProvider : ServiceProviderBase, IAnswerServiceProvider { - public AnswerServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, "/api/Answers", configuration.GetValue("EndPointSettings:AnswerUrlBase")) + public AnswerServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, configuration.GetValue("RessourceSettings:Answer"), configuration.GetValue("EndPointSettings:AnswerUrlBase")) { } public async Task> getAnswersAsync() { try { - var url = urlBase + ressource; var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); var answers = JsonConvert.DeserializeObject>(responseJsonString); @@ -33,7 +32,7 @@ namespace DamageAssesment.Api.SurveyResponses.Services { try { - var url = urlBase + "/api/AnswersByResponse/" + responseId; + url = urlBase + string.Format(configuration.GetValue("RessourceSettings:AnswerByResponse"), responseId); var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); var answers = JsonConvert.DeserializeObject>(responseJsonString); @@ -52,7 +51,6 @@ namespace DamageAssesment.Api.SurveyResponses.Services { try { - var url = urlBase + ressource; var requestJsonString = JsonConvert.SerializeObject(answer); var responseJsonString = await httpUtil.SendAsync(HttpMethod.Post, url, requestJsonString); var answers = JsonConvert.DeserializeObject(responseJsonString); diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/AttachmentServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/AttachmentServiceProvider.cs index 9c45c72..120e60f 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/AttachmentServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/AttachmentServiceProvider.cs @@ -6,7 +6,7 @@ namespace DamageAssesment.Api.SurveyResponses.Services { public class AttachmentServiceProvider : ServiceProviderBase, IAttachmentServiceProvider { - public AttachmentServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, "/api/Attachments", configuration.GetValue("EndPointSettings:AttachmentUrlBase")) + public AttachmentServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, configuration.GetValue("RessourceSettings:Attachment"), configuration.GetValue("EndPointSettings:AttachmentUrlBase")) { } @@ -14,7 +14,6 @@ namespace DamageAssesment.Api.SurveyResponses.Services { try { - var url = urlBase + ressource; var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); var attachments = JsonConvert.DeserializeObject>(responseJsonString); @@ -33,7 +32,6 @@ namespace DamageAssesment.Api.SurveyResponses.Services { try { - var url = urlBase + ressource; var requestJsonString = JsonConvert.SerializeObject(attachmentInfo); var responseJsonString = await httpUtil.SendAsync(HttpMethod.Post, url, requestJsonString); var attachments = JsonConvert.DeserializeObject>(responseJsonString); diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/EmployeeServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/EmployeeServiceProvider.cs index 46288a8..8dd1352 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/EmployeeServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/EmployeeServiceProvider.cs @@ -1,12 +1,13 @@ using DamageAssesment.Api.SurveyResponses.Interfaces; using DamageAssesment.Api.SurveyResponses.Models; +using Microsoft.AspNetCore.Mvc.Routing; using Newtonsoft.Json; namespace DamageAssesment.Api.SurveyResponses.Services { - public class EmployeeServiceProvider :ServiceProviderBase, IEmployeeServiceProvider + public class EmployeeServiceProvider : ServiceProviderBase, IEmployeeServiceProvider { - public EmployeeServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, "/api/Employees", configuration.GetValue("EndPointSettings:EmployeeUrlBase")) + public EmployeeServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, configuration.GetValue("RessourceSettings:Employee"), configuration.GetValue("EndPointSettings:EmployeeUrlBase")) { } @@ -14,7 +15,6 @@ namespace DamageAssesment.Api.SurveyResponses.Services { try { - var url = urlBase + ressource; var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); var employees = JsonConvert.DeserializeObject>(responseJsonString); @@ -29,15 +29,15 @@ namespace DamageAssesment.Api.SurveyResponses.Services } } - public async Task getEmployeeAsync(string employeeId) + public async Task getEmployeeAsync(int employeeId) { try { - var url = urlBase + "/api/Employees/" + employeeId; + url = urlBase + string.Format(configuration.GetValue("RessourceSettings:EmployeeById"), employeeId); var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); var employee = JsonConvert.DeserializeObject(responseJsonString); - if (employee == null ) + if (employee == null) return null; else return employee; } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/LocationServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/LocationServiceProvider.cs index 07e456b..2e3fa32 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/LocationServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/LocationServiceProvider.cs @@ -6,7 +6,7 @@ namespace DamageAssesment.Api.SurveyResponses.Services { public class LocationServiceProvider :ServiceProviderBase, ILocationServiceProvider { - public LocationServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, "/api/Locations", configuration.GetValue("EndPointSettings:LocationUrlBase")) + public LocationServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, configuration.GetValue("RessourceSettings:Location"), configuration.GetValue("EndPointSettings:LocationUrlBase")) { } @@ -14,7 +14,6 @@ namespace DamageAssesment.Api.SurveyResponses.Services { try { - var url = urlBase + ressource; var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); var locations = JsonConvert.DeserializeObject>(responseJsonString); diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/QuestionServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/QuestionServiceProvider.cs index 6099141..138011f 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/QuestionServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/QuestionServiceProvider.cs @@ -6,7 +6,7 @@ namespace DamageAssesment.Api.SurveyResponses.Services { public class QuestionServiceProvider : ServiceProviderBase, IQuestionServiceProvider { - public QuestionServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, "/api/Questions", configuration.GetValue("EndPointSettings:QuestionUrlBase")) + public QuestionServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, configuration.GetValue("RessourceSettings:Question"), configuration.GetValue("EndPointSettings:QuestionUrlBase")) { } @@ -14,7 +14,6 @@ namespace DamageAssesment.Api.SurveyResponses.Services { try { - var url = urlBase + ressource; var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); var questions = JsonConvert.DeserializeObject>(responseJsonString); @@ -33,7 +32,7 @@ namespace DamageAssesment.Api.SurveyResponses.Services { try { - var url = urlBase + "/api/GetSurveyQuestions/" + surveyId; + url = urlBase + string.Format(configuration.GetValue("RessourceSettings:SurveyQuestion"), surveyId); var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); var questions = JsonConvert.DeserializeObject>(responseJsonString); @@ -53,7 +52,7 @@ namespace DamageAssesment.Api.SurveyResponses.Services { try { - var url = urlBase + "/api/Questions/" + questionId; + url = urlBase + string.Format(configuration.GetValue("RessourceSettings:QuestionById"), questionId); var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); var question = JsonConvert.DeserializeObject(responseJsonString); diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/RegionServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/RegionServiceProvider.cs index f31a1e1..091512e 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/RegionServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/RegionServiceProvider.cs @@ -6,14 +6,13 @@ namespace DamageAssesment.Api.SurveyResponses.Services { public class RegionServiceProvider : ServiceProviderBase, IRegionServiceProvider { - public RegionServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, "/api/Regions", configuration.GetValue("EndPointSettings:LocationUrlBase")) + public RegionServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, configuration.GetValue("RessourceSettings:Region"), configuration.GetValue("EndPointSettings:LocationUrlBase")) { } public async Task> getRegionsAsync() { try { - var url = urlBase + ressource; var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); var regions = JsonConvert.DeserializeObject>(responseJsonString); diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/ServiceProviderBase.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/ServiceProviderBase.cs index 487975b..af1aa65 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/ServiceProviderBase.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/ServiceProviderBase.cs @@ -9,6 +9,7 @@ namespace DamageAssesment.Api.SurveyResponses.Services protected readonly ILogger logger; protected string ressource; protected string urlBase; + protected string url; public ServiceProviderBase(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger, string ressource, string urlBase) @@ -18,6 +19,7 @@ namespace DamageAssesment.Api.SurveyResponses.Services this.logger = logger; this.ressource = ressource; this.urlBase = urlBase; + url = urlBase + ressource; } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/SurveyServiceProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/SurveyServiceProvider.cs index 616afb2..c9df4db 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/SurveyServiceProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/Services/SurveyServiceProvider.cs @@ -6,7 +6,7 @@ namespace DamageAssesment.Api.SurveyResponses.Services { public class SurveyServiceProvider :ServiceProviderBase, ISurveyServiceProvider { - public SurveyServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, "/api/Surveys", configuration.GetValue("EndPointSettings:SurveyUrlBase")) + public SurveyServiceProvider(IConfiguration configuration, IHttpUtil httpUtil, ILogger logger) : base(configuration, httpUtil, logger, configuration.GetValue("RessourceSettings:Survey"), configuration.GetValue("EndPointSettings:SurveyUrlBase")) { } @@ -14,8 +14,6 @@ namespace DamageAssesment.Api.SurveyResponses.Services { try { - - var url = urlBase + ressource; var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); var surveys = JsonConvert.DeserializeObject>(responseJsonString); @@ -34,7 +32,7 @@ namespace DamageAssesment.Api.SurveyResponses.Services { try { - var url = urlBase + ressource + "/" + surveyId; + url = urlBase + string.Format(configuration.GetValue("RessourceSettings:SurveyById"), surveyId); var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null); var survey = JsonConvert.DeserializeObject(responseJsonString); diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.Development.json b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.Development.json index 0c208ae..06d7caa 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.Development.json +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.Development.json @@ -3,6 +3,30 @@ "LogLevel": { "Default": "Information", "Microsoft.AspNetCore": "Warning" + }, + "EndPointSettings": { + "AnswerUrlBase": "http://localhost:5200", + "LocationUrlBase": "http://localhost:5213", + "RegionUrlBase": "http://localhost:5211", + "QuestionUrlBase": "http://localhost:5133", + "EmployeeUrlBase": "http://localhost:5135", + "AttachmentUrlBase": "http://localhost:5243", + "SurveyUrlBase": "http://localhost:5009" + }, + + "RessourceSettings": { + "Employee": "/Employees", + "EmployeeById": "/Employees/{0}", + "Question": "/Questions", + "QuestionById": "/Questions/{0}", + "SurveyQuestion": "/Questions/BySurvey/{0}", + "Survey": "/Surveys", + "SurveyById": "/Surveys/{0}", + "Attachment": "/Attachments", + "Answer": "/Answers", + "AnswerByResponse": "/Answers/ByResponse/{0}", + "Location": "/Locations", + "Region": "/Regions" } } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.Production.json b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.Production.json new file mode 100644 index 0000000..ba719e5 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.Production.json @@ -0,0 +1,5 @@ +{ + "ConnectionStrings": { + "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true" + } +} \ No newline at end of file diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.Test.json b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.Test.json new file mode 100644 index 0000000..ba719e5 --- /dev/null +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.Test.json @@ -0,0 +1,5 @@ +{ + "ConnectionStrings": { + "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=_CHANGE_ME;Trusted_Connection=True;MultipleActiveResultSets=true" + } +} \ No newline at end of file diff --git a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.json b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.json index 2d6dfe4..d7b64fc 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.json +++ b/DamageAssesmentApi/DamageAssesment.Api.SurveyResponses/appsettings.json @@ -14,6 +14,20 @@ "EmployeeUrlBase": "http://localhost:5135", "AttachmentUrlBase": "http://localhost:5243", "SurveyUrlBase": "http://localhost:5009" + }, + "RessourceSettings": { + "Employee": "/Employees", + "EmployeeById": "/Employees/{0}", + "Question": "/Questions", + "QuestionById": "/Questions/{0}", + "SurveyQuestion": "/Questions/BySurvey/{0}", + "Survey": "/Surveys", + "SurveyById": "/Surveys/{0}", + "Attachment": "/Attachments", + "Answer": "/Answers", + "AnswerByResponse": "/Answers/ByResponse/{0}", + "Location": "/Locations", + "Region": "/Regions" } } diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/Survey.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/Survey.cs index f79158b..25f5405 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/Survey.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Models/Survey.cs @@ -9,7 +9,6 @@ namespace DamageAssesment.Api.Surveys.Models public class Survey : BaseSurvey { public IEnumerable Titles { get; set; } - } public class BaseSurvey { diff --git a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs index f843216..df04662 100644 --- a/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs +++ b/DamageAssesmentApi/DamageAssesment.Api.Surveys/Providers/SurveysProvider.cs @@ -184,17 +184,15 @@ namespace DamageAssesment.Api.Surveys.Providers { if (survey != null) { - var _survey = await surveyDbContext.Surveys.Where(s => s.Id == Id).SingleOrDefaultAsync(); + var _survey = await surveyDbContext.Surveys.AsNoTracking().Where(s => s.Id == Id).SingleOrDefaultAsync(); if (_survey != null) { var surveysTranslation = await surveyDbContext.SurveysTranslation.Where(s => s.SurveyId == Id).ToListAsync(); surveyDbContext.SurveysTranslation.RemoveRange(surveysTranslation); await surveyDbContext.SaveChangesAsync(); - - _survey.IsEnabled = survey.IsEnabled; - _survey.StartDate = survey.StartDate; - _survey.EndDate = survey.EndDate; + _survey = mapper.Map(survey); + surveyDbContext.Surveys.Update(_survey); await surveyDbContext.SaveChangesAsync(); List listSurveyTranslation = new List(); diff --git a/DamageAssesmentApi/DamageAssesment.SurveyResponses.Test/MockData.cs b/DamageAssesmentApi/DamageAssesment.SurveyResponses.Test/MockData.cs index d70772d..5be421f 100644 --- a/DamageAssesmentApi/DamageAssesment.SurveyResponses.Test/MockData.cs +++ b/DamageAssesmentApi/DamageAssesment.SurveyResponses.Test/MockData.cs @@ -24,7 +24,7 @@ namespace DamageAssesment.Api.SurveyResponses.Test public static async Task getSurveyResponseObject() { - return new Models.SurveyResponse { EmployeeId = "Emp1", LocationId = "Loc1", SurveyId = 1, Id = 1 }; + return new Models.SurveyResponse { EmployeeId = 1, LocationId = 1, SurveyId = 1, Id = 1 }; } } } diff --git a/DamageAssesmentApi/DamageAssesment.SurveyResponses.Test/SurveyResponsesServiceTest.cs b/DamageAssesmentApi/DamageAssesment.SurveyResponses.Test/SurveyResponsesServiceTest.cs index 182ec5c..47685a5 100644 --- a/DamageAssesmentApi/DamageAssesment.SurveyResponses.Test/SurveyResponsesServiceTest.cs +++ b/DamageAssesmentApi/DamageAssesment.SurveyResponses.Test/SurveyResponsesServiceTest.cs @@ -68,9 +68,9 @@ namespace DamageAssesment.SurveyResponses.Test { SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject(); var mockResponse = await MockData.getOkResponse(); - mockSurveyResponseService.Setup(service => service.GetSurveyResponsesBySurveyAndLocationAsync(1, "Loc1")).ReturnsAsync(mockResponse); + mockSurveyResponseService.Setup(service => service.GetSurveyResponsesBySurveyAndLocationAsync(1, 1)).ReturnsAsync(mockResponse); var surveyResponseProvider = new SurveyResponsesController(mockSurveyResponseService.Object); - var result = (OkObjectResult)await surveyResponseProvider.GetSurveyResponsesBySurveyAndLocationAsync(1, "Loc1"); + var result = (OkObjectResult)await surveyResponseProvider.GetSurveyResponsesBySurveyAndLocationAsync(1, 1); Assert.Equal(200, result.StatusCode); } @@ -78,9 +78,9 @@ namespace DamageAssesment.SurveyResponses.Test public async Task GetSurveyResponsesBySurveyLocationAsync_ShouldReturnStatusCode204() { var mockResponse = await MockData.getResponse(); - mockSurveyResponseService.Setup(service => service.GetSurveyResponsesBySurveyAndLocationAsync(1, "Loc1")).ReturnsAsync(mockResponse); + mockSurveyResponseService.Setup(service => service.GetSurveyResponsesBySurveyAndLocationAsync(1, 1)).ReturnsAsync(mockResponse); var surveyResponseProvider = new SurveyResponsesController(mockSurveyResponseService.Object); - var result = (NoContentResult)await surveyResponseProvider.GetSurveyResponsesBySurveyAndLocationAsync(1, "Lo1"); + var result = (NoContentResult)await surveyResponseProvider.GetSurveyResponsesBySurveyAndLocationAsync(1, 1); Assert.Equal(204, result.StatusCode); }