Exemplo n.º 1
0
        public async Task <IActionResult> Create(int?id)
        {
            if (id is null)
            {
                return(NotFound());
            }

            var test = await _testingPlatform.TestManager
                       .FindAsync(t => t.AppUserId == _userId && t.Id == id);

            if (test is null)
            {
                return(NotFound());
            }

            if (!(test.TestCode is null))
            {
                return(NotFound());
            }

            var testQuestion = new TestQuestion {
                TestId = test.Id, Test = test
            };

            return(View(testQuestion));
        }
Exemplo n.º 2
0
        public async Task <IActionResult> Edit(int id, [Bind("Id, QuestionText, TestId, PreformattedText")] TestQuestion testQuestion)
        {
            if (id != testQuestion.Id)
            {
                return(NotFound());
            }

            var test = await _testingPlatform.TestManager
                       .GetAll()
                       .AsNoTracking()
                       .FirstOrDefaultAsync(t => t.AppUserId == _userId && t.Id == testQuestion.TestId);

            if (test is null)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                testQuestion.AppUserId = _userId;
                await _testingPlatform.TestQuestionManager.UpdateAsync(testQuestion);

                return(RedirectToAction(nameof(Index), new { id = testQuestion.TestId }));
            }
            testQuestion = await _testingPlatform.TestQuestionManager.FindAsync(tq => tq.AppUserId == _userId && tq.Id == id);

            return(View(testQuestion));
        }
Exemplo n.º 3
0
    public void ShowQuestion(TestQuestion question)
    {
        ShowTestTitle();
        txtQuestion.Buffer.Text = question.Text;
        // Clean previous answers
        foreach (var child in AnswersHolder.Children)
        {
            child.Destroy();
        }
        // Create new answer items
        answers = new CheckButton[question.Answers.Count];
        // Get user selected items
        var answered = results.Answered(question);

        for (int i = 0; i < question.Answers.Count; ++i)
        {
            answers [i] = new CheckButton();
            var display    = this.Display.GetScreen(0);
            int fntSize    = (int)(answers [i].PangoContext.FontDescription.Size / Pango.Scale.PangoScale);
            int maxSymbols = display.Width / fntSize;
            answers [i].Label = StringWrapper.WordWrap(question.Answers[i].Text, maxSymbols);
            AnswersHolder.Add(answers[i]);
            // Show answers already checked by user
            foreach (var answer in answered)
            {
                if (answer == question.Answers [i])
                {
                    answers [i].Active = true;
                }
            }
        }
        AnswersHolder.ShowAll();
        // Fix focus
        FocusGrabbedByTextQuestion(null, null);
    }
Exemplo n.º 4
0
 public ActionResult AddQuestion(CreateQuestionViewModel model, FormCollection form)
 {
     //return Content(Convert.ToInt32(form["selectC"]).ToString());
     if (ModelState.IsValid)
     {
         try
         {
             TestQuestion q = new TestQuestion()
             {
                 QuestionContent = model.questionArea,
                 TestTypeID      = model.TestTypeID,
                 modifyUser      = User.Identity.Name,
                 modifyDateTime  = DateTime.Now
             };
             TestAnswer a1 = new TestAnswer()
             {
                 AnswerContent  = model.answerA,
                 TestQuestion   = q,
                 AnswerProperty = (model.answerRight == 1)? true :false
             };
             TestAnswer a2 = new TestAnswer()
             {
                 AnswerContent  = model.answerB,
                 TestQuestion   = q,
                 AnswerProperty = (model.answerRight == 2) ? true : false
             };
             TestAnswer a3 = new TestAnswer()
             {
                 AnswerContent  = model.answerC,
                 TestQuestion   = q,
                 AnswerProperty = (model.answerRight == 3) ? true : false
             };
             TestAnswer a4 = new TestAnswer()
             {
                 AnswerContent  = model.answerD,
                 TestQuestion   = q,
                 AnswerProperty = (model.answerRight == 4) ? true : false
             };
             offlineDB.TestQuestion.Add(q);
             offlineDB.TestAnswer.Add(a1);
             offlineDB.TestAnswer.Add(a2);
             offlineDB.TestAnswer.Add(a3);
             offlineDB.TestAnswer.Add(a4);
             offlineDB.SaveChanges();
             return(RedirectToAction("Index"));
         }
         catch
         {
             ModelState.AddModelError("", "出现错误");
             ViewBag.Store_System = new SelectList(offlineDB.TestType, "Id", "CustomName");
             return(View(model));
         }
     }
     else
     {
         ModelState.AddModelError("", "出现错误");
         ViewBag.Store_System = new SelectList(offlineDB.TestType, "Id", "CustomName");
         return(View(model));
     }
 }
Exemplo n.º 5
0
        private void NextButton_Click(object sender, RoutedEventArgs e)
        {
            var cond = _answered.Count == _questionManager.GetFirstListCount() ||
                       (_answered.Count == _settings.QuestionLimitCount && _settings.EnableLimit == true);

            if (cond)
            {
                //_settings = SettingsController.Load();
                //swearLabel.Content = _settings.ShowSwearing ? Const.SwearsEnabled : Const.SwearsDisabled;
                FinishTesting();
            }
            else
            {
                CheckQuestion();
                _currentQuestion = _questionManager.GetNext();
                LoadToLabels(_currentQuestion);
                DisplayProgress(_questionManager.GetCurrentPosition());

                var remain = !_settings.EnableLimit ?
                             _questionManager.GetCount() - _answered.Count :
                             _settings.QuestionLimitCount - _answered.Count;

                InformationLabel.Content = $"Осталось вопросов: {remain}";

                if (remain == 0)
                {
                    NextButton.Content = Const.ShowResult;
                }
            }
        }
Exemplo n.º 6
0
        /// <summary>
        /// 新增试题
        /// </summary>
        /// <param name="addTestQuestionViewModel"></param>
        /// <returns></returns>
        public ActionResult AddTestQuestion(addTestQuestionViewModel addTestQuestionViewModel)
        {
            bool         b            = false;
            TestQuestion testQuestion = new TestQuestion();

            if (addTestQuestionViewModel.ViewTestQuestionType == 0.ToString())                 //选择题
            {
                testQuestion.TestQuestionType = addTestQuestionViewModel.ViewTestQuestionType; //类型
                //问题&$答案A....
                testQuestion.TestQuestionName   = string.Format("{0}&${1}&${2}&${3}&${4}", addTestQuestionViewModel.ViewTestQuestionName, addTestQuestionViewModel.optionA, addTestQuestionViewModel.optionB, addTestQuestionViewModel.optionC, addTestQuestionViewModel.optionD);
                testQuestion.TestQuestionResult = addTestQuestionViewModel.ViewTestQuestionResult;   //答案
                testQuestion.TestQuestionGrade  = addTestQuestionViewModel.ViewTestQuestionGrade;    //分值
                b = testQuestionService.Add(testQuestion);
            }
            else                                                                                   //非选择题(判断题用 y或者x表示)
            {
                testQuestion.TestQuestionType   = addTestQuestionViewModel.ViewTestQuestionType;   //类型
                testQuestion.TestQuestionName   = addTestQuestionViewModel.ViewTestQuestionName;   //问题
                testQuestion.TestQuestionResult = addTestQuestionViewModel.ViewTestQuestionResult; //答案
                testQuestion.TestQuestionGrade  = addTestQuestionViewModel.ViewTestQuestionGrade;  //分值
                b = testQuestionService.Add(testQuestion);
            }
            if (b == true)
            {
                return(Content("ok"));
            }
            else
            {
                return(Content("no"));
            }
        }
Exemplo n.º 7
0
        public async Task <IActionResult> CreateExam(ExamForAddDto examForAddDto)
        {
            var exam = new Test
            {
                Name        = examForAddDto.Name,
                Description = examForAddDto.Description,
                Time        = examForAddDto.Time,
                Point       = examForAddDto.Point,
                CreatedAt   = DateTime.Now
            };

            _repo.Add(exam);
            if (await _repo.SaveAll())
            {
                var examToReturn = _mapper.Map <Test>(exam);

                foreach (var question in examForAddDto.Questions)
                {
                    var examQuestion = new TestQuestion
                    {
                        QuestionId = question.Id,
                        TestId     = examToReturn.Id
                    };
                    _repo.Add(examQuestion);
                    await _repo.SaveAll();
                }
                return(Ok());
                // return CreatedAtRoute("GetQuestion", new { id = question.Id }, questionToReturn);
            }

            return(BadRequest("Could not add the photo"));
        }
Exemplo n.º 8
0
        private void AskTestQuestion(TestQuestion test, out bool result)
        {
            var currConsoleColor = Console.ForegroundColor;
            int id;

            Console.WriteLine($"Вопрос: {test.Text}");

            ShowAnswers(test);

            do
            {
                Console.Write("Введите ответ: ");

                var answer = Console.ReadLine();

                if (!int.TryParse(answer, out id))
                {
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Ошибка ввода, попробуйте снова.\a");
                    Console.ForegroundColor = currConsoleColor;
                }
            } while (id < 1);


            WriteResult(string.Equals(test.Answer, test.GetAnswerInList(id - 1), StringComparison.CurrentCultureIgnoreCase),
                        out result);
        }
Exemplo n.º 9
0
        public ActionResult AddQuestion(int id)
        {
            if (!user.IsManager())
            {
                return(View("Error"));
            }
            TestQuestion check = db.TestQuestions.FirstOrDefault(c => c.TestCode == id);

            if (check == null)
            {
                //   Model.UpdateLastSeen("Xóa Sinh Viên", Url.Action("DeleteStudent"));
                int id_student = id;
                int del        = managerDal.AddQFT(id_student);
                TempData["CandidateID"] = true;
                TempData["statusAQ"]    = "Add questions successfull!!!!";

                return(RedirectToAction("TestCode"));
            }

            else
            {
                TempData["CandidateID"] = false;
                TempData["statusAQ"]    = "This test already had questions";
                return(RedirectToAction("TestCode"));
            }
        }
Exemplo n.º 10
0
 private void ShowAnswers(TestQuestion test)
 {
     for (int i = 0; i < test.Answers.Count; i++)
     {
         Console.WriteLine(i + 1 + ")" + test.Answers[i]);
     }
 }
        public async Task <IActionResult> Edit(int id, [Bind("Id")] TestQuestion testQuestion)
        {
            if (id != testQuestion.Id)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(testQuestion);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!TestQuestionExists(testQuestion.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        throw;
                    }
                }
                return(RedirectToAction(nameof(Index)));
            }
            return(View(testQuestion));
        }
        public IHttpActionResult AddTest(int UserId, int TestStructureId)
        {
            Test test = new Test();

            test.SetProperties(UserId: UserId, TestStructureId: TestStructureId);
            db.Tests.Add(test);
            db.SaveChanges();
            TestStructure   testStructure = db.TestStructures.Find(TestStructureId);
            Random          rng           = new Random();
            List <Question> questions     = db.Questions.Where(q => q.Technology == testStructure.Technology &&
                                                               q.Level == testStructure.Level &&
                                                               q.QuestionFile.IsCurrent == true).ToList();

            if (questions.Count == 0)
            {
                db.Tests.Remove(test);
                db.SaveChanges();
                return(Ok(new List <TestQuestion>()));
            }
            for (int i = 0; i < testStructure.NumberOfQuestions; i++)
            {
                TestQuestion testQuestion = new TestQuestion();
                testQuestion.SetProperties(TestId: test.Id, QuestionId: questions[rng.Next(0, questions.Count)].Id);
                db.TestQuestions.Add(testQuestion);
                db.SaveChanges();
            }
            test.StartTime = System.DateTime.Now;
            test.EndTime   = test.StartTime.Value.AddMinutes(testStructure.MaxMinutes);
            db.SaveChanges();
            return(CreatedAtRoute("DefaultApi", new { id = test.Id }, db.TestQuestions.Where(tq => tq.TestId == test.Id).ToList()));
        }
Exemplo n.º 13
0
        public bool AddTestQuestion(TestQuestion testQuestion)
        {
            _appDbContext.Add(testQuestion);
            _appDbContext.SaveChanges();

            return(true);
        }
Exemplo n.º 14
0
        public QuestionViewModel MapTestQuestion(TestQuestion testQuestion)
        {
            var mappedQuestion = _mapper.Map <QuestionViewModel>(testQuestion);

            mappedQuestion.IsValid = _advancedLogicService.IsQuestionValid(testQuestion);
            return(mappedQuestion);
        }
        public void CreateQuestionForTest(string testGuid, TestQuestion question)
        {
            var test = _testRepository.Get(t => t.Guid == testGuid);

            test.TestQuestions.Add(question);
            _testRepository.Update(test);
        }
Exemplo n.º 16
0
        public async Task <IActionResult> Delete(TestQuestion testQuestion)
        {
            if (!string.IsNullOrEmpty(testQuestion.Image))
            {
                var path = Path.Combine(_env.WebRootPath, "images", "test-questions", testQuestion.Image);
                System.IO.File.Delete(path);
            }

            _db.TestQuestions.Remove(testQuestion);
            await _db.SaveChangesAsync();

            if (testQuestion.IsLastQuestion)
            {
                var testQuestions = await _db.TestQuestions
                                    .Where(tq => tq.TestId == testQuestion.TestId)
                                    .ToListAsync();

                var lastQuestion = testQuestions.Last();
                lastQuestion.IsLastQuestion   = true;
                _db.Entry(lastQuestion).State = EntityState.Modified;
                await _db.SaveChangesAsync();
            }

            return(RedirectToAction("Edit", "Tests", new { id = testQuestion.TestId }));
        }
Exemplo n.º 17
0
        public TestInput LoadTestInput(string fileName)
        {
            var fileLines           = File.ReadAllLines(fileName).ToList();
            var testQuestions       = new List <TestQuestion>();
            var currentTestQuestion = new TestQuestion();

            foreach (var fileLine in fileLines)
            {
                if (string.IsNullOrWhiteSpace(fileLine))
                {
                    testQuestions.Add(currentTestQuestion);
                    currentTestQuestion = new TestQuestion();
                    continue;
                }
                if (string.IsNullOrWhiteSpace(currentTestQuestion.Question))
                {
                    currentTestQuestion.Question = fileLine;
                    continue;
                }
                currentTestQuestion.Answers.Add(fileLine);
            }
            return(new TestInput()
            {
                TestQuestions = testQuestions,
            });
        }
Exemplo n.º 18
0
        public void ExecutesAggregator()
        {
            var testee = new AggregatorStrategy <TestQuestion, string, int>();

            var context        = new Context();
            var aggregatorMock = new Mock <IAggregator <string, string, int> >();

            var expressionProviderMock = new Mock <IExpressionProvider <TestQuestion, string, int, string> >();
            var question   = new TestQuestion();
            var expression = new TestExpression <string>();

            expressionProviderMock.Setup(provider => provider.GetExpressions(question)).Returns(new[] { expression });

            var definition = new TestableDefinition <string>
            {
                Aggregator          = aggregatorMock.Object,
                ExpressionProviders = new[] { expressionProviderMock.Object }
            };

            const int Parameter = 7;

            testee.Execute(question, Parameter, definition, context);

            AssertThatAggregatorIsCalledWithExpressionsFromDefinition(aggregatorMock, new[] { expression }, Parameter);
        }
Exemplo n.º 19
0
        private int StoreReceivedQuestionAndParameterAndReturnResult(TestQuestion question, string parameter)
        {
            this.receivedQuestion  = question;
            this.receivedParameter = parameter;

            return(Result);
        }
Exemplo n.º 20
0
        public async Task <IActionResult> UpdateExam(int id, ExamForUpdatedDto examForUpdatedDto)
        {
            var examFormRepo = await _repo.GetExam(id);

            var qOlds = await _repo.GetQuestionsByTest(id);

            var test = await _repo.GetTestQuestion(id);

            _mapper.Map(examForUpdatedDto, examFormRepo);
            await _repo.SaveAll();

            foreach (var t in test)
            {
                _repo.Delete(t);
            }

            foreach (var qNew in examForUpdatedDto.Questions)
            {
                var testQuestion = new TestQuestion
                {
                    TestId     = examFormRepo.Id,
                    QuestionId = qNew.Id
                };
                _repo.Add(testQuestion);
                await _repo.SaveAll();
            }

            return(Ok());
        }
Exemplo n.º 21
0
        public async Task <IActionResult> Create([Bind("QuestionText, TestId, PreformattedText")] TestQuestion testQuestion)
        {
            var test = await _testingPlatform.TestManager
                       .FindAsync(t => t.AppUserId == _userId && t.Id == testQuestion.TestId);

            if (test is null)
            {
                return(NotFound());
            }

            if (ModelState.IsValid)
            {
                testQuestion.AppUserId = _userId;
                await _testingPlatform.TestQuestionManager.AddAsync(testQuestion);

                return(RedirectToAction(nameof(Index), new { id = testQuestion.TestId }));
            }

            test = await _testingPlatform.TestManager
                   .FindAsync(t => t.AppUserId == _userId && t.Id == testQuestion.TestId);

            if (test is null)
            {
                return(NotFound());
            }

            if (!(test.TestCode is null))
            {
                return(NotFound());
            }

            return(View(new TestQuestion {
                TestId = test.Id, Test = test
            }));
        }
Exemplo n.º 22
0
        public bool UpdateTestQuestion(TestQuestion testQuestion)
        {
            _appDbContext.TestQuestion.Update(testQuestion);
            _appDbContext.SaveChanges();

            return(true);
        }
Exemplo n.º 23
0
        public void ExecutesAggregator_WhenStrategyWithMappingIsUsed()
        {
            const string Answer = "42";

            var testee = new AggregatorStrategy <TestQuestion, string, int, int>();

            var context    = new Context();
            var aggregator = A.Fake <IAggregator <int, string, int> >();

            var expressionProvider = A.Fake <IExpressionProvider <TestQuestion, string, int, int> >();
            var question           = new TestQuestion();
            var expression         = new TestExpression <int>();

            A.CallTo(() => expressionProvider.GetExpressions(question)).Returns(new[] { expression });
            var definition = new TestableDefinition <int>
            {
                Aggregator          = aggregator,
                ExpressionProviders = new[] { expressionProvider }
            };

            const int Parameter = 7;

            A.CallTo(() => aggregator.Aggregate(
                         A <IEnumerable <IExpression <int, int> > > .That.Matches(_ => _.Contains(expression) && _.Count() == 1),
                         Parameter,
                         A <Context> ._)).Returns(Answer);

            string result = testee.Execute(question, Parameter, definition, context);

            result.Should().Be(Answer);
        }
Exemplo n.º 24
0
        private void NextButton_Click(object sender, RoutedEventArgs e)
        {
            CheckQuestion();
            _currentQuestion = _questionManager.GetNext();
            LoadToLabels(_currentQuestion);
            DisplayProgress(_questionManager.GetCurrentPosition());

            var remain = !_settings.EnableLimit ?
                         _questionManager.GetCount() - _answered.Count :
                         _settings.QuestionLimitCount - _answered.Count;

            InformationLabel.Content = $"Осталось вопросов: {remain}";

            if (remain == 1)
            {
                NextButton.Content = Const.ShowResult;
            }
            foreach (var rb in _radioButtonsList)
            {
                rb.IsChecked = false;
            }
            var cond = _answered.Count == _questionManager.GetFirstListCount() ||
                       (_answered.Count == _settings.QuestionLimitCount && _settings.EnableLimit == true);

            if (cond)
            {
                FinishTesting();
            }
        }
Exemplo n.º 25
0
        public ActionResult getCurrentQuestion(int examId)
        {
            var exam = offlineDB.Examination.SingleOrDefault(m => m.ID == examId);

            if (exam != null)
            {
                int currentSequence = exam.CurrentSequence ?? 0;
                if (currentSequence < exam.MaxSequence)
                {
                    ExaminationDetails details = (from m in offlineDB.ExaminationDetails
                                                  where m.ExaminationID == exam.ID && m.Sequence == currentSequence
                                                  select m).FirstOrDefault();
                    TestQuestion question = details.TestQuestion;
                    return(PartialView(question));
                }
                else
                {
                    return(RedirectToAction("FinishExam", new { examId = exam.ID }));
                }
            }
            else
            {
                return(PartialView());
            }
        }
Exemplo n.º 26
0
        private int GetWeightedValue(TestQuestion answer)
        {
            var res = answer.Value;

            if (!answer.PlusKey)
            {
                switch (answer.Value)
                {
                case 1: res = 5;
                    break;

                case 2: res = 4;
                    break;

                case 3: res = 3;
                    break;

                case 4: res = 2;
                    break;

                case 5: res = 1;
                    break;
                }
            }

            return(res);
        }
Exemplo n.º 27
0
        public void СreateTestQuestion([FromBody] TestQuestion testQuestion)
        {
            tQuestion newQuestion = new tQuestion
            {
                questionText  = testQuestion.Question,
                fkTheme       = testQuestion.ThemeId,
                fkClassNumber = testQuestion.ClassId,
                fkType        = _entities.tQuestionType
                                .Where(qt => qt.name == testQuestion.TypeName)
                                .Select(qt => qt.pk).FirstOrDefault()
            };

            _entities.tQuestion.Add(newQuestion);

            try
            {
                _entities.SaveChanges();
            }
            catch (Exception ex)
            {
                var resp = new HttpResponseMessage(HttpStatusCode.NotFound)
                {
                    Content = new StringContent(string.Format("Ошибка при сохранении данных"))
                };
                throw new HttpResponseException(resp);
            }
        }
Exemplo n.º 28
0
        public InlineExpressionTest()
        {
            this.question         = new TestQuestion();
            this.inlineExpression = (q, p) => this.StoreReceivedQuestionAndParameterAndReturnResult(q, p);

            this.testee = new InlineExpression <TestQuestion, string, int>(this.question, this.inlineExpression);
        }
Exemplo n.º 29
0
        private void button3_Click(object sender, EventArgs e)
        {
            string   text       = tbText.Text;
            Subject  subj       = cbSubjects.SelectedItem as Subject;
            int      complexity = rbVeryEz.Checked ? 1 : rbEz.Checked ? 2 : rbMiddle.Checked ? 3 : rbHard.Checked ? 4 : rbHardcore.Checked ? 5 : 0;
            Question q;

            if (lbOptions.Items.Count > 0)
            {
                List <string> strings = new List <string>();
                foreach (var t in lbOptions.Items)
                {
                    strings.Add(t.ToString());
                }
                q = new TestQuestion(strings, text, complexity, subj);
            }
            else
            {
                q = new SimpleQuestion(text, complexity, subj);
            }
            if (updateMode == false)
            {
                controller.AddQuestion(q);
            }
            else
            {
                q.ID = this.q.ID;
                controller.UpdateQuestion(q);
            }

            Close();
        }
Exemplo n.º 30
0
        public async Task <Test> DuplicateTest(int testId, Test newTest)
        {
            //Fetch categories present in that particular test and store them in a variable of type list
            var testCategoryList = _dbContext.TestCategory.Where(x => x.TestId == testId);
            // Fetch questions present in that particular test and store them in a variable of type list
            var testQuestionList = _dbContext.TestQuestion.Where(x => x.TestId == testId);
            var test             = await _dbContext.Test.FindAsync(newTest.Id);

            //Fetch Ip Addresses in that particular test and store them in a variable of type list
            var testIpAddressList = await _dbContext.TestIpAddresses.Where(x => x.TestId == testId).ToListAsync();

            if (testCategoryList.Any())
            {
                var categoryList = new List <TestCategory>();
                foreach (TestCategory categoryObject in testCategoryList)
                {
                    var categoryObj = new TestCategory();
                    categoryObj.CategoryId = categoryObject.CategoryId;
                    categoryObj.Test       = test;
                    categoryObj.TestId     = test.Id;
                    categoryList.Add(categoryObj);
                }
                await _dbContext.TestCategory.AddRangeAsync(categoryList);

                await _dbContext.SaveChangesAsync();

                var questionList = new List <TestQuestion>();
                if (testQuestionList.Any())
                {
                    foreach (TestQuestion questionObject in testQuestionList)
                    {
                        var questionObj = new TestQuestion();
                        questionObj.QuestionId = questionObject.QuestionId;
                        questionObj.Test       = test;
                        questionObj.TestId     = test.Id;
                        questionList.Add(questionObj);
                    }
                    await _dbContext.TestQuestion.AddRangeAsync(questionList);

                    await _dbContext.SaveChangesAsync();
                }
                var ipAddressList = new List <TestIpAddress>();
                if (testIpAddressList.Any())
                {
                    foreach (TestIpAddress testIpAddressObject in testIpAddressList)
                    {
                        var ipAddressObject = new TestIpAddress();
                        ipAddressObject.Test      = test;
                        ipAddressObject.TestId    = test.Id;
                        ipAddressObject.IpAddress = testIpAddressObject.IpAddress;
                        ipAddressList.Add(ipAddressObject);
                    }
                    await _dbContext.TestIpAddresses.AddRangeAsync(ipAddressList);

                    await _dbContext.SaveChangesAsync();
                }
            }
            return(test);
        }
        private void LoadData()
        {
            if (Tile.TileParms.GetParm("item") == null) return;

            _questionType = Tile.TileParms.GetParm("item").GetType();
            if (_questionType.Name == "BankQuestion")
            {
                _oBankQuestion = (BankQuestion) Tile.TileParms.GetParm("item");
                _oQuestionBase = (QuestionBase) _oBankQuestion;
            }
            else
            {
                _oTestQuestion = (TestQuestion) Tile.TileParms.GetParm("item");
                _oQuestionBase = (QuestionBase) _oTestQuestion;
            }

            lblGrade.Text = _oQuestionBase.Grade;
            lblSubject.Text = _oQuestionBase.Subject;
            lblItemBanks.Text = ItemBankMasterList.Filtered_ItemBank_Labels(_oQuestionBase.ItemBankList, SessionObject.LoggedInUser);
            lblStatus.Text = _oQuestionBase.Status;
            lblReservation.Text = _oQuestionBase.Reservation;
            lblAnchorItem.Text = _oQuestionBase.IsAnchorItem ? "Yes" : "No";
           
            
            switch (_oQuestionBase.QuestionType)
            {
                case QuestionTypes.E:
                    lblType.Text = "Essay";
                    break;
                case QuestionTypes.MC3:
                    lblType.Text = "Multiple Choice (3 Distractors)";
                    break;
                case QuestionTypes.MC4:
                    lblType.Text = "Multiple Choice (4 Distractors)";
                    break;
                case QuestionTypes.MC5:
                    lblType.Text = "Multiple Choice (5 Distractors)";
                    break;
                case QuestionTypes.S:
                    lblType.Text = "Short Answer";
                    break;
                case QuestionTypes.T:
                    lblType.Text = "True/False";
                    break;
                default:
                    lblType.Text = "Unknown";
                    break;
            }
            

            lblScoreType.Text = _oQuestionBase.ScoreType;

            lblKeywords.Text = _oQuestionBase.Keywords;
            lblCopyright.Text = String.IsNullOrEmpty(_oQuestionBase.Copyright) ? "No" : _oQuestionBase.Copyright;
            lblCopyRightExpiryDate.Text = _oQuestionBase.CopyRightExpiryDate == null ? "Not defined" : _oQuestionBase.CopyRightExpiryDate.GetValueOrDefault().Date.ToString("MM/dd/yyyy");
            lblSource.Text = _oQuestionBase.Source;
            lblCredit.Text = _oQuestionBase.Credit;



            /* Figure out contextually how to display rubric info.  If the question's scoretype is not rubric then there is no need to display the "rubric type", "Rubric Scoring" or Rubric Name.
            * If the question's scoretype is rubric, display rubric type, display rubric scoring, then consider whether it is a "Basic", "holistic", or "analytical" rubric:
            *      If "Basic", then
            *              Also make rubric scoring a hyperlink - when clicked provide pop-up window of rubric's criteria.
            *              don't display rubric name since it is basic (and there isn't any name).
            *      
            *      If "Holistic", then
            *              display rubric name.
            *              Also make rubric name a hyperlink - when clicked provide pop-up window of rubric's criteria.
            *              in popup, provide a link to take user to rubric object page.
            *              
            *      If "Analytical", then
            *              Make rubric scoring a hyperlink - when clicked provide pop-up window of rubric's criteria.
            *              In popup, provide a link to take user to the rubric object page.
            *              Don't display rubric name since it is Analytical.
            *              
            */

            if (_oQuestionBase.ScoreType == "Rubric")
            {
                lblRubricType.Text = _oQuestionBase.Rubric.TypeDesc;
                rowRubricType.Style["display"] = "block";

                lblRubricScoring.Text = _oQuestionBase.Rubric.Scoring;
                rowRubricScoring.Style["display"] = "block";

                ItemIDTile_hdnRubricName.Value = _oQuestionBase.Rubric.Name;
                ItemIDTile_hdnRubricContent.Value = _oQuestionBase.Rubric.Content;

                switch (_oQuestionBase.Rubric.TypeDesc)
                {
                    case "Basic":
                        hlRubricScoring.Attributes.Add("onClick", "displayRubricCriteria();");
                        rowRubricName.Style["display"] = "none";
                        break;
                    case "Analytical":
                        ItemIDTile_hdnRubricPageUrl.Value = "../../Record/RubricPage.aspx?xID=" + _oQuestionBase.Rubric.ID_Encrypted;
                        hlRubricScoring.Attributes.Add("onClick", "displayRubricCriteria();");
                        rowRubricName.Style["display"] = "none";
                        break;
                    case "Holistic":
                        lblRubricName.Text = _oQuestionBase.Rubric.Name;
                        ItemIDTile_hdnRubricPageUrl.Value = "../../Record/RubricPage.aspx?xID=" + _oQuestionBase.Rubric.ID_Encrypted;
                        hlRubricName.Attributes.Add("onClick", "displayRubricCriteria();");
                        hlRubricScoring.HRef = "";
                        rowRubricName.Style["display"] = "block";
                        break;
                }
            }
        }
        private void SetQuestion(object item)
        {
            Debug.Assert(item != null);
            Debug.Assert(_questionType != null);
            Debug.Assert(!string.IsNullOrWhiteSpace(_questionType.Name));

            if (_questionType.Name == BankQuestionTypeName)
            {
                _oBankQuestion = item as BankQuestion;
                _oTestQuestion = null;
                Debug.Assert(_oBankQuestion != null);
            }
            else
            {
                _oTestQuestion = item as TestQuestion;
                _oBankQuestion = null;
                Debug.Assert(_oTestQuestion != null);
            }
        }
        private void LoadItem()
        {
            _sItemID = "" + Request.QueryString["xID"];
            _sQuestionType = "" + Request.QueryString["qType"];
            _iItemID = Cryptography.GetDecryptedID(SessionObject.LoggedInUser.CipherKey);
            _iAssessmentID = Cryptography.GetDecryptedID(SessionObject.LoggedInUser.CipherKey, "AssessmentID");
            lbl_TestCategory.Value = Request.QueryString["TestCategory"];

            if (_sItemID == null)
            {
                SessionObject.RedirectMessage = "No entity ID provided in URL.";
                Response.Redirect("~/PortalSelection.aspx", true);
            }
            else
            {
                if (_sQuestionType.Equals("TestQuestion"))
                {
                    // Remove the copy item button if we are coming from the item editor.
                    if (_iItemID == 0 && _iAssessmentID > 0 && !String.IsNullOrEmpty(_sItemID))
                    {
                        _itemTestQuestion = TestQuestion.GetTestQuestionByID(DataIntegrity.ConvertToInt(_sItemID), false);
                        _iItemID = _itemTestQuestion.ID;
                        if (_itemTestQuestion.TestID != _iAssessmentID)
                        {
                            SessionObject.RedirectMessage = "Invalid entity ID provided in URL.";
                            Response.Redirect("~/PortalSelection.aspx", true);
                        }
                    }
                    else
                    {
                        _itemTestQuestion = TestQuestion.GetTestQuestionByID(_iItemID, false);
                    }
                    useTestQuestion = true;
                    //_itemTestQuestion.LoadItemAndScoreTypes();
                    //_itemTestQuestion.LoadRubric();
                }
                else
                {
                    _itemBankQUestion = BankQuestion.GetQuestionByID(_iItemID);
                    _itemBankQUestion.LoadAddendum();
                    useTestQuestion = false;
                }

                LoadStandards();
                LoadItemText();

            }

        }
Exemplo n.º 34
0
 public void AddToTestQuestions(TestQuestion testQuestion)
 {
     base.AddObject("TestQuestions", testQuestion);
 }
        /// <summary>
        /// Load Item from query string
        /// </summary>
        private void LoadItem()
        {
            _sItemID = "" + Request.QueryString["xID"];
            _sQuestionType = "" + Request.QueryString["qType"];         
            ItemID = Cryptography.GetDecryptedID(SessionObject.LoggedInUser.CipherKey);

            _iAssessmentID = Cryptography.GetDecryptedID(SessionObject.LoggedInUser.CipherKey, "AssessmentID");
            lbl_TestCategory.Value = Request.QueryString["TestCategory"];

            lbl_TestType.Value = Request.QueryString["TestType"];
            if (_sItemID == null)
            {
                SessionObject.RedirectMessage = "No entity ID provided in URL.";
                Response.Redirect("~/PortalSelection.aspx", true);
            }
            else
            {
                if (_sQuestionType.Equals("TestQuestion"))
                {
                    // Remove the copy item button if we are coming from the item editor.
                    btnCopyItem.Visible = false;
                    if (ItemID == 0 && _iAssessmentID > 0 && !String.IsNullOrEmpty(_sItemID))
                    {
                        _itemTestQuestion = TestQuestion.GetTestQuestionByID(DataIntegrity.ConvertToInt(_sItemID), false);
                        ItemID = _itemTestQuestion.ID;
                        if (_itemTestQuestion.TestID != _iAssessmentID)
                        {
                            SessionObject.RedirectMessage = "Invalid entity ID provided in URL.";
                            Response.Redirect("~/PortalSelection.aspx", true);
                        }
                    }
                    else
                    {
                        _itemTestQuestion = TestQuestion.GetTestQuestionByID(ItemID, false);
                    }
                    UseTq = true;
                }
                else
                {
                    _itemBankQuestion = BankQuestion.GetQuestionByID(ItemID);
                    _itemBankQuestion.LoadAddendum();
                    UseTq = false;
                }

                LoadAddendums();
                LoadStandards();
                LoadItemText();

                _itemReservation = "No";
                if (UserHasPermission(Permission.Access_ItemReservation))
                    _itemReservation = "Yes";
                else
                    reservationDropDown.Enabled = false;

                string qType = UseTq ? "TestQuestion" : "";
                ScriptManager.RegisterStartupScript(this, typeof(string), "SetQType", "setQuestionType('"+qType+"');", true);
            }

            if (Request.QueryString["isCopy"] == "true")
            
                ScriptManager.RegisterStartupScript(this, typeof(string), "AlertForCopiedItem", "AlertForCopiedItem();", true);
        }
        /// <summary>
        /// This method stores the question and its responses provided by the user in the object of TestQuestion class.
        /// </summary>
        private void StoreQuestionResponses()
        {
            TestQuestion ques = new TestQuestion();
            ques.QuestionText = quesTxt.Text;
            ques.Number = quesCount;
            if (selectedQuesType == QuesTypeVal.MCQ.ToString())
            {
                ques.Type = "MCQ";

                var option1 = new TestQuestionOption1 { Answer = "No", Value = textBox2.Text };
                var option2 = new TestQuestionOption2 { Answer = "No", Value = textBox3.Text };
                var option3 = new TestQuestionOption3 { Answer = "No", Value = textBox4.Text };
                var option4 = new TestQuestionOption4 { Answer = "No", Value = textBox5.Text };

                if (radioButton1.Checked == true)
                {
                    option1.Answer = "Yes";
                }
                else if (radioButton2.Checked == true)
                {
                    option2.Answer = "Yes";
                }
                else if (radioButton3.Checked == true)
                {
                    option3.Answer = "Yes";
                }
                else if (radioButton4.Checked == true)
                {
                    option4.Answer = "Yes";
                }

                ques.Option1 = option1;
                ques.Option2 = option2;
                ques.Option3 = option3;
                ques.Option4 = option4;
            }
            else if (selectedQuesType == QuesTypeVal.Text.ToString())
            {
                ques.Type = "Text";

                TestQuestionAnswer ans = new TestQuestionAnswer();
                ans.Text = textTypeAnswerTxt.Text;

                ques.Answer = ans;
            }
            else if (selectedQuesType == QuesTypeVal.EssayText.ToString())
            {
                ques.Type = "EssayText";

                ques.NumberOfParagraphs = Convert.ToInt32(textTypeAnswerTxt.Text);
                ques.TotalNumberOfWords = Convert.ToInt32(noOfKeywordsTxt.Text);

                TestQuestionAnswer essayAns = new TestQuestionAnswer();
                List<string> keywordList = new List<string>();
                keywordList = essayAnsTxt.Text.Split(';').ToList<string>();
                essayAns.Keyword = new string[keywordList.Count];

                int i = 0;
                foreach (string k in keywordList)
                {
                    essayAns.Keyword[i] = k;
                    i++;
                }

                ques.Answer = essayAns;
            }

            testQuesList.Add(ques);
        }        
Exemplo n.º 37
0
        private void LoadData()
        {
           
            if (Tile.TileParms.GetParm("item") == null) return;

            _questionType = Tile.TileParms.GetParm("item").GetType();
            if (_questionType.Name == "BankQuestion")
            {
                _oBankQuestion = (BankQuestion)Tile.TileParms.GetParm("item");
                _oQuestionBase = (QuestionBase)_oBankQuestion;
            }
            else
            {
                _oTestQuestion = (TestQuestion)Tile.TileParms.GetParm("item");
                _oQuestionBase = (QuestionBase)_oTestQuestion;
            }

            var dparms = DistrictParms.LoadDistrictParms();
            ItemContentTile_lbl_OTCUrl.Value = AppSettings.OTCUrl + dparms.ClientID;
            ItemContentTile_itemID.Value = _oQuestionBase.ID.ToString();
            ItemContentTile_itemType.Value = _questionType.Name.ToString();

            /* set up our image element to point
             * to the item's thumbnail image */
            var imgFilePath = AppSettings.ItemThumbnailWebPath_Content + _oQuestionBase.ThumbnailName;
            
            if (!System.IO.File.Exists(Server.MapPath(imgFilePath))) imgFilePath = "~/Images/thumb_none.png";

            ItemContentTile_imgThumbnail.Src = imgFilePath;

            /* determine size of image.  If it is smaller 
             * than the space we allow, then increase its 
             * height or width.  If it is larger than the 
             * space we allow, then use max-width and max 
             * height to shrink it. */
            System.Drawing.Image imgThumbNail = System.Drawing.Image.FromFile(Server.MapPath(imgFilePath));
            var fImgHeight = imgThumbNail.PhysicalDimension.Height;
            var fImgWidth = imgThumbNail.PhysicalDimension.Width;
            var lImgTagMaxHeight = DataIntegrity.ConvertToNullableFloat(ItemContentTile_imgThumbnail.Style["max-height"].ToString().Replace("px","").Replace("%",""));
            var lImgTagMaxWidth = DataIntegrity.ConvertToNullableFloat(ItemContentTile_imgThumbnail.Style["max-width"].ToString().Replace("px", "").Replace("%", ""));

            if (fImgHeight < lImgTagMaxHeight && fImgWidth < lImgTagMaxWidth)
            {
                if (fImgHeight > fImgWidth)
                    ItemContentTile_imgThumbnail.Height = DataIntegrity.ConvertToInt(lImgTagMaxHeight);
                else
                    ItemContentTile_imgThumbnail.Width = DataIntegrity.ConvertToInt(lImgTagMaxWidth);
            }



            /* Set up our online preview link's onClick
             * event with the item's ID. */
            ItemContentTile_hdnThumbnailURL.Value = @"display.asp?formatoption=search results&key=9120&retrievemode=searchpage&ahaveSkipped=normal&??Question=" + _oQuestionBase.ID.ToString() + @"&??TestID=0&qreview=y";
            imgPreviewIcon.Src = ResolveUrl("../../Images/preview_small.png");
            
            /* Set up our Print Preview hidden text box
             * to hold the encrypted ID of the item */
            ItemContentTile_hdnPrintPreviewInfo.Value = ResolveUrl("../../Record/RenderItemAsPDF.aspx?xID=") + 
                                                        Encryption.EncryptString(_oQuestionBase.ID.ToString()) + 
                                                        "&TestQuestion=" + Encryption.EncryptString((_questionType.Name=="BankQuestion") ? "false" : "true");
            imgPrintPreviewIcon.Src = ResolveUrl("../../Images/mag_glass.png");

            /* See if the item has an addendum. If so then
             * set up and display link to pop up Addendum.
             * Otherwise make sure it doesn't display.*/
            if (_oQuestionBase.AddendumID == 0)
            {
                divDisplayAddendum.Style["visibility"] = "hidden"; 
            }
            else
            {
                if (_questionType.Name == "BankQuestion") _oBankQuestion.LoadAddendum();
                //_oQuestionBase.LoadAddendum();
                hlLaunchAddendumPage.InnerText = _oQuestionBase.Addendum.Addendum_Name;
                hlLaunchAddendumPage.Attributes["onClick"] = "window.open('" + ResolveUrl("../../Record/AddendumPage.aspx?xID=") + Encryption.EncryptString(_oQuestionBase.AddendumID.ToString()) + "'); return false;";

                divAddendumContent.InnerHtml = _oQuestionBase.Addendum.Addendum_Text;

                hlDisplayAddendum.Attributes["onClick"] = "displayAddendumClick();";

                HtmlImage imgAddendumIcon = new HtmlImage();
                imgAddendumIcon.ID = "imgAddendumIcon";
                imgAddendumIcon.Src = ResolveUrl("../../Images/Addendum_small.png");
                imgAddendumIcon.Height = 20;
                hlDisplayAddendum.Controls.Add(imgAddendumIcon);

                Label lblAddendum_Name = new Label();
                lblAddendum_Name.Text = _oQuestionBase.Addendum.Addendum_Name;
                hlDisplayAddendum.Controls.Add(lblAddendum_Name);
                //hlDisplayAddendum.InnerText = oItem.Addendum.Addendum_Name;
                divDisplayAddendum.Style["visibility"] = "visible";
            }


        }
Exemplo n.º 38
0
 public static TestQuestion CreateTestQuestion(int id)
 {
     TestQuestion testQuestion = new TestQuestion();
     testQuestion.ID = id;
     return testQuestion;
 }
Exemplo n.º 39
0
        private void LoadData()
        {
            HtmlTableRow oRow;
            HtmlTableCell oCell;
            HtmlGenericControl oDiv;
            if (Tile.TileParms.GetParm("item") == null) return;

            _questionType = Tile.TileParms.GetParm("item").GetType();
            if (_questionType.Name == "BankQuestion")
            {
                _oBankQuestion = (BankQuestion)Tile.TileParms.GetParm("item");
                _oQuestionBase = (QuestionBase)_oBankQuestion;
            }
            else
            {
                _oTestQuestion = (TestQuestion)Tile.TileParms.GetParm("item");
                _oQuestionBase = (QuestionBase)_oTestQuestion;
            }

            /*******************************************************************************
             * Although for any given version of the Elements application there is only one
             * type of rigor (either Webb, Marzano, or RBT), and this is determined by the 
             * value of DOK in the Parms table in the database, a bank question may have 
             * all three rigors in its full rigor string. Its just that only one of the 
             * three rigors is used.  If displaying a bank question, we intend to display 
             * all the rigors listed in the full rigor string.  The full rigor string looks 
             * something like:
             *      Webb=3|RBT=4|Marzano=4|
             * We get to parse out the different rigors and then use the numeric code of 
             * each and fetch from the database the actual text or description for the code.
             * 
             * We expect each rigor to be divided by vertical bar '|', and each rigor to be 
             * be of a format: {rigor name}={numeric code} (e.g. RBT=2).
             * 
             * If displaying a test question, then we will only display the single rigor de-
             * fined at the district.
             * *****************************************************************************/

            var rgxRigorFormat = new Regex(@"[a-zA-Z]+=\d+"); //this regex pattern should match above format for rigor.


            /*list of rigors and codes to pass to the database in order to look up code's text*/
            dtGeneric_String_Int dtListOfRigors = new dtGeneric_String_Int();

            if (_questionType.Name == "BankQuestion")
            {
                /*array of strings from full string rigor, each holding a rigor=value pattern, we hope.*/
                string[] aRigors = _oQuestionBase.Rigor.FullRigorString.Split('|');

                /*loop through array of strings and collect a set of legit rigor/code values in dtListOfRigors*/
                foreach (var sRigor in aRigors)
                {
                    if (rgxRigorFormat.IsMatch(sRigor))
                    {
                        dtListOfRigors.Add(sRigor.Substring(0, sRigor.IndexOf('=')), DataIntegrity.ConvertToInt(sRigor.Substring(sRigor.IndexOf('=') + 1)));
                    }
                }

                /*Pass dtListOfRigors via SP to database in order to look up each rigor's code's text value.*/
                var dt = ThinkgateDataAccess.FetchDataTable("E3_RIGOR_GetDescriptionsFromListOfCodes", new object[] { dtListOfRigors.ToSql() });

                /* Loop through our result set and build into our tableItemAdvanced html table for displaying */
                DataRow drRigor;
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    drRigor = dt.Rows[i];
                    oRow = new HtmlTableRow();

                    oCell = new HtmlTableCell();
                    oCell.Attributes.Add("class", "fieldLabel");
                    oCell.Attributes.Add("style", "width:130px");
                    oCell.InnerText = drRigor["Field"].ToString() + ":";
                    oRow.Cells.Add(oCell);

                    oCell = new HtmlTableCell();
                    oCell.InnerText = drRigor["Text"].ToString();
                    oRow.Cells.Add(oCell);

                    tblItemAdvanced.Rows.Insert(i, oRow);
                }
            }
            else
            {
                var distParms = DistrictParms.LoadDistrictParms();
                oRow = new HtmlTableRow();

                oCell = new HtmlTableCell();
                oCell.Attributes.Add("class", "fieldLabel");
                oCell.Attributes.Add("style", "width:130px");
                oCell.InnerText = distParms.DOK; 
                oRow.Cells.Add(oCell);

                oCell = new HtmlTableCell();
                oCell.InnerText = _oQuestionBase.Rigor.ToString();
                oRow.Cells.Add(oCell);

                tblItemAdvanced.Rows.Insert(0, oRow);
            }

            lblItemDifficulty.Text = string.Format("{0:#.00##}", _oQuestionBase.ItemDifficulty);
            lblDifficultyIndex.Text = _oQuestionBase.DifficultyIndex.ToString();

            /******************************************************
             * The number of Distractor Rationale values vary, so 
             * we need to build the HTML to represent these.
             * ***************************************************/
            foreach (var sDistractorRationale in _oQuestionBase.DistractorRationale)
            {
                oDiv = new HtmlGenericControl();
                oDiv.InnerHtml = sDistractorRationale;

                oCell = new HtmlTableCell();
                oCell.ColSpan = 2;
                oCell.Controls.Add(oDiv);
                
                oRow = new HtmlTableRow();
                oRow.Cells.Add(oCell);

                tblItemAdvanced.Rows.Add(oRow);
            }
        }
Exemplo n.º 40
0
		private Test Load( XmlDocument document )
		{
			XmlNode testNode = document.GetElementsByTagName( Constants.TAG_ROOT ).Item( 0 );

			Test test = new Test ( testNode.Attributes.GetNamedItem ( Constants.ATTR_NAME ).Value );

			XmlNode questionsNode = document.GetElementsByTagName( Constants.TAG_QUESTIONS ).Item( 0 );
			foreach ( XmlNode questionNode in questionsNode.ChildNodes )
			{
				TestQuestion question = new TestQuestion ( questionNode.Attributes.GetNamedItem (Constants.ATTR_TEXT).Value );

				foreach ( XmlNode variantNode in questionNode.ChildNodes )
				{
					question.Add( new TestQuestionVariant(
							variantNode.Attributes.GetNamedItem( Constants.ATTR_TEXT ).Value
						,	int.Parse( variantNode.Attributes.GetNamedItem( Constants.ATTR_WEIGHT ).Value )
					) );
				}

				test.Add ( question );
			}

			XmlNode conclusionsNode = document.GetElementsByTagName( Constants.TAG_CONCLUSIONS ).Item( 0 );
			test.Conclusions.AllowedLimit = int.Parse ( conclusionsNode.Attributes.GetNamedItem ( Constants.ATTR_ALLOWED ).Value );
			foreach ( XmlNode conclusionNode in conclusionsNode )
			{
				test.Conclusions.Add ( new TestConclusion (
						int.Parse( conclusionNode.Attributes.GetNamedItem( Constants.ATTR_FROM ).Value )
					,	int.Parse( conclusionNode.Attributes.GetNamedItem( Constants.ATTR_TO ).Value )
					,	conclusionNode.InnerText
				) );
			}

			return test;
		}