예제 #1
0
        public IActionResult Session(int quizId, int questionId)
        {
            QuestionsAnswersViewModel questionsAnswers = new QuestionsAnswersViewModel {
            };

            questionsAnswers.Questions = db.Questions.Where(q => q.QuizId == quizId).ToList();
            foreach (Question question in questionsAnswers.Questions)
            {
                question.Answers = db.Answers.Where(a => a.QuestionId == question.QuestionId).ToList();
            }

            TempData["quizId"] = quizId;
            if (questionId == 0)
            {
                TempData["questionId"] = questionsAnswers.Questions.Select(q => q.QuestionId).FirstOrDefault();

                string userEmail = this.User.Identity.Name;
                User   user      = db.Users.FirstOrDefault(u => u.Email == userEmail);

                TimeSpan?ts         = db.Quizes.Where(q => q.QuizId == quizId).Select(q => q.QuizTime).FirstOrDefault();
                DateTime finishTime = DateTime.Now + (TimeSpan)ts;
                //Записать финиш тайм тоже в бд
                TempData["finishTime"] = finishTime;

                db.UserQuizzes.Add(new UserQuiz {
                    UserId = user.UserId, QuizId = quizId, StartTme = System.DateTime.Now, Points = 0, FinishTime = finishTime, RightAnswersAmount = 0, Finished = false
                });
                db.SaveChanges();

                return(View(questionsAnswers.Questions.First()));
            }

            return(View(questionsAnswers.Questions.FirstOrDefault(q => q.QuestionId == questionId)));
        }
예제 #2
0
        public int GetTestResultInPoints(QuestionsAnswersViewModel questionsAnswers, string testName)
        {
            var managerComputedTest = new ManagerComputedTestResultHandler();
            var testResultInPoints  = managerComputedTest.GetTestResultInPoints(questionsAnswers, testName);

            return(testResultInPoints);
        }
예제 #3
0

        
예제 #4
0
        public IActionResult Session(int chosenAnswer)
        {
            QuestionsAnswersViewModel questionsAnswers = new QuestionsAnswersViewModel {
            };

            questionsAnswers.Questions = db.Questions.Where(q => q.QuizId == (int)TempData.Peek("quizId")).ToList();
            foreach (Question q in questionsAnswers.Questions)
            {
                q.Answers = db.Answers.Where(a => a.QuestionId == q.QuestionId).ToList();
            }

            string userEmail = this.User.Identity.Name;
            User   user      = db.Users.FirstOrDefault(u => u.Email == userEmail);

            Question question    = db.Questions.FirstOrDefault(q => q.QuestionId == (int)TempData.Peek("quizId"));
            Answer   rightAnswer = db.Answers.FirstOrDefault(a => (a.Correct == true) && (a.QuestionId == (int)TempData.Peek("questionId")));

            UserQuiz userSession = (from uq in db.UserQuizzes
                                    where (uq.UserId == user.UserId) && (uq.QuizId == (int)TempData.Peek("quizId"))
                                    select uq).OrderBy(uq => uq.StartTme).LastOrDefault();

            if (chosenAnswer == rightAnswer.AnswerId)
            {
                userSession.Points             += question.QuestionPoints;
                userSession.RightAnswersAmount += 1;
                db.SaveChanges();
            }


            int nextQuestionId = questionsAnswers.Questions.SkipWhile(q => q.QuestionId != (int)TempData["questionId"])
                                 .Skip(1).Select(q => q.QuestionId).FirstOrDefault();

            if (nextQuestionId != 0)
            {
                TempData["questionId"] = nextQuestionId;
                return(RedirectToAction("Session", "QuizSession", new
                {
                    quizId = TempData.Peek("quizId"),
                    questionId = nextQuestionId
                }));
            }
            else
            {
                userSession.FinishTime = System.DateTime.Now;
                userSession.Finished   = true;
                db.SaveChanges();
                TempData["time"] = userSession.FinishTime;
                //Реализовать здесь обработку результата пользователя c учетом времени


                return(RedirectToAction("ShowQuizResults", "QuizSession", new {
                    quizId = TempData["quizId"]
                }));
            }
        }
예제 #5
0

        
예제 #6
0
 /// <summary>
 /// Расчет баллов для результирующих баллов для теста Тест Спилбергера
 /// </summary>
 /// <param name="questionsAnswers"> Перечень вопросов и ответов на них. </param>
 /// <param name="testName"> Наименование теста. </param>
 /// <returns></returns>
 public override int ComputedTestResult(QuestionsAnswersViewModel questionsAnswers, string testName)
 {
     if (testName.Equals("Тест Спилбергера"))
     {
         return(GetPoints(questionsAnswers));
     }
     else
     {
         return(base.ComputedTestResult(questionsAnswers, testName));
     }
 }
예제 #7
0
        public ActionResult Question(QuestionsAnswersViewModel model)
        {
            if (ModelState.IsValid)
            {
                model.Answers.Date   = DateTime.Now;
                model.Answers.Votes  = 0;
                model.Answers.UserID = User.Identity.GetUserId();
                db.Answers.Add(model.Answers);
                db.SaveChanges();
                return(RedirectToAction(model.Answers.QuestionID + ""));
            }

            model.Questions = db.Questions.Find(model.Answers.QuestionID);
            return(View(model));
        }
예제 #8
0
 /// <summary>
 /// Базовый обработчик, если не поддерживается формат документа, то записывает в лог и выдает Exception.
 /// </summary>
 /// <param name="questionsAnswers"> Входящий документа в виде массива байтов. </param>
 /// <param name="testName"> Название теста. </param>
 public virtual int ComputedTestResult(QuestionsAnswersViewModel questionsAnswers, string testName)
 {
     if (next != null)
     {
         return(next.ComputedTestResult(questionsAnswers, testName));
     }
     else
     {
         int sum = 0;
         foreach (var questionsAnswer in questionsAnswers.QuestionsAnswerList)
         {
             sum += questionsAnswer.AnswerValue;
         }
         return(sum);
     }
 }
예제 #9
0
        // GET: Index/Question/id
        public ActionResult Question(int id)
        {
            QuestionsAnswersViewModel qa = new QuestionsAnswersViewModel();

            qa.Questions = db.Questions.Find(id);

            if (qa.Questions == null)
            {
                return(HttpNotFound());
            }

            qa.Questions.Views += 1;
            db.SaveChanges();

            return(View(qa));
        }
예제 #10
0
        // GET: Profile
        // information about the user and a list of their questions and answers
        public new ActionResult Profile()
        {
            QuestionsAnswersViewModel qa = new QuestionsAnswersViewModel();

            qa.QuestionsList = db.Questions.Include(m => m.User).Where(x => x.User.UserName == User.Identity.Name).OrderByDescending(i => i.Date).ToList();
            qa.AnswersList   = db.Answers.Include(m => m.User).Where(x => x.User.UserName == User.Identity.Name).OrderByDescending(i => i.Date).ToList();

            if (qa.QuestionsList == null || qa.AnswersList == null)
            {
                return(HttpNotFound());
            }

            db.SaveChanges();

            return(View(qa));
        }
예제 #11
0
        protected override int GetPoints(QuestionsAnswersViewModel questionsAnswers)
        {
            int[] directQuestions    = new int[] { 3, 4, 6, 7, 9, 12, 13, 14, 17, 18, 22, 23, 24, 25, 28, 29, 31, 32, 34, 35, 37, 38, 40 };
            int[] backQuestions      = new int[] { 1, 2, 5, 8, 10, 11, 15, 16, 19, 20, 21, 26, 27, 30, 33, 36, 39 };
            int   sumDirectQuestions = 0;
            int   sumBackQuestions   = 0;

            foreach (var item in questionsAnswers.QuestionsAnswerList)
            {
                if (directQuestions.Any(x => x == item.SortLevel))
                {
                    sumDirectQuestions += item.AnswerValue;
                }

                if (backQuestions.Any(x => x == item.SortLevel))
                {
                    sumBackQuestions += item.AnswerValue;
                }
            }
            var result = sumDirectQuestions - sumBackQuestions + 40;

            return(result);
        }
예제 #12
0
 /// <summary>
 /// Алгоритм расчета баллов.
 /// </summary>
 /// <param name="questionsAnswers"></param>
 /// <returns></returns>
 protected abstract int GetPoints(QuestionsAnswersViewModel questionsAnswers);
예제 #13
0
 public async Task <PatientTestResult> CreateAndGetPatientTestResultAsnyc(int doctorId, int patientId, int testId, int testResultInPoints, QuestionsAnswersViewModel questionsAnswers)
 {
     return(await _testRepository.CreateAndGetPatientTestResultRepositoryAsnyc(doctorId, patientId, testId, testResultInPoints, questionsAnswers));
 }
예제 #14
0
        /// <summary>
        /// Маппинг массива данных Вопрос-Ответ. Сохранения данных в БД.
        /// </summary>
        /// <param name="patientId"> Идентификатор пациента. </param>
        /// <param name="testId"> Идентификатор теста. </param>
        /// <param name="questionsAnswers"> Входящий массив вопросов и ответов. </param>
        /// <returns> Записи БД Вопрос-Ответ. </returns>
        private async Task <ICollection <QuestionAnswer> > CreateQuestionsAnswersRepositoryAsync(int patientId, int testId, QuestionsAnswersViewModel questionsAnswers)
        {
            List <QuestionAnswer> questionAnswersList = new List <QuestionAnswer>();

            foreach (var item in questionsAnswers.QuestionsAnswerList)
            {
                QuestionAnswer questionAnswer = new QuestionAnswer()
                {
                    PatientId    = patientId,
                    TestId       = testId,
                    QuestionId   = item.QuestionId,
                    AnswersValue = item.AnswerValue
                };
                await _context.QuestionsAnswers.AddAsync(questionAnswer);

                await _context.SaveChangesAsync();

                questionAnswersList.Add(questionAnswer);
            }
            return(questionAnswersList);
        }
예제 #15
0
        public async Task <PatientTestResult> CreateAndGetPatientTestResultRepositoryAsnyc(int doctorId, int patientId, int testId, int testResultInPoints, QuestionsAnswersViewModel questionsAnswers)
        {
            var testResult = await _context.ProcessingInterpretationOfResults.SingleOrDefaultAsync(tr => tr.TestId == testId &&
                                                                                                   tr.MinValue <= testResultInPoints &&
                                                                                                   tr.MaxValue >= testResultInPoints);

            if (testResult == null)
            {
                throw new Exception("Не предвиденная ошибка, не верное расчитаны количество баллов");
            }

            var questionsAnswersList = await CreateQuestionsAnswersRepositoryAsync(patientId, testId, questionsAnswers);

            var patientTestResult = new PatientTestResult(doctorId, patientId, testId, testResultInPoints, testResult.Id, DateTime.Now, questionsAnswersList);

            await _context.PatientTestResult.AddAsync(patientTestResult);

            await _context.SaveChangesAsync();

            return(patientTestResult);
        }
예제 #16
0
        public async Task <IActionResult> CreateTestResult(int doctorId, int patientId, int testId, QuestionsAnswersViewModel questionsAnswers)
        {
            if (doctorId != int.Parse(User.FindFirst(ClaimTypes.NameIdentifier).Value))
            {
                return(Unauthorized("Пользователь не авторизован"));
            }

            var test = await _testService.GetTestAsync(testId);

            if (test == null)
            {
                BadRequest("Теста с указаным идентификаторм не существет");
            }

            var testResultInPoints = _testService.GetTestResultInPoints(questionsAnswers, test.Name);

            var patientTestResult = await _testService.CreateAndGetPatientTestResultAsnyc(doctorId, patientId, testId, testResultInPoints, questionsAnswers);

            return(Ok(patientTestResult));
        }
예제 #17
0
 /// <summary>
 /// Расчет баллов.
 /// </summary>
 /// <param name="questionsAnswers"> Входящий массив вопросов и ответов. </param>
 /// <param name="testName"> Название теста. </param>
 /// <returns></returns>
 public int GetTestResultInPoints(QuestionsAnswersViewModel questionsAnswers, string testName)
 {
     return(beckDepressionInventoryTestResultHandler.ComputedTestResult(questionsAnswers, testName));
 }
예제 #18
0
        public ActionResult Create([Bind(Include = "SecurityQuestionsID,AspNetUserID,QuestionID,Answer")] SecurityQuestion securityQuestion,
                                   string answer1, string answer2, string answer3)
        {
            string id = g_create_id;
            //Create an instance of a ViewModel:
            var vModel = new QuestionsAnswersViewModel();
            //Record any error:
            Boolean thereIsAnError = false;
            //Check if input is valid
            Boolean answer1SpecialCharatcer = ContainsSpecialChars(answer1);
            Boolean answer2SpecialCharatcer = ContainsSpecialChars(answer2);
            Boolean answer3SpecialCharatcer = ContainsSpecialChars(answer3);

            //Check input for answer1:
            //if answer has a special:
            if (answer1SpecialCharatcer)
            {
                ModelState.AddModelError("answer1", "The special characters like: ~, `, !, @, #, $, %, ^, &, *, (, ), +, =, \" are not allowed");
                thereIsAnError = true;
            }
            //Check input not empty
            else if (string.IsNullOrWhiteSpace(answer1))
            {
                ModelState.AddModelError("answer1", "The field for Answer 1 is required");
                thereIsAnError = true;
            }
            //Check for answer2 input:
            if (answer2SpecialCharatcer)
            {
                ModelState.AddModelError("answer2", "The special characters like: ~, `, !, @, #, $, %, ^, &, *, (, ), +, =, \" are not allowed");
                thereIsAnError = true;
            }
            //Check input not empty
            else if (string.IsNullOrWhiteSpace(answer2))
            {
                ModelState.AddModelError("answer2", "The field for Answer 2 is required");
                thereIsAnError = true;
            }

            //Check for answer3 input:
            if (answer3SpecialCharatcer)
            {
                ModelState.AddModelError("answer3", "The special characters like: ~, `, !, @, #, $, %, ^, &, *, (, ), +, =, \" are not allowed");
                thereIsAnError = true;
            }
            //Check input not empty
            else if (string.IsNullOrWhiteSpace(answer3))
            {
                ModelState.AddModelError("answer3", "The field for Answer 3 is required");
                thereIsAnError = true;
            }


            //if input is invalid, return view
            if (thereIsAnError)
            {
                return(View(vModel));
            }
            //else, store in db for the selected userID
            saveNewAnswers(answer1, answer2, answer3, id);
            //then go to home page:
            return(RedirectToAction("Index", ""));
        }