Пример #1
0
 public static Answer Map(AnswerViewModel viewModel)
 {
     //Answer answer = new Answer();
     //answer.Id = viewModel.Id;
     //answer.UserId = viewModel.AuthorId;
     //answer.QuestionId = viewModel.QuestionId;
     //answer.Text = viewModel.Text;
     //answer.PostedDate = viewModel.PostedDate
     var model = mapper.Map(viewModel);
     model.UserId = viewModel.AuthorId;
     model.QuestionId = viewModel.QuestionId;
     return model;
 }
Пример #2
0
 protected override void DoSetup()
 {
     _answerForTest = JsonConvert.DeserializeObject <AnswerViewModel>(FileHelper.ReadFileFromResources("TestAnswer"));
 }
Пример #3
0
 public ActionResult SaveAnswerJson(AnswerViewModel answer)
 {
     p_repo.SaveAnswer(answer);
     return(Json(answer));
 }
 public ActionResult EditAnswer(AnswerViewModel a)
 {
     AnswerViewModel answerFromBase = answerService.GetAnswerEntity(a.Id).ToMvcAnswer();
     answerFromBase.AnswerValue = a.AnswerValue;
     a = answerFromBase;
     QuestionViewModel q = questionService.GetById(a.QuestionId).ToMvcQuestion();
     var post = Request.Form;
     int j = 0;
     for (int i = 0; i < q.Items.Count; i++)
     {
         switch(q.Items[i].ItemType)
         {
             case DisplayType.Text:
                 break;
             case DisplayType.CheckBox:
                 a.Items[j].Value = post[i.ToString()] != null ? "true" : "false";
                 j++;
                 break;
             case DisplayType.RadioButton:
                 a.Items[j].Value = post[i.ToString()] != null ? "true" : "false";
                 j++;
                 break;
             case DisplayType.TextBox:
                 a.Items[j].Value = post[i.ToString()];
                 j++;
                 break;
         }
     }
     answerService.UpdateAnswer(a.ToBllAnswer());
     ViewBag.Question = questionService.GetById(a.QuestionId).ToMvcQuestion();
     return View(a);
 }
Пример #5
0
 public PropertiesInterceptor(AnswerViewModel viewModel)
 {
     this.viewModel             = viewModel;
     viewModel.PropertyChanged += (sender, args) => DoStuff();
 }
Пример #6
0
        public async Task <IActionResult> Details(int questionId)
        {
            try
            {
                var simpleQuestion = await _repository.GetQuestionByIdWithoutDetailsAsync(questionId);

                if (simpleQuestion == null)
                {
                    Response.StatusCode      = 404;
                    ViewData["ErrorMessage"] = "404 Resource not found.";
                    return(View("Error"));
                }
                var question = await _repository.GetQuestionByIdAsync(questionId);

                // pack question comments
                var questionCommentsViewModel = new List <QuestionCommentViewModel>();
                if (question.QuestionComments != null && question.QuestionComments.Count != 0)
                {
                    questionCommentsViewModel = _mapper.Map <List <QuestionComment>, List <QuestionCommentViewModel> >(question.QuestionComments);
                }
                // pack Tags
                List <int> tagIds = await _repository.GetTagIdsForQuestionId(questionId);

                List <Tag> tagsFromDb = await _repository.GetTagsFromListFromDb(tagIds);

                var questionTagsViewModel = _mapper.Map <List <Tag>, List <TagViewModel> >(tagsFromDb);

                // pack answersVM with commentsVM
                var answersViewModel = new List <AnswerViewModel>();         // create answersVM List to attach to qVM

                if (question.Answers != null && question.Answers.Count != 0) // if the q has answers, proceed with process
                {
                    foreach (var answer in question.Answers)                 // for each answer (not VM) in the list
                    {
                        AnswerViewModel tempAnswerVM = _mapper.Map <Answer, AnswerViewModel>(answer);
                        // pack comments
                        if (answer.AnswerComments != null && answer.AnswerComments.Count != 0) // if the answer has comments, proceed with process
                        {
                            var answerCommentsVM = _mapper.Map <List <AnswerComment>, List <AnswerCommentViewModel> >(answer.AnswerComments);
                            tempAnswerVM.AnswerComments = answerCommentsVM;
                        }
                        // add tempAnswerVM to the list answersVM
                        answersViewModel.Add(tempAnswerVM);
                    }
                }
                var questionViewModel = _mapper.Map <Question, QuestionViewModel>(question);
                questionViewModel.Answers          = answersViewModel;
                questionViewModel.QuestionComments = questionCommentsViewModel;
                questionViewModel.Tags             = questionTagsViewModel;

                return(View("Details", questionViewModel));
            }
            catch (DbUpdateException dbex)
            {
                ViewData["ErrorMessage"] = "DB issue - " + dbex.Message;
                return(View("Error"));
            }
            catch (Exception ex)
            {
                ViewData["ErrorMessage"] = ex.Message;
                return(View("Error"));
            }
        }
Пример #7
0
        public ActionResult PostAnswer(AnswerViewModel model)
        {
            if (model.token == null)
            {
                TempData["message"] = "You have invalid token. Please re-login and try again.";
                return(RedirectToAction("Index", "Login"));
            }

            using (CyberSchoolEntities context = new CyberSchoolEntities())
            {
                try
                {
                    int            isCorrect    = 0;
                    TestEntry      objTestEntry = context.TestEntry.Where(x => x.Token == model.token).FirstOrDefault();
                    List <Answers> objAnswerList;
                    if (objTestEntry.TotalMarks == null)
                    {
                        objTestEntry.TotalMarks = 0;
                    }
                    if (objTestEntry.RightAnswers != null)
                    {
                        string answers = objTestEntry.RightAnswers;
                        objAnswerList = JsonConvert.DeserializeObject <List <Answers> >(answers);
                        if (objAnswerList.Any(x => x.QuestionID == model.QuestionID))
                        {
                            var updateChoiceID = objAnswerList.FirstOrDefault(x => x.QuestionID == model.QuestionID);
                            if (updateChoiceID != null)
                            {
                                if (model.CorrectAnswer == model.choiceID && updateChoiceID.ChoiceID != model.choiceID)
                                {
                                    updateChoiceID.IsCorrect = 1;
                                    objTestEntry.TotalMarks += model.mark;
                                }
                                else
                                {
                                    if (updateChoiceID.ChoiceID == model.CorrectAnswer && model.CorrectAnswer != model.choiceID)
                                    {
                                        updateChoiceID.IsCorrect = 0;
                                        objTestEntry.TotalMarks -= model.mark;
                                    }
                                }
                                updateChoiceID.ChoiceID = model.choiceID;
                                //updateChoiceID.QuestionNumber = model.QuestionNumber;

                                objTestEntry.RightAnswers         = JsonConvert.SerializeObject(objAnswerList.ToList());
                                context.Entry(objTestEntry).State = EntityState.Modified;
                                context.SaveChanges();
                            }
                        }
                        else
                        {
                            if (model.CorrectAnswer == model.choiceID)
                            {
                                isCorrect = 1;
                            }
                            else
                            {
                                isCorrect = 0;
                            }
                            objAnswerList.Add(new Answers {
                                QuestionID = model.QuestionID, ChoiceID = model.choiceID, IsCorrect = isCorrect, QuestionNumber = model.QuestionNumber
                            });

                            if (isCorrect == 1)
                            {
                                objTestEntry.TotalMarks += model.mark;
                            }
                            objTestEntry.RightAnswers         = JsonConvert.SerializeObject(objAnswerList.ToList());
                            context.Entry(objTestEntry).State = EntityState.Modified;
                            context.SaveChanges();
                        }
                    }
                    else
                    {
                        objAnswerList = new List <Answers>();
                        if (model.CorrectAnswer == model.choiceID)
                        {
                            isCorrect = 1;
                        }
                        else
                        {
                            isCorrect = 0;
                        }
                        objAnswerList.Add(new Answers {
                            QuestionID = model.QuestionID, ChoiceID = model.choiceID, IsCorrect = isCorrect, QuestionNumber = model.QuestionNumber
                        });

                        if (isCorrect == 1)
                        {
                            objTestEntry.TotalMarks = model.mark;
                        }
                        objTestEntry.RightAnswers         = JsonConvert.SerializeObject(objAnswerList.ToList());
                        context.Entry(objTestEntry).State = EntityState.Modified;
                        context.SaveChanges();
                    }

                    model.AnswerList = objAnswerList;
                    //model.AnswerList.Add(model.choiceID.ToString());
                    string answerModel = JsonConvert.SerializeObject(model.AnswerList.ToList());
                }
                catch (Exception)
                {
                    TempData["dbError"] = "Server Error. Please Login again.";
                    return(RedirectToAction("Index", "Login"));
                }
            }

            if (model.Direction == "forward")
            {
                model.QuestionNumber++;
            }
            else if (model.Direction == "backward")
            {
                model.QuestionNumber--;
            }
            else if (model.SelectQuestionNumber != 0)
            {
                model.QuestionNumber = model.SelectQuestionNumber;
            }
            else
            {
                return(RedirectToAction("FinalResult", "Exam", new { token = model.token }));
            }

            return(RedirectToAction("ViewQuestion", "Exam", new { questionNumber = model.QuestionNumber, token = model.token, answerModel = JsonConvert.SerializeObject(model.AnswerList.ToList()) }));
        }
Пример #8
0
 public IActionResult Post(AnswerViewModel m)
 {
     throw new NotImplementedException();
 }
Пример #9
0
 private void AddAnswer()
 {
     if (IsNewAnswer) return;
     IsNewAnswer = true;
     SelectedAnswer = new AnswerViewModel();
 }
Пример #10
0
 private void SaveAnswer()
 {
     if (string.IsNullOrEmpty(SelectedAnswer.Text))
         MessageBox.Show("Vul a.u.b. een tekst in.");
     else if (IsNewAnswer)
     {
         var poco = SelectedAnswer.Poco;
         poco.QuestionId = SelectedQuestion.QuestionId;
         poco = _answerRepository.CreateAnswer(SelectedAnswer);
         SelectedAnswer = new AnswerViewModel(poco);
         Answers.Add(SelectedAnswer);
         IsNewAnswer = false;
         MessageBox.Show("Antwoord toegevoegd.");
     }
     else if (SelectedAnswer != null)
     {
         _answerRepository.UpdateAnswer(SelectedAnswer);
         MessageBox.Show("Antwoord aagepast.");
     }
 }
Пример #11
0
 public IActionResult Post(AnswerViewModel model)
 {
     return(Content("Not implemented (yet)"));
 }
        public ActionResult UpdateForGrid([DataSourceRequest] DataSourceRequest request, AnswerViewModel answer)
        {
            ANSWER entity = db.ANSWERS.Get().FirstOrDefault(c => c.ID == answer.id);

            if (entity == null)
            {
                ModelState.AddModelError("ANSWER", "Невозможно редактировать данный ответ!< br > Ошибка: Ответ не обнаружен в базе данных!");
            }

            if (ModelState.IsValid)
            {
                entity = answer.ToEntity(entity);

                try
                {
                    db.ANSWERS.Update(entity);
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("ANSWER", ex.Message);
                }
            }

            return(Json(new[] { answer }.ToDataSourceResult(request, ModelState)));
        }
        public ActionResult CreateForGrid([DataSourceRequest] DataSourceRequest request, AnswerViewModel answer, long _questionid)
        {
            if (!db.QUESTIONS.Get().Any(q => q.ID == _questionid))
            {
                ModelState.AddModelError("ANSWER", "Невозможно добавить данный ответ!<br> Ошибка: Вопрос не обнаружен в базе данных!");
            }
            if (ModelState.IsValid)
            {
                answer.questionid = _questionid;
                answer.ordernum   = (short)(db.ANSWERS.Get().Where(q => q.QUESTIONID == _questionid).Count() + 1);

                ANSWER entity = answer.ToEntity(new ANSWER());
                try
                {
                    db.ANSWERS.Create(entity);
                    answer.id = entity.ID;
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("ANSWER", ex.Message);
                }
            }

            return(Json(new[] { answer }.ToDataSourceResult(request, ModelState)));
        }
        public ActionResult DestroyForGrid([DataSourceRequest] DataSourceRequest request, AnswerViewModel answer)
        {
            ANSWER entity = db.ANSWERS.Get().FirstOrDefault(a => a.ID == answer.id);

            if (entity == null)
            {
                ModelState.AddModelError("ANSWER", "Ответ не обнаружен в базе данных!");
            }

            if (ModelState.IsValid)
            {
                try
                {
                    db.ANSWERS.Delete(entity);
                    //Recalculate ordernum
                    db.ANSWERS.Get().Where(a => a.QUESTIONID == answer.questionid && a.ORDERNUM > answer.ordernum).ToList().ForEach(an =>
                    {
                        an.ORDERNUM -= 1;
                        db.ANSWERS.Update(an);
                    });
                }
                catch (Exception ex)
                {
                    ModelState.AddModelError("ANSWER", ex.Message);
                }
            }

            return(Json(new[] { answer }.ToDataSourceResult(request, ModelState)));
        }
Пример #15
0
        public AnswerViewModel GetScore(QuestionViewModel vm, int questionId, string name)
        {
            AnswerViewModel answer = new AnswerViewModel();
            int             score  = 0;

            string[] rightAnswer = new string[10];
            int      index       = 0;

            switch (questionId)
            {
            case 0:
                List <qIntroduction> DB = GetQIntroductions(false);
                index = 0;
                foreach (var item in DB)
                {
                    rightAnswer[index] = item.RightChoices;
                    index++;
                }
                break;

            case 1:
                List <qHindiaBelanda> DBa = GetQHindiaBelanda(false);
                index = 0;
                foreach (var item in DBa)
                {
                    rightAnswer[index] = item.RightChoices;
                    index++;
                }
                break;

            case 2:
                List <qTarakanBattle> DBb = GetQTarakanBattle(false);
                index = 0;
                foreach (var item in DBb)
                {
                    rightAnswer[index] = item.RightChoices;
                    index++;
                }
                break;
            }

            if (vm.SelectedAnswer1 == rightAnswer[0])
            {
                score += 10;
            }
            if (vm.SelectedAnswer2 == rightAnswer[1])
            {
                score += 10;
            }
            if (vm.SelectedAnswer3 == rightAnswer[2])
            {
                score += 10;
            }
            if (vm.SelectedAnswer4 == rightAnswer[3])
            {
                score += 10;
            }
            if (vm.SelectedAnswer5 == rightAnswer[4])
            {
                score += 10;
            }
            if (vm.SelectedAnswer6 == rightAnswer[5])
            {
                score += 10;
            }
            if (vm.SelectedAnswer7 == rightAnswer[6])
            {
                score += 10;
            }
            if (vm.SelectedAnswer8 == rightAnswer[7])
            {
                score += 10;
            }
            if (vm.SelectedAnswer9 == rightAnswer[8])
            {
                score += 10;
            }
            if (vm.SelectedAnswer10 == rightAnswer[9])
            {
                score += 10;
            }

            answer.Score      = score;
            answer.QuestionId = questionId;
            return(answer);
        }
Пример #16
0
 public AnswerWindow(MainViewModel main, bool additing)
 {
     InitializeComponent();
     DataContext = new AnswerViewModel(main, this.Close, additing);
 }
Пример #17
0
 public void UpdateAnswer(AnswerViewModel model)
 {
     _answerRepository.Update(_mapper.Map <Answer>(model));
 }
Пример #18
0
 private void DeleteAnswer()
 {
     _answerRepository.DeleteAnswer(SelectedAnswer);
     Answers.Remove(SelectedAnswer);
     SelectedAnswer = null;
 }
Пример #19
0
        public ActionResult CheckTest(int testId, int number, bool isTheEnd, int testPoints, int allPoints, string text, Dictionary <int, string> answers)
        {
            AnswerViewModel answer = new AnswerViewModel()
            {
                AllPoints = allPoints, IsTheEnd = isTheEnd, TestId = testId, Text = text, TestPoints = testPoints, NumInTest = number
            };

            if (answer.NumInTest != 0)
            {
                Question question1 = db.Questions.Where(q => q.NumInTest == number && q.TestId == answer.TestId).First();
                answer.Question = question1;
                answers.Add(number, text);
                answer.answers = answers;
                if (answer.Question.Answer.ToLower().CompareTo(answer.Text.ToLower()) == 0)
                {
                    int point = answer.AllPoints + answer.Question.Points;
                    answer.AllPoints = point;
                }
            }
            int numInTest = answer.NumInTest + 1;

            answer.NumInTest = numInTest;
            if (numInTest > db.Questions.Where(q => q.TestId == answer.TestId).Count())
            {
                string       userId   = User.Identity.GetUserId();
                PersonalArea area     = db.PersonalAreas.Where(p => p.AspNetUserId.CompareTo(userId) == 0).First();
                Test         test1    = db.Tests.Find(answer.TestId);
                int          idPar    = test1.ParagraphId;
                Paragraph    parag    = db.Paragraphs.Find(idPar);
                int          courseId = parag.CourseId;
                ViewBag.CourseId = courseId;
                if (answer.TestPoints == answer.AllPoints)
                {
                    var structure     = area.CourseStructures.Where(c => c.IdCourse == courseId).First();
                    var parStructures = db.ParagraphStructures.Where(p => p.CourseStructureId == structure.Id);
                    List <ParagraphStructure> sortParag = parStructures.OrderBy(p => p.NumInCourse).ToList();
                    foreach (var par in sortParag)
                    {
                        var testStructures            = db.TestStructures.Where(t => t.ParagraphStructureId == par.Id);
                        List <TestStructure> testSort = testStructures.OrderBy(t => t.NumInParagraph).ToList();
                        foreach (var test in testSort)
                        {
                            if (test.IdTest == answer.TestId)
                            {
                                var queStructures = db.QuestionStructures.Where(q => q.TestStructureId == test.Id);
                                List <QuestionStructure> queSort = queStructures.OrderBy(q => q.NumInTest).ToList();
                                foreach (var que in queSort)
                                {
                                    que.Passed          = true;
                                    db.Entry(que).State = System.Data.Entity.EntityState.Modified;
                                }
                            }
                        }
                    }
                    db.SaveChanges();
                }
                answer.IsTheEnd = true;
                return(View(answer));
            }
            Question question = db.Questions.Where(q => q.NumInTest == numInTest && q.TestId == answer.TestId).First();

            answer.Question = question;
            answer.Text     = "";
            return(View(answer));
        }
Пример #20
0
 public IActionResult InsertOrUpdateAnswerToQuestion([FromBody] AnswerViewModel viewModel)
 {
     return(Ok(this.quizBusiness.InsertOrUpdateAnwerOfQuestion(mapper.Map <Answer>(viewModel))));
 }
Пример #21
0
        public ViewResult Create()
        {
            var model = new AnswerViewModel();

            return(View(model));
        }
Пример #22
0
        private static IEnumerable <FormViewModel> GetListOfImportedForms(string context)
        {
            const int ImportCoulumnsCount = 12;
            var       formsList           = new List <FormViewModel>();
            var       lines         = context.Split(new[] { "\n" }, StringSplitOptions.RemoveEmptyEntries);
            var       header        = lines[0].Split(new[] { "," }, StringSplitOptions.RemoveEmptyEntries);
            var       headerIndexer = GetFileHeaderIndexer(header);

            var curForm      = string.Empty;
            var curQuestion  = string.Empty;
            var curAnswer    = string.Empty;
            var nextForm     = string.Empty;
            var nextQuestion = string.Empty;
            var nextAnswer   = string.Empty;

            FormViewModel     form     = null;
            QuestionViewModel question = null;
            AnswerViewModel   answer   = null;

            for (int i = 1; i < lines.Length; i++)
            {
                try
                {
                    var fields = CleanLineInput(lines[i]).Split(new[] { "," }, StringSplitOptions.None);

                    if (fields.Length != ImportCoulumnsCount)
                    {
                        continue;
                    }

                    curForm     = fields[headerIndexer["FormId"]];
                    curQuestion = fields[headerIndexer["QuestionId"]];
                    curAnswer   = fields[headerIndexer["AnswerId"]];
                    if (curForm != nextForm)
                    {
                        form = new FormViewModel
                        {
                            Name               = fields[headerIndexer.FirstOrDefault(k => k.Key == "FormName").Value],
                            Title              = fields[headerIndexer["Title"]],
                            Description        = fields[headerIndexer["Description"]],
                            FormTypeId         = int.Parse(fields[headerIndexer["FormType"]]) + 1,
                            StudyId            = int.Parse(fields[headerIndexer.FirstOrDefault(k => k.Key == "StudyId").Value]),
                            QuestionsViewModel = new List <QuestionViewModel>()
                        };

                        formsList.Add(form);
                    }

                    if (curQuestion != nextQuestion)
                    {
                        question = new QuestionViewModel
                        {
                            QuestionText     = fields[headerIndexer["QuestionText"]],
                            AnswersViewModel = new List <AnswerViewModel>(),
                        };
                        form.QuestionsViewModel.Add(question);
                    }

                    if (curAnswer != nextAnswer)
                    {
                        answer = new AnswerViewModel()
                        {
                            AnswerText      = fields[headerIndexer["AnswerText"]],
                            FieldDataTypeId = int.Parse(fields[headerIndexer["QuestionTypeId"]]),
                        };
                        question.AnswersViewModel.Add(answer);
                    }
                }
                catch (Exception ex)
                {
                    Console.Out.WriteLine(ex.Message);
                }
                nextForm     = curForm;
                nextQuestion = curQuestion;
                nextAnswer   = curAnswer;
            }

            return(formsList);
        }
Пример #23
0
 private void Select(AnswerViewModel answer)
 {
     var selection = Answers.Where(a => a.IsSelected);
     foreach (var selected in selection)
         selected.IsSelected = false;
     answer.IsSelected = !answer.IsSelected;
     SelectedAnswer = answer;
 }
Пример #24
0
 public static IEnumerable <AnswerModel> RetrieveAnswerModelParents(this AnswerViewModel @this)
 {
     return(@this.ParentsInfo?.Select(x => x.ToAnswerModel()));
 }
 public ActionResult AddAnswer(int? testId, int? questionId)
 {
     if (testId == null || questionId == null)
     {
         return View("Error");
     }
     AnswerViewModel a = new AnswerViewModel()
     {
         AnswerValue = 0,
         QuestionId = questionId.Value
     };
     QuestionViewModel q = questionService.GetById(a.QuestionId).ToMvcQuestion();
     foreach (QuestionItem item in q.Items)
     {
         a.Items.Add(new AnswerItem() {ItemType = item.ItemType, BoolValue = false, Value = ""});
     }
     answerService.CreateAnswer(a.ToBllAnswer());
     a = answerService.GetByPredicate(entity => entity.QuestionId == questionId.Value).Last().ToMvcAnswer();
     return RedirectToAction("EditAnswer", new {answerId = a.Id});
 }
Пример #26
0
 public static IEnumerable <AnswerModel> RetrieveAnswerModelChildren(this AnswerViewModel @this)
 {
     return(@this.ChildrenInfo?.Select(x => x.ToAnswerModel()));
 }
Пример #27
0
 public void Put(AnswerViewModel m)
 {
     throw new NotImplementedException();
 }
 public IActionResult Put(int id, [FromBody] AnswerViewModel question)
 {
     throw new NotImplementedException();
 }
        public ActionResult EditAnswer(int answerId)
        {
            AnswerViewModel answer = answerService.GetAnswersByQuestionID(answerId);

            return(View(answer));
        }
Пример #30
0
        public HttpResponseMessage Get(int answerId)
        {
            var answer = new AnswerViewModel(_repository.GetAnswer(answerId, ActiveModule.ModuleID));

            return(Request.CreateResponse(answer));
        }
Пример #31
0
        public IActionResult ViewIdeationReply(int id)
        {
            IdeationReply reply    = _ideationManager.GetIdeationReply(id);
            Ideation      ideation = reply.Ideation;

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

            if (ideation == null)
            {
                return(StatusCode(500));
            }

            var vm = new IdeationReplyViewModel()
            {
                IdeationReplyId = reply.IdeationReplyId,
                CentralQuestion = ideation.CentralQuestion,
                DateTime        = reply.Created,
                Answers         = new List <AnswerViewModel>(),
                UserDisplayName = reply.User.GetDisplayName(),
                UpVotes         = reply.Upvotes,
                Title           = reply.Title,
                DownVotes       = reply.Downvotes,
            };

            foreach (Answer answer in reply.Answers)
            {
                Question question = ideation.Questions.Find(q => q.OrderIndex == answer.QuestionIndex);
                if (question != null)
                {
                    AnswerViewModel answervm = new AnswerViewModel
                    {
                        FieldType      = question.FieldType,
                        QuestionString = question.QuestionString,
                    };
                    switch (question.FieldType)
                    {
                    case FieldType.OpenText:
                        answervm.OpenAnswer = (string)answer.GetValue();
                        break;

                    case FieldType.Image:
                    case FieldType.Video:
                        answervm.FileAnswer = (Media)answer.GetValue();
                        break;

                    case FieldType.SingleChoice:
                    case FieldType.DropDown:
                        int    singleAnswer         = (int)answer.GetValue();
                        string singleAnswerAsString = question.Options[singleAnswer];
                        answervm.SingleAnswer = singleAnswerAsString;
                        break;

                    case FieldType.MultipleChoice:
                        List <bool>   multiAnswer          = (List <bool>)answer.GetValue();
                        List <string> multiAnswerAsStrings = new List <string>();
                        for (int i = 0; i < question.Options.Count; i++)
                        {
                            if (multiAnswer[i])
                            {
                                multiAnswerAsStrings.Add(question.Options[i]);
                            }
                        }

                        answervm.MultipleAnswer = multiAnswerAsStrings;
                        break;

                    case FieldType.Location:
                        answervm.LocationAnswer = (Location)answer.GetValue();
                        break;

                    default:
                        throw new ArgumentOutOfRangeException();
                    }

                    vm.Answers.Add(answervm);
                }
            }


            return(Ok(vm));
        }
Пример #32
0
        private Question ValidateFormAndAddAnswer(int questionId, string possibleAnswerContent)
        {
            Question dbQuestion;
            try
            {
                dbQuestion = this.questionService.GetById(questionId);
            }
            catch (Exception)
            {
                throw new HttpException(404, "Question not found");
            }

            if (!dbQuestion.PossibleAnswers.Any(x => x.Content == possibleAnswerContent))
            {
                throw new HttpException(404, "Answer not found");
            }

            var possibleAnswer = dbQuestion.PossibleAnswers.FirstOrDefault(a => a.Content == possibleAnswerContent);
            var newAnswer = new AnswerViewModel()
            {
                QuestionId = dbQuestion.Id,
                PossibleAnswerId = possibleAnswer.Id
            };

            currentAnswers.Add(newAnswer);
            return dbQuestion;
        }
Пример #33
0
 public void CreateAnswer(AnswerViewModel model)
 {
     _answerRepository.Insert(_mapper.Map <Answer>(model));
 }
Пример #34
0
 public IActionResult FinalAnswer(AnswerViewModel model)
 {
     return(View(model));
 }
Пример #35
0
        public void CheckQuizResultShouldReturnTrueIFPassedAndNumberOfCorrectAnswers()
        {
            var quizViewModel = new QuizViewModel();

            quizViewModel.Questions = new List <QuestionViewModel>();

            var question = new QuestionViewModel()
            {
                QuestionText = "Question test",
            };

            var answer = new AnswerViewModel()
            {
                AnswerText      = "A",
                QuestionId      = question.Id,
                IsCorrectAnswer = true,
            };

            var anotherAnswer = new AnswerViewModel()
            {
                AnswerText      = "B",
                QuestionId      = question.Id,
                IsCorrectAnswer = false,
            };

            question.Answers = new List <AnswerViewModel>();
            question.Answers.Add(answer);
            question.Answers.Add(anotherAnswer);

            quizViewModel.Questions.Add(question);

            var questionInput = new QuestionInputModel()
            {
                QuestionText = "B??",
                QuizId       = "123",
            };
            var firstNewAnswer = new AnswerInputModel()
            {
                AnswerText      = "A",
                IsCorrectAnswer = true,
            };
            var secondNewAnswer = new AnswerInputModel()
            {
                AnswerText      = "B",
                IsCorrectAnswer = false,
            };

            questionInput.Answers = new List <AnswerInputModel>();
            questionInput.Answers.Add(firstNewAnswer);
            questionInput.Answers.Add(secondNewAnswer);

            var quizInputModel = new QuizInputModel();

            quizInputModel.Questions = new List <QuestionInputModel>();
            quizInputModel.Questions.Add(questionInput);

            var result = this.Service.CheckQuizResults(quizInputModel, quizViewModel);

            Assert.True(result.Item1);
            Assert.Equal(1, result.Item2);
        }
Пример #36
0
        public IActionResult View(int id)
        {
            var           tenant = Util.Util.GetSubdomain(HttpContext.Request.Host.ToString());
            IdeationReply reply  = _ideationManager.GetIdeationReply(id);

            if (reply == null)
            {
                return(RedirectToAction("NotFound", "Home"));
            }

            Ideation ideation = reply.Ideation;

            User user = _userManager.GetUserAsync(User).Result;

            if (ideation == null)
            {
                return(StatusCode(500));
            }

            var subdomain         = Util.Util.GetSubdomain(HttpContext.Request.Host.ToString());
            var ideationSubDomain = ideation.Project.Platform.Tenant;

            if (subdomain != ideationSubDomain)
            {
                return(RedirectToAction("NotFound", "Home"));
            }

            Vote vote = null;

            if (user != null)
            {
                vote = reply.Votes.Find(v => v.User == user);
            }

            ViewBag.IsAdminIdeation = ideation.IdeationType == IdeationType.Admin;
            ViewBag.ProjectId       = ideation.Project.ProjectId;
            ViewBag.IdeationId      = ideation.IdeationId;

            bool isMod = false;

            if (user != null)
            {
                isMod = _userManager.IsUserModOrAboveForProject(user, ideation.Project, tenant);
            }

            ViewBag.IsMod = isMod;
            IdeationReport report = reply.Reports.Find(r => r.User == user && r.ReportedIdeation == reply);

            ViewBag.HasReported = (report != null);

            var vm = new IdeationReplyViewModel()
            {
                IdeationReplyId = reply.IdeationReplyId,
                CentralQuestion = ideation.CentralQuestion,
                DateTime        = reply.Created,
                Title           = reply.Title,
                Answers         = new List <AnswerViewModel>(),
                UserDisplayName = reply.User.GetDisplayName(),
                UserHasVoted    = vote != null,
                UpVotes         = reply.Upvotes,
                DownVotes       = reply.Downvotes,
                IsFlagged       = reply.Reports.Any(),
                ReviewedByMod   = reply.ReviewedByMod,
                Hidden          = reply.Hidden
            };

            if (_userManager.IsUserAdminOrAbove(reply.User, tenant))
            {
                vm.UserDisplayName = reply.User.GetFullName();
            }

            if ((user != null && _userManager.IsUserModOrAbove(user, tenant)) || _userManager.IsUserOrganisation(reply.User))
            {
                //Mods can see the full name
                vm.UserDisplayName = reply.User.GetFullName();
            }

            foreach (Answer answer in reply.Answers)
            {
                Question        question = ideation.Questions.Find(q => q.OrderIndex == answer.QuestionIndex);
                AnswerViewModel answervm = new AnswerViewModel()
                {
                    FieldType      = question.FieldType,
                    QuestionString = question.QuestionString,
                };
                switch (question.FieldType)
                {
                case FieldType.OpenText:
                    answervm.OpenAnswer = (string)answer.GetValue();
                    break;

                case FieldType.Image:
                case FieldType.Video:
                    answervm.FileAnswer = (Media)answer.GetValue();
                    break;

                case FieldType.SingleChoice:
                case FieldType.DropDown:
                    int    singleAnswer         = (int)answer.GetValue();
                    string singleAnswerAsString = question.Options[singleAnswer];
                    answervm.SingleAnswer = singleAnswerAsString;
                    break;

                case FieldType.MultipleChoice:
                    List <bool>   multiAnswer          = (List <bool>)answer.GetValue();
                    List <string> multiAnswerAsStrings = new List <string>();
                    for (int i = 0; i < question.Options.Count; i++)
                    {
                        if (multiAnswer[i])
                        {
                            multiAnswerAsStrings.Add(question.Options[i]);
                        }
                    }

                    answervm.MultipleAnswer = multiAnswerAsStrings;
                    break;

                case FieldType.Location:
                    answervm.LocationAnswer = (Location)answer.GetValue();
                    break;

                default:
                    throw new ArgumentOutOfRangeException();
                }

                vm.Answers.Add(answervm);
            }

            return(View(vm));
        }
Пример #37
0
        public void CreateAnswer(string questionGuid, AnswerViewModel answer)
        {
            var testAnswer = _mapper.Map <TestAnswer>(answer);

            _lowLevelTestManagementService.CreateAnswerForQuestion(questionGuid, testAnswer);
        }
Пример #38
0
 public ActionResult CheckTest(AnswerViewModel answer)
 {
     return(RedirectToAction("CheckTest", new { testId = answer.TestId, number = answer.NumInTest, isTheEnd = answer.IsTheEnd, testPoints = answer.TestPoints, allPoints = answer.AllPoints, text = answer.Text, answers = answer.answers }));
 }