forked from MDCPS/DamageAssessment_Backend
		
	Compare commits
	
		
			9 Commits
		
	
	
		
			DocumentsA
			...
			DbContext_
		
	
	| Author | SHA1 | Date | |
|---|---|---|---|
| 82f2ae265a | |||
| 099055d088 | |||
| fe1614fee3 | |||
| 448950ea27 | |||
| 47b0c7b202 | |||
| cf3a04891b | |||
| e56ffae1a4 | |||
| 9345ee2ca5 | |||
| 22261f42ca | 
@ -95,10 +95,10 @@ namespace DamageAssesment.Api.Answers.Test
 | 
			
		||||
            var mockAnswerService = new Mock<IAnswersProvider>();
 | 
			
		||||
            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<IAnswersProvider>();
 | 
			
		||||
            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<IAnswersProvider>();
 | 
			
		||||
            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<IAnswersProvider>();
 | 
			
		||||
            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<IAnswersProvider>();
 | 
			
		||||
            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);
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
@ -43,9 +43,9 @@ namespace DamageAssesment.Api.Answers.Test
 | 
			
		||||
            return (false, list, null);
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        public static async Task<Answers.Db.Answer> getInputAnswerData()
 | 
			
		||||
        public static async Task<Answers.Models.Answer> 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 };
 | 
			
		||||
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
@ -14,7 +14,10 @@ namespace DamageAssesment.Api.Answers.Controllers
 | 
			
		||||
        public AnswersController(IAnswersProvider answersProvider) { 
 | 
			
		||||
        this.answerProvider=answersProvider;
 | 
			
		||||
        }
 | 
			
		||||
        //get all answers
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// Get all answers
 | 
			
		||||
        /// </summary>
 | 
			
		||||
        
 | 
			
		||||
        [HttpGet("Answers")]
 | 
			
		||||
        public async Task<ActionResult> GetAnswersAsync() {
 | 
			
		||||
        
 | 
			
		||||
@ -26,7 +29,11 @@ namespace DamageAssesment.Api.Answers.Controllers
 | 
			
		||||
               return NoContent();
 | 
			
		||||
 | 
			
		||||
        }
 | 
			
		||||
        //get answer based on answerid
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// Get an answer based on answerId.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
        [HttpGet("Answers/{Id}")]
 | 
			
		||||
        public async Task<ActionResult> GetAnswerByIdAsync(int Id)
 | 
			
		||||
        {
 | 
			
		||||
@ -39,7 +46,9 @@ namespace DamageAssesment.Api.Answers.Controllers
 | 
			
		||||
            return NotFound();
 | 
			
		||||
 | 
			
		||||
        }
 | 
			
		||||
        // get all answers based on response id
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// Get all answers based on responseId.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
        [HttpGet("AnswersByResponse/{ResponseId}")]
 | 
			
		||||
        public async Task<IActionResult> GetAnswersByResponseId(int ResponseId)
 | 
			
		||||
        {
 | 
			
		||||
@ -50,7 +59,10 @@ namespace DamageAssesment.Api.Answers.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return NoContent();
 | 
			
		||||
        }
 | 
			
		||||
        // get all answers based on question id
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// Get all answers based on questionId.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpGet("AnswersByQuestion/{QuestionId}")]
 | 
			
		||||
        public async Task<IActionResult> AnswersByQuestionId(int QuestionId)
 | 
			
		||||
        {
 | 
			
		||||
@ -61,14 +73,16 @@ namespace DamageAssesment.Api.Answers.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return NotFound();
 | 
			
		||||
        }
 | 
			
		||||
        //update existing answer
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// Update an existing answer.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpPut("Answers")]
 | 
			
		||||
        public async Task<IActionResult> UpdateAnswer(Db.Answer answer)
 | 
			
		||||
        public IActionResult UpdateAnswer(Models.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);
 | 
			
		||||
@ -80,13 +94,16 @@ namespace DamageAssesment.Api.Answers.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return NotFound();
 | 
			
		||||
        }
 | 
			
		||||
        //save new answer
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// Save a new answer.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpPost("Answers")]
 | 
			
		||||
        public async Task<IActionResult> CreateAnswer(Db.Answer answer)
 | 
			
		||||
        public IActionResult CreateAnswer(Models.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);
 | 
			
		||||
@ -95,7 +112,10 @@ namespace DamageAssesment.Api.Answers.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return CreatedAtRoute("DefaultApi", new { id = answer.Id }, answer);
 | 
			
		||||
        }
 | 
			
		||||
        //delete existing answer
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        ///  Delete an existing answer.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpDelete("Answers/{id}")]
 | 
			
		||||
        public async Task<IActionResult> DeleteAnswer(int id)
 | 
			
		||||
        {
 | 
			
		||||
 | 
			
		||||
@ -4,10 +4,12 @@
 | 
			
		||||
    <TargetFramework>net6.0</TargetFramework>
 | 
			
		||||
    <Nullable>enable</Nullable>
 | 
			
		||||
    <ImplicitUsings>enable</ImplicitUsings>
 | 
			
		||||
    <GenerateDocumentationFile>True</GenerateDocumentationFile>
 | 
			
		||||
  </PropertyGroup>
 | 
			
		||||
 | 
			
		||||
  <ItemGroup>
 | 
			
		||||
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
 | 
			
		||||
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.21" />
 | 
			
		||||
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.9" />
 | 
			
		||||
    <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.9" />
 | 
			
		||||
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
 | 
			
		||||
 | 
			
		||||
@ -10,7 +10,13 @@ namespace DamageAssesment.Api.Answers.Db
 | 
			
		||||
            
 | 
			
		||||
        }
 | 
			
		||||
        public DbSet<Db.Answer> Answers { get; set; }
 | 
			
		||||
       
 | 
			
		||||
        protected override void OnModelCreating(ModelBuilder modelBuilder)
 | 
			
		||||
        {
 | 
			
		||||
            base.OnModelCreating(modelBuilder);
 | 
			
		||||
            modelBuilder.Entity<Answer>()
 | 
			
		||||
                .Property(item => item.Id)
 | 
			
		||||
                .ValueGeneratedOnAdd();
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@ -6,8 +6,8 @@
 | 
			
		||||
        Task<(bool IsSuccess, IEnumerable<Models.Answer> Answers, string ErrorMessage)> GetAnswersByQuestionAsync(int questionId);
 | 
			
		||||
        Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> GetAnswerByIdAsync(int Id);
 | 
			
		||||
        Task<(bool IsSuccess, IEnumerable<Models.Answer> 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(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);
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@ -7,6 +7,7 @@ namespace DamageAssesment.Api.Answers.Profiles
 | 
			
		||||
        public AnswersProfile()
 | 
			
		||||
        {
 | 
			
		||||
            CreateMap<Db.Answer,Models.Answer>();
 | 
			
		||||
            CreateMap<Models.Answer, Db.Answer>();
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@ -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<IAnswersProvider, AnswersProvider>();
 | 
			
		||||
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); //4/30
 | 
			
		||||
builder.Services.AddDbContext<AnswerDbContext>(option =>
 | 
			
		||||
 | 
			
		||||
@ -108,16 +108,17 @@ 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(Models.Answer Answer)
 | 
			
		||||
        {
 | 
			
		||||
            try
 | 
			
		||||
            {
 | 
			
		||||
                logger?.LogInformation("Query Answer");
 | 
			
		||||
                if (!AnswerExists(Answer.Id))
 | 
			
		||||
                {
 | 
			
		||||
                    answerDbContext.Answers.Add(Answer);
 | 
			
		||||
                    Db.Answer answer = mapper.Map<Models.Answer, Db.Answer>(Answer);
 | 
			
		||||
                    answerDbContext.Answers.Add(answer);
 | 
			
		||||
                    answerDbContext.SaveChanges();
 | 
			
		||||
                    var result = mapper.Map<Db.Answer, Models.Answer>(Answer);
 | 
			
		||||
                    var result = mapper.Map<Db.Answer, Models.Answer>(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 async Task<(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<Models.Answer, Db.Answer>(Answer);
 | 
			
		||||
                        answerDbContext.Answers.Update(answer);
 | 
			
		||||
                        answerDbContext.SaveChanges();
 | 
			
		||||
                        return (true, mapper.Map<Db.Answer, Models.Answer>(Answer), "Successful");
 | 
			
		||||
                        return (true, mapper.Map<Db.Answer, Models.Answer>(answer), "Successful");
 | 
			
		||||
                    }
 | 
			
		||||
                    else
 | 
			
		||||
                    {
 | 
			
		||||
 | 
			
		||||
@ -1,4 +1,7 @@
 | 
			
		||||
{
 | 
			
		||||
  "JwtSettings": {
 | 
			
		||||
    "securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk="
 | 
			
		||||
  },
 | 
			
		||||
  "Logging": {
 | 
			
		||||
    "LogLevel": {
 | 
			
		||||
      "Default": "Information",
 | 
			
		||||
 | 
			
		||||
@ -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<IUploadService>();
 | 
			
		||||
            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<IUploadService>();
 | 
			
		||||
            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);
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
@ -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<List<Attachments.Db.Attachment>> getInputAttachmentData()
 | 
			
		||||
        public static async Task<List<Attachments.Models.Attachment>> getInputAttachmentData()
 | 
			
		||||
        {
 | 
			
		||||
            List<Attachments.Db.Attachment> Attachments=new List<Db.Attachment>();
 | 
			
		||||
            Attachments.Add(new Db.Attachment{ Id = 0, AnswerId = 10, ResponseId = 10, URI = "sample", IsDeleted = false,FileName="sample1" }) ;
 | 
			
		||||
            List<Attachments.Models.Attachment> Attachments=new List<Models.Attachment>();
 | 
			
		||||
            Attachments.Add(new Models.Attachment{ Id = 0, AnswerId = 10, ResponseId = 10, URI = "sample", IsDeleted = false,FileName="sample1" }) ;
 | 
			
		||||
            return Attachments;
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
@ -19,7 +19,10 @@ namespace DamageAssesment.Api.Attachments.Controllers
 | 
			
		||||
            this.AttachmentProvider = AttachmentsProvider;
 | 
			
		||||
            this.UploadService = uploadService;  
 | 
			
		||||
        }
 | 
			
		||||
        //get all Attachments
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// Get all attachments.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpGet("Attachments")]
 | 
			
		||||
        public async Task<ActionResult> GetAttachmentsAsync()
 | 
			
		||||
        {
 | 
			
		||||
@ -32,7 +35,9 @@ namespace DamageAssesment.Api.Attachments.Controllers
 | 
			
		||||
            return NoContent();
 | 
			
		||||
 | 
			
		||||
        }
 | 
			
		||||
        //get all Attachment by Id
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// Get all attachments by attachmentId.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
        [HttpGet("Attachments/{id}")]
 | 
			
		||||
        public async Task<ActionResult> GetAttachmentbyIdAsync(int id)
 | 
			
		||||
        {
 | 
			
		||||
@ -73,17 +78,20 @@ namespace DamageAssesment.Api.Attachments.Controllers
 | 
			
		||||
        //    }
 | 
			
		||||
        //}
 | 
			
		||||
 | 
			
		||||
        //Save new Attachment
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// Save new Attachment(s)
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpPost("Attachments"), DisableRequestSizeLimit]
 | 
			
		||||
        public async Task<IActionResult> UploadAttachmentAsync(AttachmentInfo attachmentInfo)
 | 
			
		||||
        public IActionResult UploadAttachmentAsync(AttachmentInfo attachmentInfo)
 | 
			
		||||
        {
 | 
			
		||||
            try
 | 
			
		||||
            {
 | 
			
		||||
                if (attachmentInfo.Answers.Count > 0)
 | 
			
		||||
                {
 | 
			
		||||
                    var Attachments = await this.AttachmentProvider.GetAttachmentCounter();
 | 
			
		||||
                    List<Db.Attachment> attachments = UploadService.UploadAttachment(attachmentInfo.ResponseId, Attachments.counter, attachmentInfo.Answers);
 | 
			
		||||
                    var result = await this.AttachmentProvider.PostAttachmentAsync(attachments);
 | 
			
		||||
                    var Attachments =  this.AttachmentProvider.GetAttachmentCounter();
 | 
			
		||||
                    List<Models.Attachment> attachments = UploadService.UploadAttachment(attachmentInfo.ResponseId, Attachments.counter, attachmentInfo.Answers);
 | 
			
		||||
                    var result =  this.AttachmentProvider.PostAttachmentAsync(attachments);
 | 
			
		||||
                    if (result.IsSuccess)
 | 
			
		||||
                    {
 | 
			
		||||
                        return Ok(result.Attachments);
 | 
			
		||||
@ -97,20 +105,22 @@ namespace DamageAssesment.Api.Attachments.Controllers
 | 
			
		||||
                return BadRequest($"Internal server error: {ex}");
 | 
			
		||||
            }
 | 
			
		||||
        }
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// Modify an new attachment.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        //Save new Attachment
 | 
			
		||||
        [HttpPut("Attachments"), DisableRequestSizeLimit]
 | 
			
		||||
        public async Task<IActionResult> 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<Db.Attachment> attachments = UploadService.UpdateAttachments(attachmentInfo.ResponseId, attachmentInfo.Answers, res.Attachments);
 | 
			
		||||
                        var result = await this.AttachmentProvider.PutAttachmentAsync(attachments);
 | 
			
		||||
                        List<Models.Attachment> attachments = UploadService.UpdateAttachments(attachmentInfo.ResponseId, attachmentInfo.Answers, res.Attachments);
 | 
			
		||||
                        var result = this.AttachmentProvider.PutAttachmentAsync(attachments);
 | 
			
		||||
                        if (result.IsSuccess)
 | 
			
		||||
                        {
 | 
			
		||||
                            return Ok(result.Attachments);
 | 
			
		||||
@ -126,7 +136,9 @@ namespace DamageAssesment.Api.Attachments.Controllers
 | 
			
		||||
                return BadRequest($"Internal server error: {ex}");
 | 
			
		||||
            }
 | 
			
		||||
        }
 | 
			
		||||
        //delete existing Attachment
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// Delete an existing attachment.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
        [HttpDelete("Delete")]
 | 
			
		||||
        public async Task<IActionResult> DeleteAttachment(int Id)
 | 
			
		||||
        {
 | 
			
		||||
 | 
			
		||||
@ -4,11 +4,13 @@
 | 
			
		||||
    <TargetFramework>net6.0</TargetFramework>
 | 
			
		||||
    <Nullable>enable</Nullable>
 | 
			
		||||
    <ImplicitUsings>enable</ImplicitUsings>
 | 
			
		||||
    <GenerateDocumentationFile>True</GenerateDocumentationFile>
 | 
			
		||||
  </PropertyGroup>
 | 
			
		||||
 | 
			
		||||
  <ItemGroup>
 | 
			
		||||
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
 | 
			
		||||
    <PackageReference Include="Azure.Storage.Blobs" Version="12.16.0" />
 | 
			
		||||
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.21" />
 | 
			
		||||
    <PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.7" />
 | 
			
		||||
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
 | 
			
		||||
    <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.5" />
 | 
			
		||||
 | 
			
		||||
@ -8,5 +8,12 @@ namespace DamageAssesment.Api.Attachments.Db
 | 
			
		||||
        {
 | 
			
		||||
        }
 | 
			
		||||
        public DbSet<Db.Attachment> Attachments { get; set; }
 | 
			
		||||
        protected override void OnModelCreating(ModelBuilder modelBuilder)
 | 
			
		||||
        {
 | 
			
		||||
            base.OnModelCreating(modelBuilder);
 | 
			
		||||
            modelBuilder.Entity<Attachment>()
 | 
			
		||||
                .Property(item => item.Id)
 | 
			
		||||
                .ValueGeneratedOnAdd();
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@ -6,12 +6,12 @@ namespace DamageAssesment.Api.Attachments.Interfaces
 | 
			
		||||
    {
 | 
			
		||||
        Task<(bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage)> GetAttachmentsAsync();
 | 
			
		||||
        Task<(bool IsSuccess, Models.Attachment Attachment, string ErrorMessage)> GetAttachmentByIdAsync(int Id);
 | 
			
		||||
        Task<(bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage)> PostAttachmentAsync(List<Db.Attachment> Attachments);
 | 
			
		||||
        Task<(bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage)> PutAttachmentAsync(List<Db.Attachment> Attachments);
 | 
			
		||||
        (bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage) PostAttachmentAsync(List<Models.Attachment> Attachments);
 | 
			
		||||
        (bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage) PutAttachmentAsync(List<Models.Attachment> 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<int> answerIds);
 | 
			
		||||
        Task<(bool IsSuccess, int counter, string message)> GetAttachmentCounter();
 | 
			
		||||
        Task<(bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage)> GetAttachmentInfo(List<AnswerInfo> answers);
 | 
			
		||||
        (bool IsSuccess, int counter, string message) GetAttachmentCounter();
 | 
			
		||||
        (bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage) GetAttachmentInfo(List<AnswerInfo> answers);
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@ -4,9 +4,9 @@ namespace DamageAssesment.Api.Attachments.Interfaces
 | 
			
		||||
{
 | 
			
		||||
    public interface IUploadService
 | 
			
		||||
    {
 | 
			
		||||
        List<Db.Attachment> UploadAttachment(int responseId,int answerId, int counter, List<IFormFile> postedFile);
 | 
			
		||||
        List<Db.Attachment> UploadAttachment(int responseId, int counter, List<AnswerInfo> answers);
 | 
			
		||||
        public List<Db.Attachment> UpdateAttachments(int responseId, List<AnswerInfo> answers, IEnumerable<Models.Attachment> attachments);
 | 
			
		||||
        List<Models.Attachment> UploadAttachment(int responseId,int answerId, int counter, List<IFormFile> postedFile);
 | 
			
		||||
        List<Models.Attachment> UploadAttachment(int responseId, int counter, List<AnswerInfo> answers);
 | 
			
		||||
        public List<Models.Attachment> UpdateAttachments(int responseId, List<AnswerInfo> answers, IEnumerable<Models.Attachment> attachments);
 | 
			
		||||
        void Deletefile(string path);
 | 
			
		||||
        void Movefile(string path);
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
@ -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;
 | 
			
		||||
        //}
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@ -5,6 +5,7 @@
 | 
			
		||||
        public AttachmentsProfiles()
 | 
			
		||||
        {
 | 
			
		||||
            CreateMap<Db.Attachment, Models.Attachment>();
 | 
			
		||||
            CreateMap<Models.Attachment, Db.Attachment>();
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@ -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<IAttachmentsProvider, AttachmentsProvider>();
 | 
			
		||||
builder.Services.AddScoped<IUploadService, UploadService>();
 | 
			
		||||
builder.Services.AddScoped<IAzureBlobService,AzureBlobService>();
 | 
			
		||||
 | 
			
		||||
@ -65,14 +65,15 @@ namespace DamageAssesment.Api.Attachments.Providers
 | 
			
		||||
                return (false, null, ex.Message);
 | 
			
		||||
            }
 | 
			
		||||
        }
 | 
			
		||||
        public async Task<(bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage)> PostAttachmentAsync(List<Db.Attachment> Attachments)
 | 
			
		||||
        public (bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage) PostAttachmentAsync(List<Models.Attachment> Attachments)
 | 
			
		||||
        {
 | 
			
		||||
            try
 | 
			
		||||
            {
 | 
			
		||||
                logger?.LogInformation("Query Attachment");
 | 
			
		||||
                AttachmentDbContext.Attachments.AddRange(Attachments);
 | 
			
		||||
                List<Db.Attachment> attachments = mapper.Map<List<Models.Attachment>, List<Db.Attachment>>(Attachments);
 | 
			
		||||
                AttachmentDbContext.Attachments.AddRange(attachments);
 | 
			
		||||
                AttachmentDbContext.SaveChanges();
 | 
			
		||||
                var result = mapper.Map<IEnumerable<Db.Attachment>, IEnumerable<Models.Attachment>>(Attachments);
 | 
			
		||||
                var result = mapper.Map<IEnumerable<Db.Attachment>, IEnumerable<Models.Attachment>>(attachments);
 | 
			
		||||
                return (true, result, null);
 | 
			
		||||
            }
 | 
			
		||||
            catch (Exception ex)
 | 
			
		||||
@ -82,14 +83,15 @@ namespace DamageAssesment.Api.Attachments.Providers
 | 
			
		||||
            }
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        public async Task<(bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage)> PutAttachmentAsync(List<Db.Attachment> Attachments)
 | 
			
		||||
        public (bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage) PutAttachmentAsync(List<Models.Attachment> Attachments)
 | 
			
		||||
        {
 | 
			
		||||
            try
 | 
			
		||||
            {
 | 
			
		||||
                logger?.LogInformation("Query Attachment");
 | 
			
		||||
                AttachmentDbContext.Attachments.UpdateRange(Attachments);
 | 
			
		||||
                List<Db.Attachment> attachments = mapper.Map<List<Models.Attachment>, List<Db.Attachment>>(Attachments);
 | 
			
		||||
                AttachmentDbContext.Attachments.UpdateRange(attachments);
 | 
			
		||||
                AttachmentDbContext.SaveChanges();
 | 
			
		||||
                var result = mapper.Map<IEnumerable<Db.Attachment>, IEnumerable<Models.Attachment>>(Attachments);
 | 
			
		||||
                var result = mapper.Map<IEnumerable<Db.Attachment>, IEnumerable<Models.Attachment>>(attachments);
 | 
			
		||||
                return (true, result, null);
 | 
			
		||||
            }
 | 
			
		||||
            catch (Exception ex)
 | 
			
		||||
@ -119,7 +121,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 +154,7 @@ namespace DamageAssesment.Api.Attachments.Providers
 | 
			
		||||
                return (false, AttachmentId, "");
 | 
			
		||||
            }
 | 
			
		||||
        }
 | 
			
		||||
        public async Task<(bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage)>GetAttachmentInfo(List<AnswerInfo> answers)
 | 
			
		||||
        public (bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage) GetAttachmentInfo(List<AnswerInfo> answers)
 | 
			
		||||
        {
 | 
			
		||||
            try
 | 
			
		||||
            {
 | 
			
		||||
@ -204,10 +206,11 @@ namespace DamageAssesment.Api.Attachments.Providers
 | 
			
		||||
                FileModel fileModel= new FileModel(){AttachmentId=0,FileName="Sample",FileContent= "c2FtcGxl",FileExtension=".txt"};
 | 
			
		||||
                List<AnswerInfo> answerInfos=new List<AnswerInfo>();
 | 
			
		||||
                answerInfos.Add(new AnswerInfo(){ AnswerId = 1,postedFiles=new List<FileModel> { fileModel }});
 | 
			
		||||
                List<Db.Attachment> attachments = uploadservice.UploadAttachment(1, 0, answerInfos);
 | 
			
		||||
                List<Models.Attachment> attachments = uploadservice.UploadAttachment(1, 0, answerInfos);
 | 
			
		||||
                if (attachments.Count > 0)
 | 
			
		||||
                {
 | 
			
		||||
                    AttachmentDbContext.Attachments.AddRange(attachments);
 | 
			
		||||
                    List<Db.Attachment> Attachments = mapper.Map<List<Models.Attachment>, List<Db.Attachment>>(attachments);
 | 
			
		||||
                    AttachmentDbContext.Attachments.AddRange(Attachments);
 | 
			
		||||
                    AttachmentDbContext.SaveChanges();
 | 
			
		||||
                }
 | 
			
		||||
            }
 | 
			
		||||
 | 
			
		||||
@ -24,7 +24,7 @@ namespace DamageAssesment.Api.Attachments.Providers
 | 
			
		||||
            uploadpath = configuration.GetValue<string>("Fileupload:folderpath");
 | 
			
		||||
            Deletepath = configuration.GetValue<string>("Fileupload:Deletepath");
 | 
			
		||||
        }
 | 
			
		||||
        public List<Db.Attachment> UploadAttachment(int responseId,int answerId,int counter, List<IFormFile> postedFile)
 | 
			
		||||
        public List<Models.Attachment> UploadAttachment(int responseId,int answerId,int counter, List<IFormFile> postedFile)
 | 
			
		||||
        {
 | 
			
		||||
            var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), uploadpath);
 | 
			
		||||
            String responseDirectory = "Response-" + responseId;
 | 
			
		||||
@ -42,7 +42,7 @@ namespace DamageAssesment.Api.Attachments.Providers
 | 
			
		||||
                    Deletefile(searchFile);
 | 
			
		||||
                }
 | 
			
		||||
            }
 | 
			
		||||
            List<Db.Attachment> attachments = new List<Db.Attachment>();
 | 
			
		||||
            List<Models.Attachment> attachments = new List<Models.Attachment>();
 | 
			
		||||
            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<Db.Attachment> UploadAttachment(int responseId, int counter,List<AnswerInfo> answers)
 | 
			
		||||
        public List<Models.Attachment> UploadAttachment(int responseId, int counter,List<AnswerInfo> answers)
 | 
			
		||||
        {
 | 
			
		||||
            List<Db.Attachment> attachments = new List<Db.Attachment>();
 | 
			
		||||
            List<Models.Attachment> attachments = new List<Models.Attachment>();
 | 
			
		||||
            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<Db.Attachment>();
 | 
			
		||||
                return new List<Models.Attachment>();
 | 
			
		||||
            }
 | 
			
		||||
 | 
			
		||||
           
 | 
			
		||||
        }
 | 
			
		||||
        public List<Db.Attachment> UpdateAttachments(int responseId,List<AnswerInfo> answers,IEnumerable<Models.Attachment> attachments)
 | 
			
		||||
        public List<Models.Attachment> UpdateAttachments(int responseId,List<AnswerInfo> answers,IEnumerable<Models.Attachment> attachments)
 | 
			
		||||
        {
 | 
			
		||||
            List<Db.Attachment> Dbattachments = new List<Db.Attachment>();
 | 
			
		||||
            List<Models.Attachment> Dbattachments = new List<Models.Attachment>();
 | 
			
		||||
            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;
 | 
			
		||||
 | 
			
		||||
@ -1,4 +1,7 @@
 | 
			
		||||
{
 | 
			
		||||
  "JwtSettings": {
 | 
			
		||||
    "securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk="
 | 
			
		||||
  },
 | 
			
		||||
  "Logging": {
 | 
			
		||||
    "LogLevel": {
 | 
			
		||||
      "Default": "Information",
 | 
			
		||||
 | 
			
		||||
@ -15,7 +15,11 @@ namespace DamageAssesment.Api.Employees.Controllers
 | 
			
		||||
        {
 | 
			
		||||
            this.EmployeeProvider = EmployeesProvider;
 | 
			
		||||
        }
 | 
			
		||||
        //get all Employees
 | 
			
		||||
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// GET request for retrieving employees.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpGet("Employees")]
 | 
			
		||||
        public async Task<ActionResult> GetEmployeesAsync()
 | 
			
		||||
        {
 | 
			
		||||
@ -28,7 +32,11 @@ namespace DamageAssesment.Api.Employees.Controllers
 | 
			
		||||
            return NoContent();
 | 
			
		||||
 | 
			
		||||
        }
 | 
			
		||||
        //get Employee based on Employeeid
 | 
			
		||||
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// GET request for retrieving an employee by ID.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
        
 | 
			
		||||
        [HttpGet("Employees/{Id}")]
 | 
			
		||||
        public async Task<ActionResult> GetEmployeeByIdAsync(string Id)
 | 
			
		||||
        {
 | 
			
		||||
@ -41,8 +49,11 @@ namespace DamageAssesment.Api.Employees.Controllers
 | 
			
		||||
            return NotFound();
 | 
			
		||||
 | 
			
		||||
        }
 | 
			
		||||
        //update existing Employee
 | 
			
		||||
   
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// PUT request for updating an existing employee.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
        /// <param name="Employee">The updated employee object.</param>
 | 
			
		||||
        [HttpPut("Employees")]
 | 
			
		||||
        public async Task<IActionResult> UpdateEmployee(Db.Employee Employee)
 | 
			
		||||
        {
 | 
			
		||||
@ -60,7 +71,11 @@ namespace DamageAssesment.Api.Employees.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return NotFound();
 | 
			
		||||
        }
 | 
			
		||||
        //save new Employee
 | 
			
		||||
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// POST request for creating a new employee.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
        /// <param name="Employee">The employee information for creating a new employee.</param>
 | 
			
		||||
        [HttpPost("Employees")]
 | 
			
		||||
        public async Task<IActionResult> CreateEmployee(Db.Employee Employee)
 | 
			
		||||
        {
 | 
			
		||||
@ -75,7 +90,10 @@ namespace DamageAssesment.Api.Employees.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return CreatedAtRoute("DefaultApi", new { id = Employee.Id }, Employee);
 | 
			
		||||
        }
 | 
			
		||||
        //delete existing Employee
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// DELETE request for deleting an existing employee.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
        /// <param name="id">The ID of the employee to be deleted.</param>
 | 
			
		||||
        [HttpDelete("Employees/{id}")]
 | 
			
		||||
        public async Task<IActionResult> DeleteEmployee(string id)
 | 
			
		||||
        {
 | 
			
		||||
 | 
			
		||||
@ -1,13 +1,15 @@
 | 
			
		||||
<Project Sdk="Microsoft.NET.Sdk.Web">
 | 
			
		||||
<Project Sdk="Microsoft.NET.Sdk.Web">
 | 
			
		||||
 | 
			
		||||
  <PropertyGroup>
 | 
			
		||||
    <TargetFramework>net6.0</TargetFramework>
 | 
			
		||||
    <Nullable>enable</Nullable>
 | 
			
		||||
    <ImplicitUsings>enable</ImplicitUsings>
 | 
			
		||||
    <GenerateDocumentationFile>True</GenerateDocumentationFile>
 | 
			
		||||
  </PropertyGroup>
 | 
			
		||||
 | 
			
		||||
  <ItemGroup>
 | 
			
		||||
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
 | 
			
		||||
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.21" />
 | 
			
		||||
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
 | 
			
		||||
    <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.5" />
 | 
			
		||||
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
 | 
			
		||||
 | 
			
		||||
@ -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";
 | 
			
		||||
 | 
			
		||||
@ -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<IEmployeesProvider, EmployeesProvider>();
 | 
			
		||||
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); //4/30
 | 
			
		||||
builder.Services.AddDbContext<EmployeeDbContext>(option =>
 | 
			
		||||
 | 
			
		||||
@ -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();
 | 
			
		||||
            }
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
@ -1,4 +1,7 @@
 | 
			
		||||
{
 | 
			
		||||
  "JwtSettings": {
 | 
			
		||||
    "securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk="
 | 
			
		||||
  },
 | 
			
		||||
  "Logging": {
 | 
			
		||||
    "LogLevel": {
 | 
			
		||||
      "Default": "Information",
 | 
			
		||||
 | 
			
		||||
@ -14,7 +14,10 @@ namespace DamageAssesment.Api.Locations.Controllers
 | 
			
		||||
        {
 | 
			
		||||
            this.LocationProvider = LocationsProvider;
 | 
			
		||||
        }
 | 
			
		||||
        // Get all Locations
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// Get all locations.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpGet("Locations")]
 | 
			
		||||
        public async Task<ActionResult> GetLocationsAsync()
 | 
			
		||||
        {
 | 
			
		||||
@ -27,7 +30,10 @@ namespace DamageAssesment.Api.Locations.Controllers
 | 
			
		||||
            return NotFound();
 | 
			
		||||
 | 
			
		||||
        }
 | 
			
		||||
        // Get all Location based on Id
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// Get all locations based on locationdId.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpGet("Locations/{id}")]
 | 
			
		||||
        public async Task<ActionResult> GetLocationByIdAsync(string id)
 | 
			
		||||
        {
 | 
			
		||||
@ -40,7 +46,10 @@ namespace DamageAssesment.Api.Locations.Controllers
 | 
			
		||||
            return NotFound();
 | 
			
		||||
 | 
			
		||||
        }
 | 
			
		||||
        // Update Location entity
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// Update a Location.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpPut("Locations")]
 | 
			
		||||
        public async Task<IActionResult> UpdateLocation(Db.Location Location)
 | 
			
		||||
        {
 | 
			
		||||
@ -55,7 +64,10 @@ namespace DamageAssesment.Api.Locations.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return NotFound();
 | 
			
		||||
        }
 | 
			
		||||
        //save new location
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// Save a new location.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpPost("Locations")]
 | 
			
		||||
        public async Task<IActionResult> CreateLocation(Db.Location Location)
 | 
			
		||||
        {
 | 
			
		||||
@ -70,7 +82,10 @@ namespace DamageAssesment.Api.Locations.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return CreatedAtRoute("DefaultApi", new { id = Location.Id }, Location);
 | 
			
		||||
        }
 | 
			
		||||
        //delete existing location
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// Delete an existing location.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpDelete("Locations/{id}")]
 | 
			
		||||
        public async Task<IActionResult> DeleteLocation(string id)
 | 
			
		||||
        {
 | 
			
		||||
 | 
			
		||||
@ -13,8 +13,10 @@ namespace DamageAssesment.Api.Locations.Controllers
 | 
			
		||||
        {
 | 
			
		||||
            this.regionProvider = regionProvider;
 | 
			
		||||
        }
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// Get all regions.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        // Get all Regions
 | 
			
		||||
        [HttpGet]
 | 
			
		||||
        public async Task<ActionResult> GetRegionsAsync()
 | 
			
		||||
        {
 | 
			
		||||
@ -25,6 +27,9 @@ namespace DamageAssesment.Api.Locations.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return NoContent();
 | 
			
		||||
        }
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// GET request for retrieving a region by its ID.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpGet("{Id}")]
 | 
			
		||||
        public async Task<ActionResult> GetRegionAsync(string Id)
 | 
			
		||||
@ -36,6 +41,9 @@ namespace DamageAssesment.Api.Locations.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return NotFound();
 | 
			
		||||
        }
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// POST request for creating a new region.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpPost]
 | 
			
		||||
        public async Task<ActionResult> PostRegionAsync(Models.Region region)
 | 
			
		||||
@ -47,6 +55,9 @@ namespace DamageAssesment.Api.Locations.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return BadRequest(result.ErrorMessage);
 | 
			
		||||
        }
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// PUT request for updating an existing region.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpPut]
 | 
			
		||||
        public async Task<ActionResult> PutRegionAsync(Models.Region region)
 | 
			
		||||
@ -61,6 +72,10 @@ namespace DamageAssesment.Api.Locations.Controllers
 | 
			
		||||
 | 
			
		||||
            return BadRequest(result.ErrorMessage);
 | 
			
		||||
        }
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// DELETE request for deleting a region based on ID.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
        [HttpDelete("{Id}")]
 | 
			
		||||
        public async Task<ActionResult> DeleteRegionAsync(string Id)
 | 
			
		||||
 | 
			
		||||
@ -4,10 +4,12 @@
 | 
			
		||||
    <TargetFramework>net6.0</TargetFramework>
 | 
			
		||||
    <Nullable>enable</Nullable>
 | 
			
		||||
    <ImplicitUsings>enable</ImplicitUsings>
 | 
			
		||||
    <GenerateDocumentationFile>True</GenerateDocumentationFile>
 | 
			
		||||
  </PropertyGroup>
 | 
			
		||||
 | 
			
		||||
  <ItemGroup>
 | 
			
		||||
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
 | 
			
		||||
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.21" />
 | 
			
		||||
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
 | 
			
		||||
    <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.5" />
 | 
			
		||||
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
 | 
			
		||||
 | 
			
		||||
@ -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<ILocationsProvider, LocationsProvider>();
 | 
			
		||||
builder.Services.AddScoped<IRegionsProvider, RegionsProvider>();
 | 
			
		||||
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); //4/30
 | 
			
		||||
 | 
			
		||||
@ -1,4 +1,7 @@
 | 
			
		||||
{
 | 
			
		||||
  "JwtSettings": {
 | 
			
		||||
    "securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk="
 | 
			
		||||
  },
 | 
			
		||||
  "Logging": {
 | 
			
		||||
    "LogLevel": {
 | 
			
		||||
      "Default": "Information",
 | 
			
		||||
 | 
			
		||||
@ -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
 | 
			
		||||
@ -19,33 +15,52 @@ namespace DamageAssesment.Api.Questions.Controllers
 | 
			
		||||
            this.questionsProvider = questionsProvider;
 | 
			
		||||
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// GET request for retrieving questions.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        // get all questions
 | 
			
		||||
        [HttpGet("Questions")]
 | 
			
		||||
        public async Task<IActionResult> GetQuestionsAsync()
 | 
			
		||||
        [Route("{Language}/Questions")]
 | 
			
		||||
        [Route("Questions")]
 | 
			
		||||
        [HttpGet]
 | 
			
		||||
        public async Task<IActionResult> GetQuestionsAsync(string? Language)
 | 
			
		||||
        {
 | 
			
		||||
            var result = await this.questionsProvider.GetQuestionsAsync();
 | 
			
		||||
            var result = await this.questionsProvider.GetQuestionsAsync(Language);
 | 
			
		||||
            if (result.IsSuccess)
 | 
			
		||||
            {
 | 
			
		||||
                return Ok(result.Questions);
 | 
			
		||||
            }
 | 
			
		||||
            return NoContent();
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        //Get questions based on question id
 | 
			
		||||
        [HttpGet("Questions/{id}")]
 | 
			
		||||
        public async Task<IActionResult> GetQuestionAsync(int id)
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// GET request for retrieving a question by ID.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
        [Route("{Language}/Questions/{id}")]
 | 
			
		||||
        [Route("Questions/{id}")]
 | 
			
		||||
        [HttpGet]
 | 
			
		||||
        public async Task<IActionResult> 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);
 | 
			
		||||
            }
 | 
			
		||||
            return NotFound();
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        //get all questions based on survey id
 | 
			
		||||
        [HttpGet("GetSurveyQuestions/{surveyId}")]
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// GET request for retrieving survey questions based on a survey ID.
 | 
			
		||||
        /// Uri: {Optional language}/GetSurveyQuestions/{surveyId} :Default returns question in all languages 
 | 
			
		||||
        /// </summary>
 | 
			
		||||
        [Route("{Language}/GetSurveyQuestions/{surveyId}")]
 | 
			
		||||
        [Route("GetSurveyQuestions/{surveyId}")]
 | 
			
		||||
        [HttpGet]
 | 
			
		||||
        public async Task<IActionResult> GetSurveyQuestions(int surveyId,string? Language)
 | 
			
		||||
        {
 | 
			
		||||
            if (string.IsNullOrEmpty(Language)) Language = "en";
 | 
			
		||||
            var result = await this.questionsProvider.GetSurveyQuestionAsync(surveyId, Language);
 | 
			
		||||
            if (result.IsSuccess)
 | 
			
		||||
            {
 | 
			
		||||
@ -53,7 +68,10 @@ namespace DamageAssesment.Api.Questions.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return NotFound();
 | 
			
		||||
        }
 | 
			
		||||
        //update existing question
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// PUT request for updating a question (multilingual).
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpPut("Questions")]
 | 
			
		||||
        public async Task<IActionResult> UpdateQuestion(Models.Question question)
 | 
			
		||||
        {
 | 
			
		||||
@ -71,7 +89,10 @@ namespace DamageAssesment.Api.Questions.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return CreatedAtRoute("DefaultApi", new { id = question.Id }, question);
 | 
			
		||||
        }
 | 
			
		||||
        //save new question
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// POST request for creating a new question (multilingual).
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpPost("Questions")]
 | 
			
		||||
        public async Task<IActionResult> CreateQuestion(Models.Question question)
 | 
			
		||||
        {
 | 
			
		||||
@ -86,7 +107,10 @@ namespace DamageAssesment.Api.Questions.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return CreatedAtRoute("DefaultApi", new { id = question.Id }, question);
 | 
			
		||||
        }
 | 
			
		||||
        // delete existing question
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// DELETE request for deleting a question based on ID.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpDelete("Questions/{id}")]
 | 
			
		||||
        public async Task<IActionResult> DeleteQuestion(int id)
 | 
			
		||||
        {
 | 
			
		||||
@ -98,8 +122,10 @@ namespace DamageAssesment.Api.Questions.Controllers
 | 
			
		||||
            return NotFound();
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// GET request for retrieving question categories.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        // get all questions
 | 
			
		||||
        [HttpGet("QuestionCategories")]
 | 
			
		||||
        public async Task<IActionResult> GetQuestionCategoriesAsync()
 | 
			
		||||
        {
 | 
			
		||||
@ -110,7 +136,10 @@ namespace DamageAssesment.Api.Questions.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return NoContent();
 | 
			
		||||
        }
 | 
			
		||||
        //Get questions based on question id
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// GET request for retrieving a question category by ID.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpGet("QuestionCategories/{id}")]
 | 
			
		||||
        public async Task<IActionResult> GetQuestionCategoryAsync(int id)
 | 
			
		||||
        {
 | 
			
		||||
@ -123,7 +152,10 @@ namespace DamageAssesment.Api.Questions.Controllers
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
        //update existing question
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// PUT request for updating a question category.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpPut("QuestionCategories")]
 | 
			
		||||
        public async Task<IActionResult> UpdateQuestionCategory(Models.QuestionCategory questionCategory)
 | 
			
		||||
        {
 | 
			
		||||
@ -141,7 +173,10 @@ namespace DamageAssesment.Api.Questions.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return CreatedAtRoute("DefaultApi", new { id = questionCategory.Id }, questionCategory);
 | 
			
		||||
        }
 | 
			
		||||
        //save new question
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// POST request for creating a new question category.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpPost("QuestionCategories")]
 | 
			
		||||
        public async Task<IActionResult> CreateQuestionCategory(Models.QuestionCategory questionCategory)
 | 
			
		||||
        {
 | 
			
		||||
@ -156,7 +191,10 @@ namespace DamageAssesment.Api.Questions.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return CreatedAtRoute("DefaultApi", new { id = questionCategory.Id }, questionCategory);
 | 
			
		||||
        }
 | 
			
		||||
        // delete existing question
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// DELETE request for deleting a question category based on ID.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpDelete("QuestionCategories/{id}")]
 | 
			
		||||
        public async Task<IActionResult> DeleteQuestionCategory(int id)
 | 
			
		||||
        {
 | 
			
		||||
 | 
			
		||||
@ -1,13 +1,15 @@
 | 
			
		||||
<Project Sdk="Microsoft.NET.Sdk.Web">
 | 
			
		||||
<Project Sdk="Microsoft.NET.Sdk.Web">
 | 
			
		||||
 | 
			
		||||
  <PropertyGroup>
 | 
			
		||||
    <TargetFramework>net6.0</TargetFramework>
 | 
			
		||||
    <Nullable>enable</Nullable>
 | 
			
		||||
    <ImplicitUsings>enable</ImplicitUsings>
 | 
			
		||||
    <GenerateDocumentationFile>True</GenerateDocumentationFile>
 | 
			
		||||
  </PropertyGroup>
 | 
			
		||||
 | 
			
		||||
  <ItemGroup>
 | 
			
		||||
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
 | 
			
		||||
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.21" />
 | 
			
		||||
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
 | 
			
		||||
    <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.5" />
 | 
			
		||||
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
 | 
			
		||||
 | 
			
		||||
@ -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; }
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
@ -14,12 +14,21 @@ namespace DamageAssesment.Api.Questions.Db
 | 
			
		||||
        {
 | 
			
		||||
 | 
			
		||||
        }
 | 
			
		||||
        //protected override void OnModelCreating(ModelBuilder modelBuilder)
 | 
			
		||||
        //{
 | 
			
		||||
        //    modelBuilder.Entity<Question>()
 | 
			
		||||
        //        .HasOne(a => a.QuestionType)
 | 
			
		||||
        //        .WithOne(b => b.Question)
 | 
			
		||||
        //        .HasForeignKey<QuestionType>(b => b.QuestionTypeID);
 | 
			
		||||
        //}
 | 
			
		||||
        protected override void OnModelCreating(ModelBuilder modelBuilder)
 | 
			
		||||
        {
 | 
			
		||||
            base.OnModelCreating(modelBuilder);
 | 
			
		||||
            modelBuilder.Entity<Question>()
 | 
			
		||||
                .Property(item => item.Id)
 | 
			
		||||
                .ValueGeneratedOnAdd();
 | 
			
		||||
            modelBuilder.Entity<QuestionType>()
 | 
			
		||||
                .Property(item => item.Id)
 | 
			
		||||
                .ValueGeneratedOnAdd();
 | 
			
		||||
            modelBuilder.Entity<QuestionsTranslation>()
 | 
			
		||||
                .Property(item => item.Id)
 | 
			
		||||
                .ValueGeneratedOnAdd();
 | 
			
		||||
            modelBuilder.Entity<QuestionCategory>()
 | 
			
		||||
                .Property(item => item.Id)
 | 
			
		||||
                .ValueGeneratedOnAdd();
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@ -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<Models.Question> Questions, string ErrorMessage)> GetQuestionsAsync();
 | 
			
		||||
        Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> GetQuestionAsync(int Id, string Language);
 | 
			
		||||
        Task<(bool IsSuccess, IEnumerable<Models.Question> Questions, string ErrorMessage)> GetQuestionsAsync(string Language);
 | 
			
		||||
        Task<(bool IsSuccess, List<SurveyQuestions> 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);
 | 
			
		||||
 | 
			
		||||
@ -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; }
 | 
			
		||||
    }
 | 
			
		||||
 | 
			
		||||
@ -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<QuestionDbContext>(option =>
 | 
			
		||||
{
 | 
			
		||||
    option.UseInMemoryDatabase("Questions");
 | 
			
		||||
 | 
			
		||||
@ -24,54 +24,49 @@ namespace DamageAssesment.Api.Questions.Providers
 | 
			
		||||
            SeedData();
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
        private void SeedData()
 | 
			
		||||
        {
 | 
			
		||||
 | 
			
		||||
            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" });
 | 
			
		||||
                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();
 | 
			
		||||
            }
 | 
			
		||||
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        public async Task<(bool IsSuccess, IEnumerable<Models.Question> Questions, string ErrorMessage)> GetQuestionsAsync()
 | 
			
		||||
        public async Task<(bool IsSuccess, IEnumerable<Models.Question> Questions, string ErrorMessage)> GetQuestionsAsync(string Language)
 | 
			
		||||
        {
 | 
			
		||||
            try
 | 
			
		||||
            {
 | 
			
		||||
@ -82,10 +77,20 @@ namespace DamageAssesment.Api.Questions.Providers
 | 
			
		||||
 | 
			
		||||
                    //logger?.LogInformation($"{question} customer(s) found");
 | 
			
		||||
                    var result = mapper.Map<IEnumerable<Db.Question>, IEnumerable<Models.Question>>(questions);
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
                    foreach (var question in result)
 | 
			
		||||
                    {
 | 
			
		||||
                        question.Questions=mapper.Map<List<Db.QuestionsTranslation>,List<Models.QuestionsTranslation>>(
 | 
			
		||||
                            questionDbContext.QuestionsTranslations.Where(a=>a.QuestionId==question.Id).ToList());
 | 
			
		||||
                        if (string.IsNullOrEmpty(Language))
 | 
			
		||||
                        {
 | 
			
		||||
                            question.Questions = mapper.Map<List<Db.QuestionsTranslation>, List<Models.QuestionsTranslation>>(
 | 
			
		||||
                            questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == question.Id).ToList());
 | 
			
		||||
                        }
 | 
			
		||||
                        else
 | 
			
		||||
                        {
 | 
			
		||||
                            question.Questions = mapper.Map<List<Db.QuestionsTranslation>, List<Models.QuestionsTranslation>>(
 | 
			
		||||
                            questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == question.Id && a.Language == Language).ToList());
 | 
			
		||||
                        }
 | 
			
		||||
                    }
 | 
			
		||||
                    return (true, result, null);
 | 
			
		||||
                }
 | 
			
		||||
@ -97,7 +102,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 +112,17 @@ namespace DamageAssesment.Api.Questions.Providers
 | 
			
		||||
                {
 | 
			
		||||
                    logger?.LogInformation($"{question} customer(s) found");
 | 
			
		||||
                    var result = mapper.Map<Db.Question, Models.Question>(question);
 | 
			
		||||
                    result.Questions = mapper.Map<List<Db.QuestionsTranslation>, List<Models.QuestionsTranslation>>(
 | 
			
		||||
                            questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == result.Id).ToList());
 | 
			
		||||
 | 
			
		||||
                    if (string.IsNullOrEmpty(Language))
 | 
			
		||||
                    {
 | 
			
		||||
                        result.Questions = mapper.Map<List<Db.QuestionsTranslation>, List<Models.QuestionsTranslation>>(
 | 
			
		||||
                                questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == result.Id).ToList());
 | 
			
		||||
                    }
 | 
			
		||||
                    else
 | 
			
		||||
                    {
 | 
			
		||||
                        result.Questions = mapper.Map<List<Db.QuestionsTranslation>, List<Models.QuestionsTranslation>>(
 | 
			
		||||
                     questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == result.Id && a.Language == Language).ToList());
 | 
			
		||||
                    }
 | 
			
		||||
                    return (true, result, null);
 | 
			
		||||
                }
 | 
			
		||||
                return (false, null, "Not found");
 | 
			
		||||
@ -119,12 +133,23 @@ namespace DamageAssesment.Api.Questions.Providers
 | 
			
		||||
                return (false, null, ex.Message);
 | 
			
		||||
            }
 | 
			
		||||
        }
 | 
			
		||||
        public List<Models.Question>  GetSurveyQuestion(List<Models.Question> questions,string Language)
 | 
			
		||||
        public List<Models.Question> GetSurveyQuestion(List<Models.Question> questions, string Language)
 | 
			
		||||
        {
 | 
			
		||||
            foreach (var item in questions)
 | 
			
		||||
            if (string.IsNullOrEmpty(Language))
 | 
			
		||||
            {
 | 
			
		||||
                item.Questions= mapper.Map<List<Db.QuestionsTranslation>, List<Models.QuestionsTranslation>>(
 | 
			
		||||
                            questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == item.Id && a.Language== Language).ToList());
 | 
			
		||||
                foreach (var item in questions)
 | 
			
		||||
                {
 | 
			
		||||
                    item.Questions = mapper.Map<List<Db.QuestionsTranslation>, List<Models.QuestionsTranslation>>(
 | 
			
		||||
                                questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == item.Id).ToList());
 | 
			
		||||
                }
 | 
			
		||||
            }
 | 
			
		||||
            else
 | 
			
		||||
            {
 | 
			
		||||
                foreach (var item in questions)
 | 
			
		||||
                {
 | 
			
		||||
                    item.Questions = mapper.Map<List<Db.QuestionsTranslation>, List<Models.QuestionsTranslation>>(
 | 
			
		||||
                                questionDbContext.QuestionsTranslations.Where(a => a.QuestionId == item.Id && a.Language == Language).ToList());
 | 
			
		||||
                }
 | 
			
		||||
            }
 | 
			
		||||
            return questions;
 | 
			
		||||
        }
 | 
			
		||||
@ -133,12 +158,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<SurveyQuestions> surveyQuestionsList = new List<SurveyQuestions>();
 | 
			
		||||
                    List<int> CategoryIds=questions.Select(a=>a.CategoryId).Distinct().ToList();
 | 
			
		||||
                    var questioncategories = await questionDbContext.QuestionCategories.Where(a =>CategoryIds.Contains(a.Id)).ToListAsync();
 | 
			
		||||
                    List<int> 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,7 +194,7 @@ namespace DamageAssesment.Api.Questions.Providers
 | 
			
		||||
                logger?.LogInformation("Query Question");
 | 
			
		||||
                var dbquestion = mapper.Map<Models.Question, Db.Question>(Question);
 | 
			
		||||
                var dbquestiontranslation = mapper.Map<List<Models.QuestionsTranslation>, List<Db.QuestionsTranslation>>(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);
 | 
			
		||||
@ -192,7 +217,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);
 | 
			
		||||
@ -231,8 +256,6 @@ namespace DamageAssesment.Api.Questions.Providers
 | 
			
		||||
            }
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
        //Question Category Logic
 | 
			
		||||
 | 
			
		||||
        public async Task<(bool IsSuccess, IEnumerable<Models.QuestionCategory> QuestionCategories, string ErrorMessage)> GetQuestionCategoriesAsync()
 | 
			
		||||
@ -284,7 +307,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)
 | 
			
		||||
 | 
			
		||||
@ -1,4 +1,7 @@
 | 
			
		||||
{
 | 
			
		||||
  "JwtSettings": {
 | 
			
		||||
    "securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk="
 | 
			
		||||
  },
 | 
			
		||||
  "Logging": {
 | 
			
		||||
    "LogLevel": {
 | 
			
		||||
      "Default": "Information",
 | 
			
		||||
 | 
			
		||||
@ -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
 | 
			
		||||
{
 | 
			
		||||
@ -18,7 +11,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);
 | 
			
		||||
        }
 | 
			
		||||
@ -31,7 +24,7 @@ namespace DamageAssesment.Api.Questions.Test
 | 
			
		||||
            for (int i = 0; i < 10; i++)
 | 
			
		||||
            {
 | 
			
		||||
                List<Models.Question> question = new List<Models.Question>();
 | 
			
		||||
                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,
 | 
			
		||||
@ -79,7 +72,7 @@ namespace DamageAssesment.Api.Questions.Test
 | 
			
		||||
            };
 | 
			
		||||
            List<Models.QuestionsTranslation> QuestionsTranslations = new List<Models.QuestionsTranslation>();
 | 
			
		||||
            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};
 | 
			
		||||
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
@ -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<IQuestionsProvider>();
 | 
			
		||||
            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<IQuestionsProvider>();
 | 
			
		||||
            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<IQuestionsProvider>();
 | 
			
		||||
            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<IQuestionsProvider>();
 | 
			
		||||
            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);
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
@ -16,6 +16,9 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers
 | 
			
		||||
        {
 | 
			
		||||
            this.surveyResponseProvider = surveyResponseProvider;
 | 
			
		||||
        }
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// GET request for retrieving survey responses.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpGet("SurveyResponses")]
 | 
			
		||||
        public async Task<ActionResult> GetSurveyResponsesAsync()
 | 
			
		||||
@ -31,6 +34,9 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers
 | 
			
		||||
 | 
			
		||||
            return BadRequest(result.ErrorMessage);
 | 
			
		||||
        }
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// GET request for retrieving survey responses by survey ID.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
       
 | 
			
		||||
        [HttpGet("SurveyResponses/{surveyId}")]
 | 
			
		||||
        public async Task<ActionResult> GetSurveyResponsesAsync(int surveyId)
 | 
			
		||||
@ -42,6 +48,11 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return NoContent();
 | 
			
		||||
        }
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// GET request for retrieving survey responses by survey and location IDs.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
        /// <param name="surveyId">The ID of the survey for which responses are to be retrieved.</param>
 | 
			
		||||
        /// <param name="locationId">The ID of the location for which responses are to be retrieved.</param>
 | 
			
		||||
 | 
			
		||||
        [HttpGet("Responses/{surveyId}/{locationId}")]
 | 
			
		||||
        public async Task<ActionResult> GetSurveyResponsesBySurveyAndLocationAsync(int surveyId, string locationId)
 | 
			
		||||
@ -54,6 +65,12 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers
 | 
			
		||||
 | 
			
		||||
            return NoContent();
 | 
			
		||||
        }
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// GET request for retrieving survey responses by survey, question, and answer.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
        /// <param name="surveyId">The ID of the survey for which responses are to be retrieved.</param>
 | 
			
		||||
        /// <param name="questionId">The ID of the question for which responses are to be retrieved.</param>
 | 
			
		||||
        /// <param name="answer">The answer for which responses are to be retrieved.</param>
 | 
			
		||||
 | 
			
		||||
        [HttpGet("ResponsesByAnswer/{surveyId}/{questionId}/{answer}")]
 | 
			
		||||
        public async Task<ActionResult> GetSurveyResponsesByAnswerAsyncAsync(int surveyId, int questionId, string answer)
 | 
			
		||||
@ -66,6 +83,10 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers
 | 
			
		||||
 | 
			
		||||
            return NoContent();
 | 
			
		||||
        }
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// GET request for retrieving answers from survey responses by survey ID and region.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
        /// <param name="surveyId">The ID of the survey for which answers are to be retrieved.</param>
 | 
			
		||||
 | 
			
		||||
        [HttpGet("AnswersByRegion/{surveyId}")]
 | 
			
		||||
        public async Task<ActionResult> GetAnswersByRegionAsync(int surveyId)
 | 
			
		||||
@ -77,6 +98,10 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return NoContent();
 | 
			
		||||
        }
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// GET request for retrieving survey responses by survey ID and maintenance center.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
        /// <param name="surveyId">The ID of the survey for which responses are to be retrieved.</param>
 | 
			
		||||
 | 
			
		||||
        [HttpGet("AnswersByMaintenanceCenter/{surveyId}")]
 | 
			
		||||
        public async Task<ActionResult> GetAnswersByMaintenaceCentersync(int surveyId)
 | 
			
		||||
@ -88,6 +113,10 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return NoContent();
 | 
			
		||||
        }
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// GET request for retrieving a survey response by response ID.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
        /// <param name="responseId">The ID of the survey response to be retrieved.</param>
 | 
			
		||||
 | 
			
		||||
        [HttpGet("SurveyResponse/{responseId}")]
 | 
			
		||||
        public async Task<ActionResult> GetSurveyResponseByIdAsync(int responseId)
 | 
			
		||||
@ -100,6 +129,10 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers
 | 
			
		||||
            return NoContent();
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// POST request for creating a new survey response.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
        /// <param name="surveyResponse">The survey response object to be created.</param>
 | 
			
		||||
 | 
			
		||||
        [HttpPost("SurveyResponses")]
 | 
			
		||||
        public async Task<ActionResult> PostSurveysAsync(Models.SurveyResponse surveyResponse)
 | 
			
		||||
@ -111,6 +144,11 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return BadRequest(result.ErrorMessage);
 | 
			
		||||
        }
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// PUT request for updating an existing survey response.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
        /// <param name="Id">The ID of the survey response to be updated.</param>
 | 
			
		||||
        /// <param name="surveyResponse">The updated survey response object.</param>
 | 
			
		||||
 | 
			
		||||
        [HttpPut("SurveyResponses/{Id}")]
 | 
			
		||||
        public async Task<ActionResult> PutSurveyResponseAsync(int Id, Models.SurveyResponse surveyResponse)
 | 
			
		||||
@ -125,6 +163,9 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers
 | 
			
		||||
 | 
			
		||||
            return BadRequest(result.ErrorMessage);
 | 
			
		||||
        }
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// DELETE request for deleting an existing survey response.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
       
 | 
			
		||||
        [HttpDelete("SurveyResponses/{Id}")]
 | 
			
		||||
        public async Task<ActionResult> DeleteSurveyResponseAsync(int Id)
 | 
			
		||||
@ -136,6 +177,10 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return NotFound();
 | 
			
		||||
        }
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// POST request for submitting survey with multiple answers.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
        /// <param name="answers">The answers to be submitted for the survey.</param>
 | 
			
		||||
 | 
			
		||||
        [HttpPost("SurveyResponses/Answers")]
 | 
			
		||||
        public async Task<ActionResult> PostSurveyAnswersAsync(AnswerRequest answers)
 | 
			
		||||
 | 
			
		||||
@ -4,13 +4,14 @@
 | 
			
		||||
    <TargetFramework>net6.0</TargetFramework>
 | 
			
		||||
    <Nullable>enable</Nullable>
 | 
			
		||||
    <ImplicitUsings>enable</ImplicitUsings>
 | 
			
		||||
    <GenerateDocumentationFile>True</GenerateDocumentationFile>
 | 
			
		||||
  </PropertyGroup>
 | 
			
		||||
 | 
			
		||||
  <ItemGroup>
 | 
			
		||||
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
 | 
			
		||||
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.21" />
 | 
			
		||||
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
 | 
			
		||||
    <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.5" />
 | 
			
		||||
    <PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="7.0.0" />
 | 
			
		||||
    <PackageReference Include="Microsoft.Extensions.Http.Polly" Version="7.0.5" />
 | 
			
		||||
    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
 | 
			
		||||
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
 | 
			
		||||
 | 
			
		||||
@ -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<SurveyTranslation> Titles { get; set; }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@ -0,0 +1,13 @@
 | 
			
		||||
namespace DamageAssesment.Api.SurveyResponses.Models
 | 
			
		||||
{
 | 
			
		||||
    public class SurveyTranslation
 | 
			
		||||
    {        
 | 
			
		||||
        public string Title { get; set; }
 | 
			
		||||
        public string Language { get; set; }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
@ -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<ISurveyServiceProvider, SurveyServiceProvider>().
 | 
			
		||||
 | 
			
		||||
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<SurveyResponseDbContext>(option =>
 | 
			
		||||
{
 | 
			
		||||
    option.UseInMemoryDatabase("SurveyResponses");
 | 
			
		||||
 | 
			
		||||
@ -709,16 +709,16 @@ namespace DamageAssesment.Api.SurveyResponses.Providers
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
        async Task<bool> 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<AnswerInfo> listAnswerInfo = new List<AnswerInfo>();
 | 
			
		||||
                    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
 | 
			
		||||
 | 
			
		||||
@ -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<Surveys.Models.Survey> 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) };
 | 
			
		||||
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
@ -14,10 +14,10 @@ namespace DamageAssesment.Api.Surveys.Test
 | 
			
		||||
        {
 | 
			
		||||
            var mockSurveyService = new Mock<ISurveyProvider>();
 | 
			
		||||
            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<ISurveyProvider>();
 | 
			
		||||
            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<ISurveyProvider>();
 | 
			
		||||
            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<ISurveyProvider>();
 | 
			
		||||
            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);
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
@ -1,10 +1,9 @@
 | 
			
		||||
using DamageAssesment.Api.Surveys.Interfaces;
 | 
			
		||||
using Microsoft.AspNetCore.Http;
 | 
			
		||||
using Microsoft.AspNetCore.Mvc;
 | 
			
		||||
 | 
			
		||||
namespace DamageAssesment.Api.Surveys.Controllers
 | 
			
		||||
{
 | 
			
		||||
    [Route("api/[controller]")]
 | 
			
		||||
    [Route("api")]
 | 
			
		||||
    [ApiController]
 | 
			
		||||
    public class SurveysController : ControllerBase
 | 
			
		||||
    {
 | 
			
		||||
@ -14,29 +13,43 @@ namespace DamageAssesment.Api.Surveys.Controllers
 | 
			
		||||
        {
 | 
			
		||||
            this.surveyProvider = surveyProvider;
 | 
			
		||||
        }
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// GET request for retrieving surveys.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [Route("Surveys")]
 | 
			
		||||
        [Route("{Language}/Surveys")]
 | 
			
		||||
        [HttpGet]
 | 
			
		||||
        public async Task<ActionResult> GetSurveysAsync()
 | 
			
		||||
        public async Task<ActionResult> GetSurveysAsync(string? Language)
 | 
			
		||||
        {
 | 
			
		||||
            var result = await this.surveyProvider.GetSurveysAsync();
 | 
			
		||||
            var result = await this.surveyProvider.GetSurveysAsync(Language);
 | 
			
		||||
            if (result.IsSuccess)
 | 
			
		||||
            {
 | 
			
		||||
                return Ok(result.Surveys);
 | 
			
		||||
            }
 | 
			
		||||
            return NoContent();
 | 
			
		||||
        }
 | 
			
		||||
        [HttpGet("{Id}")]
 | 
			
		||||
        public async Task<ActionResult> GetSurveysAsync(int Id)
 | 
			
		||||
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// GET request for retrieving surveys by ID.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
        [Route("Surveys/{Id}")]
 | 
			
		||||
        [Route("{Language}/Surveys/{Id}")]
 | 
			
		||||
        [HttpGet]
 | 
			
		||||
        public async Task<ActionResult> 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);
 | 
			
		||||
            }
 | 
			
		||||
            return NotFound();
 | 
			
		||||
        }
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// POST request for creating a new survey.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpPost]
 | 
			
		||||
        [HttpPost("Surveys")]
 | 
			
		||||
        public async Task<ActionResult> PostSurveysAsync(Models.Survey survey)
 | 
			
		||||
        {
 | 
			
		||||
            var result = await this.surveyProvider.PostSurveyAsync(survey);
 | 
			
		||||
@ -46,11 +59,15 @@ namespace DamageAssesment.Api.Surveys.Controllers
 | 
			
		||||
            }
 | 
			
		||||
            return BadRequest(result.ErrorMessage);
 | 
			
		||||
        }
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// PUT request for updating an existing survey (surveyId,Updated Survey data).
 | 
			
		||||
        /// </summary>
 | 
			
		||||
 | 
			
		||||
        [HttpPut("{Id}")]
 | 
			
		||||
 | 
			
		||||
        [HttpPut("Surveys/{Id}")]
 | 
			
		||||
        public async Task<ActionResult> 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);
 | 
			
		||||
@ -61,7 +78,10 @@ namespace DamageAssesment.Api.Surveys.Controllers
 | 
			
		||||
            return BadRequest(result.ErrorMessage);
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        [HttpDelete("{Id}")]
 | 
			
		||||
        /// <summary>
 | 
			
		||||
        /// DELETE request for deleting a survey by ID.
 | 
			
		||||
        /// </summary>
 | 
			
		||||
        [HttpDelete("Surveys/{Id}")]
 | 
			
		||||
        public async Task<ActionResult> DeleteSurveysAsync(int Id)
 | 
			
		||||
        {
 | 
			
		||||
            var result = await this.surveyProvider.DeleteSurveyAsync(Id);
 | 
			
		||||
 | 
			
		||||
@ -1,13 +1,15 @@
 | 
			
		||||
<Project Sdk="Microsoft.NET.Sdk.Web">
 | 
			
		||||
<Project Sdk="Microsoft.NET.Sdk.Web">
 | 
			
		||||
 | 
			
		||||
  <PropertyGroup>
 | 
			
		||||
    <TargetFramework>net6.0</TargetFramework>
 | 
			
		||||
    <Nullable>enable</Nullable>
 | 
			
		||||
    <ImplicitUsings>enable</ImplicitUsings>
 | 
			
		||||
    <GenerateDocumentationFile>True</GenerateDocumentationFile>
 | 
			
		||||
  </PropertyGroup>
 | 
			
		||||
 | 
			
		||||
  <ItemGroup>
 | 
			
		||||
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
 | 
			
		||||
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.21" />
 | 
			
		||||
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
 | 
			
		||||
    <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.5" />
 | 
			
		||||
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
 | 
			
		||||
 | 
			
		||||
@ -1,4 +1,5 @@
 | 
			
		||||
using System.ComponentModel.DataAnnotations;
 | 
			
		||||
using System.ComponentModel.DataAnnotations.Schema;
 | 
			
		||||
 | 
			
		||||
namespace DamageAssesment.Api.Surveys.Db
 | 
			
		||||
{
 | 
			
		||||
@ -6,23 +7,20 @@ 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; }
 | 
			
		||||
 | 
			
		||||
        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; }
 | 
			
		||||
 | 
			
		||||
        //[StringLength(6)]
 | 
			
		||||
        //public string EmployeeID { get; set; }
 | 
			
		||||
        public DateTime CreatedDate { get; set; } = DateTime.Now;
 | 
			
		||||
        /*
 | 
			
		||||
        [StringLength(10)]
 | 
			
		||||
        [ForeignKey("Employee")]
 | 
			
		||||
        public string EmployeeId { get; set; }
 | 
			
		||||
        */
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@ -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; }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
@ -2,13 +2,25 @@
 | 
			
		||||
 | 
			
		||||
namespace DamageAssesment.Api.Surveys.Db
 | 
			
		||||
{
 | 
			
		||||
    public class SurveysDbContext:DbContext
 | 
			
		||||
    public class SurveysDbContext : DbContext
 | 
			
		||||
    {
 | 
			
		||||
        public DbSet<Db.Survey> Surveys { get; set; }
 | 
			
		||||
        public DbSet<Db.SurveyTranslation> SurveysTranslation { get; set; }
 | 
			
		||||
        public SurveysDbContext(DbContextOptions options) : base(options)
 | 
			
		||||
        {
 | 
			
		||||
 | 
			
		||||
        }
 | 
			
		||||
        public DbSet<Db.Survey> Surveys { get; set; }
 | 
			
		||||
        protected override void OnModelCreating(ModelBuilder modelBuilder)
 | 
			
		||||
        {
 | 
			
		||||
            base.OnModelCreating(modelBuilder);
 | 
			
		||||
 | 
			
		||||
            modelBuilder.Entity<Survey>()
 | 
			
		||||
                .Property(item => item.Id)
 | 
			
		||||
                .ValueGeneratedOnAdd();
 | 
			
		||||
 | 
			
		||||
            modelBuilder.Entity<SurveyTranslation>()
 | 
			
		||||
            .Property(item => item.Id)
 | 
			
		||||
            .ValueGeneratedOnAdd();
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@ -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);
 | 
			
		||||
 | 
			
		||||
@ -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 StartDate { get; set; }
 | 
			
		||||
        public DateTime EndDate { get; set; }
 | 
			
		||||
        public DateTime CreatedDate { get; set; }
 | 
			
		||||
        public IEnumerable<SurveyTranslation> Titles { get; set; }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
@ -0,0 +1,13 @@
 | 
			
		||||
namespace DamageAssesment.Api.Surveys.Models
 | 
			
		||||
{
 | 
			
		||||
    public class SurveyTranslation
 | 
			
		||||
    {        
 | 
			
		||||
        public string Title { get; set; }
 | 
			
		||||
        public string Language { get; set; }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
@ -1,18 +1,47 @@
 | 
			
		||||
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;
 | 
			
		||||
using System.Reflection;
 | 
			
		||||
 | 
			
		||||
var builder = WebApplication.CreateBuilder(args);
 | 
			
		||||
 | 
			
		||||
// Add services to the container.
 | 
			
		||||
var authkey = builder.Configuration.GetValue<string>("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
 | 
			
		||||
builder.Services.AddScoped<ISurveyProvider, SurveysProvider>();
 | 
			
		||||
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<SurveysDbContext>(option =>
 | 
			
		||||
{
 | 
			
		||||
    option.UseInMemoryDatabase("Surveys");
 | 
			
		||||
@ -26,6 +55,7 @@ if (app.Environment.IsDevelopment())
 | 
			
		||||
    app.UseSwaggerUI();
 | 
			
		||||
}
 | 
			
		||||
 | 
			
		||||
app.UseAuthentication();
 | 
			
		||||
app.UseAuthorization();
 | 
			
		||||
 | 
			
		||||
app.MapControllers();
 | 
			
		||||
 | 
			
		||||
@ -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,87 @@ 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.SaveChanges();
 | 
			
		||||
                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<Models.Survey> Surveys, string ErrorMessage)> GetSurveysAsync()
 | 
			
		||||
        public async Task<(bool IsSuccess, IEnumerable<Models.Survey> Surveys, string ErrorMessage)> GetSurveysAsync(string Language)
 | 
			
		||||
        {
 | 
			
		||||
            IEnumerable<Models.Survey> 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<Db.Survey>, IEnumerable<Models.Survey>>(surveys);
 | 
			
		||||
                    return (true, result, null);
 | 
			
		||||
                    return (true, surveysList, null);
 | 
			
		||||
                }
 | 
			
		||||
                return (false, null, "Not found");
 | 
			
		||||
            }
 | 
			
		||||
@ -50,16 +115,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<Db.Survey, Models.Survey>(survey);
 | 
			
		||||
                    return (true, result, null);
 | 
			
		||||
                }
 | 
			
		||||
                return (false, null, "Not found");
 | 
			
		||||
@ -78,10 +182,21 @@ namespace DamageAssesment.Api.Surveys.Providers
 | 
			
		||||
                if (survey != null)
 | 
			
		||||
                {
 | 
			
		||||
                    var surveys = await surveyDbContext.Surveys.ToListAsync();
 | 
			
		||||
                    survey.Id = surveys.Count + 1;
 | 
			
		||||
                    surveyDbContext.Surveys.Add(mapper.Map<Models.Survey, Db.Survey>(survey));
 | 
			
		||||
                    surveyDbContext.SaveChanges();
 | 
			
		||||
                    return (true, survey, "Successful");
 | 
			
		||||
 | 
			
		||||
                    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 });
 | 
			
		||||
                    }
 | 
			
		||||
                    await surveyDbContext.SaveChangesAsync();
 | 
			
		||||
                    survey.Id = _survey.Id; 
 | 
			
		||||
                    return (true,survey, "Successful");
 | 
			
		||||
                }
 | 
			
		||||
                else
 | 
			
		||||
                {
 | 
			
		||||
@ -106,12 +221,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;
 | 
			
		||||
                        surveyDbContext.SaveChanges();
 | 
			
		||||
                        return (true, mapper.Map<Db.Survey, Models.Survey>(_survey), "Successful");
 | 
			
		||||
                        await surveyDbContext.SaveChangesAsync();
 | 
			
		||||
 | 
			
		||||
                        List<Db.SurveyTranslation> listSurveyTranslation = new List<Db.SurveyTranslation>();
 | 
			
		||||
                        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
 | 
			
		||||
                    {
 | 
			
		||||
@ -141,7 +284,7 @@ namespace DamageAssesment.Api.Surveys.Providers
 | 
			
		||||
                if (survey != null)
 | 
			
		||||
                {
 | 
			
		||||
                    surveyDbContext.Surveys.Remove(survey);
 | 
			
		||||
                    surveyDbContext.SaveChanges();
 | 
			
		||||
                    await surveyDbContext.SaveChangesAsync();
 | 
			
		||||
                    return (true, mapper.Map<Db.Survey, Models.Survey>(survey), $"Survey Id: {Id} deleted Successfuly");
 | 
			
		||||
                }
 | 
			
		||||
                else
 | 
			
		||||
 | 
			
		||||
@ -1,4 +1,7 @@
 | 
			
		||||
{
 | 
			
		||||
  "JwtSettings": {
 | 
			
		||||
    "securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk="
 | 
			
		||||
  },
 | 
			
		||||
  "Logging": {
 | 
			
		||||
    "LogLevel": {
 | 
			
		||||
      "Default": "Information",
 | 
			
		||||
 | 
			
		||||
@ -0,0 +1,21 @@
 | 
			
		||||
namespace DamageAssesment.Api.UsersAccess.Bases
 | 
			
		||||
{
 | 
			
		||||
    public class ServiceProviderBase
 | 
			
		||||
    {
 | 
			
		||||
        protected readonly IConfiguration configuration;
 | 
			
		||||
        protected readonly HttpClient httpClient;
 | 
			
		||||
        protected private readonly ILogger<ServiceProviderBase> logger;
 | 
			
		||||
        protected string ressource;
 | 
			
		||||
        protected string urlBase;
 | 
			
		||||
        
 | 
			
		||||
 | 
			
		||||
        public ServiceProviderBase(IConfiguration configuration, HttpClient httpClient, ILogger<ServiceProviderBase> logger, string ressource, string urlBase)
 | 
			
		||||
        {
 | 
			
		||||
            this.configuration = configuration;
 | 
			
		||||
            this.httpClient = httpClient;
 | 
			
		||||
            this.logger = logger;
 | 
			
		||||
            this.ressource = ressource;
 | 
			
		||||
            this.urlBase = urlBase;
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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<ActionResult> 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<ActionResult> 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<ActionResult> GetUsersAsync()
 | 
			
		||||
        {
 | 
			
		||||
            var result = await userAccessProvider.GetUsersAsync();
 | 
			
		||||
            if (result.IsSuccess)
 | 
			
		||||
            {
 | 
			
		||||
                return Ok(result.Users);
 | 
			
		||||
            }
 | 
			
		||||
            return NoContent();
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        [HttpGet("users/{Id}")]
 | 
			
		||||
        public async Task<ActionResult> GetUsersAsync(int Id)
 | 
			
		||||
        {
 | 
			
		||||
            var result = await userAccessProvider.GetUsersAsync(Id);
 | 
			
		||||
            if (result.IsSuccess)
 | 
			
		||||
            {
 | 
			
		||||
                return Ok(result.User);
 | 
			
		||||
            }
 | 
			
		||||
            return NotFound();
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        [HttpPost("users")]
 | 
			
		||||
        public async Task<ActionResult> 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<ActionResult> 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<ActionResult> DeleteSurveysAsync(int Id)
 | 
			
		||||
        {
 | 
			
		||||
            var result = await userAccessProvider.DeleteUserAsync(Id);
 | 
			
		||||
            if (result.IsSuccess)
 | 
			
		||||
            {
 | 
			
		||||
                return Ok(result.User);
 | 
			
		||||
            }
 | 
			
		||||
            return NotFound();
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -0,0 +1,19 @@
 | 
			
		||||
<Project Sdk="Microsoft.NET.Sdk.Web">
 | 
			
		||||
 | 
			
		||||
  <PropertyGroup>
 | 
			
		||||
    <TargetFramework>net6.0</TargetFramework>
 | 
			
		||||
    <Nullable>enable</Nullable>
 | 
			
		||||
    <ImplicitUsings>enable</ImplicitUsings>
 | 
			
		||||
  </PropertyGroup>
 | 
			
		||||
 | 
			
		||||
  <ItemGroup>
 | 
			
		||||
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="12.0.1" />
 | 
			
		||||
    <PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.21" />
 | 
			
		||||
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
 | 
			
		||||
    <PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.5" />
 | 
			
		||||
    <PackageReference Include="Microsoft.Extensions.Http.Polly" Version="7.0.10" />
 | 
			
		||||
    <PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
 | 
			
		||||
    <PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
 | 
			
		||||
  </ItemGroup>
 | 
			
		||||
 | 
			
		||||
</Project>
 | 
			
		||||
@ -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; }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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; }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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; }
 | 
			
		||||
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -0,0 +1,17 @@
 | 
			
		||||
using Microsoft.EntityFrameworkCore;
 | 
			
		||||
 | 
			
		||||
namespace DamageAssesment.Api.UsersAccess.Db
 | 
			
		||||
{
 | 
			
		||||
    public class UsersAccessDbContext:DbContext
 | 
			
		||||
    {
 | 
			
		||||
        public DbSet<Db.User> Users { get; set; }
 | 
			
		||||
        public DbSet<Db.Role> Roles { get; set; }
 | 
			
		||||
        public DbSet<Db.Token> Tokens { get; set; }
 | 
			
		||||
        public UsersAccessDbContext(DbContextOptions options) : base(options)
 | 
			
		||||
        {
 | 
			
		||||
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -0,0 +1,10 @@
 | 
			
		||||
using DamageAssesment.Api.UsersAccess.Models;
 | 
			
		||||
 | 
			
		||||
namespace DamageAssesment.Api.UsersAccess.Interfaces
 | 
			
		||||
{
 | 
			
		||||
    public interface IEmployeeServiceProvider
 | 
			
		||||
    {
 | 
			
		||||
        Task<List<Employee>> getEmployeesAsync();
 | 
			
		||||
        Task<Employee> getEmployeeAsync(string employeeID);
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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);
 | 
			
		||||
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -0,0 +1,11 @@
 | 
			
		||||
using DamageAssesment.Api.UsersAccess.Models;
 | 
			
		||||
using System.Security.Claims;
 | 
			
		||||
 | 
			
		||||
namespace DamageAssesment.Api.UsersAccess.Interfaces
 | 
			
		||||
{
 | 
			
		||||
    public interface ITokenServiceProvider
 | 
			
		||||
    {
 | 
			
		||||
        Task<string> GenerateToken(User user);
 | 
			
		||||
        Task<TokenResponse> TokenAuthenticate(User user, Claim[] claims);
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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<Models.Role> 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);
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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; }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -0,0 +1,9 @@
 | 
			
		||||
using System.ComponentModel.DataAnnotations;
 | 
			
		||||
namespace DamageAssesment.Api.UsersAccess.Models
 | 
			
		||||
{
 | 
			
		||||
 | 
			
		||||
    public class JwtSettings
 | 
			
		||||
    {
 | 
			
		||||
        public string securitykey { get; set; }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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; }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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; }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -0,0 +1,8 @@
 | 
			
		||||
namespace DamageAssesment.Api.UsersAccess.Models
 | 
			
		||||
{
 | 
			
		||||
    public class TokenResponse
 | 
			
		||||
    {
 | 
			
		||||
        public string? jwttoken { get; set; }
 | 
			
		||||
        public string? refreshtoken { get; set; }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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; }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -0,0 +1,5 @@
 | 
			
		||||
public class UserCredentials
 | 
			
		||||
{
 | 
			
		||||
    public string? username { get; set; }
 | 
			
		||||
   // public string? password { get; set; }
 | 
			
		||||
}
 | 
			
		||||
@ -0,0 +1,14 @@
 | 
			
		||||
namespace DamageAssesment.Api.UsersAccess.Profiles
 | 
			
		||||
{
 | 
			
		||||
    public class UsersAccessProfile : AutoMapper.Profile
 | 
			
		||||
    {
 | 
			
		||||
        public UsersAccessProfile()
 | 
			
		||||
        {
 | 
			
		||||
            CreateMap<Db.User, Models.User>();
 | 
			
		||||
            CreateMap<Models.User, Db.User>();
 | 
			
		||||
 | 
			
		||||
            CreateMap<Db.Role, Models.Role>();
 | 
			
		||||
            CreateMap<Models.Role, Db.Role>();
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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<string>("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>(_jwtsettings);
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
builder.Services.AddHttpClient<IEmployeeServiceProvider, EmployeeServiceProvider>().
 | 
			
		||||
    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<IUsersAccessProvider, UsersAccessProvider>();
 | 
			
		||||
builder.Services.AddScoped<ITokenServiceProvider, TokenServiceProvider>();
 | 
			
		||||
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
 | 
			
		||||
builder.Services.AddEndpointsApiExplorer();
 | 
			
		||||
builder.Services.AddSwaggerGen();
 | 
			
		||||
builder.Services.AddDbContext<UsersAccessDbContext>(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();
 | 
			
		||||
@ -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"
 | 
			
		||||
      }
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
@ -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<EmployeeServiceProvider> logger) : base(configuration, httpClient, logger, "/api/Employees", configuration.GetValue<string>("EndPointSettings:EmployeeUrlBase"))
 | 
			
		||||
        {
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
        public async Task<List<Employee>> 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<List<Employee>>(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<Employee> 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<Employee>(responseString);
 | 
			
		||||
 | 
			
		||||
                if (employee == null )
 | 
			
		||||
                    return null;
 | 
			
		||||
                else return employee;
 | 
			
		||||
            }
 | 
			
		||||
            catch (Exception ex)
 | 
			
		||||
            {
 | 
			
		||||
                logger?.LogError($"Exception Found : {ex.Message} - Ref: EmployeeServiceProvider.getEmployeeAsync()");
 | 
			
		||||
                return null;
 | 
			
		||||
            }
 | 
			
		||||
        }
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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<JwtSettings> options,UsersAccessDbContext usersAccessDbContext)
 | 
			
		||||
    {
 | 
			
		||||
        this.usersAccessDbContext = usersAccessDbContext;
 | 
			
		||||
        this.jwtSettings = options.Value;
 | 
			
		||||
    }
 | 
			
		||||
    public async Task<string> 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<TokenResponse> 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) };
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -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<UsersAccessProvider> logger;
 | 
			
		||||
        private readonly IMapper mapper;
 | 
			
		||||
        private readonly IEmployeeServiceProvider employeeServiceProvider;
 | 
			
		||||
        private readonly JwtSettings jwtSettings;
 | 
			
		||||
        private readonly ITokenServiceProvider tokenServiceProvider;
 | 
			
		||||
 | 
			
		||||
        public UsersAccessProvider(IOptions<JwtSettings> options, ITokenServiceProvider tokenServiceProvider, UsersAccessDbContext userAccessDbContext, IEmployeeServiceProvider employeeServiceProvider, ILogger<UsersAccessProvider> 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<Models.User> 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<Db.User>, IEnumerable<Models.User>>(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<Db.User, Models.User>(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<Models.User, Db.User>(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<Db.User, Models.User>(_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<Db.User, Models.User>(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<Claim> {
 | 
			
		||||
                             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<Models.Role> 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<Db.Role>, IEnumerable<Models.Role>>(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<Db.User, Models.User>(user);
 | 
			
		||||
            var response = tokenServiceProvider.TokenAuthenticate(_user, principal.Claims.ToArray()).Result;
 | 
			
		||||
            return (true, response, "Token authenticated and refreshed.");
 | 
			
		||||
        }
 | 
			
		||||
 | 
			
		||||
 | 
			
		||||
    }
 | 
			
		||||
}
 | 
			
		||||
@ -0,0 +1,8 @@
 | 
			
		||||
{
 | 
			
		||||
  "Logging": {
 | 
			
		||||
    "LogLevel": {
 | 
			
		||||
      "Default": "Information",
 | 
			
		||||
      "Microsoft.AspNetCore": "Warning"
 | 
			
		||||
    }
 | 
			
		||||
  }
 | 
			
		||||
}
 | 
			
		||||
@ -0,0 +1,15 @@
 | 
			
		||||
{
 | 
			
		||||
  "JwtSettings": {
 | 
			
		||||
    "securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk="
 | 
			
		||||
  },
 | 
			
		||||
  "Logging": {
 | 
			
		||||
    "LogLevel": {
 | 
			
		||||
      "Default": "Information",
 | 
			
		||||
      "Microsoft.AspNetCore": "Warning"
 | 
			
		||||
    }
 | 
			
		||||
  },
 | 
			
		||||
  "EndPointSettings": {
 | 
			
		||||
    "EmployeeUrlBase": "http://localhost:5135"
 | 
			
		||||
  },
 | 
			
		||||
  "AllowedHosts": "*"
 | 
			
		||||
}
 | 
			
		||||
@ -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
 | 
			
		||||
 | 
			
		||||
		Reference in New Issue
	
	Block a user