예제 #1
0
        public async Task <IActionResult> Post([FromBody] NewQuestion question)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new ResponseStatus()
                {
                    Status = "All fields are mandatory"
                }));
            }

            SavedQuestion savedQuestion = new SavedQuestion();

            savedQuestion.ImageUrl     = question.ImageUrl;
            savedQuestion.ThumbUrl     = question.ThumbUrl;
            savedQuestion.QuestionText = question.QuestionText;
            savedQuestion.Choices      = question.Choices.Select(c => new ChoicesVotes()
            {
                Choice = c, Votes = 0
            }).ToList();
            savedQuestion.PublishedAt = DateTime.Now;

            string id = await _provider.Save(savedQuestion);

            return(CreatedAtAction(nameof(GetById), new { Id = id }, savedQuestion));
        }
예제 #2
0
 /// <summary>
 /// (button)添加新试题
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void showAddNewQuestion(object sender, RoutedEventArgs e)
 {
     #region
     NewQuestion frmquestion = new NewQuestion(ExamQuestionState.NormalAdd);
     frmquestion.InitUI();
     frmquestion.ShowDialog();
     #endregion
 }
        public Question NewQuestion(NewQuestion question)
        {
            try
            {
                using (SqlConnection connection = new SqlConnection(builder.ConnectionString))
                {
                    connection.Open();
                    String sql = "INSERT INTO Questions VALUES @questiontext, @questioncorrectid,"
                                 + " @questionanswerone, @questionanswertwo,"
                                 + " @questionanswerthree, @questionanswerfour"
                                 + " OUTPUT INSERTED.*";
                    using (SqlCommand command = new SqlCommand(sql, connection))
                    {
                        var textParam = new SqlParameter("questiontext", SqlDbType.VarChar);
                        textParam.Value = question.questiontext;
                        var correctParam = new SqlParameter("questioncorrectid", SqlDbType.Int);
                        correctParam.Value = question.questioncorrectid;
                        var qoneParam = new SqlParameter("questionanswerone", SqlDbType.VarChar);
                        qoneParam.Value = question.questionanswers[0];
                        var qtwoParam = new SqlParameter("questionanswertwo", SqlDbType.VarChar);
                        qtwoParam.Value = question.questionanswers[1];
                        var qthreeParam = new SqlParameter("questionanswerthree", SqlDbType.VarChar);
                        qthreeParam.Value = question.questionanswers[2];
                        var qfourParam = new SqlParameter("questionanswerfour", SqlDbType.VarChar);
                        qfourParam.Value = question.questionanswers[3];

                        command.Parameters.Add(textParam);
                        command.Parameters.Add(correctParam);
                        command.Parameters.Add(qoneParam);
                        command.Parameters.Add(qtwoParam);
                        command.Parameters.Add(qthreeParam);
                        command.Parameters.Add(qfourParam);
                        SqlDataReader reader = command.ExecuteReader();
                        reader.Read();
                        Question returnQuestion = new Question(
                            reader.GetInt32(0)
                            , reader.GetString(1)
                            , reader.GetInt32(2)
                            , new string[] { reader.GetString(3)
                                             , reader.GetString(4)
                                             , reader.GetString(5)
                                             , reader.GetString(6) }
                            );
                        return(returnQuestion);
                    }
                }
            }
            catch (SqlException e)
            {
                this._logger.LogInformation(e.ToString());
                return(null);
            }
        }
예제 #4
0
        public async Task PostReturnsCreatedAtActionResultWhenQuestionIsValidAndStored()
        {
            NewQuestion question = new NewQuestion {
                Choices = new[] { Choices.ObjectiveC }, ImageUrl = "", QuestionText = "Some question", ThumbUrl = ""
            };

            _mockProvider.Setup(x => x.Save(It.IsAny <SavedQuestion>())).ReturnsAsync(() => "");
            controller = new QuestionsController(null, _mockProvider.Object);

            var result = await controller.Post(question);

            Assert.IsInstanceOf <CreatedAtActionResult>(result);
        }
예제 #5
0
        /// <summary>
        /// Get all the unanswered questions and wrap them into a MatchQuestionModelRequest.
        /// </summary>
        /// <param name="list">A list of ChatbotNewQuestionModels to process.</param>
        /// <returns>A MatchQuestionModelRequest containing all the answered questions from the forum.</returns>
        public static MatchQuestionModelRequest GenerateModelCompareToOpenQuestions(NewQuestion newQuestion)
        {
            MatchQuestionModelRequest mqmr = new MatchQuestionModelRequest();

            List <DBQuestion> result  = new List <DBQuestion>();
            DBManager         manager = new DBManager(true);

            StringBuilder sb = new StringBuilder();

            sb.Append("SELECT * ");
            sb.Append("FROM Questions q ");
            sb.Append("WHERE q.answer_id IS NOT NULL; ");
            String sqlCommand = sb.ToString();

            var reader = manager.Read(sqlCommand);

            while (reader.Read())
            {
                DBQuestion answer = new DBQuestion();
                answer.Question_id = (int)reader["question_id"];
                answer.Question    = (String)reader["question"];
                answer.Answer_id   = (int)reader["answer_id"];

                /****/
                answer.Question = ServerUtilities.SQLSafeToUserInput(answer.Question);
                /****/

                result.Add(answer);
            }
            manager.Close();                                //IMPORTANT! Should happen automatically, but better safe than sorry.

            mqmr.action      = "MATCH_QUESTIONS".ToLower(); //Standard
            mqmr.question    = newQuestion.question;
            mqmr.question_id = -1;                          // This id does not exist at this point

            List <NLPQuestionModelInfo> comparisonQuestions = new List <NLPQuestionModelInfo>();

            for (int i = 0; i < result.Count; i++)
            {
                comparisonQuestions.Add(new NLPQuestionModelInfo()
                {
                    question = result[i].Question, question_id = result[i].Question_id
                });
            }
            mqmr.compare_questions = comparisonQuestions.ToArray();


            mqmr.msg_id = ClusterConnector.ServerUtilities.getAndGenerateMsgIDOpenQuestions(newQuestion.chatbot_temp_id, newQuestion.question, newQuestion.user_id);

            return(mqmr);
        }
예제 #6
0
        /// <summary>
        /// 添加题目
        /// </summary>
        /// <param name="userId">题目创建用户</param>
        /// <param name="courseId">所属课程</param>
        /// <param name="type">题目类型</param>
        /// <param name="topic">题目标题</param>
        /// <param name="answerOptions">答案选项</param>
        /// <returns></returns>
        public bool Add(long userId, long courseId, int type, string topic, QuestionAnswer answerOptions)
        {
            NewQuestion question = new NewQuestion
            {
                CourseId = courseId,
                Topic    = topic,
                Type     = type,
                UserId   = userId
            };

            question.SetAnswerOptions(answerOptions);

            return(question.Save());
        }
        public async Task <ActionResult <NewQuestion> > PostQuestion(NewQuestion question)
        {
            var qr = new Question
            {
                Title        = question.Title,
                QuestionBody = question.QuestionBody,
                TimeStamp    = DateTime.UtcNow
            };

            db.Questions.Add(qr);
            await db.SaveChangesAsync();

            return(CreatedAtAction("GetQuestion", new { id = question.ID }, question));
        }
        public void AddQuestion(NewQuestion newQuestion)
        {
            var question = new Models.DataModels.NewQuestion
            {
                UserId      = newQuestion.UserId,
                Category    = newQuestion.Category,
                Question    = newQuestion.Question,
                Description = newQuestion.Description
            };

            question.TimeStamp = DateTime.Now;

            Db.Insert("Questions", question);
        }
예제 #9
0
        public async Task PostReturnsCreatedAtBadResultWhenQuestionDoesNotHaveAllMandatoryFields()
        {
            NewQuestion question = new NewQuestion {
            };

            _mockProvider.Setup(x => x.Save(It.IsAny <SavedQuestion>())).ReturnsAsync(() => "");
            controller = new QuestionsController(null, _mockProvider.Object);
            controller.ModelState.AddModelError("InvalidFields", "All fields are mandatory");

            var result = await controller.Post(question);

            Assert.IsInstanceOf <BadRequestObjectResult>(result);
            Assert.AreEqual("All fields are mandatory", ((ResponseStatus)(result as BadRequestObjectResult).Value).Status);
        }
예제 #10
0
        public ActionResult CreateQuestion(NewQuestion newQuestion)
        {
            var db       = new DatabaseContext();
            var question = new Question
            {
                QuestionTitle = newQuestion.QuestionTitle,
                QuestionText  = newQuestion.QuestionText,
                VoteValue     = newQuestion.VoteValue
            };

            db.Questions.Add(question);
            db.SaveChanges();
            return(Ok(question));
        }
        public IActionResult New([FromBody] NewQuestion incomingQuestion)
        {
            // Add a new question
            Question newReturn = _query.NewQuestion(incomingQuestion);

            // If no question returned
            if (newReturn == null)
            {
                return(BadRequest("An error occured while adding new question!"));
            }
            else
            {
                return(Ok(newReturn));
            }
        }
        private void button1_Click_1(object sender, EventArgs e)
        {
            // If the answers are palced into the correct section, at points.
            if (TrueAnswers[0] == true)
            {
                Globalvariables.points += 1;
            }
            if (TrueAnswers[1] == true)
            {
                Globalvariables.points += 1;
            }
            if (TrueAnswers[2] == true)
            {
                Globalvariables.points += 1;
            }
            if (TrueAnswers[3] == true)
            {
                Globalvariables.points += 1;
            }
            if (FalseAnswers[0] == true)
            {
                Globalvariables.points += 1;
            }
            if (FalseAnswers[1] == true)
            {
                Globalvariables.points += 1;
            }
            if (FalseAnswers[2] == true)
            {
                Globalvariables.points += 1;
            }
            if (FalseAnswers[3] == true)
            {
                Globalvariables.points += 1;
            }

            // All answers are correct
            if (TrueAnswers[0] == true && TrueAnswers[1] == true && TrueAnswers[2] == true && TrueAnswers[3] == true && FalseAnswers[0] == true &&
                FalseAnswers[1] == true && FalseAnswers[2] == true && FalseAnswers[3] == true)
            {
                Globalvariables.QuestionsCorrectB[1] = true;
            }


            // Load New Question
            RandomNumber = random.Next(1, 7);
            NewQuestion.Start();
        }
        public async Task <IActionResult> PostQuestionItem([FromForm] NewQuestion newQuestion)
        {
            if (!MultipartRequestHelper.IsMultipartContentType(Request.ContentType))
            {
                return(BadRequest($"Expected a multipart request, but got {Request.ContentType}"));
            }
            QuestionItem questionItem = new QuestionItem();

            try
            {
                using (var stream = newQuestion.image.OpenReadStream())
                {
                    var cloudBlock = await UploadToBlob(newQuestion.image.FileName, null, stream);

                    //// Retrieve the filename of the file you have uploaded
                    //var filename = provider.FileData.FirstOrDefault()?.LocalFileName;
                    if (string.IsNullOrEmpty(cloudBlock.StorageUri.ToString()))
                    {
                        return(BadRequest("An error has occured while uploading your file. Please try again."));
                    }
                    System.Drawing.Image image = System.Drawing.Image.FromStream(stream);
                    questionItem.diagramURL = cloudBlock.SnapshotQualifiedUri.AbsoluteUri;
                }
            }
            catch (Exception)
            {
                // No images was received
                questionItem.diagramURL = "";
            }

            try
            {
                questionItem.title       = newQuestion.title;
                questionItem.description = newQuestion.description;
                questionItem.tag         = newQuestion.tag;
                questionItem.authorID    = newQuestion.authorID;

                _context.QuestionItem.Add(questionItem);
                await _context.SaveChangesAsync();

                return(Ok($"File: {questionItem.title} has successfully uploaded"));
            }
            catch (Exception ex)
            {
                return(BadRequest($"An error has occured. Details: {ex.Message}"));
            }
        }
예제 #14
0
        public ActionResult GetQuestionById(int QuestionId)
        {
            NewQuestion         obj     = new NewQuestion();
            List <AnswersModel> objlist = new List <AnswersModel>();

            using (var db = new NewRegEntities())
            {
                var query = from question in db.Questions
                            join category in db.Categories on question.CatergoryId equals category.CategoryId
                            where question.QuestionId == QuestionId
                            select new QuestionsModel()
                {
                    QuestionId          = question.QuestionId,
                    Question            = question.Question1,
                    Category            = category.CategoryName,
                    CategoryId          = category.CategoryId,
                    QuestionDateAndTime = question.QuestionDateAndTime
                };
                obj.QuestionDetails = query.FirstOrDefault();

                var answerQuery = from answer in db.Answers
                                  join question in db.Questions on answer.QuestionId equals question.QuestionId
                                  where question.QuestionId == QuestionId
                                  select new AnswersModel()
                {
                    AnswerId          = answer.AnswerId,
                    Answer            = answer.Answer1,
                    QuestionId        = (int)answer.QuestionId,
                    AnswerDateAndTime = answer.AnswerDateAndTime
                };

                foreach (var item in answerQuery)
                {
                    AnswersModel objNew = new AnswersModel
                    {
                        AnswerId          = item.AnswerId,
                        Answer            = item.Answer,
                        QuestionId        = item.QuestionId,
                        AnswerDateAndTime = item.AnswerDateAndTime
                    };
                    objlist.Add(objNew);
                }
                obj.ListAnswerDetails = objlist;

                return(View(obj));
            }
        }
예제 #15
0
 public ActionResult Create(NewQuestion question)
 {
     try
     {
         if (ModelState.IsValid)
         {
             //    //unitOfWork.QuestionRepository.Insert(question);
             //    //unitOfWork.Save();
             //    //return RedirectToAction("Index");
         }
     }
     catch (DataException /* dex */)
     {
         //Log the error (uncomment dex variable name and add a line here to write a log.
         ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
     }
     return(View(question));
 }
예제 #16
0
        public async Task <ActionResult> Create(NewQuestion request)
        {
            var question = _mapper.Map <NewQuestion, Core.CoreModels.Question>(request);

            var questionId = await _questionsService.Create(question);

            if (questionId != default)
            {
                return(Ok(new CreatedQuestion()
                {
                    QuestionId = questionId
                }));
            }
            else
            {
                return(NotFound(new { Error = "Question is not created" }));
            }
        }
예제 #17
0
    void SetCurrentQuestion()
    {
        int randomQuestionIndex = Random.Range(0, unansweredQuestions.Count);

        currQuestion = unansweredQuestions[randomQuestionIndex];

        questionText.text = currQuestion.question;
        for (int i = 0; i < 4; i++)
        {
            optionsText[i].text = currQuestion.options[i];
        }

        //Animation
        if (currQuestion.correctAns == "0")
        {
            AnswerAText.text = "CORRECT";
            AnswerBText.text = "WRONG";
            AnswerCText.text = "WRONG";
            AnswerDText.text = "WRONG";
        }
        else if (currQuestion.correctAns == "1")
        {
            AnswerAText.text = "WRONG";
            AnswerBText.text = "CORRECT";
            AnswerCText.text = "WRONG";
            AnswerDText.text = "WRONG";
        }
        else if (currQuestion.correctAns == "2")
        {
            AnswerAText.text = "WRONG";
            AnswerBText.text = "WRONG";
            AnswerCText.text = "CORRECT";
            AnswerDText.text = "WRONG";
        }
        else
        {
            AnswerAText.text = "WRONG";
            AnswerBText.text = "WRONG";
            AnswerCText.text = "WRONG";
            AnswerDText.text = "CORRECT";
        }
    }
예제 #18
0
 /// <summary>
 /// 编辑选中考题
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void showEditQuestion(object sender, RoutedEventArgs e)
 {
     #region
     this.AddDBCheck(() =>
     {
         DataRowView drvquestion = null;
         if (this.dgQuestion.SelectedItem != null)
         {
             drvquestion = this.dgQuestion.SelectedItem as DataRowView;
         }
         else
         {
             ExtMessage.Show("请选中要编辑的数据!");
             return;
         }
         NewQuestion frmquestion = new NewQuestion(ExamQuestionState.NormalEdit);
         frmquestion.QuestionRow = QuestionController.QuestionData.Tables[0]
                                   .Rows.Find(drvquestion[ExamQuestionData.questionId]);
         frmquestion.InitUI();
         frmquestion.ShowDialog();
     });
     #endregion
 }
예제 #19
0
 public void SubmitQuestion([FromBody] NewQuestion newQuestion)
 {
     QuestionService.AddQuestion(newQuestion);
 }
 private void NewQuestion_Tick(object sender, EventArgs e)
 {
     if (Globalvariables.form == 5)
     {
         frmEndb Finish = new frmEndb(); // Opens end screen
         this.Hide();
         Finish.Show();                  // Opens end screen
         NewQuestion.Stop();
     }
     else
     {
         // This section of code will be used to select a new random question. It will ensure that the user does not recieve the same question twice.
         if (RandomNumber == 1 && Globalvariables.CompletedQuestionsB[0] == false)
         {
             frmQuestion1b Question1b = new frmQuestion1b();
             this.Close();
             Question1b.Show();
             NewQuestion.Stop();
         }
         else if (RandomNumber == 2 && Globalvariables.CompletedQuestionsB[1] == false)
         {
             frmQuestion2b Question2b = new frmQuestion2b();
             this.Close();
             Question2b.Show();
             NewQuestion.Stop();
         }
         else if (RandomNumber == 3 && Globalvariables.CompletedQuestionsB[2] == false)
         {
             frmQuestion3b Question3b = new frmQuestion3b();
             this.Close();
             Question3b.Show();
             NewQuestion.Stop();
         }
         else if (RandomNumber == 4 && Globalvariables.CompletedQuestionsB[3] == false)
         {
             frmQuestion4b Question4b = new frmQuestion4b();
             this.Close();
             Question4b.Show();
             NewQuestion.Stop();
         }
         else if (RandomNumber == 5 && Globalvariables.CompletedQuestionsB[4] == false)
         {
             frmQuestion5b Question5b = new frmQuestion5b();
             this.Close();
             Question5b.Show();
             NewQuestion.Stop();
         }
         else if (RandomNumber == 6 && Globalvariables.CompletedQuestionsB[5] == false)
         {
             frmQuestion6b Question6b = new frmQuestion6b();
             this.Close();
             Question6b.Show();
             NewQuestion.Stop();
         }
         else if (RandomNumber == 7 && Globalvariables.CompletedQuestionsB[6] == false)
         {
             frmQuestion7b Question7b = new frmQuestion7b();
             this.Close();
             Question7b.Show();
             NewQuestion.Stop();
         }
         else
         {
             RandomNumber = random.Next(1, 7);
         }
     }
 }