forked from MDCPS/DamageAssessment_Backend
Compare commits
46 Commits
docker-Azu
...
Sql-userac
Author | SHA1 | Date | |
---|---|---|---|
9b22249a89 | |||
947ee16281 | |||
2a2418c85e | |||
9353d6ab2c | |||
5644762e00 | |||
1b638d9367 | |||
073fbac743 | |||
5eb9314e96 | |||
34b4adf0bf | |||
4b863687d3 | |||
735a5ee62c | |||
eb28885f00 | |||
6d3f5dd5b8 | |||
2baf4b9dad | |||
4f478585cf | |||
556dc5e4e7 | |||
01bfa9c4b5 | |||
6bdbcb8e57 | |||
2a73324ff7 | |||
9b8e8ffad2 | |||
dd5351665e | |||
ff4e8de3f3 | |||
c014739fc0 | |||
70d0043e25 | |||
ff3847ecae | |||
7baff934ab | |||
28de758da0 | |||
bb87f1c8e0 | |||
52869afc3f | |||
71b8031577 | |||
4936e3e6f1 | |||
30b8d1ff9f | |||
79beaf55fa | |||
8c12477763 | |||
cc9ce4dbe5 | |||
3cd0c5f39e | |||
334c327559 | |||
87fa29d9d4 | |||
2ab8f37489 | |||
500582020b | |||
ede178042f | |||
6575c2f219 | |||
69584e6c91 | |||
1cbd6893d8 | |||
79a3073bea | |||
bdde55b3e5 |
@ -19,7 +19,10 @@
|
|||||||
</PackageReference>
|
</PackageReference>
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.9" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.9" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.9" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.9" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
|
||||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.4" />
|
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.4" />
|
||||||
|
<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
|
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
@ -9,6 +9,10 @@ using System.Reflection;
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
builder.Services.AddCors(p => p.AddPolicy("DamageAppCorsPolicy", build => {
|
||||||
|
build.WithOrigins("*").AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin();
|
||||||
|
}));
|
||||||
|
|
||||||
var authkey = builder.Configuration.GetValue<string>("JwtSettings:securitykey");
|
var authkey = builder.Configuration.GetValue<string>("JwtSettings:securitykey");
|
||||||
builder.Services.AddAuthentication(item =>
|
builder.Services.AddAuthentication(item =>
|
||||||
{
|
{
|
||||||
@ -27,6 +31,11 @@ builder.Services.AddAuthentication(item =>
|
|||||||
ClockSkew = TimeSpan.Zero
|
ClockSkew = TimeSpan.Zero
|
||||||
};
|
};
|
||||||
});
|
});
|
||||||
|
builder.Services.AddLogging(builder =>
|
||||||
|
{
|
||||||
|
//builder.AddConsole(); // Optional: Add other providers if needed
|
||||||
|
builder.AddFile("logs/answers-{Date}.txt"); // Specify the file path and format
|
||||||
|
});
|
||||||
// Add services to the container.
|
// Add services to the container.
|
||||||
|
|
||||||
builder.Services.AddControllers();
|
builder.Services.AddControllers();
|
||||||
@ -85,6 +94,7 @@ if (app.Environment.IsDevelopment())
|
|||||||
app.UseSwagger();
|
app.UseSwagger();
|
||||||
app.UseSwaggerUI();
|
app.UseSwaggerUI();
|
||||||
}
|
}
|
||||||
|
app.UseCors("DamageAppCorsPolicy");
|
||||||
app.UseAuthentication();
|
app.UseAuthentication();
|
||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
|
|
||||||
|
@ -10,8 +10,8 @@
|
|||||||
},
|
},
|
||||||
"AllowedHosts": "*",
|
"AllowedHosts": "*",
|
||||||
"ConnectionStrings": {
|
"ConnectionStrings": {
|
||||||
"AnswerConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;"
|
//"AnswerConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;"
|
||||||
//"AnswerConnection": "Server=tcp:da-dev.database.windows.net,1433;Initial Catalog=da-dev-db;Encrypt=True;User ID=admin-dev;Password=b3tgRABw8LGE75k;TrustServerCertificate=False;Connection Timeout=30;"
|
"AnswerConnection": "Server=207.180.248.35;Database=da_survey_dev;User Id=sa;Password=YourStrongPassw0rd;TrustServerCertificate=True;"
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -33,7 +33,7 @@ namespace DamageAssesment.Api.Attachments.Test
|
|||||||
public async Task GetAttachmentsAsync_ShouldReturnStatusCode204()
|
public async Task GetAttachmentsAsync_ShouldReturnStatusCode204()
|
||||||
{
|
{
|
||||||
var mockAttachmentService = new Mock<IAttachmentsProvider>();
|
var mockAttachmentService = new Mock<IAttachmentsProvider>();
|
||||||
var mockUploadService = new Mock<UploadService>();
|
var mockUploadService = new Mock<IUploadService>();
|
||||||
var mockResponse = await MockData.getNoContentResponse();
|
var mockResponse = await MockData.getNoContentResponse();
|
||||||
mockAttachmentService.Setup(service => service.GetAttachmentsAsync()).ReturnsAsync(mockResponse);
|
mockAttachmentService.Setup(service => service.GetAttachmentsAsync()).ReturnsAsync(mockResponse);
|
||||||
|
|
||||||
@ -47,7 +47,7 @@ namespace DamageAssesment.Api.Attachments.Test
|
|||||||
public async Task GetAttachmentAsync_ShouldReturnStatusCode200()
|
public async Task GetAttachmentAsync_ShouldReturnStatusCode200()
|
||||||
{
|
{
|
||||||
var mockAttachmentService = new Mock<IAttachmentsProvider>();
|
var mockAttachmentService = new Mock<IAttachmentsProvider>();
|
||||||
var mockUploadService = new Mock<UploadService>();
|
var mockUploadService = new Mock<IUploadService>();
|
||||||
var mockResponse = await MockData.getOkResponse(1);
|
var mockResponse = await MockData.getOkResponse(1);
|
||||||
mockAttachmentService.Setup(service => service.GetAttachmentByIdAsync(1)).ReturnsAsync(mockResponse);
|
mockAttachmentService.Setup(service => service.GetAttachmentByIdAsync(1)).ReturnsAsync(mockResponse);
|
||||||
|
|
||||||
@ -61,7 +61,7 @@ namespace DamageAssesment.Api.Attachments.Test
|
|||||||
public async Task GetAttachmentAsync_ShouldReturnStatusCode404()
|
public async Task GetAttachmentAsync_ShouldReturnStatusCode404()
|
||||||
{
|
{
|
||||||
var mockAttachmentService = new Mock<IAttachmentsProvider>();
|
var mockAttachmentService = new Mock<IAttachmentsProvider>();
|
||||||
var mockUploadService = new Mock<UploadService>();
|
var mockUploadService = new Mock<IUploadService>();
|
||||||
var mockResponse = await MockData.getNotFoundResponse();
|
var mockResponse = await MockData.getNotFoundResponse();
|
||||||
mockAttachmentService.Setup(service => service.GetAttachmentByIdAsync(99)).ReturnsAsync(mockResponse);
|
mockAttachmentService.Setup(service => service.GetAttachmentByIdAsync(99)).ReturnsAsync(mockResponse);
|
||||||
var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object);
|
var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object);
|
||||||
@ -73,14 +73,14 @@ namespace DamageAssesment.Api.Attachments.Test
|
|||||||
public async Task PostAttachmentAsync_ShouldReturnStatusCode200()
|
public async Task PostAttachmentAsync_ShouldReturnStatusCode200()
|
||||||
{
|
{
|
||||||
var mockAttachmentService = new Mock<IAttachmentsProvider>();
|
var mockAttachmentService = new Mock<IAttachmentsProvider>();
|
||||||
var mockUploadService = new Mock<UploadService>();
|
var mockUploadService = new Mock<IUploadService>();
|
||||||
var mockResponse = await MockData.getOkResponse();
|
var mockResponse = await MockData.getOkResponse();
|
||||||
var AttachmentResponse = await MockData.GetAttachmentInfo(0);
|
var AttachmentResponse = await MockData.GetAttachmentInfo(0);
|
||||||
var mockInputAttachment = await MockData.getInputAttachmentData();
|
var mockInputAttachment = await MockData.getInputAttachmentData();
|
||||||
mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).ReturnsAsync(mockResponse);
|
mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).ReturnsAsync(mockResponse);
|
||||||
|
|
||||||
var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object);
|
var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object);
|
||||||
var result = (NoContentResult) await AttachmentProvider.UploadAttachmentAsync(AttachmentResponse);
|
var result = (NoContentResult)await AttachmentProvider.UploadAttachmentAsync(AttachmentResponse);
|
||||||
|
|
||||||
Assert.Equal(204, result.StatusCode);
|
Assert.Equal(204, result.StatusCode);
|
||||||
}
|
}
|
||||||
@ -89,14 +89,14 @@ namespace DamageAssesment.Api.Attachments.Test
|
|||||||
public async Task PostAttachmentAsync_ShouldReturnStatusCode400()
|
public async Task PostAttachmentAsync_ShouldReturnStatusCode400()
|
||||||
{
|
{
|
||||||
var mockAttachmentService = new Mock<IAttachmentsProvider>();
|
var mockAttachmentService = new Mock<IAttachmentsProvider>();
|
||||||
var mockUploadService = new Mock<UploadService>();
|
var mockUploadService = new Mock<IUploadService>();
|
||||||
var mockInputAttachment = await MockData.getInputAttachmentData();
|
var mockInputAttachment = await MockData.getInputAttachmentData();
|
||||||
var mockResponse = await MockData.getBadRequestResponse();
|
var mockResponse = await MockData.getBadRequestResponse();
|
||||||
mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).ReturnsAsync(mockResponse);
|
mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).ReturnsAsync(mockResponse);
|
||||||
|
|
||||||
var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object);
|
var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object);
|
||||||
AttachmentInfo attachmentInfo=new AttachmentInfo();
|
AttachmentInfo attachmentInfo = new AttachmentInfo();
|
||||||
var result = (BadRequestObjectResult) await AttachmentProvider.UploadAttachmentAsync(attachmentInfo);
|
var result = (BadRequestObjectResult)await AttachmentProvider.UploadAttachmentAsync(attachmentInfo);
|
||||||
|
|
||||||
Assert.Equal(400, result.StatusCode);
|
Assert.Equal(400, result.StatusCode);
|
||||||
}
|
}
|
||||||
@ -105,14 +105,14 @@ namespace DamageAssesment.Api.Attachments.Test
|
|||||||
public async Task PutAttachmentAsync_ShouldReturnStatusCode200()
|
public async Task PutAttachmentAsync_ShouldReturnStatusCode200()
|
||||||
{
|
{
|
||||||
var mockAttachmentService = new Mock<IAttachmentsProvider>();
|
var mockAttachmentService = new Mock<IAttachmentsProvider>();
|
||||||
var mockUploadService = new Mock<UploadService>();
|
var mockUploadService = new Mock<IUploadService>();
|
||||||
var mockResponse = await MockData.getOkResponse();
|
var mockResponse = await MockData.getOkResponse();
|
||||||
var AttachmentResponse = await MockData.GetAttachmentInfo(1);
|
var AttachmentResponse = await MockData.GetAttachmentInfo(1);
|
||||||
var mockInputAttachment = await MockData.getInputAttachmentData();
|
var mockInputAttachment = await MockData.getInputAttachmentData();
|
||||||
mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).ReturnsAsync(mockResponse);
|
mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).ReturnsAsync(mockResponse);
|
||||||
|
|
||||||
var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object);
|
var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object);
|
||||||
var result = (NoContentResult) await AttachmentProvider.UpdateAttachmentAsync(AttachmentResponse);
|
var result = (NoContentResult)await AttachmentProvider.UpdateAttachmentAsync(AttachmentResponse);
|
||||||
|
|
||||||
Assert.Equal(204, result.StatusCode);
|
Assert.Equal(204, result.StatusCode);
|
||||||
}
|
}
|
||||||
@ -121,14 +121,14 @@ namespace DamageAssesment.Api.Attachments.Test
|
|||||||
public async Task PutAttachmentAsync_ShouldReturnStatusCode400()
|
public async Task PutAttachmentAsync_ShouldReturnStatusCode400()
|
||||||
{
|
{
|
||||||
var mockAttachmentService = new Mock<IAttachmentsProvider>();
|
var mockAttachmentService = new Mock<IAttachmentsProvider>();
|
||||||
var mockUploadService = new Mock<UploadService>();
|
var mockUploadService = new Mock<IUploadService>();
|
||||||
var mockInputAttachment = await MockData.getInputAttachmentData();
|
var mockInputAttachment = await MockData.getInputAttachmentData();
|
||||||
var mockResponse = await MockData.getBadRequestResponse();
|
var mockResponse = await MockData.getBadRequestResponse();
|
||||||
mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).ReturnsAsync(mockResponse);
|
mockAttachmentService.Setup(service => service.PostAttachmentAsync(mockInputAttachment)).ReturnsAsync(mockResponse);
|
||||||
|
|
||||||
var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object);
|
var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object);
|
||||||
AttachmentInfo attachmentInfo = new AttachmentInfo();
|
AttachmentInfo attachmentInfo = new AttachmentInfo();
|
||||||
var result = (BadRequestObjectResult) await AttachmentProvider.UpdateAttachmentAsync(attachmentInfo);
|
var result = (BadRequestObjectResult)await AttachmentProvider.UpdateAttachmentAsync(attachmentInfo);
|
||||||
|
|
||||||
Assert.Equal(400, result.StatusCode);
|
Assert.Equal(400, result.StatusCode);
|
||||||
}
|
}
|
||||||
@ -136,7 +136,7 @@ namespace DamageAssesment.Api.Attachments.Test
|
|||||||
public async Task DeleteAttachmentAsync_ShouldReturnStatusCode200()
|
public async Task DeleteAttachmentAsync_ShouldReturnStatusCode200()
|
||||||
{
|
{
|
||||||
var mockAttachmentService = new Mock<IAttachmentsProvider>();
|
var mockAttachmentService = new Mock<IAttachmentsProvider>();
|
||||||
var mockUploadService = new Mock<UploadService>();
|
var mockUploadService = new Mock<IUploadService>();
|
||||||
var mockResponse = await MockData.getOkResponse(1);
|
var mockResponse = await MockData.getOkResponse(1);
|
||||||
mockAttachmentService.Setup(service => service.DeleteAttachmentAsync(1)).ReturnsAsync(mockResponse);
|
mockAttachmentService.Setup(service => service.DeleteAttachmentAsync(1)).ReturnsAsync(mockResponse);
|
||||||
mockUploadService.Setup(service => service.Deletefile(""));
|
mockUploadService.Setup(service => service.Deletefile(""));
|
||||||
@ -150,7 +150,7 @@ namespace DamageAssesment.Api.Attachments.Test
|
|||||||
public async Task DeleteAttachmentAsync_ShouldReturnStatusCode404()
|
public async Task DeleteAttachmentAsync_ShouldReturnStatusCode404()
|
||||||
{
|
{
|
||||||
var mockAttachmentService = new Mock<IAttachmentsProvider>();
|
var mockAttachmentService = new Mock<IAttachmentsProvider>();
|
||||||
var mockUploadService = new Mock<UploadService>();
|
var mockUploadService = new Mock<IUploadService>();
|
||||||
var mockResponse = await MockData.getNotFoundResponse();
|
var mockResponse = await MockData.getNotFoundResponse();
|
||||||
mockAttachmentService.Setup(service => service.DeleteAttachmentAsync(1)).ReturnsAsync(mockResponse);
|
mockAttachmentService.Setup(service => service.DeleteAttachmentAsync(1)).ReturnsAsync(mockResponse);
|
||||||
var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object);
|
var AttachmentProvider = new AttachmentsController(mockAttachmentService.Object, mockUploadService.Object);
|
||||||
|
@ -139,6 +139,81 @@ namespace DamageAssesment.Api.Attachments.Controllers
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
/// download an existing attachment.
|
||||||
|
/// </summary>
|
||||||
|
[Authorize(Roles = "admin")]
|
||||||
|
[HttpGet("attachments/download/{id}")]
|
||||||
|
public async Task<IActionResult> downloadfile(int id)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await this.AttachmentProvider.GetDownloadAttachmentAsync(id);
|
||||||
|
if (!result.IsSuccess)
|
||||||
|
return NotFound();
|
||||||
|
string path = await UploadService.GetFile(result.Attachment.URI);
|
||||||
|
if (path == null)
|
||||||
|
return NotFound();
|
||||||
|
var contentType = GetContentType(result.Attachment.FileName);
|
||||||
|
if (contentType == "application/octet-stream")
|
||||||
|
return PhysicalFile(path, contentType, result.Attachment.FileName);
|
||||||
|
return PhysicalFile(path, contentType, enableRangeProcessing: true);// result.Attachment.FileName);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// Handle the exception here or log it
|
||||||
|
return StatusCode(500, "An error occurred: " + ex.Message);
|
||||||
|
}
|
||||||
|
//try
|
||||||
|
//{
|
||||||
|
// var result = await this.AttachmentProvider.GetDownloadAttachmentAsync(id);
|
||||||
|
// if(!result.IsSuccess)
|
||||||
|
// return NotFound();
|
||||||
|
// byte[] fileContent = await UploadService.DownloadFile(result.Attachment.URI);
|
||||||
|
// if (fileContent == null || fileContent.Length == 0)
|
||||||
|
// return NotFound();
|
||||||
|
// var contentType = "application/octet-stream";
|
||||||
|
// return File(fileContent, contentType, result.Attachment.FileName);
|
||||||
|
//}
|
||||||
|
//catch (Exception ex)
|
||||||
|
//{
|
||||||
|
// // Handle the exception here or log it
|
||||||
|
// return StatusCode(500, "An error occurred: " + ex.Message);
|
||||||
|
//}
|
||||||
|
}
|
||||||
|
private string GetContentType(string fileName)
|
||||||
|
{
|
||||||
|
// You can add more content types based on the file extensions
|
||||||
|
switch (Path.GetExtension(fileName).ToLower())
|
||||||
|
{
|
||||||
|
//case ".txt":
|
||||||
|
// return "text/plain";
|
||||||
|
case ".jpg":
|
||||||
|
case ".jpeg":
|
||||||
|
return "image/jpeg";
|
||||||
|
case ".png":
|
||||||
|
return "image/png";
|
||||||
|
case ".gif":
|
||||||
|
return "image/gif";
|
||||||
|
case ".bmp":
|
||||||
|
return "image/bmp";
|
||||||
|
case ".webp":
|
||||||
|
return "image/webp";
|
||||||
|
case ".csv":
|
||||||
|
return "text/csv";
|
||||||
|
case ".pdf":
|
||||||
|
return "application/pdf";
|
||||||
|
case ".docx":
|
||||||
|
case ".doc":
|
||||||
|
return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
|
||||||
|
case ".xlsx":
|
||||||
|
case ".xls":
|
||||||
|
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
||||||
|
// Add more cases as needed
|
||||||
|
default:
|
||||||
|
return "application/octet-stream";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// <summary>
|
||||||
/// Delete an existing attachment.
|
/// Delete an existing attachment.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
[Authorize(Roles = "admin")]
|
[Authorize(Roles = "admin")]
|
||||||
|
@ -27,7 +27,10 @@
|
|||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
|
||||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.4" />
|
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.4" />
|
||||||
|
<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
|
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
@ -9,6 +9,7 @@ namespace DamageAssesment.Api.Attachments.Interfaces
|
|||||||
Task<(bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage)> PostAttachmentAsync(List<Models.Attachment> Attachments);
|
Task<(bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage)> PostAttachmentAsync(List<Models.Attachment> Attachments);
|
||||||
Task<(bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage)> PutAttachmentAsync(List<Models.Attachment> Attachments);
|
Task<(bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage)> PutAttachmentAsync(List<Models.Attachment> Attachments);
|
||||||
Task<(bool IsSuccess, Models.Attachment Attachment, string Path)> DeleteAttachmentAsync(int Id);
|
Task<(bool IsSuccess, Models.Attachment Attachment, string Path)> DeleteAttachmentAsync(int Id);
|
||||||
|
Task<(bool IsSuccess, Models.Attachment Attachment, string Path)> GetDownloadAttachmentAsync(int Id);
|
||||||
Task<(bool IsSuccess, int counter, string Path)> DeleteAttachmentsAsync(int responseId, int answerId);
|
Task<(bool IsSuccess, int counter, string Path)> DeleteAttachmentsAsync(int responseId, int answerId);
|
||||||
Task<(bool IsSuccess, int counter, string Path)> DeleteBulkAttachmentsAsync(int responseId, List<int> answerIds);
|
Task<(bool IsSuccess, int counter, string Path)> DeleteBulkAttachmentsAsync(int responseId, List<int> answerIds);
|
||||||
Task<(bool IsSuccess, int counter, string message)> GetAttachmentCounter();
|
Task<(bool IsSuccess, int counter, string message)> GetAttachmentCounter();
|
||||||
|
@ -7,6 +7,8 @@ namespace DamageAssesment.Api.Attachments.Interfaces
|
|||||||
List<Models.Attachment> UploadAttachment(int responseId,int answerId, int counter, List<IFormFile> postedFile);
|
List<Models.Attachment> UploadAttachment(int responseId,int answerId, int counter, List<IFormFile> postedFile);
|
||||||
List<Models.Attachment> UploadAttachment(int responseId, int counter, List<AnswerInfo> answers);
|
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);
|
public List<Models.Attachment> UpdateAttachments(int responseId, List<AnswerInfo> answers, IEnumerable<Models.Attachment> attachments);
|
||||||
|
Task<byte[]> DownloadFile(string path);
|
||||||
|
Task<string> GetFile(string path);
|
||||||
void Deletefile(string path);
|
void Deletefile(string path);
|
||||||
void Movefile(string path);
|
void Movefile(string path);
|
||||||
}
|
}
|
||||||
|
@ -5,13 +5,22 @@ using Microsoft.AspNetCore.Authentication.JwtBearer;
|
|||||||
using Microsoft.AspNetCore.Http.Features;
|
using Microsoft.AspNetCore.Http.Features;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.FileProviders;
|
using Microsoft.Extensions.FileProviders;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
using Microsoft.IdentityModel.Tokens;
|
using Microsoft.IdentityModel.Tokens;
|
||||||
using Microsoft.OpenApi.Models;
|
using Microsoft.OpenApi.Models;
|
||||||
using System.Reflection;
|
using System.Reflection;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
builder.Services.AddCors(p => p.AddPolicy("DamageAppCorsPolicy", build => {
|
||||||
|
build.WithOrigins("*").AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin();
|
||||||
|
}));
|
||||||
var authkey = builder.Configuration.GetValue<string>("JwtSettings:securitykey");
|
var authkey = builder.Configuration.GetValue<string>("JwtSettings:securitykey");
|
||||||
|
builder.Services.AddLogging(builder =>
|
||||||
|
{
|
||||||
|
//builder.AddConsole(); // Optional: Add other providers if needed
|
||||||
|
builder.AddFile("logs/attachments-{Date}.txt"); // Specify the file path and format
|
||||||
|
});
|
||||||
builder.Services.AddAuthentication(item =>
|
builder.Services.AddAuthentication(item =>
|
||||||
{
|
{
|
||||||
item.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
item.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||||
@ -71,6 +80,7 @@ builder.Services.AddSwaggerGen(options =>
|
|||||||
|
|
||||||
options.AddSecurityRequirement(securityRequirements);
|
options.AddSecurityRequirement(securityRequirements);
|
||||||
});
|
});
|
||||||
|
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
|
||||||
builder.Services.AddScoped<IAttachmentsProvider, AttachmentsProvider>();
|
builder.Services.AddScoped<IAttachmentsProvider, AttachmentsProvider>();
|
||||||
builder.Services.AddScoped<IUploadService, UploadService>();
|
builder.Services.AddScoped<IUploadService, UploadService>();
|
||||||
builder.Services.AddScoped<IAzureBlobService,AzureBlobService>();
|
builder.Services.AddScoped<IAzureBlobService,AzureBlobService>();
|
||||||
@ -94,7 +104,7 @@ if (app.Environment.IsDevelopment())
|
|||||||
app.UseSwagger();
|
app.UseSwagger();
|
||||||
app.UseSwaggerUI();
|
app.UseSwaggerUI();
|
||||||
}
|
}
|
||||||
|
app.UseCors("DamageAppCorsPolicy");
|
||||||
app.UseAuthentication();
|
app.UseAuthentication();
|
||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
app.UseHttpsRedirection();
|
app.UseHttpsRedirection();
|
||||||
|
@ -14,14 +14,18 @@ namespace DamageAssesment.Api.Attachments.Providers
|
|||||||
private ILogger<AttachmentsProvider> logger;
|
private ILogger<AttachmentsProvider> logger;
|
||||||
private IUploadService uploadservice;
|
private IUploadService uploadservice;
|
||||||
private IMapper mapper;
|
private IMapper mapper;
|
||||||
|
private readonly IHttpContextAccessor httpContextAccessor;
|
||||||
public AttachmentsProvider(AttachmentsDbContext AttachmentDbContext, ILogger<AttachmentsProvider> logger, IMapper mapper,IUploadService uploadservice)
|
private string baseUrl;
|
||||||
|
public AttachmentsProvider(AttachmentsDbContext AttachmentDbContext, ILogger<AttachmentsProvider> logger, IMapper mapper,IUploadService uploadservice, IHttpContextAccessor httpContextAccessor)
|
||||||
{
|
{
|
||||||
this.AttachmentDbContext = AttachmentDbContext;
|
this.AttachmentDbContext = AttachmentDbContext;
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
this.mapper = mapper;
|
this.mapper = mapper;
|
||||||
this.uploadservice = uploadservice;
|
this.uploadservice = uploadservice;
|
||||||
//SeedData();
|
this.httpContextAccessor = httpContextAccessor;
|
||||||
|
baseUrl = $"{httpContextAccessor.HttpContext.Request.Scheme}://{httpContextAccessor.HttpContext.Request.Host}";
|
||||||
|
baseUrl = baseUrl + "/attachments/download";
|
||||||
|
// SeedData();
|
||||||
}
|
}
|
||||||
public async Task<(bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage)> GetAttachmentsAsync()
|
public async Task<(bool IsSuccess, IEnumerable<Models.Attachment> Attachments, string ErrorMessage)> GetAttachmentsAsync()
|
||||||
{
|
{
|
||||||
@ -32,6 +36,10 @@ namespace DamageAssesment.Api.Attachments.Providers
|
|||||||
var Attachment = await AttachmentDbContext.Attachments.AsNoTracking().Where(a => !a.IsDeleted).ToListAsync();
|
var Attachment = await AttachmentDbContext.Attachments.AsNoTracking().Where(a => !a.IsDeleted).ToListAsync();
|
||||||
if (Attachment != null)
|
if (Attachment != null)
|
||||||
{
|
{
|
||||||
|
foreach (var attachment in Attachment)
|
||||||
|
{
|
||||||
|
attachment.URI = $"{baseUrl}/{attachment.Id}";
|
||||||
|
}
|
||||||
logger?.LogInformation($"{Attachment.Count} Attachments(s) found");
|
logger?.LogInformation($"{Attachment.Count} Attachments(s) found");
|
||||||
var result = mapper.Map<IEnumerable<Db.Attachment>, IEnumerable<Models.Attachment>>(Attachment);
|
var result = mapper.Map<IEnumerable<Db.Attachment>, IEnumerable<Models.Attachment>>(Attachment);
|
||||||
return (true, result, null);
|
return (true, result, null);
|
||||||
@ -54,6 +62,7 @@ namespace DamageAssesment.Api.Attachments.Providers
|
|||||||
if (Attachment != null)
|
if (Attachment != null)
|
||||||
{
|
{
|
||||||
logger?.LogInformation($"{Attachment} customer(s) found");
|
logger?.LogInformation($"{Attachment} customer(s) found");
|
||||||
|
Attachment.URI = $"{baseUrl}/{Attachment.Id}";
|
||||||
var result = mapper.Map<Db.Attachment, Models.Attachment>(Attachment);
|
var result = mapper.Map<Db.Attachment, Models.Attachment>(Attachment);
|
||||||
return (true, result, null);
|
return (true, result, null);
|
||||||
}
|
}
|
||||||
@ -73,6 +82,10 @@ namespace DamageAssesment.Api.Attachments.Providers
|
|||||||
List<Db.Attachment> attachments = mapper.Map<List<Models.Attachment>, List<Db.Attachment>>(Attachments);
|
List<Db.Attachment> attachments = mapper.Map<List<Models.Attachment>, List<Db.Attachment>>(Attachments);
|
||||||
AttachmentDbContext.Attachments.AddRange(attachments);
|
AttachmentDbContext.Attachments.AddRange(attachments);
|
||||||
await AttachmentDbContext.SaveChangesAsync();
|
await AttachmentDbContext.SaveChangesAsync();
|
||||||
|
foreach (var attachment in attachments)
|
||||||
|
{
|
||||||
|
attachment.URI = $"{baseUrl}/{attachment.Id}";
|
||||||
|
}
|
||||||
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);
|
return (true, result, null);
|
||||||
}
|
}
|
||||||
@ -91,6 +104,10 @@ namespace DamageAssesment.Api.Attachments.Providers
|
|||||||
List<Db.Attachment> attachments = mapper.Map<List<Models.Attachment>, List<Db.Attachment>>(Attachments);
|
List<Db.Attachment> attachments = mapper.Map<List<Models.Attachment>, List<Db.Attachment>>(Attachments);
|
||||||
AttachmentDbContext.Attachments.UpdateRange(attachments);
|
AttachmentDbContext.Attachments.UpdateRange(attachments);
|
||||||
await AttachmentDbContext.SaveChangesAsync();
|
await AttachmentDbContext.SaveChangesAsync();
|
||||||
|
foreach (var attachment in attachments)
|
||||||
|
{
|
||||||
|
attachment.URI = $"{baseUrl}/{attachment.Id}";
|
||||||
|
}
|
||||||
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);
|
return (true, result, null);
|
||||||
}
|
}
|
||||||
@ -197,6 +214,24 @@ namespace DamageAssesment.Api.Attachments.Providers
|
|||||||
{
|
{
|
||||||
return AttachmentDbContext.Attachments.AsNoTracking().Count(e => e.Id == id && !e.IsDeleted) > 0;
|
return AttachmentDbContext.Attachments.AsNoTracking().Count(e => e.Id == id && !e.IsDeleted) > 0;
|
||||||
}
|
}
|
||||||
|
public async Task<(bool IsSuccess, Models.Attachment Attachment, string Path)> GetDownloadAttachmentAsync(int Id)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Db.Attachment Attachment = AttachmentDbContext.Attachments.Where(a => a.Id == Id).AsNoTracking().FirstOrDefault();
|
||||||
|
if (Attachment == null)
|
||||||
|
{
|
||||||
|
return (false, null, "Not Found");
|
||||||
|
}
|
||||||
|
return (true, mapper.Map<Db.Attachment, Models.Attachment>(Attachment), $"Attachment {Id}");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
|
||||||
|
logger?.LogError(ex.ToString());
|
||||||
|
return (false, null, ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
private void SeedData()
|
private void SeedData()
|
||||||
{
|
{
|
||||||
|
@ -24,6 +24,41 @@ namespace DamageAssesment.Api.Attachments.Providers
|
|||||||
uploadpath = configuration.GetValue<string>("Fileupload:folderpath");
|
uploadpath = configuration.GetValue<string>("Fileupload:folderpath");
|
||||||
Deletepath = configuration.GetValue<string>("Fileupload:Deletepath");
|
Deletepath = configuration.GetValue<string>("Fileupload:Deletepath");
|
||||||
}
|
}
|
||||||
|
public async Task<string> GetFile(string path)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (System.IO.File.Exists(path))
|
||||||
|
{
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null; // File not found
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// Handle or log the exception as needed
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
public async Task<byte[]> DownloadFile(string path)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (System.IO.File.Exists(path))
|
||||||
|
{
|
||||||
|
return await System.IO.File.ReadAllBytesAsync(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null; // File not found
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// Handle or log the exception as needed
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
public List<Models.Attachment> UploadAttachment(int responseId,int answerId,int counter, List<IFormFile> postedFile)
|
public List<Models.Attachment> UploadAttachment(int responseId,int answerId,int counter, List<IFormFile> postedFile)
|
||||||
{
|
{
|
||||||
var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), uploadpath);
|
var pathToSave = Path.Combine(Directory.GetCurrentDirectory(), uploadpath);
|
||||||
@ -89,7 +124,7 @@ namespace DamageAssesment.Api.Attachments.Providers
|
|||||||
{
|
{
|
||||||
counter++;
|
counter++;
|
||||||
|
|
||||||
var UserfileName = Path.GetFileName(file.FileName);
|
var UserfileName = Path.GetFileName(file.FileName+ file.FileExtension);
|
||||||
var fileName = String.Format("Attachment_{0}{1}", counter, file.FileExtension);
|
var fileName = String.Format("Attachment_{0}{1}", counter, file.FileExtension);
|
||||||
var dbPath = Path.Combine(fullDirectoryPath, fileName);
|
var dbPath = Path.Combine(fullDirectoryPath, fileName);
|
||||||
File.WriteAllBytes(dbPath, Convert.FromBase64String(file.FileContent));
|
File.WriteAllBytes(dbPath, Convert.FromBase64String(file.FileContent));
|
||||||
@ -126,7 +161,7 @@ namespace DamageAssesment.Api.Attachments.Providers
|
|||||||
foreach (var file in item.postedFiles)
|
foreach (var file in item.postedFiles)
|
||||||
{
|
{
|
||||||
Models.Attachment attachment= attachments.Where(a=>a.Id == file.AttachmentId).FirstOrDefault();
|
Models.Attachment attachment= attachments.Where(a=>a.Id == file.AttachmentId).FirstOrDefault();
|
||||||
var UserfileName = Path.GetFileName(file.FileName);
|
var UserfileName = Path.GetFileName(file.FileName + file.FileExtension);
|
||||||
var fileName = String.Format("Attachment_{0}{1}", attachment?.Id, file.FileExtension);
|
var fileName = String.Format("Attachment_{0}{1}", attachment?.Id, file.FileExtension);
|
||||||
var dbPath = Path.Combine(fullDirectoryPath, fileName);
|
var dbPath = Path.Combine(fullDirectoryPath, fileName);
|
||||||
File.WriteAllBytes(dbPath, Convert.FromBase64String(file.FileContent));
|
File.WriteAllBytes(dbPath, Convert.FromBase64String(file.FileContent));
|
||||||
|
@ -16,8 +16,8 @@
|
|||||||
"BlobContainerName": "doculinks"
|
"BlobContainerName": "doculinks"
|
||||||
},
|
},
|
||||||
"ConnectionStrings": {
|
"ConnectionStrings": {
|
||||||
"AttachmentConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;"
|
//"AttachmentConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;"
|
||||||
//"AttachmentConnection": "Server=tcp:da-dev.database.windows.net,1433;Initial Catalog=da-dev-db;Encrypt=True;User ID=admin-dev;Password=b3tgRABw8LGE75k;TrustServerCertificate=False;Connection Timeout=30;"
|
"AttachmentConnection": "Server=207.180.248.35;Database=da_survey_dev;User Id=sa;Password=YourStrongPassw0rd;TrustServerCertificate=True;"
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -197,7 +197,29 @@ namespace DamageAssesment.Api.DocuLinks.Test
|
|||||||
var result = (NotFoundResult)await DocumentProvider.DeleteDocument(1);
|
var result = (NotFoundResult)await DocumentProvider.DeleteDocument(1);
|
||||||
Assert.Equal(404, result.StatusCode);
|
Assert.Equal(404, result.StatusCode);
|
||||||
}
|
}
|
||||||
|
[Fact(DisplayName = "Update Document IsActive- Ok case")]
|
||||||
|
public async Task UpdateDocumentAsync_ShouldReturnStatusCode200()
|
||||||
|
{
|
||||||
|
var mockDocumentService = new Mock<IDoculinkProvider>();
|
||||||
|
var mockUploadService = new Mock<IUploadService>();
|
||||||
|
var mockResponse = await MockData.getOkResponse(1);
|
||||||
|
mockDocumentService.Setup(service => service.UpdateDocumentAsync(1,true)).ReturnsAsync(mockResponse);
|
||||||
|
var DocumentProvider = new DoculinkController(mockDocumentService.Object, mockUploadService.Object);
|
||||||
|
var result = (OkObjectResult)await DocumentProvider.UpdateIsActiveDocument(1,true);
|
||||||
|
|
||||||
|
Assert.Equal(200, result.StatusCode);
|
||||||
|
}
|
||||||
|
[Fact(DisplayName = "Update Document IsActive - NotFound case")]
|
||||||
|
public async Task UpdateDocumentAsync_ShouldReturnStatusCode404()
|
||||||
|
{
|
||||||
|
var mockDocumentService = new Mock<IDoculinkProvider>();
|
||||||
|
var mockUploadService = new Mock<IUploadService>();
|
||||||
|
var mockResponse = await MockData.getNotFoundResponse();
|
||||||
|
mockDocumentService.Setup(service => service.UpdateDocumentAsync(1,true)).ReturnsAsync(mockResponse);
|
||||||
|
var DocumentProvider = new DoculinkController(mockDocumentService.Object, mockUploadService.Object);
|
||||||
|
var result = (NotFoundResult)await DocumentProvider.UpdateIsActiveDocument(1,true);
|
||||||
|
Assert.Equal(404, result.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
// Link Type Test cases
|
// Link Type Test cases
|
||||||
|
|
||||||
|
@ -31,10 +31,9 @@ namespace DamageAssesment.Api.DocuLinks.Test
|
|||||||
List<DoculinkAttachments> doclinksAttachments = new List<DoculinkAttachments>();
|
List<DoculinkAttachments> doclinksAttachments = new List<DoculinkAttachments>();
|
||||||
doclinksAttachments.Add(new DoculinkAttachments()
|
doclinksAttachments.Add(new DoculinkAttachments()
|
||||||
{
|
{
|
||||||
docName = "",
|
docName = "",Path="www.google.com",
|
||||||
Path = "www.google.com",
|
Language = "en",
|
||||||
IsAttachments = false,
|
IsAttachments =false,CustomOrder=1
|
||||||
CustomOrder = 1
|
|
||||||
});
|
});
|
||||||
list.Add(new DocuLinks.Models.ResDoculink()
|
list.Add(new DocuLinks.Models.ResDoculink()
|
||||||
{
|
{
|
||||||
@ -76,6 +75,7 @@ namespace DamageAssesment.Api.DocuLinks.Test
|
|||||||
docName = "",
|
docName = "",
|
||||||
Path = "www.google.com",
|
Path = "www.google.com",
|
||||||
IsAttachments = false,
|
IsAttachments = false,
|
||||||
|
Language = "en",
|
||||||
CustomOrder = 1
|
CustomOrder = 1
|
||||||
});
|
});
|
||||||
list.Add(new DocuLinks.Models.ResDoculink()
|
list.Add(new DocuLinks.Models.ResDoculink()
|
||||||
@ -140,6 +140,7 @@ namespace DamageAssesment.Api.DocuLinks.Test
|
|||||||
docName = "",
|
docName = "",
|
||||||
Path = "www.google.com",
|
Path = "www.google.com",
|
||||||
IsAttachments = false,
|
IsAttachments = false,
|
||||||
|
Language = "en",
|
||||||
CustomOrder = 1
|
CustomOrder = 1
|
||||||
});
|
});
|
||||||
return new Models.Doculink
|
return new Models.Doculink
|
||||||
@ -167,6 +168,7 @@ namespace DamageAssesment.Api.DocuLinks.Test
|
|||||||
docName = "",
|
docName = "",
|
||||||
Path = "www.google.com",
|
Path = "www.google.com",
|
||||||
IsAttachments = false,
|
IsAttachments = false,
|
||||||
|
Language = "en",
|
||||||
CustomOrder = 1
|
CustomOrder = 1
|
||||||
});
|
});
|
||||||
List<DocuLinks.Models.Doculink> DocuLinks = new List<Models.Doculink>();
|
List<DocuLinks.Models.Doculink> DocuLinks = new List<Models.Doculink>();
|
||||||
|
@ -45,7 +45,7 @@ namespace DamageAssesment.Api.DocuLinks.Controllers
|
|||||||
[HttpGet]
|
[HttpGet]
|
||||||
[Route("doculinks/types/{id}")]
|
[Route("doculinks/types/{id}")]
|
||||||
[Route("doculinks/types/{id}/{language:alpha}")]
|
[Route("doculinks/types/{id}/{language:alpha}")]
|
||||||
public async Task<IActionResult> GetLinkTypeAsync(int id,string? language)
|
public async Task<IActionResult> GetLinkTypeAsync(int id, string? language)
|
||||||
{
|
{
|
||||||
var result = await this.documentsProvider.GetLinkTypeAsync(id, language);
|
var result = await this.documentsProvider.GetLinkTypeAsync(id, language);
|
||||||
if (result.IsSuccess)
|
if (result.IsSuccess)
|
||||||
@ -60,11 +60,11 @@ namespace DamageAssesment.Api.DocuLinks.Controllers
|
|||||||
[Authorize(Roles = "admin")]
|
[Authorize(Roles = "admin")]
|
||||||
[HttpPut]
|
[HttpPut]
|
||||||
[Route("doculinks/types/{id}")]
|
[Route("doculinks/types/{id}")]
|
||||||
public async Task<IActionResult> UpdateLinkType(int id,Models.LinkType linkType)
|
public async Task<IActionResult> UpdateLinkType(int id, Models.LinkType linkType)
|
||||||
{
|
{
|
||||||
if (linkType != null)
|
if (linkType != null)
|
||||||
{
|
{
|
||||||
var result = await this.documentsProvider.UpdateLinkTypeAsync(id,linkType);
|
var result = await this.documentsProvider.UpdateLinkTypeAsync(id, linkType);
|
||||||
if (result.IsSuccess)
|
if (result.IsSuccess)
|
||||||
{
|
{
|
||||||
return Ok(result.LinkType);
|
return Ok(result.LinkType);
|
||||||
@ -111,7 +111,82 @@ namespace DamageAssesment.Api.DocuLinks.Controllers
|
|||||||
return NotFound();
|
return NotFound();
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// Get all documents.
|
/// download an existing attachment.
|
||||||
|
/// </summary>
|
||||||
|
[Authorize(Roles = "admin")]
|
||||||
|
[HttpGet("doculinks/download/{id}")]
|
||||||
|
public async Task<IActionResult> downloadfile(int id)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var result = await this.documentsProvider.GetDownloadAttachmentAsync(id);
|
||||||
|
if (!result.IsSuccess)
|
||||||
|
return NotFound();
|
||||||
|
string path = await uploadService.GetFile(result.DoculinkAttachments.Path);
|
||||||
|
if (path == null)
|
||||||
|
return NotFound();
|
||||||
|
var contentType = GetContentType(result.DoculinkAttachments.docName);
|
||||||
|
if (contentType == "application/octet-stream")
|
||||||
|
return PhysicalFile(path, contentType, result.DoculinkAttachments.docName);
|
||||||
|
return PhysicalFile(path, contentType, enableRangeProcessing: true);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// Handle the exception here or log it
|
||||||
|
return StatusCode(500, "An error occurred: " + ex.Message);
|
||||||
|
}
|
||||||
|
//try
|
||||||
|
//{
|
||||||
|
// var result = await this.documentsProvider.GetDownloadAttachmentAsync(id);
|
||||||
|
// if (!result.IsSuccess)
|
||||||
|
// return NotFound();
|
||||||
|
// byte[] fileContent = await uploadService.DownloadFile(result.DoculinkAttachments.Path);
|
||||||
|
// if (fileContent == null || fileContent.Length == 0)
|
||||||
|
// return NotFound();
|
||||||
|
// var contentType = "application/octet-stream";
|
||||||
|
// return File(fileContent, contentType, result.DoculinkAttachments.docName);
|
||||||
|
//}
|
||||||
|
//catch (Exception ex)
|
||||||
|
//{
|
||||||
|
// // Handle the exception here or log it
|
||||||
|
// return StatusCode(500, "An error occurred: " + ex.Message);
|
||||||
|
//}
|
||||||
|
}
|
||||||
|
private string GetContentType(string fileName)
|
||||||
|
{
|
||||||
|
// You can add more content types based on the file extensions
|
||||||
|
switch (Path.GetExtension(fileName).ToLower())
|
||||||
|
{
|
||||||
|
//case ".txt":
|
||||||
|
// return "text/plain";
|
||||||
|
case ".jpg":
|
||||||
|
case ".jpeg":
|
||||||
|
return "image/jpeg";
|
||||||
|
case ".png":
|
||||||
|
return "image/png";
|
||||||
|
case ".gif":
|
||||||
|
return "image/gif";
|
||||||
|
case ".bmp":
|
||||||
|
return "image/bmp";
|
||||||
|
case ".webp":
|
||||||
|
return "image/webp";
|
||||||
|
case ".csv":
|
||||||
|
return "text/csv";
|
||||||
|
case ".pdf":
|
||||||
|
return "application/pdf";
|
||||||
|
case ".docx":
|
||||||
|
case ".doc":
|
||||||
|
return "application/vnd.openxmlformats-officedocument.wordprocessingml.document";
|
||||||
|
case ".xlsx":
|
||||||
|
case ".xls":
|
||||||
|
return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
|
||||||
|
// Add more cases as needed
|
||||||
|
default:
|
||||||
|
return "application/octet-stream";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/// <summary>
|
||||||
|
/// Get all Doculink.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|
||||||
[Authorize(Roles = "admin")]
|
[Authorize(Roles = "admin")]
|
||||||
@ -119,7 +194,7 @@ namespace DamageAssesment.Api.DocuLinks.Controllers
|
|||||||
[Route("doculinks/{linktype:alpha}")]
|
[Route("doculinks/{linktype:alpha}")]
|
||||||
[Route("doculinks/{linktype:alpha}/{language:alpha}")]
|
[Route("doculinks/{linktype:alpha}/{language:alpha}")]
|
||||||
[HttpGet]
|
[HttpGet]
|
||||||
public async Task<IActionResult> GetDocumentsAsync(string? linktype, string? language,bool? isactive)
|
public async Task<IActionResult> GetDocumentsAsync(string? linktype, string? language, bool? isactive)
|
||||||
{
|
{
|
||||||
var result = await this.documentsProvider.GetdocumentsByLinkAsync(linktype, language, isactive);
|
var result = await this.documentsProvider.GetdocumentsByLinkAsync(linktype, language, isactive);
|
||||||
if (result.IsSuccess)
|
if (result.IsSuccess)
|
||||||
@ -137,7 +212,7 @@ namespace DamageAssesment.Api.DocuLinks.Controllers
|
|||||||
[HttpGet]
|
[HttpGet]
|
||||||
public async Task<IActionResult> GetDocumentsByActiveAsync(string? linktype, string? language)
|
public async Task<IActionResult> GetDocumentsByActiveAsync(string? linktype, string? language)
|
||||||
{
|
{
|
||||||
var result = await this.documentsProvider.GetdocumentsByLinkAsync(linktype, language,true);
|
var result = await this.documentsProvider.GetdocumentsByLinkAsync(linktype, language, true);
|
||||||
if (result.IsSuccess)
|
if (result.IsSuccess)
|
||||||
{
|
{
|
||||||
return Ok(result.documents);
|
return Ok(result.documents);
|
||||||
@ -167,7 +242,7 @@ namespace DamageAssesment.Api.DocuLinks.Controllers
|
|||||||
[Route("doculinks/{id}")]
|
[Route("doculinks/{id}")]
|
||||||
[Route("doculinks/{id}/{linktype:alpha}")]
|
[Route("doculinks/{id}/{linktype:alpha}")]
|
||||||
[Route("doculinks/{id}/{linktype:alpha}/{language:alpha}")]
|
[Route("doculinks/{id}/{linktype:alpha}/{language:alpha}")]
|
||||||
public async Task<IActionResult> GetDocumentAsync(int id,string? linktype, string? language)
|
public async Task<IActionResult> GetDocumentAsync(int id, string? linktype, string? language)
|
||||||
{
|
{
|
||||||
var result = await this.documentsProvider.GetDocumentAsync(id, linktype, language);
|
var result = await this.documentsProvider.GetDocumentAsync(id, linktype, language);
|
||||||
if (result.IsSuccess)
|
if (result.IsSuccess)
|
||||||
@ -182,7 +257,7 @@ namespace DamageAssesment.Api.DocuLinks.Controllers
|
|||||||
[Authorize(Roles = "admin")]
|
[Authorize(Roles = "admin")]
|
||||||
[HttpPut]
|
[HttpPut]
|
||||||
[Route("doculinks/{id}")]
|
[Route("doculinks/{id}")]
|
||||||
public async Task<IActionResult> UpdateDocument(int id,ReqDoculink documentInfo)
|
public async Task<IActionResult> UpdateDocument(int id, ReqDoculink documentInfo)
|
||||||
{
|
{
|
||||||
if (documentInfo != null)
|
if (documentInfo != null)
|
||||||
{
|
{
|
||||||
@ -190,7 +265,7 @@ namespace DamageAssesment.Api.DocuLinks.Controllers
|
|||||||
if (dbdoc.IsSuccess)
|
if (dbdoc.IsSuccess)
|
||||||
{
|
{
|
||||||
var documents = await this.documentsProvider.GetDocumentCounter();
|
var documents = await this.documentsProvider.GetDocumentCounter();
|
||||||
Models.Doculink DocuLink= uploadService.UpdateDocuments(documents.counter,dbdoc.Document, documentInfo);
|
Models.Doculink DocuLink = uploadService.UpdateDocuments(documents.counter, dbdoc.Document, documentInfo);
|
||||||
var result = await this.documentsProvider.UpdateDocumentAsync(id, DocuLink);
|
var result = await this.documentsProvider.UpdateDocumentAsync(id, DocuLink);
|
||||||
if (result.IsSuccess)
|
if (result.IsSuccess)
|
||||||
{
|
{
|
||||||
@ -203,6 +278,20 @@ namespace DamageAssesment.Api.DocuLinks.Controllers
|
|||||||
return BadRequest(documentInfo);
|
return BadRequest(documentInfo);
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
/// update existing doclink isactive field.
|
||||||
|
/// </summary>
|
||||||
|
[HttpPut]
|
||||||
|
[Route("doculinks/{id}/{isactive}")]
|
||||||
|
public async Task<IActionResult> UpdateIsActiveDocument(int id, bool isactive)
|
||||||
|
{
|
||||||
|
var result = await this.documentsProvider.UpdateDocumentAsync(id, isactive);
|
||||||
|
if (result.IsSuccess)
|
||||||
|
{
|
||||||
|
return Ok(result.Document);
|
||||||
|
}
|
||||||
|
return NotFound();
|
||||||
|
}
|
||||||
|
/// <summary>
|
||||||
/// Create new doclink.
|
/// Create new doclink.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
// [Authorize(Roles = "admin")]
|
// [Authorize(Roles = "admin")]
|
||||||
@ -214,8 +303,8 @@ namespace DamageAssesment.Api.DocuLinks.Controllers
|
|||||||
{
|
{
|
||||||
if (documentInfo != null)
|
if (documentInfo != null)
|
||||||
{
|
{
|
||||||
//var documents = await this.documentsProvider.GetDocumentCounter();
|
var documents = await this.documentsProvider.GetDocumentCounter();
|
||||||
Models.Doculink DocuLink= uploadService.UploadDocument(1, documentInfo);
|
Models.Doculink DocuLink = uploadService.UploadDocument(documents.counter, documentInfo);
|
||||||
var result = await this.documentsProvider.PostDocumentAsync(DocuLink);
|
var result = await this.documentsProvider.PostDocumentAsync(DocuLink);
|
||||||
if (result.IsSuccess)
|
if (result.IsSuccess)
|
||||||
{
|
{
|
||||||
|
@ -25,7 +25,10 @@
|
|||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
|
||||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.4" />
|
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.4" />
|
||||||
|
<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
|
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
@ -15,5 +15,6 @@ namespace DamageAssesment.Api.DocuLinks.Db
|
|||||||
public string Path { get; set; }
|
public string Path { get; set; }
|
||||||
public bool IsAttachments { get; set; }
|
public bool IsAttachments { get; set; }
|
||||||
public int CustomOrder { get; set; }
|
public int CustomOrder { get; set; }
|
||||||
|
public string Language { get; set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -11,7 +11,9 @@ namespace DamageAssesment.Api.DocuLinks.Interfaces
|
|||||||
Task<(bool IsSuccess, IEnumerable<Models.ResDoculink> documents, string ErrorMessage)> GetdocumentsByLinkTypeIdAsync(int? linkTypeId, string? language, bool? isactive);
|
Task<(bool IsSuccess, IEnumerable<Models.ResDoculink> documents, string ErrorMessage)> GetdocumentsByLinkTypeIdAsync(int? linkTypeId, string? language, bool? isactive);
|
||||||
Task<(bool IsSuccess, Models.ResDoculink Document, string ErrorMessage)> PostDocumentAsync(Models.Doculink Document);
|
Task<(bool IsSuccess, Models.ResDoculink Document, string ErrorMessage)> PostDocumentAsync(Models.Doculink Document);
|
||||||
Task<(bool IsSuccess, Models.ResDoculink Document, string ErrorMessage)> UpdateDocumentAsync(int id, Models.Doculink Document);
|
Task<(bool IsSuccess, Models.ResDoculink Document, string ErrorMessage)> UpdateDocumentAsync(int id, Models.Doculink Document);
|
||||||
|
Task<(bool IsSuccess, Models.ResDoculink Document, string ErrorMessage)> UpdateDocumentAsync(int id, bool isactive);
|
||||||
Task<(bool IsSuccess, Models.ResDoculink Document, string ErrorMessage)> DeleteDocumentAsync(int id);
|
Task<(bool IsSuccess, Models.ResDoculink Document, string ErrorMessage)> DeleteDocumentAsync(int id);
|
||||||
|
Task<(bool IsSuccess, Models.DoculinkAttachments DoculinkAttachments, string Path)> GetDownloadAttachmentAsync(int id);
|
||||||
Task<(bool IsSuccess, int counter, string message)> GetDocumentCounter();
|
Task<(bool IsSuccess, int counter, string message)> GetDocumentCounter();
|
||||||
|
|
||||||
|
|
||||||
|
@ -7,6 +7,8 @@ namespace DamageAssesment.Api.DocuLinks.Interfaces
|
|||||||
Models.Doculink UploadDocument( int counter, ReqDoculink documentInfo);
|
Models.Doculink UploadDocument( int counter, ReqDoculink documentInfo);
|
||||||
public Models.Doculink UpdateDocuments(int counter, Models.Doculink document, ReqDoculink documentInfo);
|
public Models.Doculink UpdateDocuments(int counter, Models.Doculink document, ReqDoculink documentInfo);
|
||||||
void Deletefile(string path);
|
void Deletefile(string path);
|
||||||
|
Task<byte[]> DownloadFile(string path);
|
||||||
|
Task<string> GetFile(string path);
|
||||||
void Movefile(string path);
|
void Movefile(string path);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -8,6 +8,7 @@ namespace DamageAssesment.Api.DocuLinks.Models
|
|||||||
public string docName { get; set; }
|
public string docName { get; set; }
|
||||||
public string Path { get; set; }
|
public string Path { get; set; }
|
||||||
public bool IsAttachments { get; set; }
|
public bool IsAttachments { get; set; }
|
||||||
|
public string Language { get; set; }
|
||||||
public int CustomOrder { get; set; }
|
public int CustomOrder { get; set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,6 +7,7 @@ namespace DamageAssesment.Api.DocuLinks.Models
|
|||||||
public int Id { get; set; }
|
public int Id { get; set; }
|
||||||
public int linkTypeId { get; set; }
|
public int linkTypeId { get; set; }
|
||||||
public List<DoculinkTranslation> documentsTranslations { get; set; }
|
public List<DoculinkTranslation> documentsTranslations { get; set; }
|
||||||
|
public bool IsActive { get; set; }
|
||||||
public int CustomOrder { get; set; }
|
public int CustomOrder { get; set; }
|
||||||
public List<FileModel>? Files { get; set; }
|
public List<FileModel>? Files { get; set; }
|
||||||
}
|
}
|
||||||
@ -18,5 +19,6 @@ namespace DamageAssesment.Api.DocuLinks.Models
|
|||||||
public int CustomOrder { get; set; }
|
public int CustomOrder { get; set; }
|
||||||
public string url { get;set; }
|
public string url { get;set; }
|
||||||
public bool IsAttachments { get; set; }
|
public bool IsAttachments { get; set; }
|
||||||
|
public string Language { get; set; }
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -9,9 +9,16 @@ using System.Text;
|
|||||||
using Microsoft.OpenApi.Models;
|
using Microsoft.OpenApi.Models;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
builder.Services.AddCors(p => p.AddPolicy("DamageAppCorsPolicy", build => {
|
||||||
|
build.WithOrigins("*").AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin();
|
||||||
|
}));
|
||||||
// Add services to the container.
|
// Add services to the container.
|
||||||
var authkey = builder.Configuration.GetValue<string>("JwtSettings:securitykey");
|
var authkey = builder.Configuration.GetValue<string>("JwtSettings:securitykey");
|
||||||
|
builder.Services.AddLogging(builder =>
|
||||||
|
{
|
||||||
|
//builder.AddConsole(); // Optional: Add other providers if needed
|
||||||
|
builder.AddFile("logs/DocuLinks-{Date}.txt"); // Specify the file path and format
|
||||||
|
});
|
||||||
builder.Services.AddAuthentication(item =>
|
builder.Services.AddAuthentication(item =>
|
||||||
{
|
{
|
||||||
item.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
item.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||||
@ -69,6 +76,7 @@ builder.Services.AddSwaggerGen(options =>
|
|||||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||||
builder.Services.AddEndpointsApiExplorer();
|
builder.Services.AddEndpointsApiExplorer();
|
||||||
builder.Services.AddSwaggerGen();
|
builder.Services.AddSwaggerGen();
|
||||||
|
builder.Services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>();
|
||||||
builder.Services.AddScoped<IDoculinkProvider, DoculinkProvider>();
|
builder.Services.AddScoped<IDoculinkProvider, DoculinkProvider>();
|
||||||
builder.Services.AddScoped<IUploadService, UploadService>();
|
builder.Services.AddScoped<IUploadService, UploadService>();
|
||||||
builder.Services.AddScoped<IAzureBlobService, AzureBlobService>();
|
builder.Services.AddScoped<IAzureBlobService, AzureBlobService>();
|
||||||
@ -85,7 +93,7 @@ if (app.Environment.IsDevelopment())
|
|||||||
app.UseSwagger();
|
app.UseSwagger();
|
||||||
app.UseSwaggerUI();
|
app.UseSwaggerUI();
|
||||||
}
|
}
|
||||||
|
app.UseCors("DamageAppCorsPolicy");
|
||||||
app.UseAuthentication();
|
app.UseAuthentication();
|
||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
|
|
||||||
|
@ -2,13 +2,16 @@
|
|||||||
using DamageAssesment.Api.DocuLinks.Db;
|
using DamageAssesment.Api.DocuLinks.Db;
|
||||||
using DamageAssesment.Api.DocuLinks.Interfaces;
|
using DamageAssesment.Api.DocuLinks.Interfaces;
|
||||||
using DamageAssesment.Api.DocuLinks.Models;
|
using DamageAssesment.Api.DocuLinks.Models;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.EntityFrameworkCore.Metadata.Internal;
|
using Microsoft.EntityFrameworkCore.Metadata.Internal;
|
||||||
using System;
|
using System;
|
||||||
|
using System.Collections.Generic;
|
||||||
using System.Collections.Immutable;
|
using System.Collections.Immutable;
|
||||||
using System.Diagnostics.Eventing.Reader;
|
using System.Diagnostics.Eventing.Reader;
|
||||||
using System.Reflection.Metadata;
|
using System.Reflection.Metadata;
|
||||||
|
using System.Runtime.CompilerServices;
|
||||||
using System.Xml;
|
using System.Xml;
|
||||||
using System.Xml.Linq;
|
using System.Xml.Linq;
|
||||||
|
|
||||||
@ -23,13 +26,18 @@ namespace DamageAssesment.Api.DocuLinks.Providers
|
|||||||
private IUploadService uploadservice;
|
private IUploadService uploadservice;
|
||||||
private IAzureBlobService azureBlobService;
|
private IAzureBlobService azureBlobService;
|
||||||
private IMapper mapper;
|
private IMapper mapper;
|
||||||
|
private readonly IHttpContextAccessor httpContextAccessor;
|
||||||
|
private string baseUrl;
|
||||||
|
|
||||||
public DoculinkProvider(DoculinkDbContext DocumentDbContext, ILogger<DoculinkProvider> logger, IMapper mapper, IUploadService uploadservice, IAzureBlobService azureBlobService)
|
public DoculinkProvider(DoculinkDbContext DocumentDbContext, ILogger<DoculinkProvider> logger, IMapper mapper, IUploadService uploadservice, IAzureBlobService azureBlobService, IHttpContextAccessor httpContextAccessor)
|
||||||
{
|
{
|
||||||
this.DocumentDbContext = DocumentDbContext;
|
this.DocumentDbContext = DocumentDbContext;
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
this.mapper = mapper;
|
this.mapper = mapper;
|
||||||
this.uploadservice = uploadservice;
|
this.uploadservice = uploadservice;
|
||||||
|
this.httpContextAccessor = httpContextAccessor;
|
||||||
|
baseUrl = $"{httpContextAccessor.HttpContext.Request.Scheme}://{httpContextAccessor.HttpContext.Request.Host}";
|
||||||
|
baseUrl = baseUrl + "/doculinks/download";
|
||||||
this.azureBlobService = azureBlobService;
|
this.azureBlobService = azureBlobService;
|
||||||
//SeedData();
|
//SeedData();
|
||||||
}
|
}
|
||||||
@ -73,10 +81,10 @@ namespace DamageAssesment.Api.DocuLinks.Providers
|
|||||||
{
|
{
|
||||||
linkTypeId = 1;
|
linkTypeId = 1;
|
||||||
|
|
||||||
fileModel = new FileModel() { FileName = "Sample" + i, FileExtension = ".txt", FileContent = "c2FtcGxl", IsAttachments = true, CustomOrder = 1 };
|
fileModel = new FileModel() { FileName = "Sample" + i, FileExtension = ".txt", FileContent = "c2FtcGxl", IsAttachments = true, CustomOrder = 1, Language = "en" };
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
fileModel = new FileModel() { url = "www.google" + i + ".com", IsAttachments = false, CustomOrder = 1 };
|
fileModel = new FileModel() { url = "www.google" + i + ".com", IsAttachments = false, CustomOrder = 1,Language="en" };
|
||||||
ReqDoculink documentInfo = new ReqDoculink() { linkTypeId = i, CustomOrder = i, Files = new List<FileModel>() { fileModel } };
|
ReqDoculink documentInfo = new ReqDoculink() { linkTypeId = i, CustomOrder = i, Files = new List<FileModel>() { fileModel } };
|
||||||
Models.Doculink document = uploadservice.UploadDocument(counter, documentInfo);
|
Models.Doculink document = uploadservice.UploadDocument(counter, documentInfo);
|
||||||
DocumentDbContext.Documents.Add(mapper.Map<Models.Doculink, Db.Doculink>(document));
|
DocumentDbContext.Documents.Add(mapper.Map<Models.Doculink, Db.Doculink>(document));
|
||||||
@ -172,7 +180,42 @@ namespace DamageAssesment.Api.DocuLinks.Providers
|
|||||||
MultiLanguage = dicttitle;
|
MultiLanguage = dicttitle;
|
||||||
return MultiLanguage;
|
return MultiLanguage;
|
||||||
}
|
}
|
||||||
|
private List<Models.DoculinkAttachments> GetDocumentAttachment(int id,string? language)
|
||||||
|
{
|
||||||
|
List<Db.DoculinkAttachments> doculinkAttachments = null;
|
||||||
|
if (string.IsNullOrEmpty(language))
|
||||||
|
{
|
||||||
|
doculinkAttachments = DocumentDbContext.DoclinksAttachments.AsNoTracking().Where(a => a.DocumentId == id).ToList();
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
doculinkAttachments = DocumentDbContext.DoclinksAttachments.AsNoTracking().Where(a => a.DocumentId == id && a.Language == language).ToList();
|
||||||
|
}
|
||||||
|
foreach (var attachment in doculinkAttachments)
|
||||||
|
{
|
||||||
|
if (attachment.IsAttachments)
|
||||||
|
attachment.Path = $"{baseUrl}/{attachment.Id}";
|
||||||
|
}
|
||||||
|
return mapper.Map<List<Db.DoculinkAttachments>, List<Models.DoculinkAttachments>>(doculinkAttachments);
|
||||||
|
}
|
||||||
|
public async Task<(bool IsSuccess, Models.DoculinkAttachments DoculinkAttachments, string Path)> GetDownloadAttachmentAsync(int id)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Db.DoculinkAttachments Attachment = DocumentDbContext.DoclinksAttachments.AsNoTracking().Where(a => a.Id == id).AsNoTracking().FirstOrDefault();
|
||||||
|
if (Attachment == null)
|
||||||
|
{
|
||||||
|
return (false, null, "Not Found");
|
||||||
|
}
|
||||||
|
return (true, mapper.Map<Db.DoculinkAttachments, Models.DoculinkAttachments>(Attachment), $"Attachment {id}");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
|
||||||
|
logger?.LogError(ex.ToString());
|
||||||
|
return (false, null, ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
public async Task<(bool IsSuccess, IEnumerable<Models.ResDoculink> documents, string ErrorMessage)> GetdocumentsByLinkTypeIdAsync(int? linkTypeId, string? language, bool? isactive)
|
public async Task<(bool IsSuccess, IEnumerable<Models.ResDoculink> documents, string ErrorMessage)> GetdocumentsByLinkTypeIdAsync(int? linkTypeId, string? language, bool? isactive)
|
||||||
{
|
{
|
||||||
|
|
||||||
@ -194,8 +237,7 @@ namespace DamageAssesment.Api.DocuLinks.Providers
|
|||||||
item.titles = multilan.titles;
|
item.titles = multilan.titles;
|
||||||
item.description = multilan.description;
|
item.description = multilan.description;
|
||||||
item.linktypes = CreateMultiLanguageLinkTypeObject(GetLinkTypeTranslations(item.linkTypeId, language));
|
item.linktypes = CreateMultiLanguageLinkTypeObject(GetLinkTypeTranslations(item.linkTypeId, language));
|
||||||
item.doclinksAttachments = mapper.Map<List<Db.DoculinkAttachments>, List<Models.DoculinkAttachments>>(
|
item.doclinksAttachments = GetDocumentAttachment(item.Id,language);
|
||||||
DocumentDbContext.DoclinksAttachments.AsNoTracking().Where(a => a.DocumentId == item.Id).ToList());
|
|
||||||
}
|
}
|
||||||
// List<ResDoculinks> doculinks = result.GroupBy(a => a.linkTypeId).Select(a => new ResDoculinks() { linkTypeId = a.Key, doculinks = a.ToList() }).ToList();
|
// List<ResDoculinks> doculinks = result.GroupBy(a => a.linkTypeId).Select(a => new ResDoculinks() { linkTypeId = a.Key, doculinks = a.ToList() }).ToList();
|
||||||
return (true, result, null);
|
return (true, result, null);
|
||||||
@ -230,8 +272,7 @@ namespace DamageAssesment.Api.DocuLinks.Providers
|
|||||||
item.titles = multilan.titles;
|
item.titles = multilan.titles;
|
||||||
item.description = multilan.description;
|
item.description = multilan.description;
|
||||||
item.linktypes = CreateMultiLanguageLinkTypeObject(GetLinkTypeTranslations(item.linkTypeId, language));
|
item.linktypes = CreateMultiLanguageLinkTypeObject(GetLinkTypeTranslations(item.linkTypeId, language));
|
||||||
item.doclinksAttachments = mapper.Map<List<Db.DoculinkAttachments>, List<Models.DoculinkAttachments>>(
|
item.doclinksAttachments = GetDocumentAttachment(item.Id, language);
|
||||||
DocumentDbContext.DoclinksAttachments.AsNoTracking().Where(a => a.DocumentId == item.Id).ToList());
|
|
||||||
}
|
}
|
||||||
//List<ResDoculinks> doculinks = result.GroupBy(a => a.linkTypeId).Select(a => new ResDoculinks() { linkTypeId = a.Key, doculinks = a.ToList() }).ToList();
|
//List<ResDoculinks> doculinks = result.GroupBy(a => a.linkTypeId).Select(a => new ResDoculinks() { linkTypeId = a.Key, doculinks = a.ToList() }).ToList();
|
||||||
return (true, result, null);
|
return (true, result, null);
|
||||||
@ -286,8 +327,7 @@ namespace DamageAssesment.Api.DocuLinks.Providers
|
|||||||
result.documentsTranslations = mapper.Map<List<Db.DoculinkTranslation>, List<Models.DoculinkTranslation>>(
|
result.documentsTranslations = mapper.Map<List<Db.DoculinkTranslation>, List<Models.DoculinkTranslation>>(
|
||||||
DocumentDbContext.DocumentsTranslations.Where(a => a.DocumentId == result.Id).ToList());
|
DocumentDbContext.DocumentsTranslations.Where(a => a.DocumentId == result.Id).ToList());
|
||||||
|
|
||||||
result.doclinksAttachments = mapper.Map<List<Db.DoculinkAttachments>, List<Models.DoculinkAttachments>>(
|
result.doclinksAttachments = GetDocumentAttachment(id, "");
|
||||||
DocumentDbContext.DoclinksAttachments.AsNoTracking().Where(a => a.DocumentId == id).ToList());
|
|
||||||
return (true, result, null);
|
return (true, result, null);
|
||||||
}
|
}
|
||||||
return (false, null, "Not found");
|
return (false, null, "Not found");
|
||||||
@ -319,8 +359,7 @@ namespace DamageAssesment.Api.DocuLinks.Providers
|
|||||||
result.linktypes = CreateMultiLanguageLinkTypeObject(GetLinkTypeTranslations(result.linkTypeId, language));
|
result.linktypes = CreateMultiLanguageLinkTypeObject(GetLinkTypeTranslations(result.linkTypeId, language));
|
||||||
result.titles = multilan.titles;
|
result.titles = multilan.titles;
|
||||||
result.description = multilan.description;
|
result.description = multilan.description;
|
||||||
result.doclinksAttachments = mapper.Map<List<Db.DoculinkAttachments>, List<Models.DoculinkAttachments>>(
|
result.doclinksAttachments = GetDocumentAttachment(id, language);
|
||||||
DocumentDbContext.DoclinksAttachments.AsNoTracking().Where(a => a.DocumentId == id).ToList());
|
|
||||||
return (true, result, null);
|
return (true, result, null);
|
||||||
}
|
}
|
||||||
return (false, null, "Not found");
|
return (false, null, "Not found");
|
||||||
@ -351,7 +390,7 @@ namespace DamageAssesment.Api.DocuLinks.Providers
|
|||||||
result.linktypes = CreateMultiLanguageLinkTypeObject(GetLinkTypeTranslations(Document.linkTypeId, ""));
|
result.linktypes = CreateMultiLanguageLinkTypeObject(GetLinkTypeTranslations(Document.linkTypeId, ""));
|
||||||
result.titles = multilan.titles;
|
result.titles = multilan.titles;
|
||||||
result.description = multilan.description;
|
result.description = multilan.description;
|
||||||
result.doclinksAttachments = Document.doclinksAttachments;
|
result.doclinksAttachments = GetDocumentAttachment(document.Id,"");
|
||||||
return (true, result, null);
|
return (true, result, null);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
@ -393,7 +432,7 @@ namespace DamageAssesment.Api.DocuLinks.Providers
|
|||||||
result.linktypes = CreateMultiLanguageLinkTypeObject(GetLinkTypeTranslations(document.linkTypeId, ""));
|
result.linktypes = CreateMultiLanguageLinkTypeObject(GetLinkTypeTranslations(document.linkTypeId, ""));
|
||||||
result.titles = multilan.titles;
|
result.titles = multilan.titles;
|
||||||
result.description = multilan.description;
|
result.description = multilan.description;
|
||||||
result.doclinksAttachments = Document.doclinksAttachments;
|
result.doclinksAttachments = GetDocumentAttachment(document.Id, "");
|
||||||
return (true, result, "Successful");
|
return (true, result, "Successful");
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
@ -416,6 +455,35 @@ namespace DamageAssesment.Api.DocuLinks.Providers
|
|||||||
return (false, null, ex.Message);
|
return (false, null, ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
public async Task<(bool IsSuccess, Models.ResDoculink Document, string ErrorMessage)> UpdateDocumentAsync(int id,bool isactive)
|
||||||
|
{
|
||||||
|
|
||||||
|
try
|
||||||
|
{
|
||||||
|
Db.Doculink Document = DocumentDbContext.Documents.AsNoTracking().Where(a => a.Id == id).FirstOrDefault();
|
||||||
|
if (Document == null)
|
||||||
|
{
|
||||||
|
return (false, null, "Not Found");
|
||||||
|
}
|
||||||
|
Document.IsActive = isactive;
|
||||||
|
DocumentDbContext.Documents.Update(Document);
|
||||||
|
DocumentDbContext.SaveChanges();
|
||||||
|
var result = mapper.Map<Db.Doculink, Models.ResDoculink>(Document);
|
||||||
|
var multilan = CreateMultiLanguageObject(GetDocumentTranslations(Document.Id, ""));
|
||||||
|
result.titles = multilan.titles;
|
||||||
|
result.description = multilan.description;
|
||||||
|
result.linktypes = CreateMultiLanguageLinkTypeObject(GetLinkTypeTranslations(result.linkTypeId, ""));
|
||||||
|
result.doclinksAttachments = mapper.Map<List<Db.DoculinkAttachments>, List<Models.DoculinkAttachments>>(
|
||||||
|
DocumentDbContext.DoclinksAttachments.AsNoTracking().Where(a => a.DocumentId == id).ToList());
|
||||||
|
return (true, result, $"DocumentId {id} deleted Successfuly");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
|
||||||
|
logger?.LogError(ex.ToString());
|
||||||
|
return (false, null, ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
public async Task<(bool IsSuccess, Models.ResDoculink Document, string ErrorMessage)> DeleteDocumentAsync(int id)
|
public async Task<(bool IsSuccess, Models.ResDoculink Document, string ErrorMessage)> DeleteDocumentAsync(int id)
|
||||||
{
|
{
|
||||||
|
|
||||||
|
@ -25,6 +25,41 @@ namespace DamageAssesment.Api.DocuLinks.Providers
|
|||||||
uploadpath = configuration.GetValue<string>("Fileupload:folderpath");
|
uploadpath = configuration.GetValue<string>("Fileupload:folderpath");
|
||||||
Deletepath = configuration.GetValue<string>("Fileupload:Deletepath");
|
Deletepath = configuration.GetValue<string>("Fileupload:Deletepath");
|
||||||
}
|
}
|
||||||
|
public async Task<string> GetFile(string path)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (System.IO.File.Exists(path))
|
||||||
|
{
|
||||||
|
return path;
|
||||||
|
}
|
||||||
|
|
||||||
|
return null; // File not found
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// Handle or log the exception as needed
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
public async Task<byte[]> DownloadFile(string path)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
if (System.IO.File.Exists(path))
|
||||||
|
{
|
||||||
|
return await System.IO.File.ReadAllBytesAsync(path);
|
||||||
|
}
|
||||||
|
|
||||||
|
return null; // File not found
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
// Handle or log the exception as needed
|
||||||
|
throw;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
public Models.Doculink UploadDocument(int counter, ReqDoculink documentInfo)
|
public Models.Doculink UploadDocument(int counter, ReqDoculink documentInfo)
|
||||||
{
|
{
|
||||||
@ -44,19 +79,20 @@ namespace DamageAssesment.Api.DocuLinks.Providers
|
|||||||
counter++;
|
counter++;
|
||||||
if (item.IsAttachments)
|
if (item.IsAttachments)
|
||||||
{
|
{
|
||||||
UserfileName = Path.GetFileName(item.FileName);
|
UserfileName = Path.GetFileName(item.FileName + item.FileExtension);
|
||||||
var fileName = String.Format("Document_{0}{1}", counter, item.FileExtension);
|
var fileName = String.Format("Document_{0}{1}", counter, item.FileExtension);
|
||||||
path = Path.Combine(fullDirectoryPath, fileName);
|
path = Path.Combine(fullDirectoryPath, fileName);
|
||||||
File.WriteAllBytes(path, Convert.FromBase64String(item.FileContent));
|
File.WriteAllBytes(path, Convert.FromBase64String(item.FileContent));
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
path = item.url;
|
path = item.url;
|
||||||
attachments.Add(new Models.DoculinkAttachments { docName=UserfileName,Path=path,IsAttachments=item.IsAttachments,CustomOrder=item.CustomOrder });
|
attachments.Add(new Models.DoculinkAttachments { docName=UserfileName,Path=path,IsAttachments=item.IsAttachments,CustomOrder=item.CustomOrder,Language=item.Language });
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Documents=new Models.Doculink (){ linkTypeId = documentInfo.linkTypeId,
|
Documents=new Models.Doculink (){ linkTypeId = documentInfo.linkTypeId,
|
||||||
documentsTranslations = documentInfo.documentsTranslations,doclinksAttachments=attachments,
|
documentsTranslations = documentInfo.documentsTranslations,doclinksAttachments=attachments,
|
||||||
IsDeleted=false,CustomOrder=documentInfo.CustomOrder, IsActive =true};
|
IsDeleted=false,CustomOrder=documentInfo.CustomOrder, IsActive =documentInfo.IsActive
|
||||||
|
};
|
||||||
|
|
||||||
return Documents;
|
return Documents;
|
||||||
}
|
}
|
||||||
@ -85,22 +121,22 @@ namespace DamageAssesment.Api.DocuLinks.Providers
|
|||||||
{
|
{
|
||||||
if (item.IsAttachments)
|
if (item.IsAttachments)
|
||||||
{
|
{
|
||||||
UserfileName = Path.GetFileName(item.FileName);
|
UserfileName = Path.GetFileName(item.FileName+item.FileExtension);
|
||||||
var fileName = String.Format("Document_{0}_{1}{2}", document.Id, counter1, item.FileExtension);
|
var fileName = String.Format("Document_{0}{1}", counter1, item.FileExtension);
|
||||||
path = Path.Combine(fullDirectoryPath, fileName);
|
path = Path.Combine(fullDirectoryPath, fileName);
|
||||||
File.WriteAllBytes(path, Convert.FromBase64String(item.FileContent));
|
File.WriteAllBytes(path, Convert.FromBase64String(item.FileContent));
|
||||||
counter1++;
|
counter1++;
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
path = item.url;
|
path = item.url;
|
||||||
attachments.Add(new Models.DoculinkAttachments { docName = UserfileName, Path = path,IsAttachments=item.IsAttachments,CustomOrder=item.CustomOrder });
|
attachments.Add(new Models.DoculinkAttachments { docName = UserfileName, Path = path,IsAttachments=item.IsAttachments,CustomOrder=item.CustomOrder,Language=item.Language });
|
||||||
}
|
}
|
||||||
Models.Doculink Documents = new Models.Doculink()
|
Models.Doculink Documents = new Models.Doculink()
|
||||||
{
|
{
|
||||||
Id = documentInfo.Id,
|
Id = documentInfo.Id,
|
||||||
linkTypeId = documentInfo.linkTypeId,
|
linkTypeId = documentInfo.linkTypeId,
|
||||||
documentsTranslations=documentInfo.documentsTranslations,
|
documentsTranslations=documentInfo.documentsTranslations,
|
||||||
IsActive = true,
|
IsActive = documentInfo.IsActive,
|
||||||
IsDeleted=false,
|
IsDeleted=false,
|
||||||
CustomOrder = documentInfo.CustomOrder,
|
CustomOrder = documentInfo.CustomOrder,
|
||||||
doclinksAttachments = attachments
|
doclinksAttachments = attachments
|
||||||
|
@ -10,8 +10,8 @@
|
|||||||
},
|
},
|
||||||
"AllowedHosts": "*",
|
"AllowedHosts": "*",
|
||||||
"ConnectionStrings": {
|
"ConnectionStrings": {
|
||||||
"DoculinkConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;"
|
//"DoculinkConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;"
|
||||||
//"DoculinkConnection": "Server=tcp:da-dev.database.windows.net,1433;Initial Catalog=da-dev-db;Encrypt=True;User ID=admin-dev;Password=b3tgRABw8LGE75k;TrustServerCertificate=False;Connection Timeout=30;"
|
"DoculinkConnection": "Server=207.180.248.35;Database=da_survey_dev;User Id=sa;Password=YourStrongPassw0rd;TrustServerCertificate=True;"
|
||||||
|
|
||||||
},
|
},
|
||||||
"Fileupload": {
|
"Fileupload": {
|
||||||
|
@ -24,7 +24,10 @@
|
|||||||
<PrivateAssets>all</PrivateAssets>
|
<PrivateAssets>all</PrivateAssets>
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
|
||||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.4" />
|
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.4" />
|
||||||
|
<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
|
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
@ -9,9 +9,16 @@ using System.Reflection;
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
builder.Services.AddCors(p => p.AddPolicy("DamageAppCorsPolicy", build => {
|
||||||
|
build.WithOrigins("*").AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin();
|
||||||
|
}));
|
||||||
// Add services to the container.
|
// Add services to the container.
|
||||||
var authkey = builder.Configuration.GetValue<string>("JwtSettings:securitykey");
|
var authkey = builder.Configuration.GetValue<string>("JwtSettings:securitykey");
|
||||||
|
builder.Services.AddLogging(builder =>
|
||||||
|
{
|
||||||
|
//builder.AddConsole(); // Optional: Add other providers if needed
|
||||||
|
builder.AddFile("logs/Employees-{Date}.txt"); // Specify the file path and format
|
||||||
|
});
|
||||||
builder.Services.AddAuthentication(item =>
|
builder.Services.AddAuthentication(item =>
|
||||||
{
|
{
|
||||||
item.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
item.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||||
@ -93,7 +100,7 @@ if (app.Environment.IsDevelopment())
|
|||||||
employeesProvider.SeedData();
|
employeesProvider.SeedData();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
app.UseCors("DamageAppCorsPolicy");
|
||||||
app.UseAuthentication();
|
app.UseAuthentication();
|
||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
|
|
||||||
|
@ -77,7 +77,8 @@ namespace DamageAssesment.Api.Employees.Providers
|
|||||||
EmployeeDbContext.Employees.Add(_employee);
|
EmployeeDbContext.Employees.Add(_employee);
|
||||||
Employee.Id = _employee.Id;
|
Employee.Id = _employee.Id;
|
||||||
EmployeeDbContext.SaveChanges();
|
EmployeeDbContext.SaveChanges();
|
||||||
return (true, Employee, null);
|
//return (true, Employee, null);
|
||||||
|
return (true, mapper.Map<Db.Employee, Models.Employee>(_employee), null);
|
||||||
}
|
}
|
||||||
return (false, null, "Employee code is already exits");
|
return (false, null, "Employee code is already exits");
|
||||||
}
|
}
|
||||||
|
@ -10,8 +10,8 @@
|
|||||||
},
|
},
|
||||||
"AllowedHosts": "*",
|
"AllowedHosts": "*",
|
||||||
"ConnectionStrings": {
|
"ConnectionStrings": {
|
||||||
"EmployeeConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;"
|
//"EmployeeConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;"
|
||||||
//"EmployeeConnection": "Server=tcp:da-dev.database.windows.net,1433;Initial Catalog=da-dev-db;Encrypt=True;User ID=admin-dev;Password=b3tgRABw8LGE75k;TrustServerCertificate=False;Connection Timeout=30;"
|
"EmployeeConnection": "Server=207.180.248.35;Database=da_survey_dev;User Id=sa;Password=YourStrongPassw0rd;TrustServerCertificate=True;"
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -25,7 +25,10 @@
|
|||||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.21" />
|
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.21" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.5" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.5" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
|
||||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.4" />
|
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.4" />
|
||||||
|
<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
|
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
@ -9,9 +9,16 @@ using System.Reflection;
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
builder.Services.AddCors(p => p.AddPolicy("DamageAppCorsPolicy", build => {
|
||||||
|
build.WithOrigins("*").AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin();
|
||||||
|
}));
|
||||||
// Add services to the container.
|
// Add services to the container.
|
||||||
var authkey = builder.Configuration.GetValue<string>("JwtSettings:securitykey");
|
var authkey = builder.Configuration.GetValue<string>("JwtSettings:securitykey");
|
||||||
|
builder.Services.AddLogging(builder =>
|
||||||
|
{
|
||||||
|
//builder.AddConsole(); // Optional: Add other providers if needed
|
||||||
|
builder.AddFile("logs/Locations-{Date}.txt"); // Specify the file path and format
|
||||||
|
});
|
||||||
builder.Services.AddAuthentication(item =>
|
builder.Services.AddAuthentication(item =>
|
||||||
{
|
{
|
||||||
item.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
item.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
|
||||||
@ -96,7 +103,7 @@ if (app.Environment.IsDevelopment())
|
|||||||
regionProvider.SeedData();
|
regionProvider.SeedData();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
app.UseCors("DamageAppCorsPolicy");
|
||||||
app.UseAuthentication();
|
app.UseAuthentication();
|
||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
|
|
||||||
|
@ -9,12 +9,9 @@
|
|||||||
}
|
}
|
||||||
},
|
},
|
||||||
"AllowedHosts": "*",
|
"AllowedHosts": "*",
|
||||||
//"ConnectionStrings": {
|
|
||||||
// "LocationConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;"
|
|
||||||
//},
|
|
||||||
"ConnectionStrings": {
|
"ConnectionStrings": {
|
||||||
"LocationConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;"
|
//"LocationConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;"
|
||||||
//"LocationConnection": "Server=tcp:da-dev.database.windows.net,1433;Initial Catalog=da-dev-db;Encrypt=True;User ID=admin-dev;Password=b3tgRABw8LGE75k;TrustServerCertificate=False;Connection Timeout=30;"
|
"LocationConnection": "Server=207.180.248.35;Database=da_survey_dev;User Id=sa;Password=YourStrongPassw0rd;TrustServerCertificate=True;"
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,4 +1,5 @@
|
|||||||
using DamageAssesment.Api.Questions.Interfaces;
|
using DamageAssesment.Api.Questions.Interfaces;
|
||||||
|
using DamageAssesment.Api.Questions.Models;
|
||||||
using Microsoft.AspNetCore.Authorization;
|
using Microsoft.AspNetCore.Authorization;
|
||||||
using Microsoft.AspNetCore.Mvc;
|
using Microsoft.AspNetCore.Mvc;
|
||||||
|
|
||||||
@ -111,6 +112,26 @@ namespace DamageAssesment.Api.Questions.Controllers
|
|||||||
return CreatedAtRoute("DefaultApi", questions);
|
return CreatedAtRoute("DefaultApi", questions);
|
||||||
}
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
|
/// PUT request for update a multiple question (multilingual) for survey.
|
||||||
|
/// </summary>
|
||||||
|
[HttpPut("questions/multiple/{surveyid}")]
|
||||||
|
public async Task<IActionResult> CreateQuestions(int surveyid, List<Models.Question> questions)
|
||||||
|
{
|
||||||
|
if (questions != null)
|
||||||
|
{
|
||||||
|
var result = await this.questionsProvider.PutQuestionsAsync(surveyid,questions);
|
||||||
|
if (result.IsSuccess)
|
||||||
|
{
|
||||||
|
return Ok(result.Question);
|
||||||
|
}
|
||||||
|
if (result.ErrorMessage == "Not Found")
|
||||||
|
return NotFound(result.ErrorMessage);
|
||||||
|
|
||||||
|
return BadRequest(result.ErrorMessage);
|
||||||
|
}
|
||||||
|
return CreatedAtRoute("DefaultApi", questions);
|
||||||
|
}
|
||||||
|
/// <summary>
|
||||||
/// POST request for creating a new question (multilingual).
|
/// POST request for creating a new question (multilingual).
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
|
||||||
|
@ -25,7 +25,10 @@
|
|||||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.21" />
|
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.21" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.5" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.5" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
|
||||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.4" />
|
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.4" />
|
||||||
|
<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
|
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
@ -9,6 +9,7 @@ namespace DamageAssesment.Api.Questions.Interfaces
|
|||||||
Task<(bool IsSuccess, List<SurveyQuestions> SurveyQuestions, string ErrorMessage)> GetSurveyQuestionAsync(int surveyId,string language);
|
Task<(bool IsSuccess, List<SurveyQuestions> SurveyQuestions, string ErrorMessage)> GetSurveyQuestionAsync(int surveyId,string language);
|
||||||
Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> PostQuestionAsync(Models.Question Question);
|
Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> PostQuestionAsync(Models.Question Question);
|
||||||
Task<(bool IsSuccess, IEnumerable<Models.MultiLanguage> Question, string ErrorMessage)> PostQuestionsAsync(List<Models.Question> Questions);
|
Task<(bool IsSuccess, IEnumerable<Models.MultiLanguage> Question, string ErrorMessage)> PostQuestionsAsync(List<Models.Question> Questions);
|
||||||
|
Task<(bool IsSuccess, IEnumerable<Models.MultiLanguage> Question, string ErrorMessage)> PutQuestionsAsync(int surveyId,List<Models.Question> Questions);
|
||||||
Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question);
|
Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question);
|
||||||
Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> DeleteQuestionAsync(int id);
|
Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> DeleteQuestionAsync(int id);
|
||||||
|
|
||||||
|
@ -9,6 +9,14 @@ using System.Reflection;
|
|||||||
using System.Text;
|
using System.Text;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
builder.Services.AddCors(p => p.AddPolicy("DamageAppCorsPolicy", build => {
|
||||||
|
build.WithOrigins("*").AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin();
|
||||||
|
}));
|
||||||
|
builder.Services.AddLogging(builder =>
|
||||||
|
{
|
||||||
|
//builder.AddConsole(); // Optional: Add other providers if needed
|
||||||
|
builder.AddFile("logs/Questions-{Date}.txt"); // Specify the file path and format
|
||||||
|
});
|
||||||
// Add services to the container.
|
// Add services to the container.
|
||||||
var authkey = builder.Configuration.GetValue<string>("JwtSettings:securitykey");
|
var authkey = builder.Configuration.GetValue<string>("JwtSettings:securitykey");
|
||||||
builder.Services.AddAuthentication(item =>
|
builder.Services.AddAuthentication(item =>
|
||||||
@ -93,6 +101,7 @@ if (app.Environment.IsDevelopment())
|
|||||||
questionProvider.SeedData();
|
questionProvider.SeedData();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
app.UseCors("DamageAppCorsPolicy");
|
||||||
app.UseAuthentication();
|
app.UseAuthentication();
|
||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
|
|
||||||
|
@ -376,6 +376,36 @@ namespace DamageAssesment.Api.Questions.Providers
|
|||||||
return (false, null, ex.Message);
|
return (false, null, ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<(bool IsSuccess, IEnumerable<Models.MultiLanguage> Question, string ErrorMessage)> PutQuestionsAsync(int surveyId, List<Models.Question> Questions)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var questions=await questionDbContext.Questions.AsNoTracking().Where(a=>a.SurveyId == surveyId).ToListAsync();
|
||||||
|
if (questions != null)
|
||||||
|
{
|
||||||
|
List<int> questionids=questions.Select(a=>a.Id).ToList();
|
||||||
|
var questiontrans = await questionDbContext.QuestionsTranslations.AsNoTracking().Where(x => questionids.Contains(x.QuestionId)).ToListAsync();
|
||||||
|
if (questiontrans != null)
|
||||||
|
questionDbContext.QuestionsTranslations.RemoveRange(questiontrans);
|
||||||
|
questionDbContext.Questions.RemoveRange(questions);
|
||||||
|
questionDbContext.SaveChanges();
|
||||||
|
}
|
||||||
|
List<Models.MultiLanguage> results = new List<MultiLanguage>();
|
||||||
|
logger?.LogInformation("Query Question");
|
||||||
|
foreach (Models.Question Question in Questions)
|
||||||
|
{
|
||||||
|
Question.SurveyId = surveyId;
|
||||||
|
results.Add(InsertQuestion(Question));
|
||||||
|
}
|
||||||
|
return (true, results, null);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger?.LogError(ex.ToString());
|
||||||
|
return (false, null, ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
public async Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question)
|
public async Task<(bool IsSuccess, Models.MultiLanguage Question, string ErrorMessage)> UpdateQuestionAsync(Models.Question Question)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
@ -409,8 +439,11 @@ namespace DamageAssesment.Api.Questions.Providers
|
|||||||
|
|
||||||
if (question != null)
|
if (question != null)
|
||||||
{
|
{
|
||||||
|
var questiontrans=await questionDbContext.QuestionsTranslations.AsNoTracking().Where(x=>x.QuestionId== id).ToListAsync();
|
||||||
var result = mapper.Map<Db.Question, Models.MultiLanguage>(question);
|
var result = mapper.Map<Db.Question, Models.MultiLanguage>(question);
|
||||||
result.Text = CreateMultiLanguageObject(GetQuestionsTranslations(result.Id, ""));
|
result.Text = CreateMultiLanguageObject(GetQuestionsTranslations(result.Id, ""));
|
||||||
|
if(questiontrans!=null)
|
||||||
|
questionDbContext.QuestionsTranslations.RemoveRange(questiontrans);
|
||||||
questionDbContext.Questions.Remove(question);
|
questionDbContext.Questions.Remove(question);
|
||||||
questionDbContext.SaveChanges();
|
questionDbContext.SaveChanges();
|
||||||
return (true, result, $"QuestionID {id} deleted Successfuly");
|
return (true, result, $"QuestionID {id} deleted Successfuly");
|
||||||
|
@ -10,8 +10,8 @@
|
|||||||
},
|
},
|
||||||
"AllowedHosts": "*",
|
"AllowedHosts": "*",
|
||||||
"ConnectionStrings": {
|
"ConnectionStrings": {
|
||||||
"QuestionConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;"
|
//"QuestionConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;"
|
||||||
//"QuestionConnection": "Server=tcp:da-dev.database.windows.net,1433;Initial Catalog=da-dev-db;Encrypt=True;User ID=admin-dev;Password=b3tgRABw8LGE75k;TrustServerCertificate=False;Connection Timeout=30;"
|
"QuestionConnection": "Server=207.180.248.35;Database=da_survey_dev;User Id=sa;Password=YourStrongPassw0rd;TrustServerCertificate=True;"
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -30,8 +30,11 @@
|
|||||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.5" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.5" />
|
||||||
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="7.0.5" />
|
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="7.0.5" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
|
||||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.4" />
|
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.4" />
|
||||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||||
|
<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
|
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
@ -16,7 +16,14 @@ const int intervalToRetry = 2; //2 seconds
|
|||||||
const int maxRetryForCircuitBraker = 5;
|
const int maxRetryForCircuitBraker = 5;
|
||||||
const int intervalForCircuitBraker = 5; //5 seconds
|
const int intervalForCircuitBraker = 5; //5 seconds
|
||||||
|
|
||||||
|
builder.Services.AddCors(p => p.AddPolicy("DamageAppCorsPolicy", build => {
|
||||||
|
build.WithOrigins("*").AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin();
|
||||||
|
}));
|
||||||
|
builder.Services.AddLogging(builder =>
|
||||||
|
{
|
||||||
|
//builder.AddConsole(); // Optional: Add other providers if needed
|
||||||
|
builder.AddFile("logs/Responses-{Date}.txt"); // Specify the file path and format
|
||||||
|
});
|
||||||
// Add services to the container.
|
// Add services to the container.
|
||||||
var authkey = builder.Configuration.GetValue<string>("JwtSettings:securitykey");
|
var authkey = builder.Configuration.GetValue<string>("JwtSettings:securitykey");
|
||||||
builder.Services.AddAuthentication(item =>
|
builder.Services.AddAuthentication(item =>
|
||||||
@ -106,7 +113,7 @@ if (app.Environment.IsDevelopment())
|
|||||||
app.UseSwagger();
|
app.UseSwagger();
|
||||||
app.UseSwaggerUI();
|
app.UseSwaggerUI();
|
||||||
}
|
}
|
||||||
|
app.UseCors("DamageAppCorsPolicy");
|
||||||
app.UseAuthentication();
|
app.UseAuthentication();
|
||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
|
|
||||||
|
@ -71,16 +71,20 @@ namespace DamageAssesment.Api.Responses.Providers
|
|||||||
try
|
try
|
||||||
{
|
{
|
||||||
logger?.LogInformation("Querying to get SurveyResponse object from DB");
|
logger?.LogInformation("Querying to get SurveyResponse object from DB");
|
||||||
IQueryable<Db.SurveyResponse> listSurveyResponse = null;
|
List<Db.SurveyResponse> listSurveyResponse = null;
|
||||||
if (employeeid == 0)
|
if (employeeid == 0)
|
||||||
{
|
{
|
||||||
listSurveyResponse = surveyResponseDbContext.SurveyResponses.Where(s => s.SurveyId == surveyId);
|
listSurveyResponse = surveyResponseDbContext.SurveyResponses.Where(s => s.SurveyId == surveyId).ToList();
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
listSurveyResponse = surveyResponseDbContext.SurveyResponses.Where(s => s.SurveyId == surveyId && s.EmployeeId == employeeid);
|
listSurveyResponse = surveyResponseDbContext.SurveyResponses.Where(s => s.SurveyId == surveyId && s.EmployeeId == employeeid).ToList();
|
||||||
}
|
}
|
||||||
|
listSurveyResponse = listSurveyResponse
|
||||||
|
.OrderByDescending(obj => obj.Id)
|
||||||
|
.GroupBy(obj => new { obj.SurveyId, obj.LocationId })//obj.EmployeeId,
|
||||||
|
.Select(group => group.FirstOrDefault()) // or .FirstOrDefault() if you want to handle empty groups
|
||||||
|
.ToList();
|
||||||
if (listSurveyResponse.Any())
|
if (listSurveyResponse.Any())
|
||||||
{
|
{
|
||||||
var answers = await getAnswersByRegionAndSurveyIdAsync(listSurveyResponse);
|
var answers = await getAnswersByRegionAndSurveyIdAsync(listSurveyResponse);
|
||||||
@ -432,14 +436,13 @@ namespace DamageAssesment.Api.Responses.Providers
|
|||||||
}
|
}
|
||||||
|
|
||||||
//Method to get Answers by region with surveyId as input parameter
|
//Method to get Answers by region with surveyId as input parameter
|
||||||
private async Task<dynamic> getAnswersByRegionAndSurveyIdAsync(IQueryable<Db.SurveyResponse> surveyResponses)
|
private async Task<dynamic> getAnswersByRegionAndSurveyIdAsync(List<Db.SurveyResponse> surveyResponses)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var answersList = await answerServiceProvider.getAnswersAsync(token);
|
var answersList = await answerServiceProvider.getAnswersAsync(token);
|
||||||
if (answersList == null || !answersList.Any())
|
if (answersList == null || !answersList.Any())
|
||||||
return null;
|
return null;
|
||||||
|
|
||||||
//get all the answers for the particular survey
|
//get all the answers for the particular survey
|
||||||
var surveyAnswers = answersList.Join(
|
var surveyAnswers = answersList.Join(
|
||||||
surveyResponses,
|
surveyResponses,
|
||||||
@ -535,14 +538,14 @@ namespace DamageAssesment.Api.Responses.Providers
|
|||||||
surveyResponse.LocationId,
|
surveyResponse.LocationId,
|
||||||
surveyResponse.EmployeeId,
|
surveyResponse.EmployeeId,
|
||||||
surveyResponse.ClientDevice,
|
surveyResponse.ClientDevice,
|
||||||
surveyResponse.KeyAnswerResult,
|
// surveyResponse.KeyAnswerResult,
|
||||||
surveyResponse.Longitute,
|
surveyResponse.Longitute,
|
||||||
surveyResponse.Latitude,
|
surveyResponse.Latitude,
|
||||||
Employee = employee,
|
Employee = employee,
|
||||||
answers = from ans in answers
|
answers = from ans in answers
|
||||||
select new
|
select new
|
||||||
{
|
{
|
||||||
ans.QuestionId,
|
// ans.QuestionId,
|
||||||
ans.Id,
|
ans.Id,
|
||||||
ans.AnswerText,
|
ans.AnswerText,
|
||||||
ans.Comment,
|
ans.Comment,
|
||||||
@ -578,6 +581,11 @@ namespace DamageAssesment.Api.Responses.Providers
|
|||||||
surveyResonses = await surveyResponseDbContext.SurveyResponses.Where(x => x.SurveyId == surveyId && x.EmployeeId == employeeid).ToListAsync();
|
surveyResonses = await surveyResponseDbContext.SurveyResponses.Where(x => x.SurveyId == surveyId && x.EmployeeId == employeeid).ToListAsync();
|
||||||
employee = await employeeServiceProvider.getEmployeeAsync(employeeid, token);
|
employee = await employeeServiceProvider.getEmployeeAsync(employeeid, token);
|
||||||
}
|
}
|
||||||
|
surveyResonses = surveyResonses
|
||||||
|
.OrderByDescending(obj => obj.Id)
|
||||||
|
.GroupBy(obj => new { obj.SurveyId, obj.LocationId })//obj.EmployeeId,
|
||||||
|
.Select(group => group.FirstOrDefault()) // or .FirstOrDefault() if you want to handle empty groups
|
||||||
|
.ToList();
|
||||||
|
|
||||||
var answers = await answerServiceProvider.getAnswersAsync(token);
|
var answers = await answerServiceProvider.getAnswersAsync(token);
|
||||||
var questions = await questionServiceProvider.getQuestionsAsync(null, token);
|
var questions = await questionServiceProvider.getQuestionsAsync(null, token);
|
||||||
@ -594,16 +602,16 @@ namespace DamageAssesment.Api.Responses.Providers
|
|||||||
r.LocationId,
|
r.LocationId,
|
||||||
r.EmployeeId,
|
r.EmployeeId,
|
||||||
r.ClientDevice,
|
r.ClientDevice,
|
||||||
r.KeyAnswerResult,
|
// r.KeyAnswerResult,
|
||||||
r.Longitute,
|
r.Longitute,
|
||||||
r.Latitude,
|
r.Latitude,
|
||||||
Employee = (from e in employees where e.Id == r.EmployeeId select new { e.Id, e.Name, e.BirthDate, e.Email, e.OfficePhoneNumber }).SingleOrDefault(),
|
// Employee = (from e in employees where e.Id == r.EmployeeId select new { e.Id, e.Name, e.BirthDate, e.Email, e.OfficePhoneNumber }).SingleOrDefault(),
|
||||||
answers = from ans in answers
|
answers = from ans in answers
|
||||||
where ans.SurveyResponseId == r.Id
|
where ans.SurveyResponseId == r.Id
|
||||||
select new
|
select new
|
||||||
{
|
{
|
||||||
ans.Id,
|
ans.Id,
|
||||||
ans.QuestionId,
|
// ans.QuestionId,
|
||||||
ans.AnswerText,
|
ans.AnswerText,
|
||||||
ans.Comment,
|
ans.Comment,
|
||||||
Questions = (from q in surveyQuestions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Text }).SingleOrDefault(),
|
Questions = (from q in surveyQuestions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Text }).SingleOrDefault(),
|
||||||
@ -646,7 +654,11 @@ namespace DamageAssesment.Api.Responses.Providers
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
surveyResonses = surveyResonses
|
||||||
|
.OrderByDescending(obj => obj.Id)
|
||||||
|
.GroupBy(obj => new { obj.SurveyId, obj.EmployeeId, obj.LocationId })
|
||||||
|
.Select(group => group.FirstOrDefault()) // or .FirstOrDefault() if you want to handle empty groups
|
||||||
|
.ToList();
|
||||||
var answers = await answerServiceProvider.getAnswersAsync(token);
|
var answers = await answerServiceProvider.getAnswersAsync(token);
|
||||||
var questions = await questionServiceProvider.getQuestionsAsync(null, token);
|
var questions = await questionServiceProvider.getQuestionsAsync(null, token);
|
||||||
var attachments = await attachmentServiceProvider.getAttachmentsAsync(token);
|
var attachments = await attachmentServiceProvider.getAttachmentsAsync(token);
|
||||||
@ -659,16 +671,16 @@ namespace DamageAssesment.Api.Responses.Providers
|
|||||||
r.LocationId,
|
r.LocationId,
|
||||||
r.EmployeeId,
|
r.EmployeeId,
|
||||||
r.ClientDevice,
|
r.ClientDevice,
|
||||||
r.KeyAnswerResult,
|
// r.KeyAnswerResult,
|
||||||
r.Longitute,
|
r.Longitute,
|
||||||
r.Latitude,
|
r.Latitude,
|
||||||
Employee = employeeid != 0 ? _employee : (from e in employees where r.EmployeeId == e.Id select new { e.Id, e.Name, e.BirthDate, e.Email, e.OfficePhoneNumber }).SingleOrDefault(),
|
// Employee = employeeid != 0 ? _employee : (from e in employees where r.EmployeeId == e.Id select new { e.Id, e.Name, e.BirthDate, e.Email, e.OfficePhoneNumber }).SingleOrDefault(),
|
||||||
answers = from ans in answers
|
answers = from ans in answers
|
||||||
where ans.SurveyResponseId == r.Id
|
where ans.SurveyResponseId == r.Id
|
||||||
select new
|
select new
|
||||||
{
|
{
|
||||||
ans.Id,
|
ans.Id,
|
||||||
ans.QuestionId,
|
// ans.QuestionId,
|
||||||
ans.AnswerText,
|
ans.AnswerText,
|
||||||
ans.Comment,
|
ans.Comment,
|
||||||
Questions = (from q in questions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Text }).SingleOrDefault(),
|
Questions = (from q in questions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Text }).SingleOrDefault(),
|
||||||
@ -907,7 +919,11 @@ namespace DamageAssesment.Api.Responses.Providers
|
|||||||
_employee = new { employee.Id, employee.Name, employee.BirthDate, employee.Email, employee.OfficePhoneNumber };
|
_employee = new { employee.Id, employee.Name, employee.BirthDate, employee.Email, employee.OfficePhoneNumber };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
surveyResonses = surveyResonses
|
||||||
|
.OrderByDescending(obj => obj.Id)
|
||||||
|
.GroupBy(obj => new { obj.SurveyId, obj.LocationId }) //obj.EmployeeId,
|
||||||
|
.Select(group => group.FirstOrDefault()) // or .FirstOrDefault() if you want to handle empty groups
|
||||||
|
.ToList();
|
||||||
var answers = await answerServiceProvider.getAnswersAsync(token);
|
var answers = await answerServiceProvider.getAnswersAsync(token);
|
||||||
var questions = await questionServiceProvider.getQuestionsAsync(null, token);
|
var questions = await questionServiceProvider.getQuestionsAsync(null, token);
|
||||||
var surveyQuestions = from q in questions where q.SurveyId == surveyId select q;
|
var surveyQuestions = from q in questions where q.SurveyId == surveyId select q;
|
||||||
@ -921,16 +937,16 @@ namespace DamageAssesment.Api.Responses.Providers
|
|||||||
r.LocationId,
|
r.LocationId,
|
||||||
r.EmployeeId,
|
r.EmployeeId,
|
||||||
r.ClientDevice,
|
r.ClientDevice,
|
||||||
r.KeyAnswerResult,
|
// r.KeyAnswerResult,
|
||||||
r.Longitute,
|
r.Longitute,
|
||||||
r.Latitude,
|
r.Latitude,
|
||||||
Employee = (from e in employees where r.EmployeeId == e.Id select new { e.Id, e.Name, e.BirthDate, e.Email, e.OfficePhoneNumber }).SingleOrDefault(),
|
// Employee = (from e in employees where r.EmployeeId == e.Id select new { e.Id, e.Name, e.BirthDate, e.Email, e.OfficePhoneNumber }).SingleOrDefault(),
|
||||||
answers = from ans in answers
|
answers = from ans in answers
|
||||||
where ans.SurveyResponseId == r.Id
|
where ans.SurveyResponseId == r.Id
|
||||||
|
|
||||||
select new
|
select new
|
||||||
{
|
{
|
||||||
ans.QuestionId,
|
// ans.QuestionId,
|
||||||
ans.Id,
|
ans.Id,
|
||||||
ans.AnswerText,
|
ans.AnswerText,
|
||||||
ans.Comment,
|
ans.Comment,
|
||||||
@ -973,7 +989,11 @@ namespace DamageAssesment.Api.Responses.Providers
|
|||||||
_employee = new { employee.Id, employee.Name, employee.BirthDate, employee.Email, employee.OfficePhoneNumber };
|
_employee = new { employee.Id, employee.Name, employee.BirthDate, employee.Email, employee.OfficePhoneNumber };
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
surveyResponses = surveyResponses
|
||||||
|
.OrderByDescending(obj => obj.Id)
|
||||||
|
.GroupBy(obj => new { obj.SurveyId, obj.LocationId })//, obj.EmployeeId
|
||||||
|
.Select(group => group.FirstOrDefault()) // or .FirstOrDefault() if you want to handle empty groups
|
||||||
|
.ToList();
|
||||||
//var surveyResponses = await surveyResponseDbContext.Responses.Where(x => x.SurveyId == survey.Id).ToListAsync();
|
//var surveyResponses = await surveyResponseDbContext.Responses.Where(x => x.SurveyId == survey.Id).ToListAsync();
|
||||||
// var employees = await employeeServiceProvider.getEmployeesAsync();
|
// var employees = await employeeServiceProvider.getEmployeesAsync();
|
||||||
var answers = await answerServiceProvider.getAnswersAsync(token);
|
var answers = await answerServiceProvider.getAnswersAsync(token);
|
||||||
@ -987,10 +1007,10 @@ namespace DamageAssesment.Api.Responses.Providers
|
|||||||
r.LocationId,
|
r.LocationId,
|
||||||
r.EmployeeId,
|
r.EmployeeId,
|
||||||
r.ClientDevice,
|
r.ClientDevice,
|
||||||
r.KeyAnswerResult,
|
// r.KeyAnswerResult,
|
||||||
r.Longitute,
|
r.Longitute,
|
||||||
r.Latitude,
|
r.Latitude,
|
||||||
Employee = (from e in employees where r.EmployeeId == e.Id select new { e.Id, e.Name, e.BirthDate, e.Email, e.OfficePhoneNumber }).SingleOrDefault(),
|
// Employee = (from e in employees where r.EmployeeId == e.Id select new { e.Id, e.Name, e.BirthDate, e.Email, e.OfficePhoneNumber }).SingleOrDefault(),
|
||||||
answers = from ans in answers
|
answers = from ans in answers
|
||||||
where ans.SurveyResponseId == r.Id
|
where ans.SurveyResponseId == r.Id
|
||||||
&& ans.QuestionId == question.Id
|
&& ans.QuestionId == question.Id
|
||||||
@ -998,7 +1018,7 @@ namespace DamageAssesment.Api.Responses.Providers
|
|||||||
|
|
||||||
select new
|
select new
|
||||||
{
|
{
|
||||||
ans.QuestionId,
|
// ans.QuestionId,
|
||||||
AnswerId = ans.Id,
|
AnswerId = ans.Id,
|
||||||
ans.AnswerText,
|
ans.AnswerText,
|
||||||
ans.Comment,
|
ans.Comment,
|
||||||
|
@ -10,9 +10,8 @@
|
|||||||
"securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk="
|
"securitykey": "bWlhbWkgZGFkZSBzY2hvb2xzIHNlY3JldCBrZXk="
|
||||||
},
|
},
|
||||||
"ConnectionStrings": {
|
"ConnectionStrings": {
|
||||||
"ResponsesConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;"
|
//"ResponsesConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;"
|
||||||
//"ResponsesConnection": "Server=tcp:da-dev.database.windows.net,1433;Initial Catalog=da-dev-db;Encrypt=True;User ID=admin-dev;Password=b3tgRABw8LGE75k;TrustServerCertificate=False;Connection Timeout=30;"
|
"ResponsesConnection": "Server=207.180.248.35;Database=da_survey_dev;User Id=sa;Password=YourStrongPassw0rd;TrustServerCertificate=True;"
|
||||||
|
|
||||||
},
|
},
|
||||||
//"EndPointSettings": {
|
//"EndPointSettings": {
|
||||||
// "AnswerUrlBase": "http://localhost:5200",
|
// "AnswerUrlBase": "http://localhost:5200",
|
||||||
@ -46,10 +45,5 @@
|
|||||||
"AnswerByResponse": "/answers/byresponse/{0}",
|
"AnswerByResponse": "/answers/byresponse/{0}",
|
||||||
"Location": "/locations",
|
"Location": "/locations",
|
||||||
"Region": "/regions"
|
"Region": "/regions"
|
||||||
},
|
|
||||||
"ConnectionStrings": {
|
|
||||||
//"SurveyResponseConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;"
|
|
||||||
//"ResponsesConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;"
|
|
||||||
"ResponsesConnection": "Server=207.180.248.35;Database=da_survey_dev;User Id=sa;Password=YourStrongPassw0rd;TrustServerCertificate=True;"
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -34,7 +34,55 @@ namespace DamageAssesment.Api.Surveys.Test
|
|||||||
|
|
||||||
Assert.Equal(204, result.StatusCode);
|
Assert.Equal(204, result.StatusCode);
|
||||||
}
|
}
|
||||||
|
[Fact(DisplayName = "Get active Surveys - Ok case")]
|
||||||
|
public async Task GetActiveSurveysAsync_ShouldReturnStatusCode200()
|
||||||
|
{
|
||||||
|
var mockSurveyService = new Mock<ISurveyProvider>();
|
||||||
|
var mockResponse = await MockData.getOkResponse();
|
||||||
|
mockSurveyService.Setup(service => service.GetActiveSurveysAsync(true,null)).ReturnsAsync(mockResponse);
|
||||||
|
|
||||||
|
var surveyProvider = new SurveysController(mockSurveyService.Object);
|
||||||
|
var result = (OkObjectResult)await surveyProvider.GetActiveSurveysAsync(null);
|
||||||
|
|
||||||
|
Assert.Equal(200, result.StatusCode);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Fact(DisplayName = "Get active Surveys - NoContent Case")]
|
||||||
|
public async Task GetActiveSurveysAsync_ShouldReturnStatusCode204()
|
||||||
|
{
|
||||||
|
var mockSurveyService = new Mock<ISurveyProvider>();
|
||||||
|
var mockResponse = await MockData.getNoContentResponse();
|
||||||
|
mockSurveyService.Setup(service => service.GetActiveSurveysAsync(true,null)).ReturnsAsync(mockResponse);
|
||||||
|
|
||||||
|
var surveyProvider = new SurveysController(mockSurveyService.Object);
|
||||||
|
var result = (NoContentResult)await surveyProvider.GetActiveSurveysAsync(null);
|
||||||
|
|
||||||
|
Assert.Equal(204, result.StatusCode);
|
||||||
|
}
|
||||||
|
[Fact(DisplayName = "Get inactive Surveys - Ok case")]
|
||||||
|
public async Task GetInActiveSurveysAsync_ShouldReturnStatusCode200()
|
||||||
|
{
|
||||||
|
var mockSurveyService = new Mock<ISurveyProvider>();
|
||||||
|
var mockResponse = await MockData.getOkResponse();
|
||||||
|
mockSurveyService.Setup(service => service.GetActiveSurveysAsync(false, null)).ReturnsAsync(mockResponse);
|
||||||
|
|
||||||
|
var surveyProvider = new SurveysController(mockSurveyService.Object);
|
||||||
|
var result = (OkObjectResult)await surveyProvider.GetInActiveSurveysAsync(null);
|
||||||
|
|
||||||
|
Assert.Equal(200, result.StatusCode);
|
||||||
|
}
|
||||||
|
[Fact(DisplayName = "Get in active Surveys - NoContent Case")]
|
||||||
|
public async Task GetInActiveSurveysAsync_ShouldReturnStatusCode204()
|
||||||
|
{
|
||||||
|
var mockSurveyService = new Mock<ISurveyProvider>();
|
||||||
|
var mockResponse = await MockData.getNoContentResponse();
|
||||||
|
mockSurveyService.Setup(service => service.GetActiveSurveysAsync(false, null)).ReturnsAsync(mockResponse);
|
||||||
|
|
||||||
|
var surveyProvider = new SurveysController(mockSurveyService.Object);
|
||||||
|
var result = (NoContentResult)await surveyProvider.GetInActiveSurveysAsync(null);
|
||||||
|
|
||||||
|
Assert.Equal(204, result.StatusCode);
|
||||||
|
}
|
||||||
[Fact(DisplayName = "Get Survey by Id - Ok case")]
|
[Fact(DisplayName = "Get Survey by Id - Ok case")]
|
||||||
public async Task GetSurveyAsync_ShouldReturnStatusCode200()
|
public async Task GetSurveyAsync_ShouldReturnStatusCode200()
|
||||||
{
|
{
|
||||||
|
@ -29,7 +29,38 @@ namespace DamageAssesment.Api.Surveys.Controllers
|
|||||||
}
|
}
|
||||||
return NoContent();
|
return NoContent();
|
||||||
}
|
}
|
||||||
|
/// <summary>
|
||||||
|
/// GET request for retrieving all active surveys.
|
||||||
|
/// </summary>
|
||||||
|
[Authorize(Roles = "admin,survey,user,report")]
|
||||||
|
[Route("surveys/active")]
|
||||||
|
[Route("surveys/active/{language:alpha}")]
|
||||||
|
[HttpGet]
|
||||||
|
public async Task<ActionResult> GetActiveSurveysAsync(string? language)
|
||||||
|
{
|
||||||
|
var result = await this.surveyProvider.GetActiveSurveysAsync(true,language);
|
||||||
|
if (result.IsSuccess)
|
||||||
|
{
|
||||||
|
return Ok(result.Surveys);
|
||||||
|
}
|
||||||
|
return NoContent();
|
||||||
|
}
|
||||||
|
/// <summary>
|
||||||
|
/// GET request for retrieving all inactive surveys.
|
||||||
|
/// </summary>
|
||||||
|
[Authorize(Roles = "admin,survey,user,report")]
|
||||||
|
[Route("surveys/inactive")]
|
||||||
|
[Route("surveys/inactive/{language:alpha}")]
|
||||||
|
[HttpGet]
|
||||||
|
public async Task<ActionResult> GetInActiveSurveysAsync(string? language)
|
||||||
|
{
|
||||||
|
var result = await this.surveyProvider.GetActiveSurveysAsync(false, language);
|
||||||
|
if (result.IsSuccess)
|
||||||
|
{
|
||||||
|
return Ok(result.Surveys);
|
||||||
|
}
|
||||||
|
return NoContent();
|
||||||
|
}
|
||||||
/// <summary>
|
/// <summary>
|
||||||
/// GET request for retrieving surveys by ID.
|
/// GET request for retrieving surveys by ID.
|
||||||
/// </summary>
|
/// </summary>
|
||||||
|
@ -25,7 +25,10 @@
|
|||||||
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.21" />
|
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="6.0.21" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.5" />
|
||||||
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.5" />
|
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="7.0.5" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
|
||||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.4" />
|
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.19.4" />
|
||||||
|
<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
|
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
|
@ -3,6 +3,7 @@
|
|||||||
public interface ISurveyProvider
|
public interface ISurveyProvider
|
||||||
{
|
{
|
||||||
Task<(bool IsSuccess, IEnumerable< Models.MultiLanSurvey> Surveys, string ErrorMessage)> GetSurveysAsync(string language);
|
Task<(bool IsSuccess, IEnumerable< Models.MultiLanSurvey> Surveys, string ErrorMessage)> GetSurveysAsync(string language);
|
||||||
|
Task<(bool IsSuccess, IEnumerable<Models.MultiLanSurvey> Surveys, string ErrorMessage)> GetActiveSurveysAsync(bool IsActive,string language);
|
||||||
Task<(bool IsSuccess, Models.MultiLanSurvey Surveys, string ErrorMessage)> GetSurveysAsync(int id, string language);
|
Task<(bool IsSuccess, Models.MultiLanSurvey Surveys, string ErrorMessage)> GetSurveysAsync(int id, string language);
|
||||||
Task<(bool IsSuccess, Models.MultiLanSurvey Survey, string ErrorMessage)> PostSurveyAsync(Models.Survey Survey);
|
Task<(bool IsSuccess, Models.MultiLanSurvey Survey, string ErrorMessage)> PostSurveyAsync(Models.Survey Survey);
|
||||||
Task<(bool IsSuccess, Models.MultiLanSurvey Survey, string ErrorMessage)> PutSurveyAsync(int id, Models.Survey Survey);
|
Task<(bool IsSuccess, Models.MultiLanSurvey Survey, string ErrorMessage)> PutSurveyAsync(int id, Models.Survey Survey);
|
||||||
|
@ -9,7 +9,14 @@ using System.Reflection;
|
|||||||
using Microsoft.OpenApi.Models;
|
using Microsoft.OpenApi.Models;
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
builder.Services.AddCors(p => p.AddPolicy("DamageAppCorsPolicy", build => {
|
||||||
|
build.WithOrigins("*").AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin();
|
||||||
|
}));
|
||||||
|
builder.Services.AddLogging(builder =>
|
||||||
|
{
|
||||||
|
//builder.AddConsole(); // Optional: Add other providers if needed
|
||||||
|
builder.AddFile("logs/Surveys-{Date}.txt"); // Specify the file path and format
|
||||||
|
});
|
||||||
// Add services to the container.
|
// Add services to the container.
|
||||||
var authkey = builder.Configuration.GetValue<string>("JwtSettings:securitykey");
|
var authkey = builder.Configuration.GetValue<string>("JwtSettings:securitykey");
|
||||||
builder.Services.AddAuthentication(item =>
|
builder.Services.AddAuthentication(item =>
|
||||||
@ -93,6 +100,7 @@ if (app.Environment.IsDevelopment())
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
app.UseCors("DamageAppCorsPolicy");
|
||||||
app.UseAuthentication();
|
app.UseAuthentication();
|
||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
|
|
||||||
|
@ -101,6 +101,43 @@ namespace DamageAssesment.Api.Surveys.Providers
|
|||||||
return SurveyStatus.INACTIVE.ToString();
|
return SurveyStatus.INACTIVE.ToString();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Method to get surveys asynchronously with multi-language support
|
||||||
|
public async Task<(bool IsSuccess, IEnumerable<Models.MultiLanSurvey> Surveys, string ErrorMessage)> GetActiveSurveysAsync(bool IsActive,string language)
|
||||||
|
{
|
||||||
|
IEnumerable<Models.MultiLanSurvey> surveysList = null;
|
||||||
|
try
|
||||||
|
{
|
||||||
|
string status = SurveyStatus.ACTIVE.ToString();
|
||||||
|
if(!IsActive) status = SurveyStatus.INACTIVE.ToString();
|
||||||
|
logger?.LogInformation("Get all Surveys from DB");
|
||||||
|
//checking is enabled in survey response
|
||||||
|
var surveys = await surveyDbContext.Surveys.ToListAsync();//Where(s => s.IsEnabled == true)
|
||||||
|
|
||||||
|
if (surveys != null)
|
||||||
|
{
|
||||||
|
surveysList = from s in surveys
|
||||||
|
select new Models.MultiLanSurvey
|
||||||
|
{
|
||||||
|
Id = s.Id,
|
||||||
|
StartDate = s.StartDate,
|
||||||
|
EndDate = s.EndDate,
|
||||||
|
IsEnabled = s.IsEnabled,
|
||||||
|
CreatedDate = s.CreatedDate,
|
||||||
|
Status = GetStatus(s.StartDate, s.EndDate),
|
||||||
|
Titles = CreateMultiLanguageObject(GetSurveyTranslations(s.Id, null, language))
|
||||||
|
};
|
||||||
|
logger?.LogInformation($"{surveys.Count} Items(s) found");
|
||||||
|
return (true, surveysList.Where(a=>a.Status==status).OrderByDescending(a=>a.Id), null);
|
||||||
|
}
|
||||||
|
return (false, null, "Not found");
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
logger?.LogError(ex.ToString());
|
||||||
|
return (false, null, ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
// Method to get surveys asynchronously with multi-language support
|
// Method to get surveys asynchronously with multi-language support
|
||||||
public async Task<(bool IsSuccess, IEnumerable<Models.MultiLanSurvey> Surveys, string ErrorMessage)> GetSurveysAsync(string language)
|
public async Task<(bool IsSuccess, IEnumerable<Models.MultiLanSurvey> Surveys, string ErrorMessage)> GetSurveysAsync(string language)
|
||||||
{
|
{
|
||||||
@ -178,6 +215,11 @@ namespace DamageAssesment.Api.Surveys.Providers
|
|||||||
{
|
{
|
||||||
if (survey != null)
|
if (survey != null)
|
||||||
{
|
{
|
||||||
|
if (survey.StartDate != null && survey.EndDate != null)
|
||||||
|
{
|
||||||
|
if(survey.StartDate.Value>survey.EndDate.Value)
|
||||||
|
return (false, null, $"Survey start date should be less than enddate");
|
||||||
|
}
|
||||||
survey.CreatedDate = DateTime.Now;
|
survey.CreatedDate = DateTime.Now;
|
||||||
Db.Survey _survey = mapper.Map<Models.Survey, Db.Survey>(survey);
|
Db.Survey _survey = mapper.Map<Models.Survey, Db.Survey>(survey);
|
||||||
|
|
||||||
@ -214,6 +256,11 @@ namespace DamageAssesment.Api.Surveys.Providers
|
|||||||
{
|
{
|
||||||
if (survey != null)
|
if (survey != null)
|
||||||
{
|
{
|
||||||
|
if (survey.StartDate != null && survey.EndDate != null)
|
||||||
|
{
|
||||||
|
if (survey.StartDate.Value > survey.EndDate.Value)
|
||||||
|
return (false, null, $"Survey start date should be less than enddate");
|
||||||
|
}
|
||||||
var _survey = await surveyDbContext.Surveys.AsNoTracking().Where(s => s.Id == Id).SingleOrDefaultAsync();
|
var _survey = await surveyDbContext.Surveys.AsNoTracking().Where(s => s.Id == Id).SingleOrDefaultAsync();
|
||||||
|
|
||||||
if (_survey != null)
|
if (_survey != null)
|
||||||
|
@ -10,8 +10,8 @@
|
|||||||
},
|
},
|
||||||
"AllowedHosts": "*",
|
"AllowedHosts": "*",
|
||||||
"ConnectionStrings": {
|
"ConnectionStrings": {
|
||||||
"SurveyConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;"
|
//"SurveyConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;"
|
||||||
//"SurveyConnection": "Server=tcp:da-dev.database.windows.net,1433;Initial Catalog=da-dev-db;Encrypt=True;User ID=admin-dev;Password=b3tgRABw8LGE75k;TrustServerCertificate=False;Connection Timeout=30;"
|
"SurveyConnection": "Server=207.180.248.35;Database=da_survey_dev;User Id=sa;Password=YourStrongPassw0rd;TrustServerCertificate=True;"
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -18,9 +18,9 @@ namespace DamageAssesment.Api.UsersAccess.Test
|
|||||||
public async Task GetTokenAsync_ShouldReturnStatusCode200()
|
public async Task GetTokenAsync_ShouldReturnStatusCode200()
|
||||||
{
|
{
|
||||||
var response = await MockData.getTokenResponse(true,null);
|
var response = await MockData.getTokenResponse(true,null);
|
||||||
mockService.Setup(service => service.AuthenticateAsync("Emp1")).ReturnsAsync(response);
|
mockService.Setup(service => service.AuthenticateAsync()).ReturnsAsync(response);
|
||||||
var controller = new UsersAccessController(mockService.Object);
|
var controller = new UsersAccessController(mockService.Object);
|
||||||
var result = (OkObjectResult)await controller.AuthenticateAsync("Emp1");
|
var result = (OkObjectResult)await controller.AuthenticateAsync();
|
||||||
Assert.Equal(200, result.StatusCode);
|
Assert.Equal(200, result.StatusCode);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -28,9 +28,9 @@ namespace DamageAssesment.Api.UsersAccess.Test
|
|||||||
public async Task GetTokenAsync_ShouldReturnStatusCode401()
|
public async Task GetTokenAsync_ShouldReturnStatusCode401()
|
||||||
{
|
{
|
||||||
var response = await MockData.getTokenResponse(false, null);
|
var response = await MockData.getTokenResponse(false, null);
|
||||||
mockService.Setup(service => service.AuthenticateAsync("Emp1")).ReturnsAsync(response);
|
mockService.Setup(service => service.AuthenticateAsync()).ReturnsAsync(response);
|
||||||
var controller = new UsersAccessController(mockService.Object);
|
var controller = new UsersAccessController(mockService.Object);
|
||||||
var result = (UnauthorizedObjectResult)await controller.AuthenticateAsync("Emp1");
|
var result = (UnauthorizedObjectResult)await controller.AuthenticateAsync();
|
||||||
Assert.Equal(401, result.StatusCode);
|
Assert.Equal(401, result.StatusCode);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -8,27 +8,17 @@ namespace DamageAssesment.Api.UsersAccess.Controllers
|
|||||||
[ApiController]
|
[ApiController]
|
||||||
public class UsersAccessController : ControllerBase
|
public class UsersAccessController : ControllerBase
|
||||||
{
|
{
|
||||||
private IUsersAccessProvider userAccessProvider;
|
private readonly IUsersAccessProvider userAccessProvider;
|
||||||
|
|
||||||
public UsersAccessController(IUsersAccessProvider userAccessProvider)
|
public UsersAccessController(IUsersAccessProvider userAccessProvider)
|
||||||
{
|
{
|
||||||
this.userAccessProvider = userAccessProvider;
|
this.userAccessProvider = userAccessProvider;
|
||||||
}
|
}
|
||||||
[HttpPost("dadeschooltoken")]
|
[HttpPost("dadeschools/token")]
|
||||||
public async Task<ActionResult> DadeSchoolAuthenticateAsync(string username, string password)
|
public async Task<ActionResult> DadeSchoolAuthenticateAsync(UserCredentials userCredentials)
|
||||||
{
|
{
|
||||||
var result = await userAccessProvider.DadeSchoolAuthenticateAsync(username, password);
|
var result = await userAccessProvider.AuthenticateAsync(userCredentials.username, userCredentials.password);
|
||||||
if (result.IsSuccess)
|
|
||||||
{
|
|
||||||
return Ok(result.TokenResponse);
|
|
||||||
}
|
|
||||||
return Unauthorized(result.ErrorMessage);
|
|
||||||
}
|
|
||||||
[Authorize(Policy = "Dadeschools")]
|
|
||||||
[HttpPost("token/{employecode}")]
|
|
||||||
public async Task<ActionResult> AuthenticateAsync(string employecode)
|
|
||||||
{
|
|
||||||
var result = await userAccessProvider.AuthenticateAsync(employecode);
|
|
||||||
if (result.IsSuccess)
|
if (result.IsSuccess)
|
||||||
{
|
{
|
||||||
return Ok(result.TokenResponse);
|
return Ok(result.TokenResponse);
|
||||||
@ -37,7 +27,19 @@ namespace DamageAssesment.Api.UsersAccess.Controllers
|
|||||||
}
|
}
|
||||||
|
|
||||||
[Authorize(Policy = "Dadeschools")]
|
[Authorize(Policy = "Dadeschools")]
|
||||||
[HttpPost("refreshtoken")]
|
[HttpGet("damageapp/token")]
|
||||||
|
public async Task<ActionResult> AuthenticateAsync()
|
||||||
|
{
|
||||||
|
var result = await userAccessProvider.AuthenticateAsync();
|
||||||
|
if (result.IsSuccess)
|
||||||
|
{
|
||||||
|
return Ok(result.TokenResponse);
|
||||||
|
}
|
||||||
|
return Unauthorized(result.ErrorMessage);
|
||||||
|
}
|
||||||
|
|
||||||
|
[Authorize(Policy = "Dadeschools")]
|
||||||
|
[HttpPost("damageapp/refreshtoken")]
|
||||||
public async Task<ActionResult> RefreshTokenAsync(TokenResponse tokenResponse)
|
public async Task<ActionResult> RefreshTokenAsync(TokenResponse tokenResponse)
|
||||||
{
|
{
|
||||||
var result = await userAccessProvider.RefreshTokenAsync(tokenResponse);
|
var result = await userAccessProvider.RefreshTokenAsync(tokenResponse);
|
||||||
@ -48,7 +50,7 @@ namespace DamageAssesment.Api.UsersAccess.Controllers
|
|||||||
return Unauthorized(result.ErrorMessage);
|
return Unauthorized(result.ErrorMessage);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Authorize(Policy = "DamageApp", Roles ="admin")]
|
[Authorize(Policy = "DamageApp", Roles = "admin")]
|
||||||
[HttpGet("users")]
|
[HttpGet("users")]
|
||||||
public async Task<ActionResult> GetUsersAsync()
|
public async Task<ActionResult> GetUsersAsync()
|
||||||
{
|
{
|
||||||
@ -60,7 +62,7 @@ namespace DamageAssesment.Api.UsersAccess.Controllers
|
|||||||
return NoContent();
|
return NoContent();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Authorize(Policy = "DamageApp", Roles = "admin")]
|
// [Authorize(Policy = "DamageApp", Roles = "admin")]
|
||||||
[HttpGet("users/{Id}")]
|
[HttpGet("users/{Id}")]
|
||||||
public async Task<ActionResult> GetUsersAsync(int Id)
|
public async Task<ActionResult> GetUsersAsync(int Id)
|
||||||
{
|
{
|
||||||
@ -72,7 +74,7 @@ namespace DamageAssesment.Api.UsersAccess.Controllers
|
|||||||
return NotFound();
|
return NotFound();
|
||||||
}
|
}
|
||||||
|
|
||||||
[Authorize(Policy = "DamageApp", Roles = "admin")]
|
//[Authorize(Policy = "DamageApp", Roles = "admin")]
|
||||||
[HttpGet("roles")]
|
[HttpGet("roles")]
|
||||||
public async Task<ActionResult> GetRolesAsync()
|
public async Task<ActionResult> GetRolesAsync()
|
||||||
{
|
{
|
||||||
@ -83,7 +85,7 @@ namespace DamageAssesment.Api.UsersAccess.Controllers
|
|||||||
}
|
}
|
||||||
return NoContent();
|
return NoContent();
|
||||||
}
|
}
|
||||||
[Authorize(Policy = "DamageApp", Roles = "admin")]
|
//[Authorize(Policy = "DamageApp", Roles = "admin")]
|
||||||
[HttpPost("users")]
|
[HttpPost("users")]
|
||||||
public async Task<ActionResult> PostUserAsync(User user)
|
public async Task<ActionResult> PostUserAsync(User user)
|
||||||
{
|
{
|
||||||
@ -95,7 +97,7 @@ namespace DamageAssesment.Api.UsersAccess.Controllers
|
|||||||
return BadRequest(result.ErrorMessage);
|
return BadRequest(result.ErrorMessage);
|
||||||
}
|
}
|
||||||
|
|
||||||
[Authorize(Policy = "DamageApp", Roles = "admin")]
|
//[Authorize(Policy = "DamageApp", Roles = "admin")]
|
||||||
[HttpPut("users/{Id}")]
|
[HttpPut("users/{Id}")]
|
||||||
public async Task<ActionResult> PutUserAsync(int Id, User user)
|
public async Task<ActionResult> PutUserAsync(int Id, User user)
|
||||||
{
|
{
|
||||||
|
@ -24,9 +24,13 @@
|
|||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
||||||
</PackageReference>
|
</PackageReference>
|
||||||
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="7.0.10" />
|
<PackageReference Include="Microsoft.Extensions.Http.Polly" Version="7.0.10" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging" Version="8.0.0" />
|
||||||
|
<PackageReference Include="Microsoft.Extensions.Logging.Console" Version="8.0.0" />
|
||||||
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.18.1" />
|
<PackageReference Include="Microsoft.VisualStudio.Azure.Containers.Tools.Targets" Version="1.18.1" />
|
||||||
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
|
||||||
|
<PackageReference Include="Serilog.Extensions.Logging.File" Version="3.0.0" />
|
||||||
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
|
<PackageReference Include="Swashbuckle.AspNetCore" Version="6.2.3" />
|
||||||
|
<PackageReference Include="System.IdentityModel.Tokens.Jwt" Version="6.21.0" />
|
||||||
</ItemGroup>
|
</ItemGroup>
|
||||||
|
|
||||||
</Project>
|
</Project>
|
||||||
|
@ -4,7 +4,7 @@ namespace DamageAssesment.Api.UsersAccess.Interfaces
|
|||||||
{
|
{
|
||||||
public interface IEmployeeServiceProvider
|
public interface IEmployeeServiceProvider
|
||||||
{
|
{
|
||||||
Task<List<Employee>> getEmployeesAsync();
|
Task<List<Employee>> getEmployeesAsync(string token);
|
||||||
Task<Employee> getEmployeeAsync(int employeeId);
|
Task<Employee> getEmployeeAsync(int employeeId, string token);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -7,5 +7,7 @@ namespace DamageAssesment.Api.UsersAccess.Interfaces
|
|||||||
{
|
{
|
||||||
Task<string> GenerateToken(Models.User user);
|
Task<string> GenerateToken(Models.User user);
|
||||||
Task<TokenResponse> TokenAuthenticate(Models.User user, Claim[] claims);
|
Task<TokenResponse> TokenAuthenticate(Models.User user, Claim[] claims);
|
||||||
|
|
||||||
|
Task<string> ConvertJsonToDadeSchoolsJwt(string json);
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -4,14 +4,15 @@ namespace DamageAssesment.Api.UsersAccess.Interfaces
|
|||||||
{
|
{
|
||||||
public interface IUsersAccessProvider
|
public interface IUsersAccessProvider
|
||||||
{
|
{
|
||||||
public Task<(bool IsSuccess, IEnumerable< Models.User> Users, string ErrorMessage)> GetUsersAsync();
|
public Task<(bool IsSuccess, IEnumerable<object> Users, string ErrorMessage)> GetUsersAsync();
|
||||||
public Task<(bool IsSuccess, Models.User User, string ErrorMessage)> GetUsersAsync(int Id);
|
public Task<(bool IsSuccess, object User, string ErrorMessage)> GetUsersAsync(int Id);
|
||||||
public Task<(bool IsSuccess, Models.User User, string ErrorMessage)> PostUserAsync(Models.User User);
|
public Task<(bool IsSuccess, Models.User User, string ErrorMessage)> PostUserAsync(Models.User User);
|
||||||
public Task<(bool IsSuccess, Models.User User, string ErrorMessage)> PutUserAsync(int Id,Models.User User);
|
public Task<(bool IsSuccess, Models.User User, string ErrorMessage)> PutUserAsync(int Id,Models.User User);
|
||||||
public Task<(bool IsSuccess, Models.User User, string ErrorMessage)> DeleteUserAsync(int Id);
|
public Task<(bool IsSuccess, Models.User User, string ErrorMessage)> DeleteUserAsync(int Id);
|
||||||
public Task<(bool IsSuccess, IEnumerable<Models.Role> Roles, string ErrorMessage)> GetRolesAsync();
|
public Task<(bool IsSuccess, IEnumerable<Models.Role> Roles, string ErrorMessage)> GetRolesAsync();
|
||||||
public Task<(bool IsSuccess, Models.TokenResponse TokenResponse, string ErrorMessage)> AuthenticateAsync(string employeCode);
|
public Task<(bool IsSuccess, Models.TokenResponse TokenResponse, string ErrorMessage)> AuthenticateAsync();
|
||||||
public Task<(bool IsSuccess, Models.DadeSchoolToken TokenResponse, string ErrorMessage)> DadeSchoolAuthenticateAsync(string username, string password);
|
public Task<(bool IsSuccess, DadeSchoolToken TokenResponse, string ErrorMessage)> AuthenticateAsync(string username, string password);
|
||||||
|
|
||||||
public Task<(bool IsSuccess, Models.TokenResponse TokenResponse, string ErrorMessage)>RefreshTokenAsync(TokenResponse tokenResponse);
|
public Task<(bool IsSuccess, Models.TokenResponse TokenResponse, string ErrorMessage)>RefreshTokenAsync(TokenResponse tokenResponse);
|
||||||
public void seedData();
|
public void seedData();
|
||||||
}
|
}
|
||||||
|
@ -2,6 +2,6 @@
|
|||||||
{
|
{
|
||||||
public interface IHttpUtil
|
public interface IHttpUtil
|
||||||
{
|
{
|
||||||
Task<string> SendAsync(HttpMethod method, string url, string JsonInput);
|
Task<string> SendAsync(HttpMethod method, string url, string JsonInput, string token);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -0,0 +1,19 @@
|
|||||||
|
namespace DamageAssesment.Api.UsersAccess.Models
|
||||||
|
{
|
||||||
|
public class FakeToken
|
||||||
|
{
|
||||||
|
public long nbf { get; set; }
|
||||||
|
public long exp { get; set; }
|
||||||
|
public string iss { get; set; } = "https://dev-graph.dadeschools.net";
|
||||||
|
public string aud { get; set; } = "damage_assessment";
|
||||||
|
public long iat { get; set; }
|
||||||
|
public string at_hash { get; set; } = "Mw4sAsR_U3MfpqsffDhAqg";
|
||||||
|
public string s_hash { get; set; } = "xADDtg6lVxAXUIFK8hm0Iw";
|
||||||
|
public string sid { get; set; } = "A5EE26B57C27F28ADFEA8C021BB7C4F1";
|
||||||
|
public string sub { get; set; }
|
||||||
|
public long auth_time { get; set; }
|
||||||
|
public string idp { get; set; } = "Dadeschools";
|
||||||
|
public string[] amr { get; set; } = {"external"};
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
@ -1,5 +1,5 @@
|
|||||||
public class UserCredentials
|
public class UserCredentials
|
||||||
{
|
{
|
||||||
public string username { get; set; }
|
public string username { get; set; }
|
||||||
// public string? password { get; set; }
|
public string password { get; set; }
|
||||||
}
|
}
|
@ -17,9 +17,18 @@ const int maxRetryForCircuitBraker = 5;
|
|||||||
const int intervalForCircuitBraker = 5; //5 seconds
|
const int intervalForCircuitBraker = 5; //5 seconds
|
||||||
|
|
||||||
var builder = WebApplication.CreateBuilder(args);
|
var builder = WebApplication.CreateBuilder(args);
|
||||||
|
builder.Services.AddCors(p => p.AddPolicy("DamageAppCorsPolicy", build =>
|
||||||
|
{
|
||||||
|
build.WithOrigins("*").AllowAnyMethod().AllowAnyHeader().AllowAnyOrigin();
|
||||||
|
}));
|
||||||
|
builder.Services.AddLogging(builder =>
|
||||||
|
{
|
||||||
|
//builder.AddConsole(); // Optional: Add other providers if needed
|
||||||
|
builder.AddFile("logs/UserAccess-{Date}.txt"); // Specify the file path and format
|
||||||
|
});
|
||||||
// Add services to the container.
|
// Add services to the container.
|
||||||
var authkey = builder.Configuration.GetValue<string>("JwtSettings:securitykey");
|
var authkey = builder.Configuration.GetValue<string>("JwtSettings:securitykey");
|
||||||
|
var mode = builder.Configuration.GetValue<string>("ModeSettings:mode");
|
||||||
|
|
||||||
|
|
||||||
builder.Services.AddAuthentication().
|
builder.Services.AddAuthentication().
|
||||||
@ -50,22 +59,27 @@ builder.Services.AddAuthorization(options =>
|
|||||||
.RequireAuthenticatedUser()
|
.RequireAuthenticatedUser()
|
||||||
.AddAuthenticationSchemes("DamageApp")
|
.AddAuthenticationSchemes("DamageApp")
|
||||||
.Build();
|
.Build();
|
||||||
var DadeschoolsPolicy = new AuthorizationPolicyBuilder()
|
|
||||||
.RequireAuthenticatedUser()
|
var DadeschoolsPolicy = new AuthorizationPolicyBuilder().RequireAuthenticatedUser()
|
||||||
.AddAuthenticationSchemes("Dadeschools")
|
.AddAuthenticationSchemes("Dadeschools")
|
||||||
.Build();
|
.Build();
|
||||||
|
|
||||||
|
var DadeschoolsPolicyOffline = new AuthorizationPolicyBuilder().RequireAssertion(_ => true)
|
||||||
|
.Build();
|
||||||
|
|
||||||
var allPolicy = new AuthorizationPolicyBuilder()
|
var allPolicy = new AuthorizationPolicyBuilder()
|
||||||
.RequireAuthenticatedUser()
|
.RequireAuthenticatedUser()
|
||||||
.AddAuthenticationSchemes("DamageApp", "Dadeschools")
|
.AddAuthenticationSchemes("DamageApp", "Dadeschools")
|
||||||
.Build();
|
.Build();
|
||||||
options.AddPolicy("DamageApp", DamageAppPolicy);
|
options.AddPolicy("DamageApp", DamageAppPolicy);
|
||||||
options.AddPolicy("Dadeschools", DadeschoolsPolicy);
|
options.AddPolicy("Dadeschools", mode == "online" ? DadeschoolsPolicy : DadeschoolsPolicyOffline);
|
||||||
options.AddPolicy("AllPolicies", allPolicy);
|
options.AddPolicy("AllPolicies", allPolicy);
|
||||||
options.DefaultPolicy = options.GetPolicy("DamageApp")!;
|
options.DefaultPolicy = options.GetPolicy("DamageApp")!;
|
||||||
});
|
});
|
||||||
|
|
||||||
var _jwtsettings = builder.Configuration.GetSection("JwtSettings");
|
var _jwtsettings = builder.Configuration.GetSection("JwtSettings");
|
||||||
builder.Services.Configure<JwtSettings>(_jwtsettings);
|
builder.Services.Configure<JwtSettings>(_jwtsettings);
|
||||||
|
builder.Services.AddHttpContextAccessor();
|
||||||
|
|
||||||
builder.Services.AddControllers();
|
builder.Services.AddControllers();
|
||||||
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
|
||||||
@ -139,6 +153,7 @@ if (app.Environment.IsDevelopment())
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
app.UseCors("DamageAppCorsPolicy");
|
||||||
app.UseAuthentication();
|
app.UseAuthentication();
|
||||||
app.UseAuthorization();
|
app.UseAuthorization();
|
||||||
|
|
||||||
|
@ -2,15 +2,19 @@
|
|||||||
using DamageAssesment.Api.UsersAccess.Db;
|
using DamageAssesment.Api.UsersAccess.Db;
|
||||||
using DamageAssesment.Api.UsersAccess.Interfaces;
|
using DamageAssesment.Api.UsersAccess.Interfaces;
|
||||||
using DamageAssesment.Api.UsersAccess.Models;
|
using DamageAssesment.Api.UsersAccess.Models;
|
||||||
|
using Microsoft.AspNetCore.Http;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using Microsoft.IdentityModel.Tokens;
|
using Microsoft.IdentityModel.Tokens;
|
||||||
|
using Newtonsoft.Json;
|
||||||
|
using Newtonsoft.Json.Linq;
|
||||||
using System.Data;
|
using System.Data;
|
||||||
using Newtonsoft.Json;
|
using Newtonsoft.Json;
|
||||||
using System.IdentityModel.Tokens.Jwt;
|
using System.IdentityModel.Tokens.Jwt;
|
||||||
using System.Security.Claims;
|
using System.Security.Claims;
|
||||||
using System.Text;
|
using System.Text;
|
||||||
|
|
||||||
|
|
||||||
namespace DamageAssesment.Api.UsersAccess.Providers
|
namespace DamageAssesment.Api.UsersAccess.Providers
|
||||||
{
|
{
|
||||||
public class UsersAccessProvider : IUsersAccessProvider
|
public class UsersAccessProvider : IUsersAccessProvider
|
||||||
@ -18,21 +22,23 @@ namespace DamageAssesment.Api.UsersAccess.Providers
|
|||||||
private readonly UsersAccessDbContext userAccessDbContext;
|
private readonly UsersAccessDbContext userAccessDbContext;
|
||||||
private readonly ILogger<UsersAccessProvider> logger;
|
private readonly ILogger<UsersAccessProvider> logger;
|
||||||
private readonly IMapper mapper;
|
private readonly IMapper mapper;
|
||||||
//private readonly IEmployeeServiceProvider employeeServiceProvider;
|
private readonly IEmployeeServiceProvider employeeServiceProvider;
|
||||||
private readonly JwtSettings jwtSettings;
|
private readonly JwtSettings jwtSettings;
|
||||||
private readonly ITokenServiceProvider tokenServiceProvider;
|
private readonly ITokenServiceProvider tokenServiceProvider;
|
||||||
private readonly IConfiguration configuration;
|
private readonly IConfiguration configuration;
|
||||||
|
private readonly IHttpContextAccessor httpContextAccessor;
|
||||||
|
|
||||||
public UsersAccessProvider(IConfiguration configuration,IOptions<JwtSettings> options, ITokenServiceProvider tokenServiceProvider, UsersAccessDbContext userAccessDbContext, IEmployeeServiceProvider employeeServiceProvider, ILogger<UsersAccessProvider> logger, IMapper mapper)
|
public UsersAccessProvider(IConfiguration configuration, IOptions<JwtSettings> options, ITokenServiceProvider tokenServiceProvider, IHttpContextAccessor httpContextAccessor, UsersAccessDbContext userAccessDbContext, IEmployeeServiceProvider employeeServiceProvider, ILogger<UsersAccessProvider> logger, IMapper mapper)
|
||||||
{
|
{
|
||||||
this.userAccessDbContext = userAccessDbContext;
|
this.userAccessDbContext = userAccessDbContext;
|
||||||
//this.employeeServiceProvider = employeeServiceProvider;
|
this.employeeServiceProvider = employeeServiceProvider;
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
this.mapper = mapper;
|
this.mapper = mapper;
|
||||||
jwtSettings = options.Value;
|
jwtSettings = options.Value;
|
||||||
this.tokenServiceProvider = tokenServiceProvider;
|
this.tokenServiceProvider = tokenServiceProvider;
|
||||||
|
this.httpContextAccessor = httpContextAccessor;
|
||||||
this.configuration = configuration;
|
this.configuration = configuration;
|
||||||
// seedData();
|
seedData();
|
||||||
}
|
}
|
||||||
|
|
||||||
public void seedData()
|
public void seedData()
|
||||||
@ -47,26 +53,69 @@ namespace DamageAssesment.Api.UsersAccess.Providers
|
|||||||
|
|
||||||
if (!userAccessDbContext.Roles.Any())
|
if (!userAccessDbContext.Roles.Any())
|
||||||
{
|
{
|
||||||
userAccessDbContext.Roles.Add(new Db.Role { Name = "admin", Description ="Administrator role have full access" });
|
userAccessDbContext.Roles.Add(new Db.Role { Name = "admin", Description = "Administrator role have full access" });
|
||||||
userAccessDbContext.Roles.Add(new Db.Role { Name = "user", Description =" User role"});
|
userAccessDbContext.Roles.Add(new Db.Role { Name = "user", Description = " User role" });
|
||||||
userAccessDbContext.Roles.Add(new Db.Role { Name = "survey", Description ="Survey role" });
|
userAccessDbContext.Roles.Add(new Db.Role { Name = "survey", Description = "Survey role" });
|
||||||
userAccessDbContext.Roles.Add(new Db.Role { Name = "report", Description ="Report role"});
|
userAccessDbContext.Roles.Add(new Db.Role { Name = "report", Description = "Report role" });
|
||||||
userAccessDbContext.Roles.Add(new Db.Role { Name = "document", Description ="Document role" });
|
userAccessDbContext.Roles.Add(new Db.Role { Name = "document", Description = "Document role" });
|
||||||
userAccessDbContext.SaveChanges();
|
userAccessDbContext.SaveChanges();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
private string GetToken()
|
||||||
public async Task<(bool IsSuccess, IEnumerable<Models.User> Users, string ErrorMessage)> GetUsersAsync()
|
{
|
||||||
|
string token = httpContextAccessor.HttpContext.Request.Headers.Authorization;
|
||||||
|
if (token != null)
|
||||||
|
{
|
||||||
|
token = token.Replace("Bearer ", string.Empty);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
token = "";
|
||||||
|
}
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
public async Task<(bool IsSuccess, IEnumerable<object> Users, string ErrorMessage)> GetUsersAsync()
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
logger?.LogInformation("Gell all Users from DB");
|
logger?.LogInformation("Gell all Users from DB");
|
||||||
var users = await userAccessDbContext.Users.ToListAsync();
|
var users = await userAccessDbContext.Users.ToListAsync();
|
||||||
|
List<object> userslist = new List<object>();
|
||||||
if (users != null)
|
if (users != null)
|
||||||
{
|
{
|
||||||
|
var employees = await employeeServiceProvider.getEmployeesAsync(GetToken());
|
||||||
|
var roles = await userAccessDbContext.Roles.ToListAsync();
|
||||||
|
foreach (Db.User user in users)
|
||||||
|
{
|
||||||
|
var employee = employees.SingleOrDefault(a => a.Id == user.EmployeeId);
|
||||||
|
var role = roles.SingleOrDefault(s => s.Id == user.RoleId);
|
||||||
|
|
||||||
|
string FirstName = null, LastName = null, EmployeeName = null;
|
||||||
|
if (employee != null)
|
||||||
|
{
|
||||||
|
string[] names = employee.Name.Split(' ');
|
||||||
|
EmployeeName = employee.Name;
|
||||||
|
FirstName = names[0];
|
||||||
|
LastName = EmployeeName.Replace(FirstName + " ", "");
|
||||||
|
}
|
||||||
|
userslist.Add(new
|
||||||
|
{
|
||||||
|
Id = user.Id,
|
||||||
|
EmployeeId = user.EmployeeId,
|
||||||
|
EmployeeCode = user.EmployeeCode,
|
||||||
|
FirstName = FirstName,
|
||||||
|
LastName = LastName,
|
||||||
|
EmployeeName = EmployeeName,
|
||||||
|
RoleId = user.RoleId,
|
||||||
|
RoleName = (role != null) ? role.Name : null,
|
||||||
|
IsActive = user.IsActive,
|
||||||
|
CreatedDate = user.CreateDate,
|
||||||
|
UpdatedDate = user.UpdateDate
|
||||||
|
});
|
||||||
|
}
|
||||||
logger?.LogInformation($"{users.Count} Items(s) found");
|
logger?.LogInformation($"{users.Count} Items(s) found");
|
||||||
var result = mapper.Map<IEnumerable<Db.User>, IEnumerable<Models.User>>(users);
|
// var result = mapper.Map<IEnumerable<Db.User>, IEnumerable<Models.User>>(users);
|
||||||
return (true, result, null);
|
return (true, userslist, null);
|
||||||
}
|
}
|
||||||
return (false, null, "Not found");
|
return (false, null, "Not found");
|
||||||
}
|
}
|
||||||
@ -76,18 +125,42 @@ namespace DamageAssesment.Api.UsersAccess.Providers
|
|||||||
return (false, null, ex.Message);
|
return (false, null, ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
public async Task<(bool IsSuccess, object User, string ErrorMessage)> GetUsersAsync(int Id)
|
||||||
public async Task<(bool IsSuccess, Models.User User, string ErrorMessage)> GetUsersAsync(int Id)
|
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
logger?.LogInformation("Querying Users table");
|
logger?.LogInformation("Querying Users table");
|
||||||
|
|
||||||
var user = await userAccessDbContext.Users.SingleOrDefaultAsync(s => s.Id == Id);
|
var user = await userAccessDbContext.Users.SingleOrDefaultAsync(s => s.Id == Id);
|
||||||
if (user != null)
|
if (user != null)
|
||||||
{
|
{
|
||||||
|
var employee = await employeeServiceProvider.getEmployeeAsync(user.EmployeeId, GetToken());
|
||||||
|
var role = await userAccessDbContext.Roles.SingleOrDefaultAsync(s => s.Id == user.RoleId);
|
||||||
|
string FirstName = null, LastName = null, EmployeeName = null;
|
||||||
|
if (employee != null)
|
||||||
|
{
|
||||||
|
string[] names = employee.Name.Split(' ');
|
||||||
|
EmployeeName = employee.Name;
|
||||||
|
FirstName = names[0];
|
||||||
|
LastName = EmployeeName.Replace(FirstName + " ", "");
|
||||||
|
}
|
||||||
|
var data = new
|
||||||
|
{
|
||||||
|
Id = user.Id,
|
||||||
|
EmployeeId = user.EmployeeId,
|
||||||
|
EmployeeCode = user.EmployeeCode,
|
||||||
|
FirstName = FirstName,
|
||||||
|
LastName = LastName,
|
||||||
|
EmployeeName = EmployeeName,
|
||||||
|
RoleId = user.RoleId,
|
||||||
|
RoleName = (role != null) ? role.Name : null,
|
||||||
|
IsActive = user.IsActive,
|
||||||
|
CreatedDate = user.CreateDate,
|
||||||
|
UpdatedDate = user.UpdateDate
|
||||||
|
};
|
||||||
logger?.LogInformation($"User Id: {Id} found");
|
logger?.LogInformation($"User Id: {Id} found");
|
||||||
var result = mapper.Map<Db.User, Models.User>(user);
|
var result = mapper.Map<Db.User, Models.User>(user);
|
||||||
return (true, result, null);
|
return (true, data, null);
|
||||||
}
|
}
|
||||||
return (false, null, "Not found");
|
return (false, null, "Not found");
|
||||||
}
|
}
|
||||||
@ -133,18 +206,12 @@ namespace DamageAssesment.Api.UsersAccess.Providers
|
|||||||
|
|
||||||
if (_user != null)
|
if (_user != null)
|
||||||
{
|
{
|
||||||
int count = userAccessDbContext.Users.Where(u => u.Id != user.Id).Count();
|
Db.User vUsers = mapper.Map<Models.User, Db.User>(user);
|
||||||
if (count == 0)
|
vUsers.UpdateDate = DateTime.Now;
|
||||||
{
|
userAccessDbContext.Users.Update(vUsers);
|
||||||
await userAccessDbContext.SaveChangesAsync();
|
userAccessDbContext.SaveChanges();
|
||||||
logger?.LogInformation($"Employee Id: {user.EmployeeId} updated successfuly");
|
user.Id = Id;
|
||||||
return (true, mapper.Map<Db.User, Models.User>(_user), $"Employee Id: {_user.EmployeeId} updated successfuly");
|
return (true, user, "Successful");
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
logger?.LogInformation($"Employee Id: {user.EmployeeId} is already exist");
|
|
||||||
return (false, null, $"Employee Id: {user.EmployeeId} is already exist");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
@ -190,7 +257,19 @@ namespace DamageAssesment.Api.UsersAccess.Providers
|
|||||||
return (false, null, ex.Message);
|
return (false, null, ex.Message);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
public async Task<(bool IsSuccess, DadeSchoolToken TokenResponse, string ErrorMessage)> DadeSchoolAuthenticateAsync(string username, string password)
|
|
||||||
|
public async Task<(bool IsSuccess, DadeSchoolToken TokenResponse, string ErrorMessage)> AuthenticateAsync(string username, string password)
|
||||||
|
{
|
||||||
|
var mode = configuration.GetValue<string>("ModeSettings:mode");
|
||||||
|
if (mode == "online")
|
||||||
|
return await DadeSchoolAuthenticateAsync(username, password);
|
||||||
|
else if (mode == "offline") return await DadeSchoolAuthenticateFakeAsync(username, password);
|
||||||
|
else return (false, null, "Invalid mode");
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
private async Task<(bool IsSuccess, DadeSchoolToken TokenResponse, string ErrorMessage)> DadeSchoolAuthenticateAsync(string username, string password)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@ -212,6 +291,44 @@ namespace DamageAssesment.Api.UsersAccess.Providers
|
|||||||
return (true, JsonConvert.DeserializeObject<DadeSchoolToken>(responseString), "");
|
return (true, JsonConvert.DeserializeObject<DadeSchoolToken>(responseString), "");
|
||||||
}
|
}
|
||||||
return (false, null, responseString);
|
return (false, null, responseString);
|
||||||
|
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
return (false, null, ex.Message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async Task<(bool IsSuccess, DadeSchoolToken TokenResponse, string ErrorMessage)> DadeSchoolAuthenticateFakeAsync(string username, string password)
|
||||||
|
{
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var defaultPassword = configuration.GetValue<string>("ModeSettings:userPassword");
|
||||||
|
if (password != defaultPassword)
|
||||||
|
return (false, null, "Invalid Password");
|
||||||
|
|
||||||
|
long unixTimeNow = (long)DateTime.UtcNow.Subtract(DateTime.UnixEpoch).TotalSeconds;
|
||||||
|
var tokenObject = new Models.FakeToken
|
||||||
|
{
|
||||||
|
nbf = unixTimeNow,
|
||||||
|
exp = unixTimeNow + 259200,
|
||||||
|
iat = unixTimeNow,
|
||||||
|
auth_time = unixTimeNow,
|
||||||
|
sub = username
|
||||||
|
|
||||||
|
};
|
||||||
|
var tokenString = JsonConvert.SerializeObject(tokenObject);
|
||||||
|
var jwtToken = await tokenServiceProvider.ConvertJsonToDadeSchoolsJwt(tokenString);
|
||||||
|
|
||||||
|
var response = new DadeSchoolToken
|
||||||
|
{
|
||||||
|
access_token = jwtToken,
|
||||||
|
expires_in = 262800,
|
||||||
|
scope = "openid profile",
|
||||||
|
token_type = "Bearer"
|
||||||
|
};
|
||||||
|
|
||||||
|
return (true, response, "");
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
@ -219,19 +336,40 @@ namespace DamageAssesment.Api.UsersAccess.Providers
|
|||||||
}
|
}
|
||||||
|
|
||||||
}
|
}
|
||||||
public async Task<(bool IsSuccess, TokenResponse TokenResponse, string ErrorMessage)> AuthenticateAsync(string employecode)
|
|
||||||
{
|
|
||||||
|
|
||||||
if (employecode != null)
|
private string DecodeJwtToken(string token)
|
||||||
{
|
{
|
||||||
//implementation for dadeschools authentication
|
try
|
||||||
// var employees = await employeeServiceProvider.getEmployeesAsync();
|
{
|
||||||
// var employee = employees.Where(e=> e.EmployeeCode.ToLower() == employecode.ToLower()).SingleOrDefault();
|
var handler = new JwtSecurityTokenHandler();
|
||||||
|
var jsonToken = handler.ReadToken(token);
|
||||||
|
var tokenS = handler.ReadToken(token) as JwtSecurityToken;
|
||||||
|
|
||||||
|
if (tokenS == null)
|
||||||
|
return null;
|
||||||
|
|
||||||
|
var payload = tokenS.Payload.SerializeToJson();
|
||||||
|
return payload;
|
||||||
|
}
|
||||||
|
catch
|
||||||
|
{
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task<(bool IsSuccess, TokenResponse TokenResponse, string ErrorMessage)> AuthenticateAsync()
|
||||||
|
{
|
||||||
|
var dadeschoolsToken = GetToken();
|
||||||
|
var decodedToken = DecodeJwtToken(dadeschoolsToken);
|
||||||
|
var tokenObject = decodedToken == null ? null : JObject.Parse(decodedToken);
|
||||||
|
|
||||||
|
if (tokenObject == null)
|
||||||
|
return (false, null, "JWT authentication is required");
|
||||||
|
|
||||||
|
var employecode = (string)tokenObject["sub"];
|
||||||
var user = userAccessDbContext.Users.Where(x => x.IsActive == true && x.EmployeeCode.ToLower() == employecode.ToLower()).SingleOrDefault();
|
var user = userAccessDbContext.Users.Where(x => x.IsActive == true && x.EmployeeCode.ToLower() == employecode.ToLower()).SingleOrDefault();
|
||||||
|
|
||||||
if (user != null)
|
if (user != null)
|
||||||
{
|
{
|
||||||
|
|
||||||
var r = await GetRolesAsync();
|
var r = await GetRolesAsync();
|
||||||
var role = r.Roles.Where(x => x.Id == user.RoleId).SingleOrDefault();
|
var role = r.Roles.Where(x => x.Id == user.RoleId).SingleOrDefault();
|
||||||
|
|
||||||
@ -250,25 +388,20 @@ namespace DamageAssesment.Api.UsersAccess.Providers
|
|||||||
Audience = "",
|
Audience = "",
|
||||||
NotBefore = DateTime.Now,
|
NotBefore = DateTime.Now,
|
||||||
Subject = new ClaimsIdentity(authClaims),
|
Subject = new ClaimsIdentity(authClaims),
|
||||||
Expires = DateTime.Now.AddMinutes(30),
|
Expires = DateTime.Now.AddDays(3),
|
||||||
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(tokenkey), SecurityAlgorithms.HmacSha256)
|
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(tokenkey), SecurityAlgorithms.HmacSha256)
|
||||||
};
|
};
|
||||||
var token = tokenhandler.CreateToken(tokendesc);
|
var token = tokenhandler.CreateToken(tokendesc);
|
||||||
string finaltoken = tokenhandler.WriteToken(token);
|
string finaltoken = tokenhandler.WriteToken(token);
|
||||||
|
|
||||||
var response = new TokenResponse() { jwttoken = finaltoken, refreshtoken = await tokenServiceProvider.GenerateToken(mapper.Map<Db.User,Models.User>(user)) };
|
var response = new TokenResponse() { jwttoken = finaltoken, refreshtoken = await tokenServiceProvider.GenerateToken(mapper.Map<Db.User, Models.User>(user)) };
|
||||||
return (true, response, "Authentication success and token issued.");
|
return (true, response, "Authentication success and token issued.");
|
||||||
}
|
}
|
||||||
else
|
else
|
||||||
{
|
{
|
||||||
return (false, null, "user inactive or not exist.");
|
return (false, null, "user inactive or not exist.");
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
else
|
|
||||||
{
|
|
||||||
return (false, null, "Credentials are required to authenticate.");
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
public async Task<(bool IsSuccess, IEnumerable<Models.Role> Roles, string ErrorMessage)> GetRolesAsync()
|
public async Task<(bool IsSuccess, IEnumerable<Models.Role> Roles, string ErrorMessage)> GetRolesAsync()
|
||||||
{
|
{
|
||||||
|
@ -10,11 +10,11 @@ namespace DamageAssesment.Api.UsersAccess.Services
|
|||||||
{
|
{
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<List<Employee>> getEmployeesAsync()
|
public async Task<List<Employee>> getEmployeesAsync(string token)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null);
|
var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null,token);
|
||||||
var employees = JsonConvert.DeserializeObject<List<Employee>>(responseJsonString);
|
var employees = JsonConvert.DeserializeObject<List<Employee>>(responseJsonString);
|
||||||
|
|
||||||
if (employees == null || !employees.Any())
|
if (employees == null || !employees.Any())
|
||||||
@ -28,12 +28,12 @@ namespace DamageAssesment.Api.UsersAccess.Services
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public async Task<Employee> getEmployeeAsync(int employeeId)
|
public async Task<Employee> getEmployeeAsync(int employeeId, string token)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
url = urlBase + string.Format(configuration.GetValue<string>("RessourceSettings:EmployeeById"), employeeId);
|
url = urlBase + string.Format(configuration.GetValue<string>("RessourceSettings:EmployeeById"), employeeId);
|
||||||
var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null);
|
var responseJsonString = await httpUtil.SendAsync(HttpMethod.Get, url, null,token);
|
||||||
var employee = JsonConvert.DeserializeObject<Employee>(responseJsonString);
|
var employee = JsonConvert.DeserializeObject<Employee>(responseJsonString);
|
||||||
|
|
||||||
if (employee == null)
|
if (employee == null)
|
||||||
|
@ -14,7 +14,7 @@ namespace DamageAssesment.Api.UsersAccess.Services
|
|||||||
this.httpClient = httpClient;
|
this.httpClient = httpClient;
|
||||||
this.logger = logger;
|
this.logger = logger;
|
||||||
}
|
}
|
||||||
public async Task<string> SendAsync(HttpMethod method, string url, string JsonInput)
|
public async Task<string> SendAsync(HttpMethod method, string url, string JsonInput,string token)
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@ -22,7 +22,7 @@ namespace DamageAssesment.Api.UsersAccess.Services
|
|||||||
request.Headers.Accept.Clear();
|
request.Headers.Accept.Clear();
|
||||||
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
|
||||||
|
|
||||||
//request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
|
||||||
if (method == HttpMethod.Post)
|
if (method == HttpMethod.Post)
|
||||||
{
|
{
|
||||||
request.Content = new StringContent(JsonInput, Encoding.UTF8, "application/json");
|
request.Content = new StringContent(JsonInput, Encoding.UTF8, "application/json");
|
||||||
|
@ -6,8 +6,10 @@ using DamageAssesment.Api.UsersAccess.Db;
|
|||||||
using DamageAssesment.Api.UsersAccess.Interfaces;
|
using DamageAssesment.Api.UsersAccess.Interfaces;
|
||||||
using DamageAssesment.Api.UsersAccess.Models;
|
using DamageAssesment.Api.UsersAccess.Models;
|
||||||
using Microsoft.EntityFrameworkCore;
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.Configuration;
|
||||||
using Microsoft.Extensions.Options;
|
using Microsoft.Extensions.Options;
|
||||||
using Microsoft.IdentityModel.Tokens;
|
using Microsoft.IdentityModel.Tokens;
|
||||||
|
using Newtonsoft.Json.Linq;
|
||||||
|
|
||||||
namespace DamageAssesment.Api.UsersAccess.Services
|
namespace DamageAssesment.Api.UsersAccess.Services
|
||||||
{
|
{
|
||||||
@ -15,9 +17,11 @@ namespace DamageAssesment.Api.UsersAccess.Services
|
|||||||
{
|
{
|
||||||
private readonly UsersAccessDbContext usersAccessDbContext;
|
private readonly UsersAccessDbContext usersAccessDbContext;
|
||||||
private readonly JwtSettings jwtSettings;
|
private readonly JwtSettings jwtSettings;
|
||||||
public TokenServiceProvider(IOptions<JwtSettings> options, UsersAccessDbContext usersAccessDbContext)
|
private readonly IConfiguration configuration;
|
||||||
|
public TokenServiceProvider(IOptions<JwtSettings> options, UsersAccessDbContext usersAccessDbContext, IConfiguration configuration)
|
||||||
{
|
{
|
||||||
this.usersAccessDbContext = usersAccessDbContext;
|
this.usersAccessDbContext = usersAccessDbContext;
|
||||||
|
this.configuration = configuration;
|
||||||
this.jwtSettings = options.Value;
|
this.jwtSettings = options.Value;
|
||||||
}
|
}
|
||||||
public async Task<string> GenerateToken(Models.User user)
|
public async Task<string> GenerateToken(Models.User user)
|
||||||
@ -55,5 +59,27 @@ namespace DamageAssesment.Api.UsersAccess.Services
|
|||||||
var jwttoken = new JwtSecurityTokenHandler().WriteToken(token);
|
var jwttoken = new JwtSecurityTokenHandler().WriteToken(token);
|
||||||
return new TokenResponse() { jwttoken = jwttoken, refreshtoken = await GenerateToken(user) };
|
return new TokenResponse() { jwttoken = jwttoken, refreshtoken = await GenerateToken(user) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
public async Task<string> ConvertJsonToDadeSchoolsJwt(string json)
|
||||||
|
{
|
||||||
|
var jsonObject = JObject.Parse(json);
|
||||||
|
var claims = new Claim[jsonObject.Count];
|
||||||
|
int i = 0;
|
||||||
|
foreach (var property in jsonObject.Properties())
|
||||||
|
{
|
||||||
|
claims[i++] = new Claim(property.Name, property.Value.ToString());
|
||||||
|
}
|
||||||
|
var securityKey = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(configuration.GetValue<string>("Dadeschools:TokenClientSecret")));
|
||||||
|
var credentials = new SigningCredentials(securityKey, SecurityAlgorithms.HmacSha256);
|
||||||
|
var tokenDescriptor = new SecurityTokenDescriptor
|
||||||
|
{
|
||||||
|
Subject = new ClaimsIdentity(claims),
|
||||||
|
Expires = DateTime.UtcNow.AddDays(3),
|
||||||
|
SigningCredentials = credentials
|
||||||
|
};
|
||||||
|
var tokenHandler = new JwtSecurityTokenHandler();
|
||||||
|
var token = tokenHandler.CreateToken(tokenDescriptor);
|
||||||
|
return tokenHandler.WriteToken(token);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -8,17 +8,24 @@
|
|||||||
"Microsoft.AspNetCore": "Warning"
|
"Microsoft.AspNetCore": "Warning"
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
//"EndPointSettings": {
|
||||||
|
// "EmployeeUrlBase": "http://localhost:5135"
|
||||||
|
//},
|
||||||
"EndPointSettings": {
|
"EndPointSettings": {
|
||||||
"EmployeeUrlBase": "http://localhost:5135"
|
"EmployeeUrlBase": "http://damageassesment.api.employees:80"
|
||||||
},
|
},
|
||||||
"RessourceSettings": {
|
"RessourceSettings": {
|
||||||
"Employee": "/Employees",
|
"Employee": "/Employees",
|
||||||
"EmployeeById": "/Employees/{0}"
|
"EmployeeById": "/Employees/{0}"
|
||||||
},
|
},
|
||||||
|
"ModeSettings": {
|
||||||
|
"mode": "offline",
|
||||||
|
"userPassword": "^R,cVAvEy7Z.qPkH9"
|
||||||
|
},
|
||||||
"AllowedHosts": "*",
|
"AllowedHosts": "*",
|
||||||
"Dadeschools": {
|
"Dadeschools": {
|
||||||
"Authority": "https://dev-graph.dadeschools.net",
|
"Authority": "https://graph2.dadeschools.net",
|
||||||
"TokenUrl": "https://dev-graph.dadeschools.net/connect/token",
|
"TokenUrl": "https://graph2.dadeschools.net/connect/token",
|
||||||
"ClientId": "dmapi",
|
"ClientId": "dmapi",
|
||||||
"ClientSecret": "bfce2c8d-2064-4a02-b19d-7f1d42b16eae",
|
"ClientSecret": "bfce2c8d-2064-4a02-b19d-7f1d42b16eae",
|
||||||
"TokenClientId": "damage_assessment_postman",
|
"TokenClientId": "damage_assessment_postman",
|
||||||
@ -38,8 +45,7 @@
|
|||||||
}
|
}
|
||||||
],
|
],
|
||||||
"ConnectionStrings": {
|
"ConnectionStrings": {
|
||||||
"UsersAccessConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;"
|
// "UsersAccessConnection": "Server=DESKTOP-OF5DPLQ\\SQLEXPRESS;Database=da_survey_dev;Trusted_Connection=True;TrustServerCertificate=True;"
|
||||||
//"UsersAccessConnection": "Server=tcp:da-dev.database.windows.net,1433;Initial Catalog=da-dev-db;Encrypt=True;User ID=admin-dev;Password=b3tgRABw8LGE75k;TrustServerCertificate=False;Connection Timeout=30;"
|
"UsersAccessConnection": "Server=207.180.248.35;Database=da_survey_dev;User Id=sa;Password=YourStrongPassw0rd;TrustServerCertificate=True;"
|
||||||
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,30 +0,0 @@
|
|||||||
<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="xunit" Version="2.4.2" />
|
|
||||||
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
|
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
|
||||||
<PrivateAssets>all</PrivateAssets>
|
|
||||||
</PackageReference>
|
|
||||||
<PackageReference Include="coverlet.collector" Version="3.2.0">
|
|
||||||
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
|
|
||||||
<PrivateAssets>all</PrivateAssets>
|
|
||||||
</PackageReference>
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
<ItemGroup>
|
|
||||||
<ProjectReference Include="..\DamageAssesment.Api.Responses\DamageAssesment.Api.Responses.csproj" />
|
|
||||||
</ItemGroup>
|
|
||||||
|
|
||||||
</Project>
|
|
@ -1,30 +0,0 @@
|
|||||||
|
|
||||||
using DamageAssesment.Api.Responses.Models;
|
|
||||||
using System.Collections.Generic;
|
|
||||||
using System.Text;
|
|
||||||
|
|
||||||
namespace DamageAssesment.Api.Responses.Test
|
|
||||||
{
|
|
||||||
public class MockData
|
|
||||||
{
|
|
||||||
public static async Task<(bool, SurveyResponse, string)> getOkResponse(SurveyResponse data)
|
|
||||||
{
|
|
||||||
return (true, data, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static async Task<(bool, dynamic, string)> getOkResponse()
|
|
||||||
{
|
|
||||||
return (true, new { }, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static async Task<(bool, Models.SurveyResponse, string)> getResponse()
|
|
||||||
{
|
|
||||||
return (false, null, null);
|
|
||||||
}
|
|
||||||
|
|
||||||
public static async Task<Models.SurveyResponse> getSurveyResponseObject()
|
|
||||||
{
|
|
||||||
return new Models.SurveyResponse { EmployeeId = 1, LocationId = 1, SurveyId = 1, Id = 1 };
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,251 +0,0 @@
|
|||||||
using DamageAssesment.Api.Responses.Controllers;
|
|
||||||
using DamageAssesment.Api.Responses.Interfaces;
|
|
||||||
using DamageAssesment.Api.Responses.Models;
|
|
||||||
using DamageAssesment.Api.Responses.Test;
|
|
||||||
using Microsoft.AspNetCore.Mvc;
|
|
||||||
using Moq;
|
|
||||||
using Xunit;
|
|
||||||
|
|
||||||
|
|
||||||
namespace DamageAssesment.SurveyResponses.Test
|
|
||||||
{
|
|
||||||
public class ResponsesServiceTest
|
|
||||||
{
|
|
||||||
private Mock<ISurveysResponse> mockSurveyResponseService;
|
|
||||||
private string token { get; set; }
|
|
||||||
public ResponsesServiceTest()
|
|
||||||
{
|
|
||||||
mockSurveyResponseService = new Mock<ISurveysResponse>();
|
|
||||||
token = Guid.NewGuid().ToString();
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact(DisplayName = "Get Responses - Ok case")]
|
|
||||||
public async Task GetSurveyResponsesAsync_ShouldReturnStatusCode200()
|
|
||||||
{
|
|
||||||
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
|
|
||||||
var mockResponse = await MockData.getOkResponse(mockRequestObject);
|
|
||||||
mockSurveyResponseService.Setup(service => service.GetSurveyResponsesAsync()).ReturnsAsync(mockResponse);
|
|
||||||
var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object);
|
|
||||||
var result = (OkObjectResult)await surveyResponseProvider.GetSurveyResponsesAsync();
|
|
||||||
Assert.Equal(200, result.StatusCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact(DisplayName = "Get Responses - BadRequest case")]
|
|
||||||
public async Task GetSurveyResponsesAsync_ShouldReturnStatusCode204()
|
|
||||||
{
|
|
||||||
var mockResponse = await MockData.getResponse();
|
|
||||||
mockSurveyResponseService.Setup(service => service.GetSurveyResponsesAsync()).ReturnsAsync(mockResponse);
|
|
||||||
var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object);
|
|
||||||
var result = (BadRequestObjectResult)await surveyResponseProvider.GetSurveyResponsesAsync();
|
|
||||||
Assert.Equal(400, result.StatusCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact(DisplayName = "Get Responses by surveyId - Ok case")]
|
|
||||||
public async Task GetSurveyResponsesBySurveyAsync_ShouldReturnStatusCode200()
|
|
||||||
{
|
|
||||||
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
|
|
||||||
var mockResponse = await MockData.getOkResponse();
|
|
||||||
<<<<<<<< HEAD:DamageAssesmentApi/DamageAssesment.Api.Responses.Test/SurveyResponsesServiceTest.cs
|
|
||||||
mockSurveyResponseService.Setup(service => service.GetSurveyResponsesBySurveyAsync(1,1)).ReturnsAsync(mockResponse);
|
|
||||||
var surveyResponseProvider = new SurveyResponsesController(mockSurveyResponseService.Object);
|
|
||||||
var result = (OkObjectResult)await surveyResponseProvider.GetSurveyResponsesAsync(1,1);
|
|
||||||
========
|
|
||||||
mockSurveyResponseService.Setup(service => service.GetSurveyResponsesBySurveyAsync(1)).ReturnsAsync(mockResponse);
|
|
||||||
var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object);
|
|
||||||
var result = (OkObjectResult)await surveyResponseProvider.GetSurveyResponsesAsync(1);
|
|
||||||
>>>>>>>> Azure-Integration:DamageAssesmentApi/DamageAssesment.Responses.Test/ResponsesServiceTest.cs
|
|
||||||
Assert.Equal(200, result.StatusCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact(DisplayName = "Get Responses by surveyId - NoContent case")]
|
|
||||||
public async Task GetSurveyResponsesBySurveyAsync_ShouldReturnStatusCode204()
|
|
||||||
{
|
|
||||||
var mockResponse = await MockData.getResponse();
|
|
||||||
<<<<<<<< HEAD:DamageAssesmentApi/DamageAssesment.Api.Responses.Test/SurveyResponsesServiceTest.cs
|
|
||||||
mockSurveyResponseService.Setup(service => service.GetSurveyResponsesBySurveyAsync(1,1)).ReturnsAsync(mockResponse);
|
|
||||||
var surveyResponseProvider = new SurveyResponsesController(mockSurveyResponseService.Object);
|
|
||||||
var result = (NoContentResult)await surveyResponseProvider.GetSurveyResponsesAsync(1,1);
|
|
||||||
========
|
|
||||||
mockSurveyResponseService.Setup(service => service.GetSurveyResponsesBySurveyAsync(1)).ReturnsAsync(mockResponse);
|
|
||||||
var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object);
|
|
||||||
var result = (NoContentResult)await surveyResponseProvider.GetSurveyResponsesAsync(1);
|
|
||||||
>>>>>>>> Azure-Integration:DamageAssesmentApi/DamageAssesment.Responses.Test/ResponsesServiceTest.cs
|
|
||||||
Assert.Equal(204, result.StatusCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
[Fact(DisplayName = "Get Responses by surveyId and locationId - Ok case")]
|
|
||||||
public async Task GetSurveyResponsesBySurveyLocationAsync_ShouldReturnStatusCode200()
|
|
||||||
{
|
|
||||||
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
|
|
||||||
var mockResponse = await MockData.getOkResponse();
|
|
||||||
mockSurveyResponseService.Setup(service => service.GetSurveyResponsesBySurveyAndLocationAsync(1, 1)).ReturnsAsync(mockResponse);
|
|
||||||
var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object);
|
|
||||||
var result = (OkObjectResult)await surveyResponseProvider.GetSurveyResponsesBySurveyAndLocationAsync(1, 1);
|
|
||||||
Assert.Equal(200, result.StatusCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact(DisplayName = "Get Responses by surveyId and locationId - NoContent case")]
|
|
||||||
public async Task GetSurveyResponsesBySurveyLocationAsync_ShouldReturnStatusCode204()
|
|
||||||
{
|
|
||||||
var mockResponse = await MockData.getResponse();
|
|
||||||
mockSurveyResponseService.Setup(service => service.GetSurveyResponsesBySurveyAndLocationAsync(1, 1)).ReturnsAsync(mockResponse);
|
|
||||||
var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object);
|
|
||||||
var result = (NoContentResult)await surveyResponseProvider.GetSurveyResponsesBySurveyAndLocationAsync(1, 1);
|
|
||||||
Assert.Equal(204, result.StatusCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact(DisplayName = "Get Responses by surveyId and QuestionId and Answer - Ok case")]
|
|
||||||
public async Task GetSurveyResponsesBySurveyQuestionAnswerAsync_ShouldReturnStatusCode200()
|
|
||||||
{
|
|
||||||
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
|
|
||||||
var mockResponse = await MockData.getOkResponse();
|
|
||||||
mockSurveyResponseService.Setup(service => service.GetResponsesByAnswerAsync(1, 1, "Yes")).ReturnsAsync(mockResponse);
|
|
||||||
var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object);
|
|
||||||
var result = (OkObjectResult)await surveyResponseProvider.GetSurveyResponsesByAnswerAsyncAsync(1, 1, "Yes");
|
|
||||||
Assert.Equal(200, result.StatusCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact(DisplayName = "Get Responses by surveyId and QuestionId and Answer - NoContent case")]
|
|
||||||
public async Task GetSurveyResponsesBySurveyQuestionAnswerAsync_ShouldReturnStatusCode204()
|
|
||||||
{
|
|
||||||
var mockResponse = await MockData.getResponse();
|
|
||||||
mockSurveyResponseService.Setup(service => service.GetResponsesByAnswerAsync(1, 1, "Yes")).ReturnsAsync(mockResponse);
|
|
||||||
var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object);
|
|
||||||
var result = (NoContentResult)await surveyResponseProvider.GetSurveyResponsesByAnswerAsyncAsync(1, 1, "Yes");
|
|
||||||
Assert.Equal(204, result.StatusCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
[Fact(DisplayName = "Get Responses by region and surveyId - Ok case")]
|
|
||||||
public async Task GetSurveyResponsesByRegionSurveyAsync_ShouldReturnStatusCode200()
|
|
||||||
{
|
|
||||||
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
|
|
||||||
var mockResponse = await MockData.getOkResponse();
|
|
||||||
mockSurveyResponseService.Setup(service => service.GetAnswersByRegionAsync(1)).ReturnsAsync(mockResponse);
|
|
||||||
var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object);
|
|
||||||
var result = (OkObjectResult)await surveyResponseProvider.GetAnswersByRegionAsync(1);
|
|
||||||
Assert.Equal(200, result.StatusCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact(DisplayName = "Get Responses by region and surveyId - NoContent Case")]
|
|
||||||
public async Task GetSurveyResponsesByRegionSurveyAsync_ShouldReturnStatusCode204()
|
|
||||||
{
|
|
||||||
var mockResponse = await MockData.getResponse();
|
|
||||||
mockSurveyResponseService.Setup(service => service.GetAnswersByRegionAsync(1)).ReturnsAsync(mockResponse);
|
|
||||||
var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object);
|
|
||||||
var result = (NoContentResult)await surveyResponseProvider.GetAnswersByRegionAsync(1);
|
|
||||||
Assert.Equal(204, result.StatusCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact(DisplayName = "Get Responses by maintenanceCenter and surveyId - Ok case")]
|
|
||||||
public async Task GetSurveyResponsesMaintenanceCenterSurveyAsync_ShouldReturnStatusCode200()
|
|
||||||
{
|
|
||||||
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
|
|
||||||
var mockResponse = await MockData.getOkResponse();
|
|
||||||
mockSurveyResponseService.Setup(service => service.GetSurveyResponsesByMaintenanceCenterAsync(1)).ReturnsAsync(mockResponse);
|
|
||||||
var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object);
|
|
||||||
var result = (OkObjectResult)await surveyResponseProvider.GetAnswersByMaintenaceCentersync(1);
|
|
||||||
Assert.Equal(200, result.StatusCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact(DisplayName = "Get Responses by maintenanceCenter and surveyId - No Content Case")]
|
|
||||||
public async Task GetSurveyResponsesMaintenanceCenterSurveyAsync_ShouldReturnStatusCode204()
|
|
||||||
{
|
|
||||||
var mockResponse = await MockData.getResponse();
|
|
||||||
mockSurveyResponseService.Setup(service => service.GetSurveyResponsesByMaintenanceCenterAsync(1)).ReturnsAsync(mockResponse);
|
|
||||||
var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object);
|
|
||||||
var result = (NoContentResult)await surveyResponseProvider.GetAnswersByMaintenaceCentersync(1);
|
|
||||||
Assert.Equal(204, result.StatusCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact(DisplayName = "Get SurveyResponse by responseId- Ok case")]
|
|
||||||
public async Task GetSurveyResponsesByResponseIdyAsync_ShouldReturnStatusCode200()
|
|
||||||
{
|
|
||||||
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
|
|
||||||
var mockResponse = await MockData.getOkResponse();
|
|
||||||
mockSurveyResponseService.Setup(service => service.GetSurveyResponseByIdAsync(1)).ReturnsAsync(mockResponse);
|
|
||||||
var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object);
|
|
||||||
var result = (OkObjectResult)await surveyResponseProvider.GetSurveyResponseByIdAsync(1);
|
|
||||||
Assert.Equal(200, result.StatusCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact(DisplayName = "Get Responses by maintenanceCenter and surveyId - NoContent Case")]
|
|
||||||
public async Task GetSurveyResponsesByResponseIdyAsync_ShouldReturnStatusCode204()
|
|
||||||
{
|
|
||||||
var mockResponse = await MockData.getResponse();
|
|
||||||
mockSurveyResponseService.Setup(service => service.GetSurveyResponseByIdAsync(1)).ReturnsAsync(mockResponse);
|
|
||||||
var surveyResponseProvider = new ResponsesController(mockSurveyResponseService.Object);
|
|
||||||
var result = (NoContentResult)await surveyResponseProvider.GetSurveyResponseByIdAsync(1);
|
|
||||||
Assert.Equal(204, result.StatusCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
|
|
||||||
[Fact(DisplayName = "Post Responses - Ok case")]
|
|
||||||
public async Task PostSurveyAsync_ShouldReturnStatusCode200()
|
|
||||||
{
|
|
||||||
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
|
|
||||||
var mockResponse = await MockData.getOkResponse(mockRequestObject);
|
|
||||||
mockSurveyResponseService.Setup(service => service.PostSurveyResponseAsync(mockRequestObject)).ReturnsAsync(mockResponse);
|
|
||||||
var surveyResponseController = new ResponsesController(mockSurveyResponseService.Object);
|
|
||||||
var result = (OkObjectResult)await surveyResponseController.PostSurveysAsync(mockRequestObject);
|
|
||||||
Assert.Equal(200, result.StatusCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact(DisplayName = "Post Responses - BadRequest case")]
|
|
||||||
public async Task PostSurveyAsync_ShouldReturnStatusCode400()
|
|
||||||
{
|
|
||||||
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
|
|
||||||
var mockResponse = await MockData.getResponse();
|
|
||||||
mockSurveyResponseService.Setup(service => service.PostSurveyResponseAsync(mockRequestObject)).ReturnsAsync(mockResponse);
|
|
||||||
var surveyResponseController = new ResponsesController(mockSurveyResponseService.Object);
|
|
||||||
var result = (BadRequestObjectResult)await surveyResponseController.PostSurveysAsync(mockRequestObject);
|
|
||||||
Assert.Equal(400, result.StatusCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact(DisplayName = "Put Responses - Ok case")]
|
|
||||||
public async Task PutSurveyAsync_ShouldReturnStatusCode200()
|
|
||||||
{
|
|
||||||
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
|
|
||||||
var mockResponse = await MockData.getOkResponse(mockRequestObject);
|
|
||||||
mockSurveyResponseService.Setup(service => service.PutSurveyResponseAsync(1, mockRequestObject)).ReturnsAsync(mockResponse);
|
|
||||||
var surveyResponseController = new ResponsesController(mockSurveyResponseService.Object);
|
|
||||||
var result = (OkObjectResult)await surveyResponseController.PutSurveyResponseAsync(1, mockRequestObject);
|
|
||||||
Assert.Equal(200, result.StatusCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact(DisplayName = "Put Responses - BadRequest case")]
|
|
||||||
public async Task PutSurveyAsync_ShouldReturnStatusCode404()
|
|
||||||
{
|
|
||||||
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
|
|
||||||
var mockResponse = await MockData.getResponse();
|
|
||||||
mockSurveyResponseService.Setup(service => service.PutSurveyResponseAsync(1, mockRequestObject)).ReturnsAsync(mockResponse); ;
|
|
||||||
var surveyResponseController = new ResponsesController(mockSurveyResponseService.Object);
|
|
||||||
var result = (BadRequestObjectResult)await surveyResponseController.PutSurveyResponseAsync(1, mockRequestObject);
|
|
||||||
Assert.Equal(400, result.StatusCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact(DisplayName = "Delete Responses - Ok case")]
|
|
||||||
public async Task DeleteSurveyAsync_ShouldReturnStatusCode200()
|
|
||||||
{
|
|
||||||
SurveyResponse mockRequestObject = await MockData.getSurveyResponseObject();
|
|
||||||
var mockResponse = await MockData.getOkResponse(mockRequestObject);
|
|
||||||
mockSurveyResponseService.Setup(service => service.DeleteSurveyResponseAsync(1)).ReturnsAsync(mockResponse);
|
|
||||||
var surveyResponseController = new ResponsesController(mockSurveyResponseService.Object);
|
|
||||||
var result = (OkObjectResult)await surveyResponseController.DeleteSurveyResponseAsync(1);
|
|
||||||
Assert.Equal(200, result.StatusCode);
|
|
||||||
}
|
|
||||||
|
|
||||||
[Fact(DisplayName = "Delete Responses - NotFound case")]
|
|
||||||
public async Task DeleteSurveyAsync_ShouldReturnStatusCode404()
|
|
||||||
{
|
|
||||||
var mockResponse = await MockData.getResponse();
|
|
||||||
mockSurveyResponseService.Setup(service => service.DeleteSurveyResponseAsync(1)).ReturnsAsync(mockResponse); ;
|
|
||||||
var surveyResponseController = new ResponsesController(mockSurveyResponseService.Object);
|
|
||||||
var result = (NotFoundResult)await surveyResponseController.DeleteSurveyResponseAsync(1);
|
|
||||||
Assert.Equal(404, result.StatusCode);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,80 +0,0 @@
|
|||||||
version: '3.4'
|
|
||||||
|
|
||||||
services:
|
|
||||||
answers:
|
|
||||||
image: santhoshsnair/damageassesmentapianswers:latest
|
|
||||||
environment:
|
|
||||||
- ASPNETCORE_ENVIRONMENT=Development
|
|
||||||
ports:
|
|
||||||
- "6001:80"
|
|
||||||
|
|
||||||
attachments:
|
|
||||||
image: santhoshsnair/damageassesmentapiattachments:latest
|
|
||||||
environment:
|
|
||||||
- ASPNETCORE_ENVIRONMENT=Development
|
|
||||||
ports:
|
|
||||||
- "6002:80"
|
|
||||||
|
|
||||||
|
|
||||||
employees:
|
|
||||||
image: santhoshsnair/damageassesmentapiemployees:latest
|
|
||||||
environment:
|
|
||||||
- ASPNETCORE_ENVIRONMENT=Development
|
|
||||||
ports:
|
|
||||||
- "6003:80"
|
|
||||||
|
|
||||||
|
|
||||||
locations:
|
|
||||||
image: santhoshsnair/damageassesmentapilocations:latest
|
|
||||||
environment:
|
|
||||||
- ASPNETCORE_ENVIRONMENT=Development
|
|
||||||
ports:
|
|
||||||
- "6004:80"
|
|
||||||
|
|
||||||
|
|
||||||
questions:
|
|
||||||
image: santhoshsnair/damageassesmentapiquestions:latest
|
|
||||||
environment:
|
|
||||||
- ASPNETCORE_ENVIRONMENT=Development
|
|
||||||
ports:
|
|
||||||
- "6005:80"
|
|
||||||
|
|
||||||
|
|
||||||
responses:
|
|
||||||
image: santhoshsnair/damageassesmentapisurveyresponses:latest
|
|
||||||
environment:
|
|
||||||
- ASPNETCORE_ENVIRONMENT=Development
|
|
||||||
- services__Answers=http://10.0.0.4:19081/dasapp/answers/
|
|
||||||
- services__Locations=http://10.0.0.4:19081/dasapp/locations/
|
|
||||||
- services__Questions=http://10.0.0.4:19081/dasapp/questions/
|
|
||||||
- services__Employees=http://10.0.0.4:19081/dasapp/employees/
|
|
||||||
- services__Attachments=http://10.0.0.4:19081/dasapp/attachments/
|
|
||||||
- services__Surveys=http://10.0.0.4:19081/dasapp/survey/
|
|
||||||
|
|
||||||
ports:
|
|
||||||
- "6006:80"
|
|
||||||
|
|
||||||
|
|
||||||
surveys:
|
|
||||||
image: santhoshsnair/damageassesmentapisurveys:latest
|
|
||||||
environment:
|
|
||||||
- ASPNETCORE_ENVIRONMENT=Development
|
|
||||||
ports:
|
|
||||||
- "6007:80"
|
|
||||||
|
|
||||||
|
|
||||||
doculinks:
|
|
||||||
image: santhoshsnair/damageassesmentapidoculinks:latest
|
|
||||||
environment:
|
|
||||||
- ASPNETCORE_ENVIRONMENT=Development
|
|
||||||
ports:
|
|
||||||
- "6009:80"
|
|
||||||
sqlserver:
|
|
||||||
image: mcr.microsoft.com/mssql/server:2019-latest
|
|
||||||
environment:
|
|
||||||
- SA_PASSWORD=your_password
|
|
||||||
- ACCEPT_EULA=Y
|
|
||||||
ports:
|
|
||||||
- "1433:1433"
|
|
||||||
volumes:
|
|
||||||
- ./sql_data:/var/opt/mssql/data
|
|
@ -9,9 +9,7 @@
|
|||||||
<DockerServiceName>damageassesment.api.answers</DockerServiceName>
|
<DockerServiceName>damageassesment.api.answers</DockerServiceName>
|
||||||
</PropertyGroup>
|
</PropertyGroup>
|
||||||
<ItemGroup>
|
<ItemGroup>
|
||||||
<None Include="docker-compos.tst.yml" />
|
|
||||||
<None Include="docker-compose.sql.yml" />
|
<None Include="docker-compose.sql.yml" />
|
||||||
<None Include="docker-compose.asf.yml" />
|
|
||||||
<None Include="docker-compose.override.yml">
|
<None Include="docker-compose.override.yml">
|
||||||
<DependentUpon>docker-compose.yml</DependentUpon>
|
<DependentUpon>docker-compose.yml</DependentUpon>
|
||||||
</None>
|
</None>
|
||||||
|
@ -10,7 +10,8 @@ $microservices = @(
|
|||||||
"DamageAssesment.Api.Locations",
|
"DamageAssesment.Api.Locations",
|
||||||
"DamageAssesment.Api.Questions",
|
"DamageAssesment.Api.Questions",
|
||||||
"DamageAssesment.Api.Responses",
|
"DamageAssesment.Api.Responses",
|
||||||
"DamageAssesment.Api.Surveys"
|
"DamageAssesment.Api.Surveys",
|
||||||
|
"DamageAssesment.Api.UsersAccess"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
Reference in New Issue
Block a user