public async Task <IActionResult> SendSurveyResponses([FromBody] SurveyAnswerRequest request) { Response <SurveyStat> response = new Response <SurveyStat>(); try { var isFaulted = IsAuthenticationFaulted(UserIdentity); if (isFaulted) { response = new Response <SurveyStat> { ResponseBody = new SuccessResponse <SurveyStat> { Data = null, ResponseCode = "E009", ResponseMessage = "You do not have the permission to carry out this operation, kindly login and try again." } }; return(Unauthorized(response.ResponseBody)); } if (request.Responses.Count == 0) { ModelState.AddModelError("questionId", "questionId is required!"); ModelState.AddModelError("optionId", "optionId is required!"); } if (!ModelState.IsValid) { var requestResponse = ApiResponseFormatter.RequestResponse(ModelState); return(BadRequest(requestResponse)); } User userCredentials; Survey survey; using (var _context = new MiniSurveyContext()) { userCredentials = await _context.Users.Where(x => x.Id == UserIdentity) .Include(x => x.UserResponses) .FirstOrDefaultAsync(); survey = await _context.Surveys.Where(a => a.Id == request.SurveyId).FirstOrDefaultAsync(); } if (userCredentials == null) { response = new Response <SurveyStat> { ResponseBody = new SuccessResponse <SurveyStat> { Data = null, ResponseCode = "E003", ResponseMessage = "You do not have the permission to submit your response. Kindly login or register to share your opinion." } }; return(Unauthorized(response.ResponseBody)); } if (survey == null) { response = new Response <SurveyStat> { ResponseBody = new SuccessResponse <SurveyStat> { Data = null, ResponseCode = "E012", ResponseMessage = "The survey you selected does not exist. Kindly try again later." } }; return(NotFound(response.ResponseBody)); } if (userCredentials.UserResponses.Count == 0) { List <Models.UserResponse> selectedResponses = new List <Models.UserResponse>(); foreach (var userResponse in request.Responses) { Models.UserResponse selectedResponse = new Models.UserResponse { QuestionId = userResponse.QuestionId, OptionId = userResponse.OptionId, UserId = userCredentials.Id, DateResponded = DateTime.UtcNow, SurveyId = request.SurveyId, TextResponse = userResponse.TextAnswer }; selectedResponses.Add(selectedResponse); } using (var _context = new MiniSurveyContext()) { _context.UserResponses.AddRange(selectedResponses); await _context.SaveChangesAsync(); } } List <Models.UserResponse> userResponses = new List <Models.UserResponse>(); List <Models.QuestionOption> questionOptions = new List <QuestionOption>(); using (var _context = new MiniSurveyContext()) { userResponses = await _context.UserResponses.ToListAsync(); questionOptions = await _context.QuestionOptions.Include(a => a.Question).Include(a => a.Option).ToListAsync(); } var totalUserIds = userResponses.Select(a => a.UserId).Distinct().ToList(); var totalQuestionIds = userResponses.Select(a => a.QuestionId).Distinct().ToList(); var totalUsersCount = totalUserIds.Count; var totalQuestionsCount = totalQuestionIds.Count; List <Poll> polls = new List <Poll>(); foreach (var questionId in totalQuestionIds) { var selectedQuestionOptions = questionOptions.Where(a => a.QuestionId == questionId); var questionResponses = userResponses.Where(a => a.QuestionId == questionId); var question = selectedQuestionOptions.FirstOrDefault().Question; List <OpinionPoll> questionOpinions = new List <OpinionPoll>(); if (selectedQuestionOptions != null) { foreach (var selectedQuestionOption in selectedQuestionOptions) { var option = selectedQuestionOption.Option; var responseCount = questionResponses.Count(a => a.OptionId == option.Id); var numberDivision = (double)responseCount / (double)totalUsersCount; var responsePercentage = numberDivision * 100; var roundedUpPercentage = Math.Round(responsePercentage, 1); OpinionPoll opinionPoll = new OpinionPoll { OptionId = option.Id, Option = option.Text, Percentage = roundedUpPercentage }; questionOpinions.Add(opinionPoll); } } Poll poll = new Poll { QuestionId = questionId, Question = question.Text, OpinionPolls = questionOpinions }; polls.Add(poll); } SurveyStat stat = new SurveyStat { Polls = polls, TotalParticipants = totalUsersCount, TotalQuestions = totalQuestionsCount }; response = new Response <SurveyStat> { ResponseBody = new SuccessResponse <SurveyStat> { Data = stat, ResponseCode = "00", ResponseMessage = "You have successfully shared your opinion in the survey. Kindly view our stats to compare your responses with those of others." } }; return(Ok(response.ResponseBody)); } catch (Exception) { response = new Response <SurveyStat> { ResponseBody = new SuccessResponse <SurveyStat> { Data = null, ResponseCode = "E001", ResponseMessage = "Sorry, we are unable to process your request at the moment, kindly try again later." } }; return(StatusCode(500, response.ResponseBody)); } }
public async Task <IActionResult> Register([FromBody] UserRequest request) { Response <RegisteredUserResponse> response = new Response <RegisteredUserResponse>(); try { if (!ModelState.IsValid) { var requestResponse = ApiResponseFormatter.RequestResponse(ModelState); return(BadRequest(requestResponse)); } User userCredentials; DateTime dateRegistered; using (var _context = new MiniSurveyContext()) { userCredentials = await _context.Users.Where(x => x.EmailAddress == request.Email.Trim()) .Include(x => x.UserResponses) .FirstOrDefaultAsync(); } if (userCredentials == null) { var userRoleId = (int)Enums.Roles.User; using (var _context = new MiniSurveyContext()) { dateRegistered = DateTime.UtcNow; _context.Users.Add(new Models.User { Name = request.Name, EmailAddress = request.Email.Trim(), PasswordHash = request.Password, DateRegistered = dateRegistered, RoleId = userRoleId }); await _context.SaveChangesAsync(); } userCredentials = new User { Name = request.Name, DateRegistered = dateRegistered, EmailAddress = request.Email, RoleId = userRoleId }; } response = new Response <RegisteredUserResponse> { ResponseBody = new SuccessResponse <RegisteredUserResponse> { Data = new RegisteredUserResponse { User = new Dto.UserResponse { Email = userCredentials.EmailAddress, Name = userCredentials.Name, DateRegistered = userCredentials.DateRegistered }, Role = new DefaultResponse { Id = userCredentials.RoleId, Value = Enums.Roles.User.ToString() } }, ResponseCode = "00", ResponseMessage = "You have been successfully enrolled to participate in the survey." } }; return(Ok(response.ResponseBody)); } catch (Exception) { response = new Response <RegisteredUserResponse> { ResponseBody = new SuccessResponse <RegisteredUserResponse> { Data = null, ResponseCode = "E001", ResponseMessage = "Sorry, we are unable to process your request at the moment, kindly try again later." } }; return(StatusCode(500, response.ResponseBody)); } }
public async Task <IActionResult> CreateSurvey([FromBody] SurveyRequest request) { Response <SurveyResponse> response = new Response <SurveyResponse>(); try { var isFaulted = IsAuthenticationFaulted(UserIdentity); if (isFaulted) { response = new Response <SurveyResponse> { ResponseBody = new SuccessResponse <SurveyResponse> { Data = null, ResponseCode = "E009", ResponseMessage = "You do not have the permission to carry out this operation, kindly login and try again." } }; return(Unauthorized(response.ResponseBody)); } if (!ModelState.IsValid) { var requestResponse = ApiResponseFormatter.RequestResponse(ModelState); return(BadRequest(requestResponse)); } Survey survey = new Survey { DateCreated = DateTime.UtcNow, Description = request.Description, Status = SurveyStatus.Open.ToString(), Title = request.Title }; using (var _context = new MiniSurveyContext()) { _context.Surveys.Add(survey); await _context.SaveChangesAsync(); } SurveyResponse surveyResponse = new SurveyResponse { Id = survey.Id, Title = survey.Title, DateCreated = survey.DateCreated, Description = survey.Description, Status = survey.Status }; response = new Response <SurveyResponse> { ResponseBody = new SuccessResponse <SurveyResponse> { Data = surveyResponse, ResponseCode = "00", ResponseMessage = "You have successfully created a survey. Kindly proceed to add questions to the survey." } }; return(Ok(response.ResponseBody)); } catch (Exception) { response = new Response <SurveyResponse> { ResponseBody = new SuccessResponse <SurveyResponse> { Data = null, ResponseCode = "E001", ResponseMessage = "Sorry, we are unable to process your request at the moment, kindly try again later." } }; return(StatusCode(500, response.ResponseBody)); } }
public async Task <IActionResult> EditSurvey([FromBody] SurveyUpdateRequest request) { Response <SurveyResponse> response = new Response <SurveyResponse>(); try { var isFaulted = IsAuthenticationFaulted(UserIdentity); if (isFaulted) { response = new Response <SurveyResponse> { ResponseBody = new SuccessResponse <SurveyResponse> { Data = null, ResponseCode = "E009", ResponseMessage = "You do not have the permission to carry out this operation, kindly login and try again." } }; return(Unauthorized(response.ResponseBody)); } if (!ModelState.IsValid) { var requestResponse = ApiResponseFormatter.RequestResponse(ModelState); return(BadRequest(requestResponse)); } Survey survey; using (var _context = new MiniSurveyContext()) { survey = await _context.Surveys.Where(a => a.Id == request.Id).FirstOrDefaultAsync(); survey.Title = request.Title; survey.Description = request.Description; await _context.SaveChangesAsync(); } SurveyResponse surveyResponse = new SurveyResponse { Id = survey.Id, Title = survey.Title, DateCreated = survey.DateCreated, Description = survey.Description, Status = survey.Status }; response = new Response <SurveyResponse> { ResponseBody = new SuccessResponse <SurveyResponse> { Data = surveyResponse, ResponseCode = "00", ResponseMessage = "You have successfully updated the survey details." } }; return(Ok(response.ResponseBody)); } catch (Exception) { response = new Response <SurveyResponse> { ResponseBody = new SuccessResponse <SurveyResponse> { Data = null, ResponseCode = "E001", ResponseMessage = "Sorry, we are unable to process your request at the moment, kindly try again later." } }; return(StatusCode(500, response.ResponseBody)); } }
public async Task <IActionResult> Login([FromBody] LoginRequest request) { Response <RegisteredUserResponse> response = new Response <RegisteredUserResponse>(); try { if (!ModelState.IsValid) { var requestResponse = ApiResponseFormatter.RequestResponse(ModelState); return(BadRequest(requestResponse)); } User userCredentials; DateTime dateRegistered; using (var _context = new MiniSurveyContext()) { userCredentials = await _context.Users.Where(x => x.EmailAddress == request.Email.Trim()) .FirstOrDefaultAsync(); } if (userCredentials == null) { response = new Response <RegisteredUserResponse> { ResponseBody = new SuccessResponse <RegisteredUserResponse> { Data = null, ResponseCode = "E001", ResponseMessage = "Your email and password combination was incorrect, kindly try again later." } }; return(Unauthorized(response.ResponseBody)); } bool isPassword = userCredentials != null && _cryptographyService.ValidateHash(request.Password, userCredentials.PasswordSalt, userCredentials.PasswordHash); if (!isPassword) { response = new Response <RegisteredUserResponse> { ResponseBody = new SuccessResponse <RegisteredUserResponse> { Data = null, ResponseCode = "E001", ResponseMessage = "Your email and password combination was incorrect, kindly try again later." } }; return(Unauthorized(response.ResponseBody)); } var identity = _jwtFactory.GenerateClaimsIdentity(userCredentials.EmailAddress, userCredentials.Id.ToString()); var jwtToken = await ValueGenerator.GenerateJwt(identity, _jwtFactory, userCredentials.EmailAddress, _jwtOptions.Value, new JsonSerializerSettings { Formatting = Formatting.None }); // deserialize generated auth token to be passed to client application. var authToken = JsonConvert.DeserializeObject <Token>(jwtToken); response = new Response <RegisteredUserResponse> { ResponseBody = new SuccessResponse <RegisteredUserResponse> { Data = new RegisteredUserResponse { User = new Dto.UserResponse { Email = userCredentials.EmailAddress, Name = userCredentials.Name, DateRegistered = userCredentials.DateRegistered }, Role = new DefaultResponse { Id = userCredentials.RoleId, Value = HelperFunctions.GetRole(userCredentials.RoleId) } }, ResponseCode = "00", ResponseMessage = "You have been successfully enrolled to participate in the survey." } }; return(Ok(response.ResponseBody)); } catch (Exception) { response = new Response <RegisteredUserResponse> { ResponseBody = new SuccessResponse <RegisteredUserResponse> { Data = null, ResponseCode = "E001", ResponseMessage = "Sorry, we are unable to process your request at the moment, kindly try again later." } }; return(StatusCode(500, response.ResponseBody)); } }