Ejemplo n.º 1
0
        public void StartNewQuiz_WhenTemplateFound_ReturnsNewQuiz()
        {
            // Arrange
            var quizTemplateStub = new QuizTemplate()
            {
                Id = 1
            };
            var mockQuizTemplateRepo = new Mock <IQuizTemplateRepository>();

            mockQuizTemplateRepo.Setup(repo => repo.GetByID(It.IsAny <int>()))
            .Returns(quizTemplateStub);

            var mockQuizRepo = new Mock <IQuizRepository>();

            var mockUow = new Mock <IUnitOfWork>();

            mockUow.Setup(repo => repo.QuizRepository)
            .Returns(mockQuizRepo.Object);

            var manager      = new QuizFlowManager(mockUow.Object, null);
            var quizTemplate = new QuizTemplate()
            {
                Id = 1
            };

            // Act
            var quiz = manager.StartNewQuiz(quizTemplate);

            // Assert
            Assert.Equal(1, quiz.TemplateId);
            mockQuizRepo.Verify(repo => repo.Insert(It.IsAny <Quiz>()), Times.Once);
            mockUow.Verify(uow => uow.Save(), Times.Once);
        }
Ejemplo n.º 2
0
        public void GetQuizTemplate_WhenTemplateFound_ReturnsOkResultWithTemplatesDetails()
        {
            // Arrange
            var quizTemplateStub = new QuizTemplate()
            {
                Id = 1
            };

            var mockQuizTemplateRepo = new Mock <IQuizTemplateRepository>();

            mockQuizTemplateRepo.Setup(repo => repo.GetByID(It.IsAny <int>()))
            .Returns(value: quizTemplateStub);
            mockQuizTemplateRepo.Setup(repo => repo.GetQuestionTemplateCount(It.IsAny <int>()))
            .Returns(value: 42);

            var mockUow = new Mock <IUnitOfWork>();

            mockUow.Setup(uow => uow.QuizTemplateRepository)
            .Returns(mockQuizTemplateRepo.Object);

            var controller = new ScreenController(mockUow.Object);

            // Act
            var response = controller.GetQuizTemplate(1);

            // Assert
            var objectResult       = Assert.IsType <OkObjectResult>(response);
            var quizTemplateDetail = Assert.IsType <QuizTemplateDetailsContract>(objectResult.Value);

            Assert.Equal(42, quizTemplateDetail.QuestionsCount);
            Assert.NotNull(quizTemplateDetail.QuizTemplate);
            Assert.Equal(1, quizTemplateDetail.QuizTemplate.Id);
        }
Ejemplo n.º 3
0
        private bool CheckConditionForQuizFromTemplateOK(string questionSuiteText)
        {
            if (String.IsNullOrWhiteSpace(questionSuiteText))
            {
                TempData["ErrorQuestionSuite"] = QRefResources.Resource.Error_NoSuiteString;
                return(false);
            }
            QuizTemplate suite = Dal.Instance.GetQuestionSuiteByString(questionSuiteText);

            if (suite == null)
            {
                TempData["ErrorQuestionSuite"] = QRefResources.Resource.Error_NoSuiteString;
                return(false);
            }

            if (suite.Owner == null)
            {
                TempData["ErrorQuestionSuite"] = QRefResources.Resource.Error_QuizTemplateOwnerDoesNotExist;
                return(false);
            }
            if (suite.Questions.Count <= 0)
            {
                TempData["ErrorQuestionSuite"] = QRefResources.Resource.Error_QuizTemplateContainsNoQuestion;
                return(false);
            }
            return(true);
        }
Ejemplo n.º 4
0
        private Result ResultFromQuizModel(QuizViewModel quizModel)
        {
            List <Question> questionsAsked = new List <Question>();
            List <Answer>   answers        = new List <Answer>();

            // As questions and answers are managed differently in the quiz, we need to retrieve questions and all checked answers.
            foreach (QuestionQuizzViewModel q in quizModel.DisplayedQuestions)
            {
                questionsAsked.Add(Dal.Instance.GetQuestionById(q.Id));
                foreach (AnswerQuizzViewModel a in q.Answers)
                {
                    if (a.IsSelected)
                    {
                        answers.Add(Dal.Instance.GetAnswerById(a.Id));
                    }
                }
            }
            QuizTemplate questionSuite = null;

            if (quizModel.QuestionSuiteId.HasValue)
            {
                questionSuite = Dal.Instance.GetQuestionSuiteById(quizModel.QuestionSuiteId.Value);
            }


            Result result = new Result(Dal.Instance.GetUserByName(HttpContext.User.Identity.Name),
                                       questionsAsked, answers,
                                       quizModel.ResultType,
                                       Dal.Instance.GetDBTime(),
                                       questionSuite);

            return(result);
        }
Ejemplo n.º 5
0
 private void CheckRuntimeTemplate(QuizTemplate template)
 {
     if (runtimeTemplate == null || runtimeTemplate.Template != template)
     {
         runtimeTemplate = new QuizRuntimeTemplate(template);
     }
 }
Ejemplo n.º 6
0
    public QuizInstance(QuizTemplate template, params QuizQuestion[] additionalQuestions)
    {
        // Assign the template
        this.template = template;
        // Create a new runtime template
        runtimeTemplate = new QuizRuntimeTemplate(template, additionalQuestions);

        // Create an answer for each question
        answers = Enumerable.Repeat(-1, runtimeTemplate.Questions.Length).ToArray();
    }
Ejemplo n.º 7
0
        public IActionResult Start([FromQuery] int templateId)
        {
            QuizTemplate quizTemplate = this.Uow.QuizTemplateRepository.GetByID(templateId);

            ThrowIf.NotFound(quizTemplate, templateId);

            Quiz quiz = this.QuizFlowManager.StartNewQuiz(quizTemplate);

            return(Ok(quiz));
        }
Ejemplo n.º 8
0
        public ActionResult StartQuizFromUserQuizSuite(string questionSuiteText)
        {
            if (!CheckConditionForQuizFromTemplateOK(questionSuiteText))
            {
                return(RedirectToAction("Homepage", "Home"));
            }
            QuizTemplate  quizTemplate = Dal.Instance.GetQuestionSuiteByString(questionSuiteText);
            QuizViewModel quizModel    = new QuizViewModel(QuizType.Training, Dal.Instance.GetDBTime(), quizTemplate);

            return(View("Quiz", quizModel));
        }
Ejemplo n.º 9
0
        public ActionResult CreateQuizTemplate(String name, List <string> questionIds, string timeLimit)
        {
            //Check at least one question was selected and no more than 50
            if (questionIds.Count < 1 || questionIds.Count > 50)
            {
                ViewBag.MailError = QRefResources.Resource.QuestionSuite_ErrorNbrQuestion;
                return(View("CreateQuizTemplate", Dal.Instance.getAllQuestionsExceptRetired()));
            }
            //Check time limit is valid. If empty, set a default time limit
            if (String.IsNullOrEmpty(timeLimit))
            {
                timeLimit = questionIds.Count.ToString();
            }
            else if (timeLimit.Length > 2)
            {
                timeLimit = "90";
            }
            else if (!Int32.TryParse(timeLimit, out int test))
            {
                ViewBag.MailError = QRefResources.Resource.QuestionSuite_ErrorTime;
                return(View("CreateQuizTemplate", Dal.Instance.getAllQuestionsExceptRetired()));
            }
            //Check name is valid. If empty, set a default name
            if (String.IsNullOrEmpty(name))
            {
                name = "MyCustomExam";
            }
            else if (name.Length > 20)
            {
                name = name.Substring(0, 19);
            }

            //Create the suite
            if (!HttpContext.User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Homepage", "Home"));
            }
            User         currentUser      = Dal.Instance.GetUserByName(HttpContext.User.Identity.Name);
            QuizTemplate newQuestionSuite = new QuizTemplate(Dal.Instance.GetQuestionsById(questionIds), currentUser, name, Int32.Parse(timeLimit));

            //Update db with new suite
            Dal.Instance.CreateTemporaryQuizTemplate(newQuestionSuite);

            QuestionSuiteViewModel qsvm = new QuestionSuiteViewModel()
            {
                PreviouslyCreatedQuestionSuiteCode = newQuestionSuite.Code,
                UserQuestionSuites = Dal.Instance.GetQuestionSuiteByUser(currentUser)
            };

            //Return to the main page and add a field to copy the suite's ID
            return(View("Index", qsvm));
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Starts new quiz from specified quiz template.
        /// </summary>
        /// <param name="quizTemplate">The quiz template for new quiz.</param>
        /// <returns>New quiz.</returns>
        public Quiz StartNewQuiz(QuizTemplate quizTemplate)
        {
            ThrowIf.Null(quizTemplate, nameof(quizTemplate));

            var quiz = new Quiz
            {
                TemplateId = quizTemplate.Id,
                DateStart  = DateTime.Now
            };

            this.Uow.QuizRepository.Insert(quiz);
            this.Uow.Save();

            return(quiz);
        }
Ejemplo n.º 11
0
    public void DisplayQuizTemplate(QuizTemplate template)
    {
        // Destroy any existing question uis
        foreach (QuizQuestionUI questionUI in currentQuestionUIs)
        {
            Destroy(questionUI.gameObject);
        }
        currentQuestionUIs.Clear();

        // Get all the questions
        QuizQuestion[] allQuestions = template.AllQuestions;

        // Create a question ui for each question
        for (int i = 0; i < allQuestions.Length; i++)
        {
            QuizQuestionUI ui = Instantiate(questionUIPrefab, questionUIParent);
            ui.DisplayQuestion(allQuestions[i], i);
            currentQuestionUIs.Add(ui);
        }
    }
Ejemplo n.º 12
0
        public void Start_WhenQuizCreated_ReturnsOkResultWithQuiz()
        {
            // Arrange
            var quizTemplateStub = new QuizTemplate()
            {
                Id = 1
            };

            var mockQuizTemplateRepo = new Mock <IQuizTemplateRepository>();

            mockQuizTemplateRepo.Setup(repo => repo.GetByID(It.IsAny <int>()))
            .Returns(quizTemplateStub);

            var mockUow = new Mock <IUnitOfWork>();

            mockUow.Setup(uow => uow.QuizTemplateRepository)
            .Returns(mockQuizTemplateRepo.Object);

            var quizStub = new Quiz()
            {
                Id = 1
            };
            var mockManager = new Mock <IQuizFlowManager>();

            mockManager.Setup(manager => manager.StartNewQuiz(It.IsAny <QuizTemplate>()))
            .Returns(quizStub);

            var controller = new QuizFlowController(mockManager.Object, mockUow.Object);

            // Act
            var response = controller.Start(1);

            // Assert
            mockManager.Verify(mock => mock.StartNewQuiz(quizTemplateStub), Times.Once);
            var objectResult = Assert.IsType <OkObjectResult>(response);
            var quiz         = Assert.IsType <Quiz>(objectResult.Value);

            Assert.Equal(1, quiz.Id);
        }
Ejemplo n.º 13
0
    public QuizRuntimeTemplate(QuizTemplate template, params QuizQuestion[] additionalQuestions)
    {
        this.template = template;

        // Check if additional quiz questions were provided
        if (additionalQuestions != null && additionalQuestions.Length > 0)
        {
            // Create space for the template questions and additional questions
            QuizQuestion[] templateQuestions = template.GenerateQuestions();
            questions = new QuizQuestion[templateQuestions.Length + additionalQuestions.Length];

            // Copy the template questions into these questions
            System.Array.Copy(templateQuestions, questions, templateQuestions.Length);
            // Copy the additional questions into these questions
            System.Array.Copy(additionalQuestions, 0, questions, templateQuestions.Length, additionalQuestions.Length);
        }
        // If no additional questions were provided
        else
        {
            questions = template.GenerateQuestions();
        }
    }
Ejemplo n.º 14
0
    public override float GetPropertyHeight(SerializedProperty property, GUIContent label)
    {
        // Get the sub-properties
        SerializedProperty template = property.FindPropertyRelative(nameof(template));
        SerializedProperty answers  = property.FindPropertyRelative(nameof(answers));

        // Set height for one control
        float height = EditorExtensions.StandardControlHeight;

        if (property.isExpanded)
        {
            // Add space for the template drawer
            height += EditorExtensions.StandardControlHeight;

            // If an object reference exists then add room for the answers
            if (template.objectReferenceValue)
            {
                // Add height for the regenerate button
                height += EditorExtensions.StandardControlHeight;

                QuizTemplate quizTemplate = template.objectReferenceValue as QuizTemplate;
                CheckRuntimeTemplate(quizTemplate);
                height += quizAnswersEditor.GetPropertyHeight(answers, runtimeTemplate.Questions);

                // Add height for the results foldout
                height += EditorExtensions.StandardControlHeight;

                // Add space for three more controls if the results are folded out
                if (resultsFoldout)
                {
                    height += EditorExtensions.StandardControlHeight * 3f;
                }
            }
        }

        return(height);
    }
Ejemplo n.º 15
0
    public override void Setup()
    {
        // Use the base setup method
        base.Setup();

        GameManager gameManager = GameManager.Instance;

        // If game manager exists then get the quiz of the current level
        if (gameManager)
        {
            QuizTemplate template = gameManager.LevelData.Quiz;

            // If the template exists then display it
            if (template)
            {
                quizTemplateUI.DisplayQuizTemplate(template);
            }
        }

        // Listen for level id picker change
        levelPicker.Setup();
        levelPicker.OnLevelIDPicked.AddListener(OnLevelPickerChanged);
        OnLevelPickerChanged(levelPicker.CurrentLevelID);
    }
Ejemplo n.º 16
0
 public QuizTemplateDetailsContract(QuizTemplate quizTemplate, int questionsCount)
 {
     this.QuizTemplate   = quizTemplate;
     this.QuestionsCount = questionsCount;
 }
Ejemplo n.º 17
0
 /******************************************************
 * Purpose: Look at each button_Uid and go to the 
 *           quiz that suits the number in Uid
 ******************************************************/
 private void Quiz_Button_Click(object sender, RoutedEventArgs e)
 {
     Button button = sender as Button;
     int button_id = Int32.Parse(button.Uid);
     List<Page> pages = GetPagesInQuiz(button_id);
     QuizTemplate page = new QuizTemplate(button_id, pages, name);
     page.Show();
     this.Hide();
 }
Ejemplo n.º 18
0
        private static void InitializeData(ApplicationDatabaseContext context)
        {
            if (context.QuizTemplates.Any())
            {
                return;
            }

            var question1 = new QuestionTemplate()
            {
                QuestionType = QuestionType.SingleRight,
                Text         = "Who is the author of `Alice in Wonderland` ?"
            };
            var answerQ1A1 = new AnswerTemplate()
            {
                IsCorrect = true,
                Text      = "Charles Lutwidge Dodgson"
            };
            var answerQ1A2 = new AnswerTemplate()
            {
                IsCorrect = false,
                Text      = "Charles John Huffam Dickens"
            };
            var answerQ1A3 = new AnswerTemplate()
            {
                IsCorrect = false,
                Text      = "Agatha Mary Clarissa Christie"
            };
            var answerQ1A4 = new AnswerTemplate()
            {
                IsCorrect = false,
                Text      = "No author. It's a folklore."
            };

            question1.Answers.AddRange(new[] { answerQ1A1, answerQ1A2, answerQ1A3, answerQ1A4 });

            var question2 = new QuestionTemplate()
            {
                QuestionType = QuestionType.SingleRight,
                Text         = "Which of these novels written by Lev Nikolayevich Tolstoy are the most latest ?"
            };
            var answerQ2A1 = new AnswerTemplate()
            {
                IsCorrect = true,
                Text      = "Hadji Murat"
            };
            var answerQ2A2 = new AnswerTemplate()
            {
                IsCorrect = false,
                Text      = "The Cossacks"
            };
            var answerQ2A3 = new AnswerTemplate()
            {
                IsCorrect = false,
                Text      = "War and Peace"
            };
            var answerQ2A4 = new AnswerTemplate()
            {
                IsCorrect = false,
                Text      = "Childhood"
            };

            question2.Answers.AddRange(new[] { answerQ2A1, answerQ2A2, answerQ2A3, answerQ2A4 });

            var quizTemplate = new QuizTemplate()
            {
                Title       = "Simple literature quiz",
                Description = "Short demo quiz about literature.",
            };

            var quizQuestion1 = new QuizQuestionTemplate(quizTemplate, question1, 1)
            {
                Enabled = true
            };
            var quizQuestion2 = new QuizQuestionTemplate(quizTemplate, question2, 2)
            {
                Enabled = true
            };

            context.QuizTemplates.Add(quizTemplate);
            context.QuizQuestionTemplates.AddRange(new[] { quizQuestion1, quizQuestion2 });
        }
Ejemplo n.º 19
0
 public QuizViewModel(QuizType type, DateTime?startTime, QuizTemplate suite) : this(type, startTime, suite.TimeLimit, suite.Questions, suite.Id)
 {
 }
Ejemplo n.º 20
0
 /// <summary>
 /// Initializes a new instance of <see cref="QuizQuestionTemplate"/>.
 /// </summary>
 /// <param name="quizTemplate">Quiz template.</param>
 /// <param name="questionTemplate">Question template.</param>
 /// <param name="order">Question template order.</param>
 public QuizQuestionTemplate(QuizTemplate quizTemplate, QuestionTemplate questionTemplate, int order)
 {
     this.QuizTemplate     = quizTemplate;
     this.QuestionTemplate = questionTemplate;
     this.Order            = order;
 }
Ejemplo n.º 21
0
    public override void OnGUI(Rect position, SerializedProperty property, GUIContent label)
    {
        // Get the sub-properties
        SerializedProperty template = property.FindPropertyRelative(nameof(template));
        SerializedProperty answers  = property.FindPropertyRelative(nameof(answers));

        // Set out the foldout
        property.isExpanded = EditorGUIAuto.Foldout(ref position, property.isExpanded, label);

        if (property.isExpanded)
        {
            // Increase indent
            EditorGUI.indentLevel++;

            // Layout the template
            EditorGUIAuto.PropertyField(ref position, template);

            // If an object reference exists then layout the answers
            if (template.objectReferenceValue)
            {
                // Get the quiz template
                QuizTemplate quizTemplate = template.objectReferenceValue as QuizTemplate;
                CheckRuntimeTemplate(quizTemplate);

                // Use a button to regenerate quiz questions from the template
                GUI.enabled = quizTemplate.Dynamic;
                if (GUIAuto.Button(ref position, "Generate new questions"))
                {
                    runtimeTemplate = new QuizRuntimeTemplate(quizTemplate);
                }
                GUI.enabled = true;

                quizAnswersEditor.OnGUI(position, answers, runtimeTemplate.Questions);
                position.y += quizAnswersEditor.GetPropertyHeight(answers, runtimeTemplate.Questions);

                // Get a list of all the answers as integers
                int[] answersArray = Answers(property);
                resultsFoldout = EditorGUIAuto.Foldout(ref position, resultsFoldout, "Quiz Results");

                if (resultsFoldout)
                {
                    // Indent the next part and disable it
                    EditorGUI.indentLevel++;
                    GUI.enabled = false;

                    // Compute if the important questions passed, what the score is, and what the max score was
                    bool   passed      = QuizInstance.PassedImportantQuestions(runtimeTemplate, answersArray);
                    int    score       = QuizInstance.ComputeScoreInImportantCategories(runtimeTemplate, answersArray);
                    int    maxScore    = runtimeTemplate.GetMaximumPossibleScoreInImportantCategories();
                    string scoreString = $"{score} / {maxScore} - {(passed ? "Pass" : "Fail")}";

                    // Show the score on important questions
                    EditorGUIAuto.PrefixedLabelField(ref position, new GUIContent("Score on Important Questions"), scoreString);

                    // Compute if the unimportant questions passed, what the score is, and what the max score was
                    passed      = QuizInstance.PassedUnimportantQuestions(runtimeTemplate, answersArray);
                    score       = QuizInstance.ComputeScoreInUnimportantCategories(runtimeTemplate, answersArray);
                    maxScore    = runtimeTemplate.GetMaximumPossibleScoreInUnimportantCategories();
                    scoreString = $"{score} / {maxScore} - {(passed ? "Pass" : "Fail")}";

                    // Show the score on unimportant questions
                    EditorGUIAuto.PrefixedLabelField(ref position, new GUIContent("Score on Unimportant Questions"), scoreString);

                    // Show the final grade
                    EditorGUIAuto.PrefixedLabelField(ref position, new GUIContent("Final Grade"),
                                                     QuizInstance.ComputeGrade(runtimeTemplate, answersArray).ToString());

                    // Change the values back to before
                    EditorGUI.indentLevel--;
                    GUI.enabled = true;
                }
            }

            // Restore indent
            EditorGUI.indentLevel--;
        }
    }