Update to Async Attachement, Answer and Update Multiple Answers submission - backlog #288

This commit is contained in:
Reginald Cherenfant Jasmin
2023-08-27 11:55:58 -04:00
parent 5a641ff3aa
commit 96ccb96bf1
50 changed files with 166 additions and 1087 deletions

View File

@ -180,10 +180,10 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers
/// <summary>
/// POST request for submitting survey with multiple answers.
/// </summary>
/// <param name="answers">The answers to be submitted for the survey.</param>
/// <param name="request">The answers to be submitted for the survey.</param>
[HttpPost("SurveyResponses/Answers")]
public async Task<ActionResult> PostSurveyAnswersAsync(AnswerRequest answers)
public async Task<ActionResult> PostSurveyAnswersAsync(Request request)
{
/* var result = await this.surveyResponseProvider.PostSurveyAnswersAsync(surveyAnswers);
if (result.IsSuccess)
@ -191,7 +191,7 @@ namespace DamageAssesment.Api.SurveyResponses.Controllers
return Ok(result.SurveyResponse);
}
return BadRequest(result.ErrorMessage);*/
var result = await this.surveyResponseProvider.PostSurveyAnswersAsync(answers);
var result = await this.surveyResponseProvider.PostSurveyAnswersAsync(request);
if (result.IsSuccess)
return Ok(result.SurveyResponse);

View File

@ -10,5 +10,13 @@ namespace DamageAssesment.Api.SurveyResponses.Db
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Entity<SurveyResponse>()
.Property(item => item.Id)
.ValueGeneratedOnAdd();
}
}
}

View File

@ -17,7 +17,7 @@ namespace DamageAssesment.Api.SurveyResponses.Interfaces
Task<(bool IsSuccess, dynamic SurveyResponses, string ErrorMessage)> GetSurveyResponsesByMaintenanceCenterAsync(int surveyId);
Task<(bool IsSuccess, dynamic SurveyResponses, string ErrorMessage)> GetResponsesByAnswerAsync(int surveyId, int questionId, string answer);
Task<(bool IsSuccess, Models.SurveyResponse SurveyResponse, string ErrorMessage)> PostSurveyAnswersAsync(Models.AnswerRequest answers);
Task<(bool IsSuccess, Models.SurveyResponse SurveyResponse, string ErrorMessage)> PostSurveyAnswersAsync(Request request);
}
}

View File

@ -2,9 +2,9 @@
{
public class AnswerRequest
{
public int SurveyId { get; set; }
public string LocationId { get; set; }
public string EmployeeId { get; set; }
public List<QuestionRequest> Answers { get; set; }
public int QuestionId { get; set; }
public string AnswerText { get; set; }
public string Comment { get; set; }
public List<FileModel> PostedFiles { get; set; } = new List<FileModel>();
}
}

View File

@ -17,7 +17,7 @@ namespace DamageAssesment.Api.SurveyResponses.Models
public bool Key { get; set; }
public int? SurveyId { get; set; }
public string QuestionGroup { get; set; }
//public string QuestionGroup { get; set; }
public int CategoryId { get; set; }
// public int? Survey_SurveyID { get; set; }
}

View File

@ -1,10 +0,0 @@
namespace DamageAssesment.Api.SurveyResponses.Models
{
public class QuestionRequest
{
public int QuestionId { get; set; }
public string AnswerText { get; set; }
public string Comment { get; set; }
public List<FileModel> PostedFiles { get; set; } = new List<FileModel>();
}
}

View File

@ -0,0 +1,10 @@
namespace DamageAssesment.Api.SurveyResponses.Models
{
public class Request
{
public int SurveyId { get; set; }
public string LocationId { get; set; }
public string EmployeeId { get; set; }
public List<AnswerRequest> Answers { get; set; }
}
}

View File

@ -4,6 +4,7 @@ using DamageAssesment.Api.SurveyResponses.Providers;
using Microsoft.AspNetCore.DataProtection.XmlEncryption;
using Microsoft.EntityFrameworkCore;
using Polly;
using System.Net.Http;
using System.Reflection;
var builder = WebApplication.CreateBuilder(args);

View File

@ -7,6 +7,8 @@ using System.Data.Common;
using System.Security.Cryptography;
using System.Text.Json.Nodes;
using System.Text;
using System.Net.Http.Headers;
using System;
namespace DamageAssesment.Api.SurveyResponses.Providers
{
@ -42,8 +44,8 @@ namespace DamageAssesment.Api.SurveyResponses.Providers
try
{
httpClient.BaseAddress = new Uri(urlBase);
var response = await httpClient.GetAsync("/api/AnswersByResponse/"+ responseId);
var response = await httpClient.GetAsync("/api/AnswersByResponse/" + responseId);
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
var answers = JsonConvert.DeserializeObject<List<Answer>>(responseString);
@ -63,19 +65,26 @@ namespace DamageAssesment.Api.SurveyResponses.Providers
{
try
{
httpClient.BaseAddress = new Uri(urlBase);
var url = urlBase + ressource;
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var jsonObject = JsonConvert.SerializeObject(answer);
var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(ressource,content);
request.Content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
var response = await httpClient.SendAsync(request, CancellationToken.None);
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
var answers = JsonConvert.DeserializeObject<Answer>(responseString);
if (answers == null) {
if (answers == null)
{
logger?.LogError($"Answer cannot be added - Ref: AnswerServiceProvider.PostAnswersAsync()");
return null;
}
}
else return answers;
}
catch (Exception ex)
{

View File

@ -4,6 +4,7 @@ using DamageAssesment.Api.SurveyResponses.Models;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Runtime.Intrinsics.Arm;
using System.Text;
@ -40,10 +41,16 @@ namespace DamageAssesment.Api.SurveyResponses.Providers
{
try
{
httpClient.BaseAddress = new Uri(urlBase);
var url = urlBase + ressource;
var request = new HttpRequestMessage(HttpMethod.Post, url);
request.Headers.Accept.Clear();
request.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
//request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", token);
var jsonObject = JsonConvert.SerializeObject(attachmentInfo);
var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
var response = await httpClient.PostAsync(ressource, content);
request.Content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
var response = await httpClient.SendAsync(request, CancellationToken.None);
response.EnsureSuccessStatusCode();
var responseString = await response.Content.ReadAsStringAsync();
var attachments = JsonConvert.DeserializeObject<IEnumerable<Attachment>>(responseString);

View File

@ -4,7 +4,9 @@ using DamageAssesment.Api.SurveyResponses.Interfaces;
using DamageAssesment.Api.SurveyResponses.Models;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Internal;
using Newtonsoft.Json;
using System.Diagnostics;
using System.Text;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory;
namespace DamageAssesment.Api.SurveyResponses.Providers
@ -251,7 +253,6 @@ namespace DamageAssesment.Api.SurveyResponses.Providers
answers = new List<Models.SurveyResponse>();
return (true, answers, "Empty object returned");
}
}
catch (Exception ex)
{
@ -266,16 +267,16 @@ namespace DamageAssesment.Api.SurveyResponses.Providers
{
if (surveyResponse != null)
{
var surveyResponses = await surveyResponseDbContext.SurveyResponses.ToListAsync();
surveyResponse.Id = surveyResponses.Count + 1;
surveyResponseDbContext.SurveyResponses.Add(mapper.Map<Models.SurveyResponse, Db.SurveyResponse>(surveyResponse));
surveyResponseDbContext.SaveChanges();
var _surveyResponse = mapper.Map<Models.SurveyResponse, Db.SurveyResponse>(surveyResponse);
surveyResponseDbContext.SurveyResponses.Add(_surveyResponse);
await surveyResponseDbContext.SaveChangesAsync();
surveyResponse.Id = _surveyResponse.Id;
return (true, surveyResponse, "Request Successful");
}
else
{
logger?.LogInformation($"SurveyResponseID={surveyResponse.Id} cannot be added");
return (false, null, "Survey cannot be added");
logger?.LogInformation($"SurveyResponse cannot be added");
return (false, null, "SurveyResponse cannot be added");
}
}
catch (Exception ex)
@ -299,7 +300,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers
_SurveyResponse.SurveyId = SurveyResponse.SurveyId;
_SurveyResponse.EmployeeId = SurveyResponse.EmployeeId;
_SurveyResponse.LocationId = SurveyResponse.LocationId;
surveyResponseDbContext.SaveChanges();
await surveyResponseDbContext.SaveChangesAsync();
return (true, mapper.Map<Db.SurveyResponse, Models.SurveyResponse>(_SurveyResponse), "Successful");
}
else
@ -331,7 +332,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers
if (_SurveyResponse != null)
{
surveyResponseDbContext.Remove(_SurveyResponse);
surveyResponseDbContext.SaveChanges();
await surveyResponseDbContext.SaveChangesAsync();
return (true, mapper.Map<Db.SurveyResponse, Models.SurveyResponse>(_SurveyResponse), "Successful");
}
else
@ -458,7 +459,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers
ans.Id,
ans.AnswerText,
ans.Comment,
Questions = (from q in questions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.QuestionGroup, q.Questions }).SingleOrDefault(),
Questions = (from q in questions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Questions }).SingleOrDefault(),
Attachments = from att in attachments where att.AnswerId == ans.Id select new { att.Id, att.URI }
}
};
@ -503,7 +504,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers
ans.QuestionId,
ans.AnswerText,
ans.Comment,
Questions = (from q in surveyQuestions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.QuestionGroup, q.Questions }).SingleOrDefault(),
Questions = (from q in surveyQuestions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Questions }).SingleOrDefault(),
Attachments = from att in attachments where att.AnswerId == ans.Id select new { att.Id, att.URI }
}
@ -546,7 +547,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers
ans.QuestionId,
ans.AnswerText,
ans.Comment,
Questions = (from q in questions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.QuestionGroup, q.Questions }).SingleOrDefault(),
Questions = (from q in questions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Questions }).SingleOrDefault(),
Attachments = from att in attachments where att.AnswerId == ans.Id select new { att.Id, att.URI }
}
};
@ -650,7 +651,7 @@ namespace DamageAssesment.Api.SurveyResponses.Providers
ans.Id,
ans.AnswerText,
ans.Comment,
Questions = (from q in surveyQuestions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.QuestionGroup, q.Questions }).SingleOrDefault(),
Questions = (from q in surveyQuestions where q.Id == ans.QuestionId select new { q.Id, q.QuestionNumber, q.CategoryId, q.Questions }).SingleOrDefault(),
Attachments = from att in attachments where att.AnswerId == ans.Id select new { att.Id, att.URI }
}
};
@ -709,67 +710,75 @@ namespace DamageAssesment.Api.SurveyResponses.Providers
}
bool ProcessAnswers(QuestionRequest questionRequest, int surveyResponseId)
async Task<bool> ProcessAnswers(AnswerRequest answerRequest, int surveyResponseId)
{
if (questionRequest != null)
if (answerRequest != null)
{
var answer = answerServiceProvider.PostAnswersAsync(new Answer {QuestionId = questionRequest.QuestionId, AnswerText = questionRequest.AnswerText, Comment = questionRequest.Comment, SurveyResponseId = surveyResponseId });
if (answer != null)
{
List<AnswerInfo> listAnswerInfo = new List<AnswerInfo>();
listAnswerInfo.Add(new AnswerInfo { AnswerId = answer.Id, postedFiles = questionRequest.PostedFiles });
var attachments = attachmentServiceProvider.PostAttachmentsAsync(new AttachmentInfo { ResponseId = surveyResponseId, Answers = listAnswerInfo });
var answer = await answerServiceProvider.PostAnswersAsync(new Models.Answer {QuestionId = answerRequest.QuestionId, AnswerText = answerRequest.AnswerText, Comment = answerRequest.Comment, SurveyResponseId = surveyResponseId });
if (answer != null)
{
List<AnswerInfo> listAnswerInfo = new List<AnswerInfo>();
listAnswerInfo.Add(new AnswerInfo { AnswerId = answer.Id, postedFiles = answerRequest.PostedFiles });
var attachments = attachmentServiceProvider.PostAttachmentsAsync(new AttachmentInfo { ResponseId = surveyResponseId, Answers = listAnswerInfo });
string message = $"Answer for question {questionRequest.QuestionId} saved to the database";
logger?.LogInformation(message);
return (true);
}
else
{
string message = $"Answer for question {questionRequest.QuestionId} cannot be saved to the database";
logger?.LogInformation(message);
return (false);
}
string message = $"Answer for question {answerRequest.QuestionId} saved to the database";
logger?.LogInformation(message);
return (true);
}
else
{
string message = $"Answer for question {answerRequest.QuestionId} cannot be saved to the database";
logger?.LogInformation(message);
return (false);
}
}
else
{
var message = $"Answer for question {questionRequest.QuestionId} cannot be saved to the database - questionRequest object is null";
var message = $"Answer for question {answerRequest.QuestionId} cannot be saved to the database - answerRequest object is null";
logger?.LogInformation(message);
return (false);
}
}
public async Task<(bool IsSuccess, Models.SurveyResponse SurveyResponse, string ErrorMessage)> PostSurveyAnswersAsync(Models.AnswerRequest answers)
public async Task<(bool IsSuccess, Models.SurveyResponse SurveyResponse, string ErrorMessage)> PostSurveyAnswersAsync(Models.Request request)
{
try
{
if (answers != null)
if (request != null)
{
var response = await PostSurveyResponseAsync(new Models.SurveyResponse { Id = 0, SurveyId = answers.SurveyId, EmployeeId = answers.EmployeeId, LocationId = answers.LocationId });
var response = await PostSurveyResponseAsync(new Models.SurveyResponse {SurveyId = request.SurveyId, EmployeeId = request.EmployeeId, LocationId = request.LocationId });
if (response.IsSuccess)
{
var surveyResponse = response.SurveyResponse;
var tasks = request.Answers.Select(x => ProcessAnswers(x,surveyResponse.Id));
var answerTasks = new List<Task>(); //new List<string>();
//var tasks = answers.Answers.Select(x => ProcessAnswers(x,surveyResponse.SurveyResponseID));
foreach (QuestionRequest ans in answers.Answers)
{
ProcessAnswers(ans, surveyResponse.Id);
// foreach (AnswerRequest ans in request.Answers)
// {
// answer = new Models.Answer { QuestionId = ans.QuestionId, AnswerText = ans.AnswerText, Comment = ans.Comment, SurveyResponseId = surveyResponse.Id };
//var content = new StringContent(jsonObject.ToString(), Encoding.UTF8, "application/json");
//await Task.Delay(500);
// var rep = await answerServiceProvider.PostAnswersAsync(answer);
// var jsonObject = JsonConvert.SerializeObject(rep);
//x = x + jsonObject.ToString() + " ";
//i++;
// answer = new Models.Answer { QuestionId = ans.QuestionId, AnswerText = ans.AnswerText, Comment = ans.Comment, SurveyResponseId = surveyResponse.Id };
// await answerServiceProvider.PostAnswersAsync(answer);
//ProcessAnswers(ans, surveyResponse.Id);
//var stopwatch = new Stopwatch();
//stopwatch.Start();
// var task = Task.Run(() => ProcessAnswers(ans, surveyResponse.Id));
//var task = await ProcessAnswers(ans, surveyResponse.Id);
//answerTasks.Add(task);
//stopwatch.Stop();
//answerTasks.Add(ProcessAnswers(ans, surveyResponse.Id));
}
//await Task.WhenAll(answerTasks);
// }
await Task.WhenAll(tasks);
return (true, surveyResponse, null);
}
else