Compare commits

..

4 Commits

Author SHA1 Message Date
3b91282419 document api link type changes 2023-09-13 16:49:59 -04:00
b878cd706c 314: updated document multi language output format 2023-09-11 13:23:50 -04:00
d78d5e0ba4 Modified Documents api for InMemory Logic 2023-08-31 19:12:47 -04:00
fd65417a7b Added Document api solution 2023-08-31 19:00:51 -04:00
121 changed files with 2471 additions and 1727 deletions

View File

@ -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)).Returns(mockResponse);
mockAnswerService.Setup(service => service.PostAnswerAsync(mockInputAnswer)).ReturnsAsync(mockResponse);
var AnswerProvider = new AnswersController(mockAnswerService.Object);
var result = (OkObjectResult) AnswerProvider.CreateAnswer(mockInputAnswer);
var result = (OkObjectResult)await AnswerProvider.CreateAnswer(mockInputAnswer);
Assert.Equal(200, result.StatusCode);
}
@ -109,10 +109,10 @@ namespace DamageAssesment.Api.Answers.Test
var mockAnswerService = new Mock<IAnswersProvider>();
var mockInputAnswer = await MockData.getInputAnswerData();
var mockResponse = await MockData.getBadRequestResponse();
mockAnswerService.Setup(service => service.PostAnswerAsync(mockInputAnswer)).Returns(mockResponse);
mockAnswerService.Setup(service => service.PostAnswerAsync(mockInputAnswer)).ReturnsAsync(mockResponse);
var AnswerProvider = new AnswersController(mockAnswerService.Object);
var result = (BadRequestObjectResult) AnswerProvider.CreateAnswer(mockInputAnswer);
var result = (BadRequestObjectResult)await AnswerProvider.CreateAnswer(mockInputAnswer);
Assert.Equal(400, result.StatusCode);
}
@ -123,10 +123,10 @@ namespace DamageAssesment.Api.Answers.Test
var mockAnswerService = new Mock<IAnswersProvider>();
var mockResponse = await MockData.getOkResponse(1);
var mockInputAnswer = await MockData.getInputAnswerData();
mockAnswerService.Setup(service => service.UpdateAnswerAsync(mockInputAnswer)).Returns(mockResponse);
mockAnswerService.Setup(service => service.UpdateAnswerAsync(mockInputAnswer)).ReturnsAsync(mockResponse);
var AnswerProvider = new AnswersController(mockAnswerService.Object);
var result = (OkObjectResult) AnswerProvider.UpdateAnswer(mockInputAnswer);
var result = (OkObjectResult)await AnswerProvider.UpdateAnswer(mockInputAnswer);
Assert.Equal(200, result.StatusCode);
}
@ -137,10 +137,10 @@ namespace DamageAssesment.Api.Answers.Test
var mockAnswerService = new Mock<IAnswersProvider>();
var mockResponse = await MockData.getNotFoundResponse();
var mockInputAnswer = await MockData.getInputAnswerData();
mockAnswerService.Setup(service => service.UpdateAnswerAsync(mockInputAnswer)).Returns(mockResponse);
mockAnswerService.Setup(service => service.UpdateAnswerAsync(mockInputAnswer)).ReturnsAsync(mockResponse);
var AnswerProvider = new AnswersController(mockAnswerService.Object);
var result = (NotFoundObjectResult) AnswerProvider.UpdateAnswer(mockInputAnswer);
var result = (NotFoundObjectResult)await AnswerProvider.UpdateAnswer(mockInputAnswer);
Assert.Equal(404, result.StatusCode);
}
@ -151,10 +151,10 @@ namespace DamageAssesment.Api.Answers.Test
var mockAnswerService = new Mock<IAnswersProvider>();
var mockResponse = await MockData.getBadRequestResponse();
var mockInputAnswer = await MockData.getInputAnswerData();
mockAnswerService.Setup(service => service.UpdateAnswerAsync(mockInputAnswer)).Returns(mockResponse);
mockAnswerService.Setup(service => service.UpdateAnswerAsync(mockInputAnswer)).ReturnsAsync(mockResponse);
var AnswerProvider = new AnswersController(mockAnswerService.Object);
var result = (BadRequestObjectResult) AnswerProvider.UpdateAnswer(mockInputAnswer);
var result = (BadRequestObjectResult)await AnswerProvider.UpdateAnswer(mockInputAnswer);
Assert.Equal(400, result.StatusCode);
}

View File

@ -43,9 +43,9 @@ namespace DamageAssesment.Api.Answers.Test
return (false, list, null);
}
public static async Task<Answers.Models.Answer> getInputAnswerData()
public static async Task<Answers.Db.Answer> getInputAnswerData()
{
return new Answers.Models.Answer { Id = 1, AnswerText = "Yes", Comment = "", QuestionId = 1, SurveyResponseId = 1 };
return new Answers.Db.Answer { Id = 1, AnswerText = "Yes", Comment = "", QuestionId = 1, SurveyResponseId = 1 };
}

View File

@ -14,10 +14,7 @@ namespace DamageAssesment.Api.Answers.Controllers
public AnswersController(IAnswersProvider answersProvider) {
this.answerProvider=answersProvider;
}
/// <summary>
/// Get all answers
/// </summary>
//get all answers
[HttpGet("Answers")]
public async Task<ActionResult> GetAnswersAsync() {
@ -29,11 +26,7 @@ namespace DamageAssesment.Api.Answers.Controllers
return NoContent();
}
/// <summary>
/// Get an answer based on answerId.
/// </summary>
//get answer based on answerid
[HttpGet("Answers/{Id}")]
public async Task<ActionResult> GetAnswerByIdAsync(int Id)
{
@ -46,9 +39,7 @@ namespace DamageAssesment.Api.Answers.Controllers
return NotFound();
}
/// <summary>
/// Get all answers based on responseId.
/// </summary>
// get all answers based on response id
[HttpGet("AnswersByResponse/{ResponseId}")]
public async Task<IActionResult> GetAnswersByResponseId(int ResponseId)
{
@ -59,10 +50,7 @@ namespace DamageAssesment.Api.Answers.Controllers
}
return NoContent();
}
/// <summary>
/// Get all answers based on questionId.
/// </summary>
// get all answers based on question id
[HttpGet("AnswersByQuestion/{QuestionId}")]
public async Task<IActionResult> AnswersByQuestionId(int QuestionId)
{
@ -73,16 +61,14 @@ namespace DamageAssesment.Api.Answers.Controllers
}
return NotFound();
}
/// <summary>
/// Update an existing answer.
/// </summary>
//update existing answer
[HttpPut("Answers")]
public IActionResult UpdateAnswer(Models.Answer answer)
public async Task<IActionResult> UpdateAnswer(Db.Answer answer)
{
if (answer != null)
{
var result = this.answerProvider.UpdateAnswerAsync(answer);
var result = await this.answerProvider.UpdateAnswerAsync(answer);
if (result.IsSuccess)
{
return Ok(result.Answer);
@ -94,16 +80,13 @@ namespace DamageAssesment.Api.Answers.Controllers
}
return NotFound();
}
/// <summary>
/// Save a new answer.
/// </summary>
//save new answer
[HttpPost("Answers")]
public IActionResult CreateAnswer(Models.Answer answer)
public async Task<IActionResult> CreateAnswer(Db.Answer answer)
{
if (answer != null)
{
var result = this.answerProvider.PostAnswerAsync(answer);
var result = await this.answerProvider.PostAnswerAsync(answer);
if (result.IsSuccess)
{
return Ok(result.Answer);
@ -112,10 +95,7 @@ namespace DamageAssesment.Api.Answers.Controllers
}
return CreatedAtRoute("DefaultApi", new { id = answer.Id }, answer);
}
/// <summary>
/// Delete an existing answer.
/// </summary>
//delete existing answer
[HttpDelete("Answers/{id}")]
public async Task<IActionResult> DeleteAnswer(int id)
{

View File

@ -4,12 +4,10 @@
<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" />

View File

@ -10,13 +10,7 @@ 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();
}
}
}

View File

@ -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);
(bool IsSuccess, Models.Answer Answer, string ErrorMessage) PostAnswerAsync(Models.Answer Answer);
(bool IsSuccess, Models.Answer Answer, string ErrorMessage) UpdateAnswerAsync(Models.Answer Answer);
Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> PostAnswerAsync(Db.Answer Answer);
Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> UpdateAnswerAsync(Db.Answer Answer);
Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> DeleteAnswerAsync(int Id);
}
}

View File

@ -7,7 +7,6 @@ namespace DamageAssesment.Api.Answers.Profiles
public AnswersProfile()
{
CreateMap<Db.Answer,Models.Answer>();
CreateMap<Models.Answer, Db.Answer>();
}
}
}

View File

@ -2,7 +2,6 @@ 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);
@ -11,14 +10,7 @@ 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(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.AddSwaggerGen();
builder.Services.AddScoped<IAnswersProvider, AnswersProvider>();
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); //4/30
builder.Services.AddDbContext<AnswerDbContext>(option =>

View File

@ -108,17 +108,16 @@ namespace DamageAssesment.Api.Answers.Providers
return (false, null, ex.Message);
}
}
public (bool IsSuccess, Models.Answer Answer, string ErrorMessage) PostAnswerAsync(Models.Answer Answer)
public async Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> PostAnswerAsync(Db.Answer Answer)
{
try
{
logger?.LogInformation("Query Answer");
if (!AnswerExists(Answer.Id))
{
Db.Answer answer = mapper.Map<Models.Answer, Db.Answer>(Answer);
answerDbContext.Answers.Add(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");
@ -129,7 +128,7 @@ namespace DamageAssesment.Api.Answers.Providers
return (false, null, ex.Message);
}
}
public (bool IsSuccess, Models.Answer Answer, string ErrorMessage) UpdateAnswerAsync(Models.Answer Answer)
public async Task<(bool IsSuccess, Models.Answer Answer, string ErrorMessage)> UpdateAnswerAsync(Db.Answer Answer)
{
try
{
@ -138,10 +137,9 @@ namespace DamageAssesment.Api.Answers.Providers
var existing = answerDbContext.Answers.AsNoTracking().FirstOrDefault(x => x.Id == Answer.Id);
if (existing != null)
{
Db.Answer answer = mapper.Map<Models.Answer, Db.Answer>(Answer);
answerDbContext.Answers.Update(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
{

View File

@ -1,7 +1,4 @@
{
"JwtSettings": {
"securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk="
},
"Logging": {
"LogLevel": {
"Default": "Information",

View File

@ -77,10 +77,10 @@ namespace DamageAssesment.Api.Attachments.Test
var mockResponse = await MockData.getOkResponse();
var AttachmentResponse = await MockData.GetAttachmentInfo(0);
var mockInputAttachment = await MockData.getInputAttachmentData();
mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).Returns(mockResponse);
mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).ReturnsAsync(mockResponse);
var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object);
var result = (NoContentResult) AttachmentProvider.UploadAttachmentAsync(AttachmentResponse);
var result = (NoContentResult)await AttachmentProvider.UploadAttachmentAsync(AttachmentResponse);
Assert.Equal(204, result.StatusCode);
}
@ -92,11 +92,11 @@ namespace DamageAssesment.Api.Attachments.Test
var mockUploadService = new Mock<IUploadService>();
var mockInputAttachment = await MockData.getInputAttachmentData();
var mockResponse = await MockData.getBadRequestResponse();
mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).Returns(mockResponse);
mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).ReturnsAsync(mockResponse);
var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object);
AttachmentInfo attachmentInfo=new AttachmentInfo();
var result = (BadRequestObjectResult) AttachmentProvider.UploadAttachmentAsync(attachmentInfo);
var result = (BadRequestObjectResult)await AttachmentProvider.UploadAttachmentAsync(attachmentInfo);
Assert.Equal(400, result.StatusCode);
}
@ -109,10 +109,10 @@ namespace DamageAssesment.Api.Attachments.Test
var mockResponse = await MockData.getOkResponse();
var AttachmentResponse = await MockData.GetAttachmentInfo(1);
var mockInputAttachment = await MockData.getInputAttachmentData();
mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).Returns(mockResponse);
mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).ReturnsAsync(mockResponse);
var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object);
var result = (NoContentResult) AttachmentProvider.UpdateAttachmentAsync(AttachmentResponse);
var result = (NoContentResult)await AttachmentProvider.UpdateAttachmentAsync(AttachmentResponse);
Assert.Equal(204, result.StatusCode);
}
@ -124,11 +124,11 @@ namespace DamageAssesment.Api.Attachments.Test
var mockUploadService = new Mock<IUploadService>();
var mockInputAttachment = await MockData.getInputAttachmentData();
var mockResponse = await MockData.getBadRequestResponse();
mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).Returns(mockResponse);
mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).ReturnsAsync(mockResponse);
var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object);
AttachmentInfo attachmentInfo = new AttachmentInfo();
var result = (BadRequestObjectResult) AttachmentProvider.UpdateAttachmentAsync(attachmentInfo);
var result = (BadRequestObjectResult)await AttachmentProvider.UpdateAttachmentAsync(attachmentInfo);
Assert.Equal(400, result.StatusCode);
}

View File

@ -17,7 +17,7 @@ namespace DamageAssesment.Api.Attachments.Test
for (int i = 0; i < 10; i++)
{
list.Add(new Attachments.Models.Attachment()
list.Add(new Attachments.Models.Attachment(i, Guid.NewGuid().ToString() + "@gmail.com")
{
Id = i,
AnswerId = i,
@ -73,10 +73,10 @@ namespace DamageAssesment.Api.Attachments.Test
return (false, list, null);
}
public static async Task<List<Attachments.Models.Attachment>> getInputAttachmentData()
public static async Task<List<Attachments.Db.Attachment>> getInputAttachmentData()
{
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" }) ;
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" }) ;
return Attachments;
}

View File

@ -19,10 +19,7 @@ namespace DamageAssesment.Api.Attachments.Controllers
this.AttachmentProvider = AttachmentsProvider;
this.UploadService = uploadService;
}
/// <summary>
/// Get all attachments.
/// </summary>
//get all Attachments
[HttpGet("Attachments")]
public async Task<ActionResult> GetAttachmentsAsync()
{
@ -35,9 +32,7 @@ namespace DamageAssesment.Api.Attachments.Controllers
return NoContent();
}
/// <summary>
/// Get all attachments by attachmentId.
/// </summary>
//get all Attachment by Id
[HttpGet("Attachments/{id}")]
public async Task<ActionResult> GetAttachmentbyIdAsync(int id)
{
@ -78,20 +73,17 @@ namespace DamageAssesment.Api.Attachments.Controllers
// }
//}
/// <summary>
/// Save new Attachment(s)
/// </summary>
//Save new Attachment
[HttpPost("Attachments"), DisableRequestSizeLimit]
public IActionResult UploadAttachmentAsync(AttachmentInfo attachmentInfo)
public async Task<IActionResult> UploadAttachmentAsync(AttachmentInfo attachmentInfo)
{
try
{
if (attachmentInfo.Answers.Count > 0)
{
var Attachments = this.AttachmentProvider.GetAttachmentCounter();
List<Models.Attachment> attachments = UploadService.UploadAttachment(attachmentInfo.ResponseId, Attachments.counter, attachmentInfo.Answers);
var result = this.AttachmentProvider.PostAttachmentAsync(attachments);
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);
if (result.IsSuccess)
{
return Ok(result.Attachments);
@ -105,22 +97,20 @@ namespace DamageAssesment.Api.Attachments.Controllers
return BadRequest($"Internal server error: {ex}");
}
}
/// <summary>
/// Modify an new attachment.
/// </summary>
//Save new Attachment
[HttpPut("Attachments"), DisableRequestSizeLimit]
public IActionResult UpdateAttachmentAsync(AttachmentInfo attachmentInfo)
public async Task<IActionResult> UpdateAttachmentAsync(AttachmentInfo attachmentInfo)
{
try
{
if (attachmentInfo.Answers.Count > 0)
{
var res = this.AttachmentProvider.GetAttachmentInfo(attachmentInfo.Answers);
var res = await this.AttachmentProvider.GetAttachmentInfo(attachmentInfo.Answers);
if (res.IsSuccess)
{
List<Models.Attachment> attachments = UploadService.UpdateAttachments(attachmentInfo.ResponseId, attachmentInfo.Answers, res.Attachments);
var result = this.AttachmentProvider.PutAttachmentAsync(attachments);
List<Db.Attachment> attachments = UploadService.UpdateAttachments(attachmentInfo.ResponseId, attachmentInfo.Answers, res.Attachments);
var result = await this.AttachmentProvider.PutAttachmentAsync(attachments);
if (result.IsSuccess)
{
return Ok(result.Attachments);
@ -136,9 +126,7 @@ namespace DamageAssesment.Api.Attachments.Controllers
return BadRequest($"Internal server error: {ex}");
}
}
/// <summary>
/// Delete an existing attachment.
/// </summary>
//delete existing Attachment
[HttpDelete("Delete")]
public async Task<IActionResult> DeleteAttachment(int Id)
{

View File

@ -4,13 +4,11 @@
<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" />

View File

@ -8,12 +8,5 @@ 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();
}
}
}

View File

@ -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);
(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, 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);
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);
(bool IsSuccess, int counter, string message) GetAttachmentCounter();
(bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage) GetAttachmentInfo(List<AnswerInfo> answers);
Task<(bool IsSuccess, int counter, string message)> GetAttachmentCounter();
Task<(bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage)> GetAttachmentInfo(List<AnswerInfo> answers);
}
}

View File

@ -4,9 +4,9 @@ namespace DamageAssesment.Api.Attachments.Interfaces
{
public interface IUploadService
{
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);
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);
void Deletefile(string path);
void Movefile(string path);
}

View File

@ -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;
}
}
}

View File

@ -5,7 +5,6 @@
public AttachmentsProfiles()
{
CreateMap<Db.Attachment, Models.Attachment>();
CreateMap<Models.Attachment, Db.Attachment>();
}
}
}

View File

@ -4,7 +4,6 @@ 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);
@ -13,14 +12,7 @@ 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(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.AddSwaggerGen();
builder.Services.AddScoped<IAttachmentsProvider, AttachmentsProvider>();
builder.Services.AddScoped<IUploadService, UploadService>();
builder.Services.AddScoped<IAzureBlobService,AzureBlobService>();

View File

@ -65,15 +65,14 @@ namespace DamageAssesment.Api.Attachments.Providers
return (false, null, ex.Message);
}
}
public (bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage) PostAttachmentAsync(List<Models.Attachment> Attachments)
public async Task<(bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage)> PostAttachmentAsync(List<Db.Attachment> Attachments)
{
try
{
logger?.LogInformation("Query Attachment");
List<Db.Attachment> attachments = mapper.Map<List<Models.Attachment>, List<Db.Attachment>>(Attachments);
AttachmentDbContext.Attachments.AddRange(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)
@ -83,15 +82,14 @@ namespace DamageAssesment.Api.Attachments.Providers
}
}
public (bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage) PutAttachmentAsync(List<Models.Attachment> Attachments)
public async Task<(bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage)> PutAttachmentAsync(List<Db.Attachment> Attachments)
{
try
{
logger?.LogInformation("Query Attachment");
List<Db.Attachment> attachments = mapper.Map<List<Models.Attachment>, List<Db.Attachment>>(Attachments);
AttachmentDbContext.Attachments.UpdateRange(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)
@ -121,7 +119,7 @@ namespace DamageAssesment.Api.Attachments.Providers
return (false, AttachmentId, "");
}
}
public (bool IsSuccess,int counter,string message) GetAttachmentCounter()
public async Task<(bool IsSuccess,int counter,string message)> GetAttachmentCounter()
{
try
{
@ -154,7 +152,7 @@ namespace DamageAssesment.Api.Attachments.Providers
return (false, AttachmentId, "");
}
}
public (bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage) GetAttachmentInfo(List<AnswerInfo> answers)
public async Task<(bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage)>GetAttachmentInfo(List<AnswerInfo> answers)
{
try
{
@ -206,11 +204,10 @@ 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<Models.Attachment> attachments = uploadservice.UploadAttachment(1, 0, answerInfos);
List<Db.Attachment> attachments = uploadservice.UploadAttachment(1, 0, answerInfos);
if (attachments.Count > 0)
{
List<Db.Attachment> Attachments = mapper.Map<List<Models.Attachment>, List<Db.Attachment>>(attachments);
AttachmentDbContext.Attachments.AddRange(Attachments);
AttachmentDbContext.Attachments.AddRange(attachments);
AttachmentDbContext.SaveChanges();
}
}

View File

@ -24,7 +24,7 @@ namespace DamageAssesment.Api.Attachments.Providers
uploadpath = configuration.GetValue<string>("Fileupload:folderpath");
Deletepath = configuration.GetValue<string>("Fileupload:Deletepath");
}
public List<Models.Attachment> UploadAttachment(int responseId,int answerId,int counter, List<IFormFile> postedFile)
public List<Db.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<Models.Attachment> attachments = new List<Models.Attachment>();
List<Db.Attachment> attachments = new List<Db.Attachment>();
foreach (IFormFile item in postedFile)
{
@ -55,15 +55,15 @@ namespace DamageAssesment.Api.Attachments.Providers
{
item.CopyTo(stream);
}
attachments.Add(new Models.Attachment { AnswerId = answerId, ResponseId = responseId, IsDeleted = false, FileName = UserfileName, URI = dbPath });
attachments.Add(new Db.Attachment { AnswerId = answerId, ResponseId = responseId, IsDeleted = false, FileName = UserfileName, URI = dbPath });
}
return attachments;
}
public List<Models.Attachment> UploadAttachment(int responseId, int counter,List<AnswerInfo> answers)
public List<Db.Attachment> UploadAttachment(int responseId, int counter,List<AnswerInfo> answers)
{
List<Models.Attachment> attachments = new List<Models.Attachment>();
List<Db.Attachment> attachments = new List<Db.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 Models.Attachment { AnswerId = answerId, ResponseId = responseId, IsDeleted = false, FileName = UserfileName, URI = dbPath });
attachments.Add(new Db.Attachment { AnswerId = answerId, ResponseId = responseId, IsDeleted = false, FileName = UserfileName, URI = dbPath });
}
}
return attachments;
}
catch (Exception ex) {
return new List<Models.Attachment>();
return new List<Db.Attachment>();
}
}
public List<Models.Attachment> UpdateAttachments(int responseId,List<AnswerInfo> answers,IEnumerable<Models.Attachment> attachments)
public List<Db.Attachment> UpdateAttachments(int responseId,List<AnswerInfo> answers,IEnumerable<Models.Attachment> attachments)
{
List<Models.Attachment> Dbattachments = new List<Models.Attachment>();
List<Db.Attachment> Dbattachments = new List<Db.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 Models.Attachment { Id=attachment.Id, AnswerId = answerId, ResponseId = responseId, IsDeleted = false, FileName = UserfileName, URI = dbPath });
Dbattachments.Add(new Db.Attachment { Id=attachment.Id, AnswerId = answerId, ResponseId = responseId, IsDeleted = false, FileName = UserfileName, URI = dbPath });
}
}
return Dbattachments;

View File

@ -1,7 +1,4 @@
{
"JwtSettings": {
"securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk="
},
"Logging": {
"LogLevel": {
"Default": "Information",

View File

@ -0,0 +1,27 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<IsTestProject>true</IsTestProject>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.5.0" />
<PackageReference Include="Moq" Version="4.18.4" />
<PackageReference Include="coverlet.collector" Version="3.2.0" />
<PackageReference Include="xunit" Version="2.4.2" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\DamageAssesment.Api.Documents\DamageAssesment.Api.DocuLinks.csproj" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,331 @@
using DamageAssesment.Api.Documents.Controllers;
using DamageAssesment.Api.Documents.Interfaces;
using DamageAssesment.Api.Documents.Models;
using Microsoft.AspNetCore.Mvc;
using Moq;
using Xunit;
namespace DamageAssesment.Api.Documents.Test
{
public class DocumentServiceTest
{
[Fact(DisplayName = "Get Documents - NoContent Case")]
public async Task GetDocumentsLanguageAsync_ShouldReturnStatusCode204()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockResponse = await MockData.getNoContentResponse();
mockDocumentService.Setup(service => service.GetdocumentsByLinkAsync("forms","en")).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (NoContentResult)await DocumentProvider.GetDocumentsAsync("", "");
Assert.Equal(204, result.StatusCode);
}
[Fact(DisplayName = "Get Documents - NoContent Case")]
public async Task GetDocumentsLinkTypeAsync_ShouldReturnStatusCode204()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockResponse = await MockData.getNoContentResponse();
mockDocumentService.Setup(service => service.GetdocumentsByLinkAsync("forms","en")).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (NoContentResult)await DocumentProvider.GetDocumentsAsync("", "");
Assert.Equal(204, result.StatusCode);
}
[Fact(DisplayName = "Get Documents - Ok case")]
public async Task GetDocumentsAsync_ShouldReturnStatusCode200()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockResponse = await MockData.getOkResponse();
mockDocumentService.Setup(service => service.GetdocumentsByLinkAsync("forms","en")).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (OkObjectResult)await DocumentProvider.GetDocumentsAsync("forms","en");
Assert.Equal(200, result.StatusCode);
}
[Fact(DisplayName = "Get Documents - NoContent Case")]
public async Task GetDocumentsAsync_ShouldReturnStatusCode204()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockResponse = await MockData.getNoContentResponse();
mockDocumentService.Setup(service => service.GetdocumentsByLinkAsync("forms", "en")).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (NoContentResult)await DocumentProvider.GetDocumentsAsync("forms","en");
Assert.Equal(204, result.StatusCode);
}
[Fact(DisplayName = "Get Document by Id - Ok case")]
public async Task GetDocumentAsync_ShouldReturnStatusCode200()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockResponse = await MockData.getOkResponse(1);
mockDocumentService.Setup(service => service.GetDocumentAsync(1,"forms","en")).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (OkObjectResult)await DocumentProvider.GetDocumentAsync(1, "forms", "en");
Assert.Equal(200, result.StatusCode);
}
[Fact(DisplayName = "Get Document by Id - NotFound case")]
public async Task GetDocumentAsync_ShouldReturnStatusCode404()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockResponse = await MockData.getNotFoundResponse();
mockDocumentService.Setup(service => service.GetDocumentAsync(99, "forms", "en")).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (NotFoundResult)await DocumentProvider.GetDocumentAsync(99, "forms", "en");
Assert.Equal(404, result.StatusCode);
}
[Fact(DisplayName = "Post Document - Ok case")]
public async Task PostDocumentAsync_ShouldReturnStatusCode200()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockResponse = await MockData.getOkResponse(1);
var mockInputDocument = await MockData.getInputDocumentData();
var DocumentResponse = await MockData.GetDocumentsInfo(0);
mockDocumentService.Setup(service => service.PostDocumentAsync(mockInputDocument)).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (NoContentResult)await DocumentProvider.CreateDocument(DocumentResponse);
Assert.Equal(204, result.StatusCode);
}
[Fact(DisplayName = "Post Document - BadRequest case")]
public async Task PostDocumentAsync_ShouldReturnStatusCode400()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockInputDocument = await MockData.getInputDocumentData();
var mockResponse = await MockData.getBadRequestResponse();
DocumentInfo documentInfo = null;
mockDocumentService.Setup(service => service.PostDocumentAsync(mockInputDocument)).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (BadRequestObjectResult)await DocumentProvider.CreateDocument(documentInfo);
Assert.Equal(400, result.StatusCode);
}
[Fact(DisplayName = "Put Document - Ok case")]
public async Task PutDocumentAsync_ShouldReturnStatusCode200()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockResponse = await MockData.getOkResponse(1);
var mockInputDocument = await MockData.getInputDocumentData();
var DocumentResponse = await MockData.GetDocumentsInfo(1);
mockDocumentService.Setup(service => service.UpdateDocumentAsync(1,mockInputDocument)).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (NotFoundResult)await DocumentProvider.UpdateDocument(1,DocumentResponse);
Assert.Equal(404, result.StatusCode);
}
[Fact(DisplayName = "Put Document - BadRequest case")]
public async Task PutDocumentAsync_ShouldReturnStatusCode400()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockResponse = await MockData.getBadRequestResponse();
var mockInputDocument = await MockData.getInputDocumentData();
mockDocumentService.Setup(service => service.UpdateDocumentAsync(99,mockInputDocument)).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (BadRequestObjectResult)await DocumentProvider.UpdateDocument(99,null);
Assert.Equal(400, result.StatusCode);
}
[Fact(DisplayName = "Delete Document - Ok case")]
public async Task DeleteDocumentAsync_ShouldReturnStatusCode200()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockResponse = await MockData.getOkResponse(1);
mockDocumentService.Setup(service => service.DeleteDocumentAsync(1)).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (OkObjectResult)await DocumentProvider.DeleteDocument(1);
Assert.Equal(200, result.StatusCode);
}
[Fact(DisplayName = "Delete Document - NotFound case")]
public async Task DeleteDocumentAsync_ShouldReturnStatusCode404()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockResponse = await MockData.getNotFoundResponse();
mockDocumentService.Setup(service => service.DeleteDocumentAsync(1)).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (NotFoundResult)await DocumentProvider.DeleteDocument(1);
Assert.Equal(404, result.StatusCode);
}
// Link Type Test cases
[Fact(DisplayName = "Get Link types - Ok case")]
public async Task GetDocumentCategoriesAsync_ShouldReturnStatusCode200()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockResponse = await LinkTypeMockData.getOkResponse();
mockDocumentService.Setup(service => service.GetLinkTypesAsync()).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (OkObjectResult)await DocumentProvider.GetLinkTypesAsync();
Assert.Equal(200, result.StatusCode);
}
[Fact(DisplayName = "Get Link types - NoContent Case")]
public async Task GetDocumentCategoriesAsync_ShouldReturnStatusCode204()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockResponse = await LinkTypeMockData.getNoContentResponse();
mockDocumentService.Setup(service => service.GetLinkTypesAsync()).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (NoContentResult)await DocumentProvider.GetLinkTypesAsync();
Assert.Equal(204, result.StatusCode);
}
[Fact(DisplayName = "Get Link Type by Id - Ok case")]
public async Task GetDocumentcategoryAsync_ShouldReturnStatusCode200()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockResponse = await LinkTypeMockData.getOkResponse(1);
mockDocumentService.Setup(service => service.GetLinkTypeAsync(1)).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (OkObjectResult)await DocumentProvider.GetLinkTypeAsync(1);
Assert.Equal(200, result.StatusCode);
}
[Fact(DisplayName = "Get Link Type by Id - NotFound case")]
public async Task GetDocumentcategoryAsync_ShouldReturnStatusCode404()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockResponse = await LinkTypeMockData.getNotFoundResponse();
mockDocumentService.Setup(service => service.GetLinkTypeAsync(99)).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (NotFoundResult)await DocumentProvider.GetLinkTypeAsync(99);
Assert.Equal(404, result.StatusCode);
}
[Fact(DisplayName = "Post Link Type - Ok case")]
public async Task PostDocumentcategoryAsync_ShouldReturnStatusCode200()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockResponse = await LinkTypeMockData.getOkResponse(1);
var mockInputDocument = await LinkTypeMockData.getInputLinkData(0);
mockDocumentService.Setup(service => service.PostLinkTypeAsync(mockInputDocument)).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (OkObjectResult)await DocumentProvider.CreateLinkType(mockInputDocument);
Assert.Equal(200, result.StatusCode);
}
[Fact(DisplayName = "Post Link Type - BadRequest case")]
public async Task PostDocumentcategoryAsync_ShouldReturnStatusCode400()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockInputDocument = await LinkTypeMockData.getInputLinkData(99);
var mockResponse = await LinkTypeMockData.getBadRequestResponse();
mockDocumentService.Setup(service => service.PostLinkTypeAsync(mockInputDocument)).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (BadRequestObjectResult)await DocumentProvider.CreateLinkType(mockInputDocument);
Assert.Equal(400, result.StatusCode);
}
[Fact(DisplayName = "Put Document - Ok case")]
public async Task PutDocumentcategoryAsync_ShouldReturnStatusCode200()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockResponse = await LinkTypeMockData.getOkResponse(1);
var mockInputDocument = await LinkTypeMockData.getInputLinkData(1);
mockDocumentService.Setup(service => service.UpdateLinkTypeAsync(mockInputDocument)).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (OkObjectResult)await DocumentProvider.UpdateLinkType(mockInputDocument);
Assert.Equal(200, result.StatusCode);
}
[Fact(DisplayName = "Put Document - NotFound case")]
public async Task PutDocumentcategoryAsync_ShouldReturnStatusCode404()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockResponse = await LinkTypeMockData.getNotFoundResponse();
var mockInputDocument = await LinkTypeMockData.getInputLinkData(99);
mockDocumentService.Setup(service => service.UpdateLinkTypeAsync(mockInputDocument)).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (NotFoundObjectResult)await DocumentProvider.UpdateLinkType(mockInputDocument);
Assert.Equal(404, result.StatusCode);
}
[Fact(DisplayName = "Put Document - BadRequest case")]
public async Task PutDocumentcategoryAsync_ShouldReturnStatusCode400()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockResponse = await LinkTypeMockData.getBadRequestResponse();
var mockInputDocument = await LinkTypeMockData.getInputLinkData(1);
mockDocumentService.Setup(service => service.UpdateLinkTypeAsync(mockInputDocument)).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (BadRequestObjectResult)await DocumentProvider.UpdateLinkType(mockInputDocument);
Assert.Equal(400, result.StatusCode);
}
[Fact(DisplayName = "Delete Document - Ok case")]
public async Task DeleteDocumentcategoryAsync_ShouldReturnStatusCode200()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockResponse = await LinkTypeMockData.getOkResponse(1);
mockDocumentService.Setup(service => service.DeleteLinkTypeAsync(1)).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (OkObjectResult)await DocumentProvider.DeleteLinkType(1);
Assert.Equal(200, result.StatusCode);
}
[Fact(DisplayName = "Delete Document - NotFound case")]
public async Task DeleteDocumentcategoryAsync_ShouldReturnStatusCode404()
{
var mockDocumentService = new Mock<IDocumentsProvider>();
var mockUploadService = new Mock<IUploadService>();
var mockResponse = await LinkTypeMockData.getNotFoundResponse();
mockDocumentService.Setup(service => service.DeleteLinkTypeAsync(1)).ReturnsAsync(mockResponse);
var DocumentProvider = new DocumentsController(mockDocumentService.Object, mockUploadService.Object);
var result = (NotFoundResult)await DocumentProvider.DeleteLinkType(99);
Assert.Equal(404, result.StatusCode);
}
}
}

View File

@ -0,0 +1,61 @@
using DamageAssesment.Api.Documents.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
namespace DamageAssesment.Api.Documents.Test
{
public class LinkTypeMockData
{
public static async Task<(bool, List<Documents.Models.LinkType>, string)> getOkResponse()
{
List<Documents.Models.LinkType> list = new List<Documents.Models.LinkType>();
for (int i = 1; i < 4; i++)
{
list.Add(new Documents.Models.LinkType()
{
Id = i,
TypeText = "sample"+i,
IsActive = true
});
}
return (true, list, null);
}
public static async Task<(bool, Documents.Models.LinkType, string)> getOkResponse(int Id)
{
var Documents = await getOkResponse();
var Document = Documents.Item2.FirstOrDefault(s => s.Id == Id);
return (true, Document, null);
}
public static async Task<(bool, Documents.Models.LinkType, string)> getBadRequestResponse()
{
return (false, null, "Bad Request");
}
public static async Task<(bool, Documents.Models.LinkType, string)> getNotFoundResponse()
{
return (false, null, "Not Found");
}
public static async Task<(bool, IEnumerable<Documents.Models.LinkType>, string)> getNoContentResponse()
{
IEnumerable<Documents.Models.LinkType> list = new List<Documents.Models.LinkType>();
return (false, list, null);
}
public static async Task<Documents.Models.LinkType> getInputLinkData(int id)
{
return new Models.LinkType
{
Id = id,
TypeText = "sample",
IsActive = true
};
}
}
}

View File

@ -0,0 +1,122 @@
using DamageAssesment.Api.Documents.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Mail;
using System.Text;
using System.Threading.Tasks;
namespace DamageAssesment.Api.Documents.Test
{
public class MockData
{
public static async Task<(bool, List<Documents.Models.MultiLanDocument>, string)> getOkResponse()
{
List<Documents.Models.MultiLanDocument> list = new List<Documents.Models.MultiLanDocument>();
for (int i = 1; i < 4; i++)
{
Dictionary<string, string> dicttitle = new Dictionary<string, string>();
Dictionary<string, string> dictdesc = new Dictionary<string, string>();
dicttitle.Add("en", "test"); dicttitle.Add("fr", "tester");
dictdesc.Add("en", "test"); dictdesc.Add("fr", "tester");
List<Documents.Models.DocumentsTranslation> documentsTranslations = new List<DocumentsTranslation>();
documentsTranslations.Add(new DocumentsTranslation()
{
Language = "en",
title = "tel"+i,
description = "Sample"+i
});
list.Add(new Documents.Models.MultiLanDocument()
{
Id = i,
linkTypeId = i,
docName = "sample"+i,
url = "testurl" + i,
Path = "testpath" + i,
IsActive = true,
titles= dicttitle,
description=dictdesc,
dateCreated = DateTime.Now,
dateUpdated = DateTime.Now
});
}
return (true, list, null);
}
public static async Task<(bool, Documents.Models.MultiLanDocument, string)> getOkResponse(int Id)
{
var Documents = await getOkResponse();
var Document = Documents.Item2.FirstOrDefault(s => s.Id == Id);
return (true, Document, null);
}
public static async Task<(bool, Documents.Models.MultiLanDocument, string)> getBadRequestResponse()
{
return (false, null, "Bad Request");
}
public static async Task<(bool, Documents.Models.MultiLanDocument, string)> getNotFoundResponse()
{
return (false, null, "Not Found");
}
public static async Task<(bool, IEnumerable<Documents.Models.MultiLanDocument>, string)> getNoContentResponse()
{
IEnumerable<Documents.Models.MultiLanDocument> list = new List<Documents.Models.MultiLanDocument>();
return (false, list, null);
}
public static async Task<Documents.Models.DocumentInfo> GetDocumentsInfo(int id)
{
FileModel fileModel = new FileModel() { FileName = "Sample", FileContent = "c2FtcGxl", FileExtension = ".txt" };
return new DocumentInfo() { Id=id, linkTypeId = 1, url = "Sample", File = fileModel };
}
public static async Task<Documents.Models.Document> getInputDocumentData()
{
List<Documents.Models.DocumentsTranslation> documentsTranslations = new List<DocumentsTranslation>();
documentsTranslations.Add(new DocumentsTranslation()
{
Language = "en",
title = "tel",
description = "Sample"
});
return new Models.Document
{
Id = 1,
linkTypeId = 1,
docName = "sample",
url = "testurl",
Path = "testpath",
IsActive = true,
documentsTranslations= documentsTranslations,
dateCreated = DateTime.Now,
dateUpdated = DateTime.Now
};
}
public static async Task<List<Documents.Models.Document>> getInputDocumentsData()
{
List<Documents.Models.DocumentsTranslation> documentsTranslations = new List<DocumentsTranslation>();
documentsTranslations.Add(new DocumentsTranslation()
{
Language = "en",
title = "tel",
description="Sample"
});
List<Documents.Models.Document> Documents = new List<Models.Document>();
Documents.Add(new Models.Document
{
Id = 1,
linkTypeId = 1,
docName = "sample",
url = "testurl",
Path = "testpath",
IsActive = true,
documentsTranslations= documentsTranslations,
dateCreated = DateTime.Now,
dateUpdated = DateTime.Now
});
return Documents;
}
}
}

View File

@ -0,0 +1,224 @@
using DamageAssesment.Api.Documents.Db;
using DamageAssesment.Api.Documents.Interfaces;
using DamageAssesment.Api.Documents.Models;
using DamageAssesment.Api.Documents.Providers;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace DamageAssesment.Api.Documents.Controllers
{
[ApiController]
public class DocumentsController : ControllerBase
{
private readonly IDocumentsProvider documentsProvider;
private readonly IUploadService uploadService;
public DocumentsController(IDocumentsProvider documentsProvider,IUploadService uploadService)
{
this.documentsProvider = documentsProvider;
this.uploadService = uploadService;
}
/// <summary>
/// Get all document link type.
/// </summary>
[HttpGet]
[Route("doculinks/types")]
public async Task<IActionResult> GetLinkTypesAsync()
{
var result = await this.documentsProvider.GetLinkTypesAsync();
if (result.IsSuccess)
{
return Ok(result.LinkTypes);
}
return NoContent();
}
/// <summary>
/// Get a document link type by id.
/// </summary>
[HttpGet]
[Route("doculinks/types/{id}")]
public async Task<IActionResult> GetLinkTypeAsync(int id)
{
var result = await this.documentsProvider.GetLinkTypeAsync(id);
if (result.IsSuccess)
{
return Ok(result.LinkType);
}
return NotFound();
}
/// <summary>
/// Update a existing document link type.
/// </summary>
[HttpPut]
[Route("doculinks/types")]
public async Task<IActionResult> UpdateLinkType(Models.LinkType linkType)
{
if (linkType != null)
{
var result = await this.documentsProvider.UpdateLinkTypeAsync(linkType);
if (result.IsSuccess)
{
return Ok(result.LinkType);
}
if (result.ErrorMessage == "Not Found")
return NotFound(result.ErrorMessage);
return BadRequest(result.ErrorMessage);
}
return CreatedAtRoute("DefaultApi", new { id = linkType.Id }, linkType);
}
/// <summary>
/// Create a new document link type.
/// </summary>
[HttpPost]
[Route("doculinks/types")]
public async Task<IActionResult> CreateLinkType(Models.LinkType linkType)
{
if (linkType != null)
{
var result = await this.documentsProvider.PostLinkTypeAsync(linkType);
if (result.IsSuccess)
{
return Ok(result.LinkType);
}
return BadRequest(result.ErrorMessage);
}
return CreatedAtRoute("DefaultApi", new { id = linkType.Id }, linkType);
}
/// <summary>
/// Delete a existing document link type by id.
/// </summary>
[HttpDelete]
[Route("doculinks/types/{id}")]
public async Task<IActionResult> DeleteLinkType(int id)
{
var result = await this.documentsProvider.DeleteLinkTypeAsync(id);
if (result.IsSuccess)
{
return Ok(result.LinkType);
}
return NotFound();
}
/// <summary>
/// Get all documents.
/// </summary>
///
[Route("doculinks")]
[Route("doculinks/{linktype:alpha}")]
[Route("doculinks/{linktype:alpha}/{language:alpha}")]
[HttpGet]
public async Task<IActionResult> GetDocumentsAsync(string? linktype, string? language)
{
var result = await this.documentsProvider.GetdocumentsByLinkAsync(linktype, language);
if (result.IsSuccess)
{
return Ok(result.documents);
}
return NoContent();
}
/// <summary>
/// Get all documents.
/// </summary>
///
//[Route("doculinks/{language:alpha}")]
//[Route("doculinks")]
//[HttpGet]
//public async Task<IActionResult> GetDocumentsAsync(string? language)
//{
// var result = await this.documentsProvider.GetdocumentsAsync(language);
// if (result.IsSuccess)
// {
// return Ok(result.documents);
// }
// return NoContent();
//}
/// <summary>
/// Get a document by id.
/// </summary>
[HttpGet]
[Route("doculinks/{id}")]
[Route("doculinks/{id}/{linktype:alpha}")]
[Route("doculinks/{id}/{linktype:alpha}/{language:alpha}")]
public async Task<IActionResult> GetDocumentAsync(int id,string? linktype, string? language)
{
var result = await this.documentsProvider.GetDocumentAsync(id, linktype, language);
if (result.IsSuccess)
{
return Ok(result.Document);
}
return NotFound();
}
/// <summary>
/// Upload new document.
/// </summary>
[HttpPut]
[Route("doculinks/{id}")]
public async Task<IActionResult> UpdateDocument(int id,DocumentInfo documentInfo)
{
if (documentInfo != null)
{
var dbdoc = await this.documentsProvider.GetDocumentByidAsync(id);
if (dbdoc.IsSuccess)
{
Models.Document document = uploadService.UpdateDocuments(dbdoc.Document, documentInfo);
var result = await this.documentsProvider.UpdateDocumentAsync(id,document);
if (result.IsSuccess)
{
return Ok(result.Document);
}
return NoContent();
}
return NotFound();
}
return BadRequest(documentInfo);
}
/// <summary>
/// update existing document.
/// </summary>
[HttpPost]
[Route("doculinks")]
public async Task<IActionResult> CreateDocument(DocumentInfo documentInfo)
{
try
{
if (documentInfo != null)
{
var documents = await this.documentsProvider.GetDocumentCounter();
Models.Document document = uploadService.UploadDocument(documents.counter, documentInfo);
var result = await this.documentsProvider.PostDocumentAsync(document);
if (result.IsSuccess)
{
return Ok(result.Document);
}
return NoContent();
}
return BadRequest(documentInfo);
}
catch (Exception ex)
{
return BadRequest($"Internal server error: {ex}");
}
}
/// <summary>
/// Delete document by id.
/// </summary>
[HttpDelete]
[Route("doculinks/{id}")]
public async Task<IActionResult> DeleteDocument(int id)
{
// database soft delete
var result = await this.documentsProvider.DeleteDocumentAsync(id);
if (result.IsSuccess)
{
// deleting file from folder
uploadService.Movefile(result.Document.Path);
return Ok(result.Document);
}
return NotFound();
}
}
}

View File

@ -0,0 +1,32 @@
<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="Azure.Storage.Blobs" Version="12.16.0" />
<PackageReference Include="Microsoft.AspNetCore.Hosting" Version="2.2.7" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.9">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.5" />
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.9" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.9">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
</ItemGroup>
<ItemGroup>
<Folder Include="DASA_Documents\" />
</ItemGroup>
</Project>

View File

@ -0,0 +1,23 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DamageAssesment.Api.Documents.Db
{
public class Document
{
[Key]
public int Id { get; set; }
[ForeignKey("LinkType")]
public int linkTypeId { get; set; }
public LinkType? LinkType { get; set; }
public string docName { get; set; }
public string url { get; set; }
public string Path { get; set; }
public bool IsActive { get; set; }
public DateTime dateCreated { get; set; }
public DateTime dateUpdated { get; set; }
}
}

View File

@ -0,0 +1,30 @@
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using System.ComponentModel.DataAnnotations;
namespace DamageAssesment.Api.Documents.Db
{
public class DocumentDbContext : DbContext
{
public DocumentDbContext(DbContextOptions options) : base(options)
{
}
public DbSet<Db.Document> Documents { get; set; }
public DbSet<Db.LinkType> LinkTypes { get; set; }
public DbSet<Db.DocumentsTranslation> DocumentsTranslations { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<Document>()
.Property(item => item.Id)
.ValueGeneratedOnAdd();
modelBuilder.Entity<LinkType>()
.Property(item => item.Id)
.ValueGeneratedOnAdd();
modelBuilder.Entity<DocumentsTranslation>()
.Property(item => item.Id)
.ValueGeneratedOnAdd();
}
}
}

View File

@ -0,0 +1,16 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DamageAssesment.Api.Documents.Db
{
public class DocumentsTranslation
{
[Key]
public int Id { get; set; }
[ForeignKey("Document")]
public int DocumentId { get; set; }
public string title { get; set; }
public string description { get; set; }
public string Language { get; set; }
}
}

View File

@ -0,0 +1,13 @@
using System.ComponentModel.DataAnnotations;
namespace DamageAssesment.Api.Documents.Db
{
public class LinkType
{
[Key]
public int Id { get; set; }
public string TypeText { get; set; }
public bool IsActive { get; set; }
public bool IsAttachment { get; set; }
}
}

View File

@ -0,0 +1,10 @@
using Azure.Storage.Blobs.Models;
namespace DamageAssesment.Api.Documents.Interfaces
{
public interface IAzureBlobService
{
Task<List<Azure.Response<BlobContentInfo>>> UploadFiles(List<IFormFile> files);
void DeleteFile(string path);
}
}

View File

@ -0,0 +1,11 @@
namespace DamageAssesment.Api.Documents.Interfaces
{
public interface ILinkTypesProvider
{
Task<(bool IsSuccess, Models.LinkType LinkType, string ErrorMessage)> GetLinkTypeAsync(int Id);
Task<(bool IsSuccess, IEnumerable<Models.LinkType> LinkTypes, string ErrorMessage)> GetLinkTypesAsync();
Task<(bool IsSuccess, Models.LinkType LinkType, string ErrorMessage)> PostLinkTypeAsync(Models.LinkType LinkType);
Task<(bool IsSuccess, Models.LinkType LinkType, string ErrorMessage)> UpdateLinkTypeAsync(Models.LinkType LinkType);
Task<(bool IsSuccess, Models.LinkType LinkType, string ErrorMessage)> DeleteLinkTypeAsync(int Id);
}
}

View File

@ -0,0 +1,18 @@
using DamageAssesment.Api.Documents.Models;
namespace DamageAssesment.Api.Documents.Interfaces
{
public interface IDocumentsProvider : ILinkTypesProvider
{
Task<(bool IsSuccess, Models.MultiLanDocument Document, string ErrorMessage)> GetDocumentAsync(int id, string? linktype, string? language);
Task<(bool IsSuccess, Models.Document Document, string ErrorMessage)> GetDocumentByidAsync(int id);
// Task<(bool IsSuccess, IEnumerable<Models.MultiLanDocument> documents, string ErrorMessage)> GetDocumnetsAsync(string? language);
Task<(bool IsSuccess, IEnumerable<Models.MultiLanDocument> documents, string ErrorMessage)> GetdocumentsByLinkAsync(string? linkType, string? language);
Task<(bool IsSuccess, Models.MultiLanDocument Document, string ErrorMessage)> PostDocumentAsync(Models.Document Document);
Task<(bool IsSuccess, Models.MultiLanDocument Document, string ErrorMessage)> UpdateDocumentAsync(int id,Models.Document Document);
Task<(bool IsSuccess, Models.MultiLanDocument Document, string ErrorMessage)> DeleteDocumentAsync(int id);
Task<(bool IsSuccess, int counter, string message)> GetDocumentCounter();
}
}

View File

@ -0,0 +1,12 @@
using DamageAssesment.Api.Documents.Models;
namespace DamageAssesment.Api.Documents.Interfaces
{
public interface IUploadService
{
Models.Document UploadDocument( int counter, DocumentInfo documentInfo);
public Models.Document UpdateDocuments( Models.Document document, DocumentInfo documentInfo);
void Deletefile(string path);
void Movefile(string path);
}
}

View File

@ -0,0 +1,95 @@
// <auto-generated />
using System;
using DamageAssesment.Api.Documents.Db;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace DamageAssesment.Api.Documents.Migrations
{
[DbContext(typeof(DocumentDbContext))]
[Migration("20230828165655_InitialDocumentCreate")]
partial class InitialDocumentCreate
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.9")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("DamageAssesment.Api.Documents.Db.Document", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<string>("Path")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("dateCreated")
.HasColumnType("datetime2");
b.Property<DateTime>("dateUpdated")
.HasColumnType("datetime2");
b.Property<string>("description")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("docName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("linkTypeId")
.HasColumnType("int");
b.Property<string>("title")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("url")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Documents");
});
modelBuilder.Entity("DamageAssesment.Api.Documents.Db.LinkType", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<string>("TypeText")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("LinkTypes");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,60 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace DamageAssesment.Api.Documents.Migrations
{
/// <inheritdoc />
public partial class InitialDocumentCreate : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "Documents",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
title = table.Column<string>(type: "nvarchar(max)", nullable: false),
linkTypeId = table.Column<int>(type: "int", nullable: false),
description = table.Column<string>(type: "nvarchar(max)", nullable: false),
docName = table.Column<string>(type: "nvarchar(max)", nullable: false),
url = table.Column<string>(type: "nvarchar(max)", nullable: false),
Path = table.Column<string>(type: "nvarchar(max)", nullable: false),
IsActive = table.Column<bool>(type: "bit", nullable: false),
dateCreated = table.Column<DateTime>(type: "datetime2", nullable: false),
dateUpdated = table.Column<DateTime>(type: "datetime2", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Documents", x => x.Id);
});
migrationBuilder.CreateTable(
name: "LinkTypes",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
TypeText = table.Column<string>(type: "nvarchar(max)", nullable: false),
IsActive = table.Column<bool>(type: "bit", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_LinkTypes", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Documents");
migrationBuilder.DropTable(
name: "LinkTypes");
}
}
}

View File

@ -0,0 +1,118 @@
// <auto-generated />
using System;
using DamageAssesment.Api.Documents.Db;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace DamageAssesment.Api.Documents.Migrations
{
[DbContext(typeof(DocumentDbContext))]
[Migration("20230830200432_DocumentTranslation")]
partial class DocumentTranslation
{
/// <inheritdoc />
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.9")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("DamageAssesment.Api.Documents.Db.Document", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<string>("Path")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("dateCreated")
.HasColumnType("datetime2");
b.Property<DateTime>("dateUpdated")
.HasColumnType("datetime2");
b.Property<string>("docName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("linkTypeId")
.HasColumnType("int");
b.Property<string>("url")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Documents");
});
modelBuilder.Entity("DamageAssesment.Api.Documents.Db.DocumentsTranslation", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("DocumentId")
.HasColumnType("int");
b.Property<string>("Language")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("description")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("title")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("DocumentsTranslations");
});
modelBuilder.Entity("DamageAssesment.Api.Documents.Db.LinkType", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<bool>("IsAttachment")
.HasColumnType("bit");
b.Property<string>("TypeText")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("LinkTypes");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,70 @@
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace DamageAssesment.Api.Documents.Migrations
{
/// <inheritdoc />
public partial class DocumentTranslation : Migration
{
/// <inheritdoc />
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "description",
table: "Documents");
migrationBuilder.DropColumn(
name: "title",
table: "Documents");
migrationBuilder.AddColumn<bool>(
name: "IsAttachment",
table: "LinkTypes",
type: "bit",
nullable: false,
defaultValue: false);
migrationBuilder.CreateTable(
name: "DocumentsTranslations",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
DocumentId = table.Column<int>(type: "int", nullable: false),
title = table.Column<string>(type: "nvarchar(max)", nullable: false),
description = table.Column<string>(type: "nvarchar(max)", nullable: false),
Language = table.Column<string>(type: "nvarchar(max)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_DocumentsTranslations", x => x.Id);
});
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "DocumentsTranslations");
migrationBuilder.DropColumn(
name: "IsAttachment",
table: "LinkTypes");
migrationBuilder.AddColumn<string>(
name: "description",
table: "Documents",
type: "nvarchar(max)",
nullable: false,
defaultValue: "");
migrationBuilder.AddColumn<string>(
name: "title",
table: "Documents",
type: "nvarchar(max)",
nullable: false,
defaultValue: "");
}
}
}

View File

@ -0,0 +1,115 @@
// <auto-generated />
using System;
using DamageAssesment.Api.Documents.Db;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
#nullable disable
namespace DamageAssesment.Api.Documents.Migrations
{
[DbContext(typeof(DocumentDbContext))]
partial class DocumentDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "7.0.9")
.HasAnnotation("Relational:MaxIdentifierLength", 128);
SqlServerModelBuilderExtensions.UseIdentityColumns(modelBuilder);
modelBuilder.Entity("DamageAssesment.Api.Documents.Db.Document", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<string>("Path")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("dateCreated")
.HasColumnType("datetime2");
b.Property<DateTime>("dateUpdated")
.HasColumnType("datetime2");
b.Property<string>("docName")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<int>("linkTypeId")
.HasColumnType("int");
b.Property<string>("url")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("Documents");
});
modelBuilder.Entity("DamageAssesment.Api.Documents.Db.DocumentsTranslation", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<int>("DocumentId")
.HasColumnType("int");
b.Property<string>("Language")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("description")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.Property<string>("title")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("DocumentsTranslations");
});
modelBuilder.Entity("DamageAssesment.Api.Documents.Db.LinkType", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int");
SqlServerPropertyBuilderExtensions.UseIdentityColumn(b.Property<int>("Id"));
b.Property<bool>("IsActive")
.HasColumnType("bit");
b.Property<bool>("IsAttachment")
.HasColumnType("bit");
b.Property<string>("TypeText")
.IsRequired()
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.ToTable("LinkTypes");
});
#pragma warning restore 612, 618
}
}
}

View File

@ -0,0 +1,28 @@
using System.ComponentModel.DataAnnotations;
namespace DamageAssesment.Api.Documents.Models
{
public class Document : BaseDocument
{
public List<DocumentsTranslation> documentsTranslations { get; set; }
}
public class MultiLanDocument:BaseDocument
{
public object titles { get; set; }
public object description { get; set; }
public string LinkType { get; set; }
}
public class BaseDocument
{
public int Id { get; set; }
public int linkTypeId { get; set; }
public string docName { get; set; }
public string url { get; set; }
public string Path { get; set; }
public bool IsActive { get; set; }
public DateTime dateCreated { get; set; }
public DateTime dateUpdated { get; set; }
}
}

View File

@ -0,0 +1,19 @@
using System.ComponentModel.DataAnnotations.Schema;
namespace DamageAssesment.Api.Documents.Models
{
public class DocumentInfo
{
public int Id { get; set; }
public int linkTypeId { get; set; }
public string url { get; set; }
public List<DocumentsTranslation> documentsTranslations { get; set; }
public FileModel? File { get; set; }
}
public class FileModel
{
public string? FileName { get; set; }
public string? FileContent { get; set; }
public string? FileExtension { get; set; }
}
}

View File

@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DamageAssesment.Api.Documents.Models
{
public class DocumentsTranslation
{
public string title { get; set; }
public string description { get; set; }
public string Language { get; set; }
}
}

View File

@ -0,0 +1,12 @@
using System.ComponentModel.DataAnnotations;
namespace DamageAssesment.Api.Documents.Models
{
public class LinkType
{
public int Id { get; set; }
public string TypeText { get; set; }
public bool IsActive { get; set; }
public bool IsAttachment { get; set; }
}
}

View File

@ -0,0 +1,19 @@
using AutoMapper;
namespace DamageAssesment.Api.Documents.Profiles
{
public class DocumentProfile : AutoMapper.Profile
{
public DocumentProfile()
{
CreateMap<Db.Document, Models.MultiLanDocument>().ForMember(dest => dest.LinkType,
opt => opt.MapFrom(src => src.LinkType.TypeText)); ;
CreateMap<Db.Document, Models.Document>();
CreateMap<Models.Document, Db.Document>();
CreateMap<Db.LinkType, Models.LinkType>();
CreateMap<Models.LinkType, Db.LinkType>();
CreateMap<Db.DocumentsTranslation, Models.DocumentsTranslation>();
CreateMap<Models.DocumentsTranslation, Db.DocumentsTranslation>();
}
}
}

View File

@ -0,0 +1,43 @@
using DamageAssesment.Api.Documents.Db;
using DamageAssesment.Api.Documents.Interfaces;
using DamageAssesment.Api.Documents.Providers;
using Microsoft.EntityFrameworkCore;
using System.Reflection;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllers();
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);
});
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
builder.Services.AddScoped<IDocumentsProvider, documentsProvider>();
builder.Services.AddScoped<IUploadService, UploadService>();
builder.Services.AddScoped<IAzureBlobService, AzureBlobService>();
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); //4/30
builder.Services.AddDbContext<DocumentDbContext>(option =>
{
option.UseInMemoryDatabase("DocumentConnection");
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseSwagger();
app.UseSwaggerUI();
}
app.UseAuthorization();
app.MapControllers();
app.Run();

View File

@ -4,17 +4,17 @@
"windowsAuthentication": false,
"anonymousAuthentication": true,
"iisExpress": {
"applicationUrl": "http://localhost:28382",
"applicationUrl": "http://localhost:60754",
"sslPort": 0
}
},
"profiles": {
"DamageAssesment.Api.Users": {
"DamageAssesment.Api.Questions": {
"commandName": "Project",
"dotnetRunMessages": true,
"launchBrowser": true,
"launchUrl": "swagger",
"applicationUrl": "http://localhost:5027",
"applicationUrl": "http://localhost:5133",
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
}

View File

@ -0,0 +1,44 @@

using Azure.Storage.Blobs;
using Azure.Storage.Blobs.Models;
using Azure.Storage.Blobs.Specialized;
using DamageAssesment.Api.Documents.Interfaces;
namespace DamageAssesment.Api.Documents.Providers
{
public class AzureBlobService: IAzureBlobService
{
BlobServiceClient _blobClient;
BlobContainerClient _containerClient;
string azureConnectionString = "<Primary Connection String>";
public AzureBlobService()
{
_blobClient = new BlobServiceClient(azureConnectionString);
_containerClient = _blobClient.GetBlobContainerClient("apiimages");
}
public async Task<List<Azure.Response<BlobContentInfo>>> UploadFiles(List<IFormFile> files)
{
var azureResponse = new List<Azure.Response<BlobContentInfo>>();
foreach (var file in files)
{
string fileName = file.FileName;
using (var memoryStream = new MemoryStream())
{
file.CopyTo(memoryStream);
memoryStream.Position = 0;
var client = await _containerClient.UploadBlobAsync(fileName, memoryStream, default);
azureResponse.Add(client);
}
};
return azureResponse;
}
public void DeleteFile(string url)
{
var blob = _containerClient.GetBlockBlobClient(url);
blob.DeleteIfExists();
}
}
}

View File

@ -0,0 +1,434 @@
using AutoMapper;
using DamageAssesment.Api.Documents.Db;
using DamageAssesment.Api.Documents.Interfaces;
using DamageAssesment.Api.Documents.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System;
using System.Diagnostics.Eventing.Reader;
using System.Reflection.Metadata;
namespace DamageAssesment.Api.Documents.Providers
{
public class documentsProvider : IDocumentsProvider
{
private DocumentDbContext DocumentDbContext;
private ILogger<documentsProvider> logger;
private IUploadService uploadservice;
private IMapper mapper;
public documentsProvider(DocumentDbContext DocumentDbContext, ILogger<documentsProvider> logger, IMapper mapper, IUploadService uploadservice)
{
this.DocumentDbContext = DocumentDbContext;
this.logger = logger;
this.mapper = mapper;
this.uploadservice = uploadservice;
SeedData();
}
private void SeedData()
{
if (!DocumentDbContext.LinkTypes.Any())
{
DocumentDbContext.LinkTypes.Add(new Db.LinkType() {TypeText = "Forms",IsActive=true, IsAttachment=true });
DocumentDbContext.LinkTypes.Add(new Db.LinkType() {TypeText = "Communiques",IsActive = true,IsAttachment=false });
DocumentDbContext.LinkTypes.Add(new Db.LinkType() {TypeText = "Memos",IsActive = true,IsAttachment=true });
DocumentDbContext.SaveChanges();
}
if (!DocumentDbContext.Documents.Any())
{
FileModel fileModel = new FileModel() { FileName = "Sample", FileContent = "c2FtcGxl", FileExtension = ".txt" };
DocumentInfo documentInfo = new DocumentInfo() { linkTypeId = 1, url = "Sample", File = fileModel };
Models.Document document = uploadservice.UploadDocument(0, documentInfo);
DocumentDbContext.Documents.Add(mapper.Map<Models.Document, Db.Document>(document));
DocumentDbContext.SaveChanges();
}
if (!DocumentDbContext.DocumentsTranslations.Any())
{
Db.DocumentsTranslation documents = new Db.DocumentsTranslation { DocumentId = 1, title = "Test", description = "ss", Language = "en" };
DocumentDbContext.DocumentsTranslations.Add(documents);
DocumentDbContext.SaveChanges();
}
}
public List<Models.DocumentsTranslation> GetDocumentTranslations(int id, string? language)
{
List<Models.DocumentsTranslation> QuestionTranslations;
if (string.IsNullOrEmpty(language))
{
QuestionTranslations = mapper.Map<List<Db.DocumentsTranslation>, List<Models.DocumentsTranslation>>(
DocumentDbContext.DocumentsTranslations.AsNoTracking().Where(a => a.DocumentId == id).ToList());
}
else
{
QuestionTranslations = mapper.Map<List<Db.DocumentsTranslation>, List<Models.DocumentsTranslation>>(
DocumentDbContext.DocumentsTranslations.AsNoTracking().Where(a => a.DocumentId == id && a.Language == language).ToList());
}
return QuestionTranslations;
}
public MultiLanDocument CreateMultiLanguageObject(List<Models.DocumentsTranslation> questions)
{
MultiLanDocument MultiLanguage = new MultiLanDocument();
Dictionary<string, string> dicttitle = new Dictionary<string, string>();
Dictionary<string, string> dictdesc = new Dictionary<string, string>();
foreach (Models.DocumentsTranslation item in questions)
{
dicttitle.Add(item.Language, item.title);
dictdesc.Add(item.Language, item.description);
}
MultiLanguage.titles = dicttitle;
MultiLanguage.description = dictdesc;
return MultiLanguage;
}
public async Task<(bool IsSuccess, IEnumerable<Models.MultiLanDocument> documents, string ErrorMessage)> GetdocumentsByLinkAsync(string? linkType, string? language)
{
try
{
logger?.LogInformation("Query Question");
var documents=new List<Db.Document>();
if(String.IsNullOrEmpty(linkType))
documents = await DocumentDbContext.Documents.Include(a=>a.LinkType).AsNoTracking().Where(q => q.IsActive).ToListAsync();
else
documents = await DocumentDbContext.Documents.Include(a => a.LinkType).AsNoTracking().Where(q => q.IsActive &&
q.linkTypeId == (DocumentDbContext.LinkTypes.AsNoTracking().Where(a => a.TypeText.ToLower() == linkType.ToLower()).Select(a => a.Id).FirstOrDefault())).ToListAsync();
if (documents != null)
{
var result = mapper.Map<List<Db.Document>, List<Models.MultiLanDocument>>(documents);
foreach (var item in result)
{
var multilan = CreateMultiLanguageObject(GetDocumentTranslations(item.Id, language));
item.titles = multilan.titles;
item.description = multilan.description;
}
return (true, result, null);
}
return (false, null, "Not found");
}
catch (Exception ex)
{
logger?.LogError(ex.ToString());
return (false, null, ex.Message);
}
}
//public async Task<(bool IsSuccess, IEnumerable<Models.MultiLanDocument> documents, string ErrorMessage)> GetDocumnetsAsync(string? language)
//{
// try
// {
// logger?.LogInformation("Query Question");
// var documents = await DocumentDbContext.Documents.Include(a => a.LinkType).AsNoTracking().Where(q => q.IsActive).ToListAsync();
// if (documents != null)
// {
// logger?.LogInformation($"{documents.Count} Document(s) found");
// var result = mapper.Map<List<Db.Document>, List<Models.MultiLanDocument>>(documents);
// foreach (var item in result)
// {
// var multilan = CreateMultiLanguageObject(GetDocumentTranslations(item.Id, language));
// item.titles = multilan.titles;
// item.description = multilan.description;
// }
// return (true, result, null);
// }
// return (false, null, "Not found");
// }
// catch (Exception ex)
// {
// logger?.LogError(ex.ToString());
// return (false, null, ex.Message);
// }
//}
public async Task<(bool IsSuccess, Models.Document Document, string ErrorMessage)> GetDocumentByidAsync(int id)
{
try
{
logger?.LogInformation("Query LinkType");
var Document = await DocumentDbContext.Documents.Include(a => a.LinkType).AsNoTracking().FirstOrDefaultAsync(q => q.Id == id && q.IsActive);
if (Document != null)
{
logger?.LogInformation($"{Document} customer(s) found");
var result = mapper.Map<Db.Document, Models.Document>(Document);
result.documentsTranslations = mapper.Map<List<Db.DocumentsTranslation>, List<Models.DocumentsTranslation>>(
DocumentDbContext.DocumentsTranslations.Where(a => a.DocumentId == result.Id).ToList());
return (true, result, null);
}
return (false, null, "Not found");
}
catch (Exception ex)
{
logger?.LogError(ex.ToString());
return (false, null, ex.Message);
}
}
//added linktype filter
public async Task<(bool IsSuccess, Models.MultiLanDocument Document, string ErrorMessage)> GetDocumentAsync(int id, string? linkType, string? language)
{
try
{
logger?.LogInformation("Query LinkType");
//var Document = await DocumentDbContext.Documents.Include(a => a.LinkType).AsNoTracking().FirstOrDefaultAsync(q => q.Id == id && q.IsActive);
var Document = new Db.Document();
if (String.IsNullOrEmpty(linkType))
Document = await DocumentDbContext.Documents.Include(a => a.LinkType).AsNoTracking().Where(q => q.IsActive&&q.Id==id).FirstOrDefaultAsync();
else
Document = await DocumentDbContext.Documents.Include(a => a.LinkType).AsNoTracking().Where(q => q.IsActive && q.Id == id &&
q.linkTypeId == (DocumentDbContext.LinkTypes.AsNoTracking().Where(a => a.TypeText.ToLower() == linkType.ToLower()).Select(a => a.Id).FirstOrDefault())).FirstOrDefaultAsync();
if (Document != null)
{
logger?.LogInformation($"{Document} customer(s) found");
var result = mapper.Map<Db.Document, Models.MultiLanDocument>(Document);
var multilan = CreateMultiLanguageObject(GetDocumentTranslations(result.Id, language));
result.titles = multilan.titles;
result.description = multilan.description;
return (true, result, null);
}
return (false, null, "Not found");
}
catch (Exception ex)
{
logger?.LogError(ex.ToString());
return (false, null, ex.Message);
}
}
public async Task<(bool IsSuccess, Models.MultiLanDocument Document, string ErrorMessage)> PostDocumentAsync(Models.Document Document)
{
try
{
var document = mapper.Map<Models.Document, Db.Document>(Document);
DocumentDbContext.Documents.Add(document);
DocumentDbContext.SaveChanges();
var dbtranslation = mapper.Map<List<Models.DocumentsTranslation>, List<Db.DocumentsTranslation>>(Document.documentsTranslations);
dbtranslation.ForEach(i => i.DocumentId = document.Id);
DocumentDbContext.DocumentsTranslations.AddRange(dbtranslation);
DocumentDbContext.SaveChanges();
var result = mapper.Map<Db.Document, Models.MultiLanDocument>(document);
var multilan = CreateMultiLanguageObject(GetDocumentTranslations(document.Id, ""));
result.titles = multilan.titles;
result.description = multilan.description;
return (true, result, null);
}
catch (Exception ex)
{
logger?.LogError(ex.ToString());
return (false, null, ex.Message);
}
}
public async Task<(bool IsSuccess, Models.MultiLanDocument Document, string ErrorMessage)> UpdateDocumentAsync(int id,Models.Document Document)
{
try
{
if (Document != null)
{
var existing = DocumentDbContext.Documents.AsNoTracking().FirstOrDefault(x => x.Id == id);
if (existing != null)
{
Document.Id = existing.Id;
var document = mapper.Map<Models.Document, Db.Document>(Document);
DocumentDbContext.Documents.Update(document);
DocumentDbContext.SaveChanges();
var oldtranslations = DocumentDbContext.DocumentsTranslations.Where(a => a.DocumentId == Document.Id).ToList();
if (oldtranslations != null)
DocumentDbContext.DocumentsTranslations.RemoveRange(oldtranslations);
var dbtranslation = mapper.Map<List<Models.DocumentsTranslation>, List<Db.DocumentsTranslation>>(Document.documentsTranslations);
dbtranslation.ForEach(i => i.DocumentId = Document.Id);
DocumentDbContext.DocumentsTranslations.AddRange(dbtranslation);
DocumentDbContext.SaveChanges();
var result = mapper.Map<Db.Document, Models.MultiLanDocument>(document);
var multilan = CreateMultiLanguageObject(GetDocumentTranslations(document.Id, ""));
result.titles = multilan.titles;
result.description = multilan.description;
return (true, result, "Successful");
}
else
{
logger?.LogInformation($"{Document} Not found");
return (false, null, "Not Found");
}
}
else
{
logger?.LogInformation($"{Document} 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.MultiLanDocument Document, string ErrorMessage)> DeleteDocumentAsync(int id)
{
try
{
Db.Document Document = DocumentDbContext.Documents.Include(a => a.LinkType).AsNoTracking().Where(a => a.Id == id).FirstOrDefault();
if (Document == null)
{
return (false, null, "Not Found");
}
var result = mapper.Map<Db.Document, Models.MultiLanDocument>(Document);
var multilan = CreateMultiLanguageObject(GetDocumentTranslations(Document.Id, ""));
result.titles = multilan.titles;
result.description = multilan.description;
Document.IsActive = false;
DocumentDbContext.Documents.Update(Document);
DocumentDbContext.SaveChanges();
return (true, result, $"DocumentId {id} deleted Successfuly");
}
catch (Exception ex)
{
logger?.LogError(ex.ToString());
return (false, null, ex.Message);
}
}
public async Task<(bool IsSuccess, int counter, string message)> GetDocumentCounter()
{
try
{
int AttachmentId = DocumentDbContext.Documents.Max(a => a.Id);
return (true, AttachmentId, "");
}
catch (Exception ex)
{
return (false, 0, ex.Message);
}
}
//Link Type methods
public async Task<(bool IsSuccess, IEnumerable<Models.LinkType> LinkTypes, string ErrorMessage)> GetLinkTypesAsync()
{
try
{
logger?.LogInformation("Query Question");
var LinkType = await DocumentDbContext.LinkTypes.AsNoTracking().Where(q=>q.IsActive).ToListAsync();
if (LinkType != null)
{
logger?.LogInformation($"{LinkType.Count} LinkTypes(s) found");
var result = mapper.Map<IEnumerable<Db.LinkType>, IEnumerable<Models.LinkType>>(LinkType);
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.LinkType LinkType, string ErrorMessage)> GetLinkTypeAsync(int Id)
{
try
{
logger?.LogInformation("Query LinkType");
var LinkType = await DocumentDbContext.LinkTypes.AsNoTracking().FirstOrDefaultAsync(q => q.Id == Id&&q.IsActive);
if (LinkType != null)
{
logger?.LogInformation($"{LinkType} customer(s) found");
var result = mapper.Map<Db.LinkType, Models.LinkType>(LinkType);
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.LinkType LinkType, string ErrorMessage)> PostLinkTypeAsync(Models.LinkType LinkType)
{
try
{
logger?.LogInformation("Query LinkType");
if (!LinkTypeExists(LinkType.Id))
{
var dbLink = mapper.Map<Models.LinkType, Db.LinkType>(LinkType);
DocumentDbContext.LinkTypes.Add(dbLink);
DocumentDbContext.SaveChanges();
var result = mapper.Map<Db.LinkType, Models.LinkType>(dbLink);
return (true, result, null);
}
return (false, null, "LinkType is already exits");
}
catch (Exception ex)
{
logger?.LogError(ex.ToString());
return (false, null, ex.Message);
}
}
public async Task<(bool IsSuccess, Models.LinkType LinkType, string ErrorMessage)> UpdateLinkTypeAsync(Models.LinkType LinkType)
{
try
{
if (LinkType != null)
{
var existing = DocumentDbContext.LinkTypes.AsNoTracking().FirstOrDefault(x => x.Id == LinkType.Id);
if (existing != null)
{
var dbLink = mapper.Map<Models.LinkType, Db.LinkType>(LinkType);
DocumentDbContext.LinkTypes.Update(dbLink);
DocumentDbContext.SaveChanges();
return (true, mapper.Map<Db.LinkType, Models.LinkType>(dbLink), "Successful");
}
else
{
logger?.LogInformation($"{LinkType} Not found");
return (false, null, "Not Found");
}
}
else
{
logger?.LogInformation($"{LinkType} 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.LinkType LinkType, string ErrorMessage)> DeleteLinkTypeAsync(int Id)
{
try
{
Db.LinkType LinkType = DocumentDbContext.LinkTypes.AsNoTracking().Where(a => a.Id == Id).FirstOrDefault();
if (LinkType == null)
{
return (false, null, "Not Found");
}
LinkType.IsActive = false;
DocumentDbContext.LinkTypes.Update(LinkType);
DocumentDbContext.SaveChanges();
return (true, mapper.Map<Db.LinkType, Models.LinkType>(LinkType), $"LinkTypeId {Id} deleted Successfuly");
}
catch (Exception ex)
{
logger?.LogError(ex.ToString());
return (false, null, ex.Message);
}
}
private bool LinkTypeExists(int id)
{
return DocumentDbContext.LinkTypes.AsNoTracking().Count(e => e.Id == id) > 0;
}
}
}

View File

@ -0,0 +1,123 @@
using AutoMapper;
using Azure;
using DamageAssesment.Api.Documents.Db;
using DamageAssesment.Api.Documents.Interfaces;
using DamageAssesment.Api.Documents.Models;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using System.Diagnostics.Metrics;
using System.Net.Http;
using System.Security.AccessControl;
using System.Security.Principal;
namespace DamageAssesment.Api.Documents.Providers
{
public class UploadService : IUploadService
{
private ILogger<UploadService> logger;
private IMapper mapper;
private string uploadpath = "";
private string Deletepath = "";
public UploadService(IConfiguration configuration, ILogger<UploadService> logger, IMapper mapper)
{
this.logger = logger;
this.mapper = mapper;
uploadpath = configuration.GetValue<string>("Fileupload:folderpath");
Deletepath = configuration.GetValue<string>("Fileupload:Deletepath");
}
public Models.Document UploadDocument(int counter, DocumentInfo documentInfo)
{
Models.Document Documents = new Models.Document();
try
{
string path = "", UserfileName="";
if (documentInfo.File != null)
{
counter++;
var fullDirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), uploadpath);
if (!Directory.Exists(fullDirectoryPath)) //Create deirectory if does not exist
Directory.CreateDirectory(fullDirectoryPath);
UserfileName = Path.GetFileName(documentInfo.File.FileName);
var fileName = String.Format("Document_{0}{1}", counter, documentInfo.File.FileExtension);
path = Path.Combine(fullDirectoryPath, fileName);
File.WriteAllBytes(path, Convert.FromBase64String(documentInfo.File.FileContent));
}
Documents=new Models.Document (){ linkTypeId = documentInfo.linkTypeId,
documentsTranslations = documentInfo.documentsTranslations,
docName = UserfileName,
url = documentInfo.url, Path = path,IsActive =true,dateCreated=DateTime.Now,dateUpdated=DateTime.Now};
return Documents;
}
catch (Exception ex) {
return new Models.Document();
}
}
public Models.Document UpdateDocuments(Models.Document document, DocumentInfo documentInfo)
{
try
{
Deletefile(document.Path);
var fullDirectoryPath = Path.Combine(Directory.GetCurrentDirectory(), uploadpath);
if (!Directory.Exists(fullDirectoryPath)) //Create deirectory if does not exist
Directory.CreateDirectory(fullDirectoryPath);
string path = "", UserfileName = "";
if (documentInfo.File != null)
{
UserfileName = Path.GetFileName(documentInfo.File.FileName);
var fileName = String.Format("Document_{0}{1}", documentInfo.Id, documentInfo.File.FileExtension);
path = Path.Combine(fullDirectoryPath, fileName);
File.WriteAllBytes(path, Convert.FromBase64String(documentInfo.File.FileContent));
}
Models.Document Documents = new Models.Document()
{
Id = documentInfo.Id,
linkTypeId = documentInfo.linkTypeId,
documentsTranslations=documentInfo.documentsTranslations,
docName = UserfileName,
url = documentInfo.url,
Path = path,
IsActive = true,
dateCreated = document.dateCreated,
dateUpdated = DateTime.Now
};
return Documents;
}
catch (Exception ex) {
return new Models.Document();
}
}
public void Deletefile(string path)
{
if (path != "")
{
FileInfo file = new FileInfo(path);
if (file?.Exists??false)//check file exsit or not
{
file.Delete();
}
}
}
public void Movefile(string path)
{
if (path != "")
{
var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), Deletepath);
if (!Directory.Exists(pathToSave)) //Create deirectory if does not exist
Directory.CreateDirectory(pathToSave);
FileInfo file = new FileInfo(path);
if (file?.Exists ?? false)//check file exsit or not
{
string filename = file.Name.Replace(file.Extension, " ") + DateTime.Now.ToShortDateString().Replace("/","_") + file.Extension;
file.MoveTo(pathToSave+"\\"+ filename);
}
}
}
}
}

View File

@ -0,0 +1,13 @@
{
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*",
"Fileupload": {
"folderpath": "DASA_Documents/Active",
"Deletepath": "DASA_Documents/Deleted"
}
}

View File

@ -15,11 +15,7 @@ namespace DamageAssesment.Api.Employees.Controllers
{
this.EmployeeProvider = EmployeesProvider;
}
/// <summary>
/// GET request for retrieving employees.
/// </summary>
//get all Employees
[HttpGet("Employees")]
public async Task<ActionResult> GetEmployeesAsync()
{
@ -32,11 +28,7 @@ namespace DamageAssesment.Api.Employees.Controllers
return NoContent();
}
/// <summary>
/// GET request for retrieving an employee by ID.
/// </summary>
//get Employee based on Employeeid
[HttpGet("Employees/{Id}")]
public async Task<ActionResult> GetEmployeeByIdAsync(string Id)
{
@ -49,11 +41,8 @@ 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)
{
@ -71,11 +60,7 @@ namespace DamageAssesment.Api.Employees.Controllers
}
return NotFound();
}
/// <summary>
/// POST request for creating a new employee.
/// </summary>
/// <param name="Employee">The employee information for creating a new employee.</param>
//save new Employee
[HttpPost("Employees")]
public async Task<IActionResult> CreateEmployee(Db.Employee Employee)
{
@ -90,10 +75,7 @@ namespace DamageAssesment.Api.Employees.Controllers
}
return CreatedAtRoute("DefaultApi", new { id = Employee.Id }, Employee);
}
/// <summary>
/// DELETE request for deleting an existing employee.
/// </summary>
/// <param name="id">The ID of the employee to be deleted.</param>
//delete existing Employee
[HttpDelete("Employees/{id}")]
public async Task<IActionResult> DeleteEmployee(string id)
{

View File

@ -1,15 +1,13 @@
<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" />

View File

@ -4,10 +4,18 @@ 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";

View File

@ -2,7 +2,6 @@ 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);
@ -11,15 +10,7 @@ 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(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.AddSwaggerGen();
builder.Services.AddScoped<IEmployeesProvider, EmployeesProvider>();
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); //4/30
builder.Services.AddDbContext<EmployeeDbContext>(option =>

View File

@ -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 = "es" });
EmployeeDbContext.Employees.Add(new Db.Employee() { Id = "Emp6", Name = "ABC6", Email = "abc6@gmail.com", OfficePhoneNumber = "12345678", BirthDate = DateTime.Now.AddYears(-32) ,IsActive = true, PreferredLanguage = "es" });
EmployeeDbContext.Employees.Add(new Db.Employee() { Id = "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.SaveChanges();
}

View File

@ -1,7 +1,4 @@
{
"JwtSettings": {
"securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk="
},
"Logging": {
"LogLevel": {
"Default": "Information",

View File

@ -14,10 +14,7 @@ namespace DamageAssesment.Api.Locations.Controllers
{
this.LocationProvider = LocationsProvider;
}
/// <summary>
/// Get all locations.
/// </summary>
// Get all Locations
[HttpGet("Locations")]
public async Task<ActionResult> GetLocationsAsync()
{
@ -30,10 +27,7 @@ namespace DamageAssesment.Api.Locations.Controllers
return NotFound();
}
/// <summary>
/// Get all locations based on locationdId.
/// </summary>
// Get all Location based on Id
[HttpGet("Locations/{id}")]
public async Task<ActionResult> GetLocationByIdAsync(string id)
{
@ -46,10 +40,7 @@ namespace DamageAssesment.Api.Locations.Controllers
return NotFound();
}
/// <summary>
/// Update a Location.
/// </summary>
// Update Location entity
[HttpPut("Locations")]
public async Task<IActionResult> UpdateLocation(Db.Location Location)
{
@ -64,10 +55,7 @@ namespace DamageAssesment.Api.Locations.Controllers
}
return NotFound();
}
/// <summary>
/// Save a new location.
/// </summary>
//save new location
[HttpPost("Locations")]
public async Task<IActionResult> CreateLocation(Db.Location Location)
{
@ -82,10 +70,7 @@ namespace DamageAssesment.Api.Locations.Controllers
}
return CreatedAtRoute("DefaultApi", new { id = Location.Id }, Location);
}
/// <summary>
/// Delete an existing location.
/// </summary>
//delete existing location
[HttpDelete("Locations/{id}")]
public async Task<IActionResult> DeleteLocation(string id)
{

View File

@ -13,10 +13,8 @@ namespace DamageAssesment.Api.Locations.Controllers
{
this.regionProvider = regionProvider;
}
/// <summary>
/// Get all regions.
/// </summary>
// Get all Regions
[HttpGet]
public async Task<ActionResult> GetRegionsAsync()
{
@ -27,9 +25,6 @@ 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)
@ -41,9 +36,6 @@ 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)
@ -55,9 +47,6 @@ 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)
@ -72,10 +61,6 @@ 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)

View File

@ -4,12 +4,10 @@
<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" />

View File

@ -2,7 +2,6 @@ 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);
@ -11,14 +10,8 @@ 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(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.AddSwaggerGen();
builder.Services.AddScoped<ILocationsProvider, LocationsProvider>();
builder.Services.AddScoped<IRegionsProvider, RegionsProvider>();
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies()); //4/30

View File

@ -1,7 +1,4 @@
{
"JwtSettings": {
"securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk="
},
"Logging": {
"LogLevel": {
"Default": "Information",

View File

@ -1,4 +1,8 @@
using DamageAssesment.Api.Questions.Interfaces;
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 Microsoft.AspNetCore.Mvc;
namespace DamageAssesment.Api.Questions.Controllers
@ -15,52 +19,33 @@ namespace DamageAssesment.Api.Questions.Controllers
this.questionsProvider = questionsProvider;
}
/// <summary>
/// GET request for retrieving questions.
/// </summary>
// get all questions
[Route("{Language}/Questions")]
[Route("Questions")]
[HttpGet]
public async Task<IActionResult> GetQuestionsAsync(string? Language)
[HttpGet("Questions")]
public async Task<IActionResult> GetQuestionsAsync()
{
var result = await this.questionsProvider.GetQuestionsAsync(Language);
var result = await this.questionsProvider.GetQuestionsAsync();
if (result.IsSuccess)
{
return Ok(result.Questions);
}
return NoContent();
}
//Get questions based on question 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)
[HttpGet("Questions/{id}")]
public async Task<IActionResult> GetQuestionAsync(int id)
{
var result = await this.questionsProvider.GetQuestionAsync(id,Language);
var result = await this.questionsProvider.GetQuestionAsync(id);
if (result.IsSuccess)
{
return Ok(result.Question);
}
return NotFound();
}
//get all questions based on survey id
/// <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]
[HttpGet("GetSurveyQuestions/{surveyId}")]
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)
{
@ -68,10 +53,7 @@ namespace DamageAssesment.Api.Questions.Controllers
}
return NotFound();
}
/// <summary>
/// PUT request for updating a question (multilingual).
/// </summary>
//update existing question
[HttpPut("Questions")]
public async Task<IActionResult> UpdateQuestion(Models.Question question)
{
@ -89,10 +71,7 @@ namespace DamageAssesment.Api.Questions.Controllers
}
return CreatedAtRoute("DefaultApi", new { id = question.Id }, question);
}
/// <summary>
/// POST request for creating a new question (multilingual).
/// </summary>
//save new question
[HttpPost("Questions")]
public async Task<IActionResult> CreateQuestion(Models.Question question)
{
@ -107,10 +86,7 @@ namespace DamageAssesment.Api.Questions.Controllers
}
return CreatedAtRoute("DefaultApi", new { id = question.Id }, question);
}
/// <summary>
/// DELETE request for deleting a question based on ID.
/// </summary>
// delete existing question
[HttpDelete("Questions/{id}")]
public async Task<IActionResult> DeleteQuestion(int id)
{
@ -122,10 +98,8 @@ 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()
{
@ -136,10 +110,7 @@ namespace DamageAssesment.Api.Questions.Controllers
}
return NoContent();
}
/// <summary>
/// GET request for retrieving a question category by ID.
/// </summary>
//Get questions based on question id
[HttpGet("QuestionCategories/{id}")]
public async Task<IActionResult> GetQuestionCategoryAsync(int id)
{
@ -152,10 +123,7 @@ namespace DamageAssesment.Api.Questions.Controllers
}
/// <summary>
/// PUT request for updating a question category.
/// </summary>
//update existing question
[HttpPut("QuestionCategories")]
public async Task<IActionResult> UpdateQuestionCategory(Models.QuestionCategory questionCategory)
{
@ -173,10 +141,7 @@ namespace DamageAssesment.Api.Questions.Controllers
}
return CreatedAtRoute("DefaultApi", new { id = questionCategory.Id }, questionCategory);
}
/// <summary>
/// POST request for creating a new question category.
/// </summary>
//save new question
[HttpPost("QuestionCategories")]
public async Task<IActionResult> CreateQuestionCategory(Models.QuestionCategory questionCategory)
{
@ -191,10 +156,7 @@ namespace DamageAssesment.Api.Questions.Controllers
}
return CreatedAtRoute("DefaultApi", new { id = questionCategory.Id }, questionCategory);
}
/// <summary>
/// DELETE request for deleting a question category based on ID.
/// </summary>
// delete existing question
[HttpDelete("QuestionCategories/{id}")]
public async Task<IActionResult> DeleteQuestionCategory(int id)
{

View File

@ -1,15 +1,13 @@
<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" />

View File

@ -20,6 +20,7 @@ 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; }

View File

@ -14,21 +14,12 @@ namespace DamageAssesment.Api.Questions.Db
{
}
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();
}
//protected override void OnModelCreating(ModelBuilder modelBuilder)
//{
// modelBuilder.Entity<Question>()
// .HasOne(a => a.QuestionType)
// .WithOne(b => b.Question)
// .HasForeignKey<QuestionType>(b => b.QuestionTypeID);
//}
}
}

View File

@ -4,8 +4,8 @@ namespace DamageAssesment.Api.Questions.Interfaces
{
public interface IQuestionsProvider : IQuestionTypesProvider
{
Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> GetQuestionAsync(int Id, string Language);
Task<(bool IsSuccess, IEnumerable<Models.Question> Questions, string ErrorMessage)> GetQuestionsAsync(string Language);
Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> GetQuestionAsync(int Id);
Task<(bool IsSuccess, IEnumerable<Models.Question> Questions, string ErrorMessage)> GetQuestionsAsync();
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);

View File

@ -17,6 +17,7 @@ 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; }
}

View File

@ -3,7 +3,6 @@ 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);
@ -18,14 +17,7 @@ builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
builder.Services.AddEndpointsApiExplorer();
//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.AddSwaggerGen();
builder.Services.AddDbContext<QuestionDbContext>(option =>
{
option.UseInMemoryDatabase("Questions");

View File

@ -24,6 +24,8 @@ namespace DamageAssesment.Api.Questions.Providers
SeedData();
}
private void SeedData()
{
@ -35,38 +37,41 @@ namespace DamageAssesment.Api.Questions.Providers
questionDbContext.QuestionsTranslations.Add(new Db.QuestionsTranslation() { Id = 4, QuestionId = 2, QuestionText = "Les terrains sont-ils inondés ?", Language = "fr" });
questionDbContext.QuestionsTranslations.Add(new Db.QuestionsTranslation() { Id = 5, QuestionId = 3, QuestionText = "Is the access blocked by flooding ?", Language = "en" });
questionDbContext.QuestionsTranslations.Add(new Db.QuestionsTranslation() { Id = 6, QuestionId = 3, QuestionText = "L'accès est-il bloqué par les inondations ?", Language = "fr" });
questionDbContext.QuestionsTranslations.Add(new Db.QuestionsTranslation() { Id = 7, QuestionId = 1, QuestionText = "Puedes abrir ?", Language = "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.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.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, 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.Questions.Add(new Db.Question() { Id = 1, QuestionTypeId = 2, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, QuestionGroup = "group1",CategoryId=1 });
questionDbContext.Questions.Add(new Db.Question() { Id = 2, QuestionTypeId = 1, SurveyId = 1, QuestionNumber = 2, IsRequired = false, Comment = true, Key = false, QuestionGroup = "group1", CategoryId = 1 });
questionDbContext.Questions.Add(new Db.Question() { Id = 3, QuestionTypeId = 1, SurveyId = 1, QuestionNumber = 3, IsRequired = true, Comment = false, Key = true, QuestionGroup = "group1", CategoryId = 2 });
questionDbContext.SaveChanges();
}
if (!questionDbContext.QuestionTypes.Any())
{
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.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.SaveChanges();
}
if (!questionDbContext.QuestionCategories.Any())
{
questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 1, CategoryName = "Flooding", CategoryImage= "https://example.com/images/img1.png" });
questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 2, CategoryName = "Electrical", CategoryImage = "https://example.com/images/img2.png" });
questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 3, CategoryName = "Structural", CategoryImage = "https://example.com/images/img3.png" });
questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 4, CategoryName = "Utility", CategoryImage = "https://example.com/images/img4.png" });
questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 5, CategoryName = "Debris", CategoryImage = "https://example.com/images/img5.png" });
questionDbContext.QuestionCategories.Add(new Db.QuestionCategory() { Id = 1, 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.SaveChanges();
}
}
public async Task<(bool IsSuccess, IEnumerable<Models.Question> Questions, string ErrorMessage)> GetQuestionsAsync(string Language)
public async Task<(bool IsSuccess, IEnumerable<Models.Question> Questions, string ErrorMessage)> GetQuestionsAsync()
{
try
{
@ -77,21 +82,11 @@ 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)
{
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);
}
return (false, null, "Not found");
@ -102,7 +97,7 @@ namespace DamageAssesment.Api.Questions.Providers
return (false, null, ex.Message);
}
}
public async Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> GetQuestionAsync(int Id, string Language)
public async Task<(bool IsSuccess, Models.Question Question, string ErrorMessage)> GetQuestionAsync(int Id)
{
try
{
@ -112,17 +107,8 @@ namespace DamageAssesment.Api.Questions.Providers
{
logger?.LogInformation($"{question} customer(s) found");
var result = mapper.Map<Db.Question, Models.Question>(question);
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");
@ -134,23 +120,12 @@ namespace DamageAssesment.Api.Questions.Providers
}
}
public List<Models.Question> GetSurveyQuestion(List<Models.Question> questions,string Language)
{
if (string.IsNullOrEmpty(Language))
{
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;
}
public async Task<(bool IsSuccess, List<SurveyQuestions> SurveyQuestions, string ErrorMessage)> GetSurveyQuestionAsync(int SurveyId, string Language)
@ -256,6 +231,8 @@ namespace DamageAssesment.Api.Questions.Providers
}
}
//Question Category Logic
public async Task<(bool IsSuccess, IEnumerable<Models.QuestionCategory> QuestionCategories, string ErrorMessage)> GetQuestionCategoriesAsync()

View File

@ -1,7 +1,4 @@
{
"JwtSettings": {
"securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk="
},
"Logging": {
"LogLevel": {
"Default": "Information",

View File

@ -1,4 +1,11 @@
using System.Text;
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;
namespace DamageAssesment.Api.Questions.Test
{
@ -11,7 +18,7 @@ namespace DamageAssesment.Api.Questions.Test
for (int i = 0; i < 10; i++)
{
list.Append(new Questions.Models.Question { Id = i, TypeText = "Text" + i, SurveyId = 1, QuestionNumber = 1, IsRequired = true, Comment = false, Key = true, CategoryId=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 });
}
return (true, list, null);
}
@ -24,7 +31,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, CategoryId = i });
question.Add(new 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.SurveyQuestions
{
CategoryId = i,
@ -72,7 +79,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, CategoryId=1};
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};
}

View File

@ -1,7 +1,16 @@
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
@ -13,10 +22,10 @@ namespace DamageAssesment.Api.Questions.Test
{
var mockQuestionService = new Mock<IQuestionsProvider>();
var mockResponse = await MockData.getOkResponse();
mockQuestionService.Setup(service => service.GetQuestionsAsync(null)).ReturnsAsync(mockResponse);
mockQuestionService.Setup(service => service.GetQuestionsAsync()).ReturnsAsync(mockResponse);
var QuestionProvider = new QuestionsController(mockQuestionService.Object);
var result = (OkObjectResult)await QuestionProvider.GetQuestionsAsync(null);
var result = (OkObjectResult)await QuestionProvider.GetQuestionsAsync();
Assert.Equal(200, result.StatusCode);
}
@ -26,10 +35,10 @@ namespace DamageAssesment.Api.Questions.Test
{
var mockQuestionService = new Mock<IQuestionsProvider>();
var mockResponse = await MockData.getNoContentResponse();
mockQuestionService.Setup(service => service.GetQuestionsAsync(null)).ReturnsAsync(mockResponse);
mockQuestionService.Setup(service => service.GetQuestionsAsync()).ReturnsAsync(mockResponse);
var QuestionProvider = new QuestionsController(mockQuestionService.Object);
var result = (NoContentResult)await QuestionProvider.GetQuestionsAsync(null);
var result = (NoContentResult)await QuestionProvider.GetQuestionsAsync();
Assert.Equal(204, result.StatusCode);
}
@ -39,10 +48,10 @@ namespace DamageAssesment.Api.Questions.Test
{
var mockQuestionService = new Mock<IQuestionsProvider>();
var mockResponse = await MockData.getOkResponse(1);
mockQuestionService.Setup(service => service.GetQuestionAsync(1,null)).ReturnsAsync(mockResponse);
mockQuestionService.Setup(service => service.GetQuestionAsync(1)).ReturnsAsync(mockResponse);
var QuestionProvider = new QuestionsController(mockQuestionService.Object);
var result = (OkObjectResult)await QuestionProvider.GetQuestionAsync(1,null);
var result = (OkObjectResult)await QuestionProvider.GetQuestionAsync(1);
Assert.Equal(200, result.StatusCode);
}
@ -52,10 +61,10 @@ namespace DamageAssesment.Api.Questions.Test
{
var mockQuestionService = new Mock<IQuestionsProvider>();
var mockResponse = await MockData.getNotFoundResponse();
mockQuestionService.Setup(service => service.GetQuestionAsync(99,null)).ReturnsAsync(mockResponse);
mockQuestionService.Setup(service => service.GetQuestionAsync(99)).ReturnsAsync(mockResponse);
var QuestionProvider = new QuestionsController(mockQuestionService.Object);
var result = (NotFoundResult)await QuestionProvider.GetQuestionAsync(99,null);
var result = (NotFoundResult)await QuestionProvider.GetQuestionAsync(99);
Assert.Equal(404, result.StatusCode);
}

View File

@ -16,9 +16,6 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers
{
this.surveyResponseProvider = surveyResponseProvider;
}
/// <summary>
/// GET request for retrieving survey responses.
/// </summary>
[HttpGet("SurveyResponses")]
public async Task<ActionResult> GetSurveyResponsesAsync()
@ -34,9 +31,6 @@ 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)
@ -48,11 +42,6 @@ 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)
@ -65,12 +54,6 @@ 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)
@ -83,10 +66,6 @@ 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)
@ -98,10 +77,6 @@ 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)
@ -113,10 +88,6 @@ 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)
@ -129,10 +100,6 @@ 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)
@ -144,11 +111,6 @@ 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)
@ -163,9 +125,6 @@ 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)
@ -177,10 +136,6 @@ 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)

View File

@ -4,14 +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="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" />

View File

@ -4,11 +4,25 @@ 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; }
public IEnumerable<SurveyTranslation> Titles { get; set; }
//public DateTime CreatedDate { get; set; }
//[StringLength(6)]
//public string EmployeeID { get; set; }
}
}

View File

@ -1,13 +0,0 @@
namespace DamageAssesment.Api.SurveyResponses.Models
{
public class SurveyTranslation
{
public string Title { get; set; }
public string Language { get; set; }
}
}

View File

@ -4,7 +4,6 @@ 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;
@ -51,14 +50,7 @@ builder.Services.AddHttpClient<ISurveyServiceProvider, SurveyServiceProvider>().
builder.Services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
builder.Services.AddEndpointsApiExplorer();
//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.AddSwaggerGen();
builder.Services.AddDbContext<SurveyResponseDbContext>(option =>
{
option.UseInMemoryDatabase("SurveyResponses");

View File

@ -709,16 +709,16 @@ namespace DamageAssesment.Api.SurveyResponses.Providers
}
bool ProcessAnswers(QuestionRequest questionRequest, int surveyResponseId)
async Task<bool> ProcessAnswers(QuestionRequest questionRequest, int surveyResponseId)
{
if (questionRequest != null)
{
var answer = answerServiceProvider.PostAnswersAsync(new Answer {QuestionId = questionRequest.QuestionId, AnswerText = questionRequest.AnswerText, Comment = questionRequest.Comment, SurveyResponseId = surveyResponseId });
var answer = await answerServiceProvider.PostAnswersAsync(new Answer { Id = 0, 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 = attachmentServiceProvider.PostAttachmentsAsync(new AttachmentInfo { ResponseId = surveyResponseId, Answers = listAnswerInfo });
var attachments = await attachmentServiceProvider.PostAttachmentsAsync(new AttachmentInfo { ResponseId = surveyResponseId, Answers = listAnswerInfo });
string message = $"Answer for question {questionRequest.QuestionId} saved to the database";
logger?.LogInformation(message);
@ -757,19 +757,18 @@ 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

View File

@ -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) };
}

View File

@ -14,10 +14,10 @@ namespace DamageAssesment.Api.Surveys.Test
{
var mockSurveyService = new Mock<ISurveyProvider>();
var mockResponse = await MockData.getOkResponse();
mockSurveyService.Setup(service => service.GetSurveysAsync(null)).ReturnsAsync(mockResponse);
mockSurveyService.Setup(service => service.GetSurveysAsync()).ReturnsAsync(mockResponse);
var surveyProvider = new SurveysController(mockSurveyService.Object);
var result = (OkObjectResult) await surveyProvider.GetSurveysAsync(null);
var result = (OkObjectResult) await surveyProvider.GetSurveysAsync();
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(null)).ReturnsAsync(mockResponse);
mockSurveyService.Setup(service => service.GetSurveysAsync()).ReturnsAsync(mockResponse);
var surveyProvider = new SurveysController(mockSurveyService.Object);
var result = (NoContentResult)await surveyProvider.GetSurveysAsync(null);
var result = (NoContentResult)await surveyProvider.GetSurveysAsync();
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,null)).ReturnsAsync(mockResponse);
mockSurveyService.Setup(service => service.GetSurveysAsync(1)).ReturnsAsync(mockResponse);
var surveyProvider = new SurveysController(mockSurveyService.Object);
var result = (OkObjectResult)await surveyProvider.GetSurveysAsync(1,null);
var result = (OkObjectResult)await surveyProvider.GetSurveysAsync(1);
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,null)).ReturnsAsync(mockResponse);
mockSurveyService.Setup(service => service.GetSurveysAsync(99)).ReturnsAsync(mockResponse);
var surveyProvider = new SurveysController(mockSurveyService.Object);
var result = (NotFoundResult)await surveyProvider.GetSurveysAsync(99,null);
var result = (NotFoundResult)await surveyProvider.GetSurveysAsync(99);
Assert.Equal(404, result.StatusCode);
}

View File

@ -1,9 +1,10 @@
using DamageAssesment.Api.Surveys.Interfaces;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
namespace DamageAssesment.Api.Surveys.Controllers
{
[Route("api")]
[Route("api/[controller]")]
[ApiController]
public class SurveysController : ControllerBase
{
@ -13,43 +14,29 @@ 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(string? Language)
public async Task<ActionResult> GetSurveysAsync()
{
var result = await this.surveyProvider.GetSurveysAsync(Language);
var result = await this.surveyProvider.GetSurveysAsync();
if (result.IsSuccess)
{
return Ok(result.Surveys);
}
return NoContent();
}
/// <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)
[HttpGet("{Id}")]
public async Task<ActionResult> GetSurveysAsync(int Id)
{
var result = await this.surveyProvider.GetSurveysAsync(Id, Language);
var result = await this.surveyProvider.GetSurveysAsync(Id);
if (result.IsSuccess)
{
return Ok(result.Surveys);
}
return NotFound();
}
/// <summary>
/// POST request for creating a new survey.
/// </summary>
[HttpPost("Surveys")]
[HttpPost]
public async Task<ActionResult> PostSurveysAsync(Models.Survey survey)
{
var result = await this.surveyProvider.PostSurveyAsync(survey);
@ -59,12 +46,8 @@ namespace DamageAssesment.Api.Surveys.Controllers
}
return BadRequest(result.ErrorMessage);
}
/// <summary>
/// PUT request for updating an existing survey (surveyId,Updated Survey data).
/// </summary>
[HttpPut("Surveys/{Id}")]
[HttpPut("{Id}")]
public async Task<ActionResult> PutSurveysAsync(int Id, Models.Survey survey)
{
var result = await this.surveyProvider.PutSurveyAsync(Id,survey);
@ -78,10 +61,7 @@ namespace DamageAssesment.Api.Surveys.Controllers
return BadRequest(result.ErrorMessage);
}
/// <summary>
/// DELETE request for deleting a survey by ID.
/// </summary>
[HttpDelete("Surveys/{Id}")]
[HttpDelete("{Id}")]
public async Task<ActionResult> DeleteSurveysAsync(int Id)
{
var result = await this.surveyProvider.DeleteSurveyAsync(Id);

View File

@ -1,15 +1,13 @@
<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" />

View File

@ -1,5 +1,4 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace DamageAssesment.Api.Surveys.Db
{
@ -7,20 +6,23 @@ 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; } = DateTime.Now;
/*
[StringLength(10)]
[ForeignKey("Employee")]
public string EmployeeId { get; set; }
*/
//public DateTime CreatedDate { get; set; }
//[StringLength(6)]
//public string EmployeeID { get; set; }
}
}

View File

@ -1,23 +0,0 @@
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; }
}
}

View File

@ -4,23 +4,11 @@ namespace DamageAssesment.Api.Surveys.Db
{
public class SurveysDbContext:DbContext
{
public DbSet<Db.Survey> Surveys { get; set; }
public DbSet<Db.SurveyTranslation> SurveysTranslation { get; set; }
public SurveysDbContext(DbContextOptions options) : base(options)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
public DbSet<Db.Survey> Surveys { get; set; }
modelBuilder.Entity<Survey>()
.Property(item => item.Id)
.ValueGeneratedOnAdd();
modelBuilder.Entity<SurveyTranslation>()
.Property(item => item.Id)
.ValueGeneratedOnAdd();
}
}
}

View File

@ -2,8 +2,8 @@
{
public interface ISurveyProvider
{
Task<(bool IsSuccess, IEnumerable< Models.Survey> Surveys, string ErrorMessage)> GetSurveysAsync(string Language);
Task<(bool IsSuccess, Models.Survey Surveys, string ErrorMessage)> GetSurveysAsync(int Id, string Language);
Task<(bool IsSuccess, IEnumerable< Models.Survey> Surveys, string ErrorMessage)> GetSurveysAsync();
Task<(bool IsSuccess, Models.Survey Surveys, string ErrorMessage)> GetSurveysAsync(int Id);
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);

View File

@ -4,11 +4,25 @@ 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; }
public IEnumerable<SurveyTranslation> Titles { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
//public DateTime CreatedDate { get; set; }
//[StringLength(6)]
//public string EmployeeID { get; set; }
}
}

View File

@ -1,13 +0,0 @@
namespace DamageAssesment.Api.Surveys.Models
{
public class SurveyTranslation
{
public string Title { get; set; }
public string Language { get; set; }
}
}

View File

@ -1,47 +1,18 @@
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(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.AddSwaggerGen();
builder.Services.AddDbContext<SurveysDbContext>(option =>
{
option.UseInMemoryDatabase("Surveys");
@ -55,7 +26,6 @@ if (app.Environment.IsDevelopment())
app.UseSwaggerUI();
}
app.UseAuthentication();
app.UseAuthorization();
app.MapControllers();

View File

@ -1,9 +1,7 @@
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
{
@ -25,87 +23,24 @@ namespace DamageAssesment.Api.Surveys.Providers
{
if (!surveyDbContext.Surveys.Any())
{
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();
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();
}
}
if (!surveyDbContext.SurveysTranslation.Any())
public async Task<(bool IsSuccess, IEnumerable<Models.Survey> Surveys, string ErrorMessage)> GetSurveysAsync()
{
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(string Language)
{
IEnumerable<Models.Survey> surveysList = null;
try
{
logger?.LogInformation("Gell all Surveys from DB");
var surveys = await surveyDbContext.Surveys.Where(s => s.IsEnabled == true).ToListAsync();
var surveyTranslations = await surveyDbContext.SurveysTranslation.ToListAsync();
var surveys = await surveyDbContext.Surveys.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");
return (true, surveysList, null);
var result = mapper.Map<IEnumerable<Db.Survey>, IEnumerable<Models.Survey>>(surveys);
return (true, result, null);
}
return (false, null, "Not found");
}
@ -115,55 +50,16 @@ namespace DamageAssesment.Api.Surveys.Providers
return (false, null, ex.Message);
}
}
public async Task<(bool IsSuccess, Models.Survey Surveys, string ErrorMessage)> GetSurveysAsync(int Id, string Language)
public async Task<(bool IsSuccess, Models.Survey Surveys, string ErrorMessage)> GetSurveysAsync(int Id)
{
try
{
logger?.LogInformation("Query Survey");
var survey = await surveyDbContext.Surveys.SingleOrDefaultAsync(s => s.Id == Id && s.IsEnabled == true);
var survey = await surveyDbContext.Surveys.SingleOrDefaultAsync(s => s.Id == Id);
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");
@ -182,20 +78,9 @@ namespace DamageAssesment.Api.Surveys.Providers
if (survey != null)
{
var surveys = await surveyDbContext.Surveys.ToListAsync();
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;
survey.Id = surveys.Count + 1;
surveyDbContext.Surveys.Add(mapper.Map<Models.Survey, Db.Survey>(survey));
surveyDbContext.SaveChanges();
return (true, survey, "Successful");
}
else
@ -221,40 +106,12 @@ namespace DamageAssesment.Api.Surveys.Providers
if (_survey != null)
{
var surveysTranslation = await surveyDbContext.SurveysTranslation.Where(s => s.SurveyId == Id).ToListAsync();
surveyDbContext.SurveysTranslation.RemoveRange(surveysTranslation);
await surveyDbContext.SaveChangesAsync();
_survey.Title = survey.Title;
_survey.IsEnabled = survey.IsEnabled;
_survey.StartDate = survey.StartDate;
_survey.EndDate = survey.EndDate;
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");
surveyDbContext.SaveChanges();
return (true, mapper.Map<Db.Survey, Models.Survey>(_survey), "Successful");
}
else
{
@ -284,7 +141,7 @@ namespace DamageAssesment.Api.Surveys.Providers
if (survey != null)
{
surveyDbContext.Surveys.Remove(survey);
await surveyDbContext.SaveChangesAsync();
surveyDbContext.SaveChanges();
return (true, mapper.Map<Db.Survey, Models.Survey>(survey), $"Survey Id: {Id} deleted Successfuly");
}
else

View File

@ -1,7 +1,4 @@
{
"JwtSettings": {
"securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk="
},
"Logging": {
"LogLevel": {
"Default": "Information",

View File

@ -1,21 +0,0 @@
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;
}
}
}

View File

@ -1,97 +0,0 @@
using DamageAssesment.Api.UsersAccess.Interfaces;
using DamageAssesment.Api.UsersAccess.Models;
using Microsoft.AspNetCore.Mvc;
namespace DamageAssesment.Api.UsersAccess.Controllers
{
[Route("api")]
[ApiController]
public class UsersAccessController : ControllerBase
{
private IUsersAccessProvider userAccessProvider;
public UsersAccessController(IUsersAccessProvider userAccessProvider)
{
this.userAccessProvider = userAccessProvider;
}
[HttpPost("authenticate")]
public async Task<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();
}
}
}

View File

@ -1,19 +0,0 @@
<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>

View File

@ -1,21 +0,0 @@
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Text.Json.Serialization;
namespace DamageAssesment.Api.UsersAccess.Db
{
public class Role
{
[Key]
public int Id { get; set; }
[StringLength(100)]
[Required]
public string Name { get; set; }
// add a status field
[StringLength(100)]
public string? Description { get; set; }
}
}

Some files were not shown because too many files have changed in this diff Show More