public async Task <IActionResult> Post([FromBody] SaveQuizDTO quiz)
        {
            try
            {
                //1 map save quiz dto naar quiz
                var mappedQuiz = _mapper.Map <Quiz>(quiz);

                if (mappedQuiz == null)
                {
                    return(NotFound());
                }

                //  2. ADD TO REPO

                _quizrepo.Create(mappedQuiz);

                // 3 . savechanges async
                await _quizrepo.SaveAsync();

                // 4. map to dto (niet save dto)
                var quizDto = _mapper.Map <QuizDTO>(mappedQuiz);

                // 5 . return created at action
                return(Ok(quizDto));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return(BadRequest());
            }
        }
Exemplo n.º 2
0
        public async Task <UserQuiz> SaveUserQuiz(List <int> choices, int id, string userId)
        {
            var userChoices = new List <UserChoice>();

            foreach (var choice in choices)
            {
                userChoices.Add(new UserChoice()
                {
                    ChoiceId = choice
                });
            }

            var correctChoicesFromQuiz = await _choiceRepo.GetCorrectChoiceByQuiz(id) as List <Choice>;

            var correctChoices = correctChoicesFromQuiz.Where(c => choices.Any(ch => ch == c.Id));
            var totalScore     = correctChoices.Sum(c => c.Question.ScoreValue);

            // Add new UserQuiz
            var userQuiz = new UserQuiz()
            {
                QuizId      = id,
                UserId      = userId,
                UserChoices = userChoices,
                Timestamp   = DateTime.Now,
                EndScore    = totalScore
            };

            //  savechanges
            _quizRepo.AddUserQuiz(userQuiz);
            await _quizRepo.SaveAsync();

            return(userQuiz);
        }
Exemplo n.º 3
0
        public async Task <IActionResult> CreateQuiz([Bind("Title,DifficultyId,Questions")] Quiz quiz)
        {
            try
            {
                if (quiz.DifficultyId == 0)
                {
                    quiz.DifficultyId = 1;
                }
                _quizRepo.Create(quiz);
                await _quizRepo.SaveAsync();

                //return View(quiz);
                return(RedirectToAction(nameof(Index)));
            }
            catch (Exception ex)
            {
                _logger.LogError(ex.Message);
                return(View("Error", new ErrorViewModel()
                {
                    RequestId = HttpContext.TraceIdentifier
                }));
            }
        }