Ejemplo n.º 1
0
        /// <summary>
        /// 获取问题列表
        /// </summary>
        /// <param name="CurrentPage"></param>
        /// <param name="PageSize"></param>
        /// <param name="keyWord"></param>
        /// <returns></returns>
        public List <Model.Question> GetQuestionList(int CurrentPage, int PageSize, string keyWord)
        {
            SqlConnection co = new SqlConnection();

            co.ConnectionString = url;
            co.Open();
            SqlCommand cm = new SqlCommand();

            keyWord        = "'%" + keyWord + "%'";
            cm.CommandText = "select top " + PageSize + " * from t_base_question where  id not in (select top " + PageSize * (CurrentPage - 1) + " id from t_base_question  where content like " + keyWord + ")     and  content like " + keyWord;
            cm.Connection  = co;

            List <Model.Question> lst = new List <Model.Question>();
            SqlDataReader         dr  = cm.ExecuteReader();

            while (dr.Read())
            {
                Model.Question question = new Model.Question();
                question.Id      = Convert.ToInt32(dr["Id"]);
                question.Content = Convert.ToString(dr["Content"]);

                lst.Add(question);
            }
            dr.Close();
            co.Close();
            return(lst);
        }
Ejemplo n.º 2
0
        public JsonResult GetModel(int HeadId, int TeacherId)
        {
            BLL.QuestionnaireHead   bll   = new BLL.QuestionnaireHead();
            Model.QuestionnaireHead model = bll.GetModel(HeadId, TeacherId);

            List <object> fullItem = new List <object>();

            for (int i = 0; i < model.Item.Count; i++)
            {
                Model.SelectQuestion sq       = model.Item[i];
                Model.Question       question = new Model.Question();
                question.Id      = sq.Question.Id;
                question.Content = sq.Question.Content;

                object obj = new
                {
                    Question       = question,
                    QuestionHeadId = sq.QuestionHeadId,
                    AVGScore       = model.ScoreList[i] / new BLL.QuestionnaireHead().GetWritenTimes(sq.QuestionHeadId, TeacherId)
                };
                fullItem.Add(obj);
            }

            return(Json(new { Item = fullItem }));
            //return Json(model);
        }
Ejemplo n.º 3
0
 protected void Bind()
 {
     Model.Question      question        = new Model.Question();
     BLL.QuestionManager questionManager = new BLL.QuestionManager();
     GridView1.DataSource = questionManager.GetAllQuestion();
     GridView1.DataBind();
 }
Ejemplo n.º 4
0
        public Model.QuestionnaireHead GetModel(int HeadId, int TeacherId)
        {
            SqlConnection co  = SQLSeverOpen();
            SqlCommand    cmd = new SqlCommand();

            cmd.Connection = co;
            Model.QuestionnaireHead Questionnaire = new Model.QuestionnaireHead();
            Questionnaire.Item = new List <Model.SelectQuestion>();
            cmd.CommandText    = "select * from [V_SelectQuestion_Question] where QuestionnaireHeadId=@QuestionnaireHeadId";
            cmd.Parameters.AddWithValue("@QuestionnaireHeadId", HeadId);
            cmd.Connection = co;
            SqlDataReader dr = cmd.ExecuteReader();

            while (dr.Read())
            {
                Model.SelectQuestion item = new Model.SelectQuestion();
                item.QuestionHeadId = HeadId;
                item.QuestionId     = Convert.ToInt32(dr["QuestionId"]);
                Model.Question question = new Model.Question();
                question.Id      = item.QuestionId;
                question.Content = Convert.ToString(dr["content"]);
                item.Question    = question;
                Questionnaire.Item.Add(item);
                Questionnaire.ScoreList = GetQuestionScore(HeadId, TeacherId);
            }
            dr.Close();
            co.Close();
            return(Questionnaire);
        }
Ejemplo n.º 5
0
        public void ShouldReturnTheSameNumber()
        {
            TestQuestionFactory factory = new TestQuestionFactory();
            Question = new Model.Question();
            Question.PredefinedAnswers = new List<PredefinedAnswer>();
            pre1 = new PredefinedAnswer();
            pre2 = new PredefinedAnswer();
            pre1.Id = 1;
            pre1.Text = "Ja";
            pre2.Id = 2;
            pre2.Text = "Nee";
            Question.PredefinedAnswers.Add(pre1);
            Question.PredefinedAnswers.Add(pre2);

            answer1 = new UserAnswer();
            answer2 = new UserAnswer();
            answer3 = new UserAnswer();
            answer1.PredefinedAnswer_Id = pre1.Id;
            answer2.PredefinedAnswer_Id = pre2.Id;
            answer3.PredefinedAnswer_Id = pre1.Id;

            foreach (PredefinedAnswer item in Question.PredefinedAnswers)
            {
                Question.PredefinedAnswerCount++;
            }

            Assert.AreEqual(Question.PredefinedAnswerCount, 3);
        }
Ejemplo n.º 6
0
 void when_validating_the_Difficulty_property_with_a_valid_value()
 {
     new[] { 1, 2, 3, 4, 5 }.Do(value =>
     {
         Model.Question q = new Model.Question { Difficulty = value };
         it["of {0}, should be no errors".With(value)] = () => this.Validate(q, "Difficulty").should_be_empty();
     });
 }
Ejemplo n.º 7
0
 void when_validating_the_QuestionText_field_with_an_invalid_value()
 {
     new[] { null, "" }.Do(value =>
     {
         Model.Question q = new Model.Question { QuestionText = value };
         it["of {0}, should be no errors".With(value ?? "null")] = () => this.Validate(q, "QuestionText").should_not_be_empty();
     });
 }
Ejemplo n.º 8
0
 protected void Bind()
 {
     //Model.Admin admin1 = new Model.Admin();
     //BLL.AdminManager admin2 = new BLL.AdminManager();
     //GridView1.DataSource = admin2.GetList();
     //GridView1.DataBind();
     Model.Question      question1 = new Model.Question();
     BLL.QuestionManager question2 = new BLL.QuestionManager();
     GridView1.DataSource = question2.GetAllList();
     GridView1.DataBind();
 }
Ejemplo n.º 9
0
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            Model.Question      question3 = new Model.Question();
            BLL.QuestionManager question4 = new BLL.QuestionManager();
            int  QuestionID = Convert.ToInt32((GridView1.Rows[e.RowIndex].FindControl("LabelquestionID") as Label).Text);
            bool bo         = question4.Delete(QuestionID);

            if (bo == true)
            {
                Bind();
            }
        }
Ejemplo n.º 10
0
        public async Task <IActionResult> Put(int id, [FromBody] Model.Question question)
        {
            if (id != question.ID)
            {
                return(BadRequest());
            }

            context.Entry(question).State = EntityState.Modified;

            await context.SaveChangesAsync();

            return(Ok(question));
        }
Ejemplo n.º 11
0
        public void BindData()
        {
            Model.Question      question1 = new Model.Question();
            BLL.QuestionManager question2 = new BLL.QuestionManager();


            DataSet       ds       = new DataSet();
            StringBuilder strWhere = new StringBuilder();

            ds = question2.GetList(strWhere.ToString());
            gridView.DataSource = ds;
            gridView.DataBind();
        }
Ejemplo n.º 12
0
        private Tuple <List <Model.Question>, List <Model.Answer> > getRandom(string type, int num_ques)
        {
            List <Model.Question> returnQues = new List <Model.Question>();
            List <Model.Answer>   returnAns  = new List <Model.Answer>();

            List <Model.Question> lsques = new List <Model.Question>();
            List <Model.Answer>   lsans  = new List <Model.Answer>();

            if (type == "db")
            {
                for (int i = 0; i < ListObj.LsQuesDB.Count; i++)
                {
                    lsques.Add(ListObj.LsQuesDB[i]);
                }
                for (int i = 0; i < ListObj.LsAnsDB.Count; i++)
                {
                    lsans.Add(ListObj.LsAnsDB[i]);
                }
            }
            else
            {
                for (int i = 0; i < ListObj.LsQuesFile.Count; i++)
                {
                    lsques.Add(ListObj.LsQuesFile[i]);
                }
                for (int i = 0; i < ListObj.LsAnsFile.Count; i++)
                {
                    lsans.Add(ListObj.LsAnsFile[i]);
                }
            }

            for (int i = 0; i < num_ques; i++)
            {
                var            random = new Random();
                int            index  = random.Next(lsques.Count);
                Model.Question ques   = lsques[index];
                for (int j = 0; j < lsans.Count; j++)
                {
                    if (lsans[j].Id_ques == ques.Id)
                    {
                        returnAns.Add(lsans[j]);
                    }
                }
                returnQues.Add(ques);
                lsques.Remove(ques);
            }

            txtCmd.Invoke(new richTXTChange(AppendText), new object[] { txtCmd, sckClient.RemoteEndPoint + " connected", new Tuple <int, int, int>(0, 128, 0) });

            return(new Tuple <List <Model.Question>, List <Model.Answer> >(returnQues, returnAns));
        }
Ejemplo n.º 13
0
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            string idlist = GetSelIDlist();

            if (idlist.Trim().Length == 0)
            {
                return;
            }
            Model.Question      question1 = new Model.Question();
            BLL.QuestionManager question2 = new BLL.QuestionManager();
            question2.DeleteList(idlist);

            BindData();
        }
Ejemplo n.º 14
0
        //private int getCount(int TeacherId, int ClassId)
        //{
        //    SqlConnection co = SQLSeverOpen();
        //    SqlCommand cmd = new SqlCommand();
        //    cmd.Connection = co;
        //    List<Model.Score> list = new List<Model.Score>();
        //    cmd.CommandText = "select COUNT(1) from V_QuestionHead_Select where TeacherId = " + TeacherId + " and ClassId = " + ClassId;

        //    return (int)cmd.ExecuteScalar();
        //}
        public List <Model.Score> GetTeacherClassScore(int TeacherId, int ClassId)
        {
            SqlConnection co  = SQLSeverOpen();
            SqlCommand    cmd = new SqlCommand();

            cmd.Connection = co;
            List <Model.Score> list = new List <Model.Score>();

            cmd.CommandText = "select  top 10 * from V_QuestionHead_Select where TeacherId = " + TeacherId + " and ClassId = " + ClassId;
            SqlDataReader         reader       = cmd.ExecuteReader();
            List <Model.Question> questionList = new List <Model.Question>();

            Model.Score score = new Model.Score();

            while (reader.Read())
            {
                try
                {
                    Model.Teacher  teacher   = new Model.Teacher();
                    Model.Class    tempClass = new Model.Class();
                    Model.Question question  = new Model.Question();
                    score.TeacherId  = Convert.ToInt32(reader["TeacherId"]);
                    score.ClassId    = Convert.ToInt32(reader["ClassId"]);
                    score.TotalScore = Convert.ToInt32(reader["TotalScore"]);
                    score.TeacherId  = Convert.ToInt32(reader["TeacherId"]);
                    List <int> scoreList = GetTotalScore(TeacherId, ClassId);
                    score.QScore     = scoreList;
                    question.Content = Convert.ToString(reader["Content"]);
                    questionList.Add(question);
                    ;
                    tempClass.Id        = Convert.ToInt32(reader["ClassId"]);
                    tempClass.ClassName = Convert.ToString(reader["ClassName"]);
                    teacher.Id          = Convert.ToInt32(reader["TeacherId"]);
                    teacher.TeacherName = Convert.ToString(reader["TeacherName"]);
                    score.Teacher       = teacher;
                    score.Class         = tempClass;

                    score.Question = questionList;
                    list.Add(score);
                }
                catch (Exception)
                {
                    continue;
                }
            }

            reader.Close();
            co.Close();
            return(list);
        }
Ejemplo n.º 15
0
        public async Task <IActionResult> Post([FromBody] Model.Question question)
        {
            var quiz = context.Quiz.SingleOrDefault(q => q.ID == question.QuizId);

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

            context.Questions.Add(question);
            await context.SaveChangesAsync();

            return(Ok(question));
        }
Ejemplo n.º 16
0
        public void SelectListByIdWithTwoQuestions_ShouldReturnQuestionAmountOfTwo()
        {
            TestViewQuestionList view = new TestViewQuestionList();
            ListQuestionListController QuestionListController = new ListQuestionListController(view);
            QuestionListController.SetBaseFactory(new TestQuestionListFactory());
            QuestionListController.Load();

            Model.Question q = new Model.Question();
            view.AddToList(q, 1);
            view.AddToList(q, 2);
            view.AddToList(q, 2);

            Model.QuestionList list = view.getById(2);

            Assert.AreEqual(list.MCQuestions.Count, 2);
        }
Ejemplo n.º 17
0
        public ICollection <Model.Question> GetQuestions(int TopicId)
        {
            List <Model.Question> questionBank = new List <Model.Question>();

            Mutex.WaitOne();
            var x = this.GetDbSet <Controller.Database.Tables.Question>().Include(q => q.Answers).Where(q => q.TopicId == TopicId && q.IsCustom == 0);

            Mutex.ReleaseMutex();
            foreach (Controller.Database.Tables.Question question in x)
            {
                Model.Question q = new Model.Question();
                q.FromEntity(question);
                questionBank.Add(q);
            }
            return(questionBank);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Model.Question DataRowToModel(DataRow row)
        {
            Model.Question model = new Model.Question();

            if (row != null)
            {
                if (row["ID"] != null && row["ID"].ToString() != "")
                {
                    model.ID = long.Parse(row["ID"].ToString());
                }

                if (row["QuestionaryID"] != null && row["QuestionaryID"].ToString() != "")
                {
                    model.QuestionaryID = long.Parse(row["QuestionaryID"].ToString());
                }

                if (row["Content"] != null)
                {
                    model.Content = row["Content"].ToString();
                }

                if (row["Answer"] != null)
                {
                    model.Answer = row["Answer"].ToString().Split('|');

                }

                if (row["Orders"] != null && row["Orders"].ToString() != "")
                {
                    model.Orders = int.Parse(row["Orders"].ToString());
                }

                if (row["IsSingle"] != null && row["IsSingle"].ToString() != "")
                {
                    if ((row["IsSingle"].ToString() == "1") || (row["IsSingle"].ToString().ToLower() == "true"))
                    {
                        model.IsSingle = true;
                    }
                    else
                    {
                        model.IsSingle = false;
                    }
                }
               }
               return model;
        }
Ejemplo n.º 19
0
        protected override void OnLoad(EventArgs e)
        {
            var id = Request.QueryString["id"].TryParseToInt32(0);

            if (id == 0)
            {
                Response.Redirect("/Question/");
            }

            var questionSvr = unity.GetInstance <IQuestionService>();

            Model = questionSvr.GetQuestion(id);

            Model.Click += 1;

            questionSvr.Modify(Model);
        }
Ejemplo n.º 20
0
        /// <summary>
        /// 保存增加的问题
        /// </summary>
        /// <param name="question"></param>
        /// <returns></returns>
        public int saveQuestion(Model.Question question)
        {
            SqlConnection co = new SqlConnection();

            co.ConnectionString = url;
            co.Open();

            SqlCommand cm = new SqlCommand();

            cm.Connection  = co;
            cm.CommandText = "insert into t_base_question(content) values(@Content)";
            cm.Parameters.AddWithValue("@Content", question.Content);

            int result = cm.ExecuteNonQuery();

            co.Close();
            return(result);
        }
Ejemplo n.º 21
0
        protected void BntSave_Click(object sender, EventArgs e)
        {
            Model.Question question = new Model.Question();
            question.question   = txtQuestion.Text.Trim();
            question.solution   = txtSolution.Text.Trim();
            question.categoryID = Convert.ToInt32(DropDownList_Category.SelectedValue.ToString());

            BLL.QuestionManager questionManager = new BLL.QuestionManager();
            bool bo = questionManager.Add(question);

            if (bo == true)
            {
                Response.Write("<script language=javascript>alert('添加成功!')</script>");
                BindData();
            }
            else
            {
                Response.Write("<script language=javascript>alert('添加失败!请重试')");
            }
        }
Ejemplo n.º 22
0
        public async Task <bool> CreateQuestions(List <QuestionCreate> newQuestions, string userId)
        {
            foreach (var newQuestion in newQuestions)
            {
                //TODO: check for question duplication
                Model.Question question = _mapper.Map <Model.Question>(newQuestion);
                question.Creator = userId;
                //TODO: check question difficulty
                question.Difficulty = QuestionDifficulty.EASY;
                question.Answers    = _mapper.Map <ICollection <Model.Answer> >(newQuestion.Answers);

                _unitOfWork.QuestionRepository.Insert(question);
            }

            if (await _unitOfWork.SaveAsync() <= 0)
            {
                throw new CommonException("QUESTION_ADD", "Error in CreateQuestion");
                // return _mapper.Map<QuestionCreate>(await _unitOfWork.QuestionRepository.Get());
            }
            return(true);
        }
Ejemplo n.º 23
0
        protected void GridView1_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            //Model.Admin admin1 = new Model.Admin();
            //BLL.AdminManager admin2 = new BLL.AdminManager();
            //admin1.ID = Convert.ToInt32((GridView1.Rows[e.RowIndex].FindControl("Label1") as Label).Text);
            //admin1.adminName = (GridView1.Rows[e.RowIndex].FindControl("TextBox1") as TextBox).Text.ToString();
            //admin1.department = (GridView1.Rows[e.RowIndex].FindControl("TextBox2") as TextBox).Text.ToString();
            //bool bo = admin2.Update(admin1);
            //GridView1.EditIndex = -1;
            //Bind();

            Model.Question      question1 = new Model.Question();
            BLL.QuestionManager question2 = new BLL.QuestionManager();
            question1.questionID = Convert.ToInt32((GridView1.Rows[e.RowIndex].FindControl("LabelquestionID") as Label).Text);
            question1.question   = (GridView1.Rows[e.RowIndex].FindControl("txbQuestion") as TextBox).Text.ToString();
            question1.solution   = (GridView1.Rows[e.RowIndex].FindControl("txbSolution") as TextBox).Text.ToString();
            bool bo = question2.Update(question1);

            GridView1.EditIndex = -1;
            Bind();
        }
Ejemplo n.º 24
0
        protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            //Model.Admin admin1 = new Model.Admin();
            //BLL.AdminManager admin2 = new BLL.AdminManager();
            //int adminID = Convert.ToInt32((GridView1.Rows[e.RowIndex].FindControl("Label1") as Label).Text);

            //bool bo = admin2.Delete(adminID);
            //if (bo == true)
            //{
            //    Bind();
            //}
            Model.Question      question3 = new Model.Question();
            BLL.QuestionManager question4 = new BLL.QuestionManager();
            int  QuestionID = Convert.ToInt32((GridView1.Rows[e.RowIndex].FindControl("Label1") as Label).Text);
            bool bo         = question4.Delete(QuestionID);

            if (bo == true)
            {
                Bind();
            }
        }
Ejemplo n.º 25
0
        protected void gridView_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            Model.Question question = new Model.Question();
            question.question   = (gridView.Rows[e.RowIndex].FindControl("txtQuestion") as TextBox).Text;
            question.solution   = (gridView.Rows[e.RowIndex].FindControl("txtSolution") as TextBox).Text;
            question.questionID = Convert.ToInt32(gridView.DataKeys[e.RowIndex].Value);
            question.categoryID = Int32.Parse((gridView.Rows[e.RowIndex].FindControl("txtCcategory") as Label).Text);

            BLL.QuestionManager questionManager = new BLL.QuestionManager();
            bool bo = questionManager.Update(question);

            if (bo == true)
            {
                Response.Write("<script language=javascript>alert('修改成功!')</script>");
                gridView.EditIndex = -1;
                BindData();
            }
            else
            {
                Response.Write("<script language=javascript>alert('修改失败!请重试')");
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// 获取单个问题
        /// </summary>
        /// <param name="Id"></param>
        /// <returns></returns>
        public Model.Question GetQustion(int Id)
        {
            SqlConnection co = new SqlConnection();

            co.ConnectionString = url;
            co.Open();
            SqlCommand cm = new SqlCommand();

            cm.Connection  = co;
            cm.CommandText = "select * from t_base_question where Id = " + Id;
            SqlDataReader reader = cm.ExecuteReader();

            Model.Question question = new Model.Question();
            while (reader.Read())
            {
                question.Id      = Convert.ToInt32(reader["Id"]);
                question.Content = Convert.ToString(reader["Content"]);
            }
            reader.Close();
            co.Close();
            return(question);
        }
Ejemplo n.º 27
0
        public List <Model.Question> showNaireQuestion(int HeadId)
        {
            SqlConnection co = new SqlConnection();

            co.ConnectionString = url;
            co.Open();

            string                SqlWords = "select t_base_selectquestion.Id Id, content Content from t_base_Question , t_base_selectquestion  where t_base_Question.Id=t_base_selectquestion.QuestionId and QuestionnaireHeadId=" + HeadId;
            SqlCommand            cm       = new SqlCommand(SqlWords, co);
            List <Model.Question> lst      = new List <Model.Question>();
            SqlDataReader         dr       = cm.ExecuteReader();

            while (dr.Read())
            {
                Model.Question naire = new Model.Question();
                naire.Id      = Convert.ToInt32(dr["Id"]);
                naire.Content = Convert.ToString(dr["Content"]);
                lst.Add(naire);
            }
            dr.Close();
            co.Close();
            return(lst);
        }
Ejemplo n.º 28
0
        protected void Page_Load(object sender, EventArgs e)
        {
            var questionSvr = unity.GetInstance <IQuestionService>();

            if ("POST".Equals(Request.RequestType.ToUpper()))
            {
                var question = new Model.Question();
                question.Title    = Request.Form["title"];
                question.Info     = Request.Form["content"];
                question.Type_Id  = Request.Form["default1"].TryParseToInt32(0);
                question.User_Id  = LoggedUser.Id;
                question.Add_Time = DateTime.Now.ToUnixTimestamp();

                question.From      = "";
                question.Img       = "";
                question.Url       = "";
                question.Resp      = "";
                question.Seo_Title = "";
                question.Seo_Keys  = "";
                question.Seo_Desc  = "";
                question.Filename  = "";

                try
                {
                    questionSvr.Add(question);
                    ViewState["Message"] = "问题发布成功。";
                }
                catch (ApplicationException ex)
                {
                    ViewState["Message"] = ex.Message;
                }
                catch
                {
                    ViewState["Message"] = "系统异常";
                }
            }
        }
Ejemplo n.º 29
0
        public bool CheckQuestion(Model.Question question, string answers)
        {
            int count = 0;

            foreach (char character in question.GetCorrectAnswers())
            {
                if (character == 'A' || character == 'B' || character == 'C')
                {
                    count++;
                }
            }
            if (count != answers.Count())
            {
                return(false);
            }
            foreach (char answer in answers)
            {
                if (!question.GetCorrectAnswers().Contains(answer))
                {
                    return(false);
                }
            }
            return(true);
        }
Ejemplo n.º 30
0
        public void ShouldReturnTheSameNumber()
        {
            Question = new Model.Question();
            Question.PredefinedAnswers = new List<PredefinedAnswer>();
            answer1 = new PredefinedAnswer();
            answer2 = new PredefinedAnswer();
            answer3 = new PredefinedAnswer();
            answer1.Id = 1;
            answer1.Text = "Ja";
            answer2.Id = 2;
            answer2.Text = "Ja";
            answer3.Id = 3;
            answer3.Text = "Nee";
            Question.PredefinedAnswers.Add(answer1);
            Question.PredefinedAnswers.Add(answer2);
            Question.PredefinedAnswers.Add(answer3);

            foreach (PredefinedAnswer item in Question.PredefinedAnswers)
            {
                Question.PredefinedAnswerCount++;
            }

            Assert.AreEqual(Question.PredefinedAnswerCount, 3);
        }
Ejemplo n.º 31
0
        private void setQuiz(int index)
        {
            panelQuiz.Controls.Clear();
            lsSaveUC.Clear();

            Model.Question ques;
            ques = quesList[index].Item2;

            var setupQues = setQues(quesList[index].Item1 + ") " + ques.Content);

            int width  = setupQues.Item1;
            int height = setupQues.Item2;

            setAnswers(setupQues.Item1, setupQues.Item2, ques.Id, ques.Num_answer_right);

            quesCurrent    = ques;
            integerCurrent = quesList[index].Item1;


            if (countPrev() != 0)
            {
                btnPrev.Visible = true;
            }
            else
            {
                btnPrev.Visible = false;
            }
            if (countNext() != 0)
            {
                btnNext.Visible = true;
            }
            else
            {
                btnNext.Visible = false;
            }
        }
Ejemplo n.º 32
0
 public Model.Question ToModel()
 {
     Model.Answer[] answers = new Model.Answer[Answers.Length + 1];
     answers[0] = new Model.Answer()
     {
         IsCorrect = true,
         Text      = Answer
     };
     for (int i = 0; i < Answers.Length; i++)
     {
         answers[i + 1] = new Model.Answer()
         {
             IsCorrect = false,
             Text      = Answers[i]
         };
     }
     Model.Question question = new Model.Question()
     {
         QuestionStr = Question,
         TopicId     = this.TopicId,
         Answers     = answers,
     };
     return(question);
 }
Ejemplo n.º 33
0
 protected void rbtnSubmit_Click(object sender, EventArgs e)
 {
     string title = RTB_Title.Text;
     if (title.Trim().Equals(""))
     {
         RadScriptManager.RegisterStartupScript(this.Page, this.GetType(), "c1", "OpenAlert('抱歉,标题不能为空!');", true);
         return;
     }
     SmartLaw.Model.Questionary qnModel = qn.GetQnModel(QnID);
     List<SmartLaw.Model.Question> qsModelList = qn.GetQsModelList(1, QnID.ToString());
     List<SmartLaw.Model.Question> qsnewModelList = new List<Model.Question>();
     if (!RadButton2.Checked)
     {
         qnModel.IsValid = true;
         for (int i = 0; i < RadGrid1.Items.Count; i++)
         {
             RadTextBox idbox = (RadTextBox)RadGrid1.Items[i].FindControl("idbox");
             SmartLaw.Model.Question qsM = new Model.Question();
             long iid = long.Parse(idbox.Text);
             if (iid != -1)
             {
                 qsM = qn.GetQsModel(iid);
             }
             else
             {
                 qsM.ID = -1;
             }
             qsM.Orders = i;
             RadTextBox box = (RadTextBox)RadGrid1.Items[i].FindControl("content");
             string Content = box.Text;
             if (Content.Trim() == "")
             {
                 RadScriptManager.RegisterStartupScript(this.Page, this.GetType(), "c1", "OpenAlert('抱歉,问题不能为空!');", true);
                 return;
             }
             qsM.Content = Content;
             RadTextBox box1 = (RadTextBox)RadGrid1.Items[i].FindControl("answer1");
             string Answer1 = box1.Text;
             RadTextBox box2 = (RadTextBox)RadGrid1.Items[i].FindControl("answer2");
             string Answer2 = box2.Text;
             RadTextBox box3 = (RadTextBox)RadGrid1.Items[i].FindControl("answer3");
             string Answer3 = box3.Text;
             RadTextBox box4 = (RadTextBox)RadGrid1.Items[i].FindControl("answer4");
             string Answer4 = box4.Text;
             StringBuilder ansSb = new StringBuilder();
             if (Answer1.Trim() != "")
             {
                 ansSb.Append(Answer1.Trim() + "|");
             }
             if (Answer2.Trim() != "")
             {
                 ansSb.Append(Answer2.Trim() + "|");
             }
             if (Answer3.Trim() != "")
             {
                 ansSb.Append(Answer3.Trim() + "|");
             }
             if (Answer4.Trim() != "")
             {
                 ansSb.Append(Answer4.Trim() + "|");
             }
             if (ansSb.ToString().Equals(""))
             {
                 RadScriptManager.RegisterStartupScript(this.Page, this.GetType(), "c1", "OpenAlert('抱歉,一个问题至少有一个选项!');", true);
                 return;
             }
             string[] ans = ansSb.ToString().Substring(0, ansSb.ToString().Length - 1).Split('|');
             qsM.Answer = ans;
             RadButton rbt = RadGrid1.Items[i].FindControl("RadButton3") as RadButton;
             qsM.IsSingle = rbt.Checked;
             qsM.QuestionaryID = QnID;
             qsnewModelList.Add(qsM);
         }
     }
     else
     {
         qnModel.IsValid = false;
     }
     SmartLaw.Model.Log logM = new Model.Log();
     logM.OperationItem = "修改调查问卷";
     logM.OperationDetail = "标题:" + title;
     logM.OperationTime = DateTime.Now;
     logM.Operator = user.UserInfo.UserID;
     logM.Memo = "";
     bool isUpdate = false;
     try
     {
         qnModel.Title = title;
         if (qnModel.IsValid)
         {
             isUpdate = qn.UpdateQuestionary(qnModel);
             if (isUpdate)
             {
                 List<long> oldIds = new List<long>();
                 foreach (SmartLaw.Model.Question qsM in qsnewModelList)
                 {
                     if (qsM.ID != -1)
                     {
                         isUpdate = false;
                         oldIds.Add(qsM.ID);
                         isUpdate = qn.UpdateQuestion(qsM);
                         if (!isUpdate)
                         {
                             break;
                         }
                     }
                     else
                     {
                         if (qn.AddQuestion(QnID, qsM) == 0)
                         {
                             isUpdate = false;
                             break;
                         }
                     }
                 }
                 foreach (SmartLaw.Model.Question qsoldM in qsModelList)
                 {
                     if (!oldIds.Contains(qsoldM.ID))
                     {
                         qn.DeleteQuestion(qsoldM.ID);
                     }
                 }
             }
         }
         else
         {
             if (qsModelList.Count > 0)
             {
                 isUpdate = qn.DeleteAllQuestionsInQn(QnID);
             }
             if (isUpdate)
             {
                 isUpdate = qn.UpdateQuestionary(qnModel);
             }
         }
         if (isUpdate)
         {
             logM.Memo += "成功";
         }
         else
         {
             logM.Memo += "失败";
         }
     }
     catch (Exception ex)
     {
         logM.Memo += ex.Message;
     }
     finally
     {
         log.Add(logM);
         if (isUpdate)
         {
             RadScriptManager.RegisterStartupScript(this.Page, this.GetType(), "c", "OpenAlert('恭喜!修改成功!');", true);
         }
         else
         {
             RadScriptManager.RegisterStartupScript(this.Page, this.GetType(), "c3", "OpenAlert('抱歉!修改失败!');", true);
         }
     }
 }
Ejemplo n.º 34
0
 public void Delete(Model.Question entity)
 {
     entity.IsActive = false;
     _questionDAL.Update(entity);
 }
Ejemplo n.º 35
0
        //Literally goes to the next question if there is one, otherwise it'll go back to the waitingscreen.
        public void goToNextQuestion()
        {
            view.startLabelTimer();

            view.cleanUpPreviousQuestion();
            view.getAnswerButtons().Clear();
            questionTimer.Stop();

            if (controller.getCurrentQuestionIndex() < this.questionList.MCQuestions.Count + this.questionList.OpenQuestions.Count) {
                controller.setCurrentQuestionIndex(controller.getCurrentQuestionIndex() + 1);
            }

            if (this.questionList.MCQuestions.Count + this.questionList.OpenQuestions.Count  - 1 >= controller.getCurrentQuestionIndex())
            {
                if (controller.getCurrentQuestionIndex() < this.questionList.MCQuestions.Count)
                {
                    view.initMCQuestionScreen();
                    busy = true;
                    questionTimeProgressBar.Value = questionTimeProgressBar.Maximum;

                    currentMCQuestion = this.questionList.MCQuestions[controller.getCurrentQuestionIndex()];
                    if (currentMCQuestion.Time > 1)
                    {
                        questionTimeProgressBar.Maximum = currentMCQuestion.Time * 1000;
                        questionTimeProgressBar.Value = currentMCQuestion.Time * 1000;
                        questionTimer.Start();
                        this.questionCountLabel.Location = new Point(this.getProgressBar().Location.X + this.getProgressBar().Width - this.questionCountLabel.Width, this.getProgressBar().Location.Y - this.questionCountLabel.Height);
                    }
                    else
                    {
                        questionTimeProgressBar.Visible = false;
                        timeLabel.Visible = false;
                        this.questionCountLabel.Location = new Point(this.getProgressBar().Location.X + this.getProgressBar().Width - this.questionCountLabel.Width, this.getProgressBar().Location.Y + this.getProgressBar().Height - this.questionCountLabel.Height);
                    }
                    this.view.adjustSizeOfButtons(currentMCQuestion);
                    questionLabel.Text = currentMCQuestion.Text;
                }
                else
                {
                    view.initOpenQuestionScreen();
                    currentOpenQuestion = this.questionList.OpenQuestions[controller.getCurrentQuestionIndex() - this.questionList.MCQuestions.Count];
                    busy = true;
                    questionLabel.Text = currentOpenQuestion.Text;
                }

            }
            else if (this.questionList.Ended)
            {
                MessageBox.Show("De vragenlijst is gestopt.");
                this.questionList.Ended = false;

            }
            else
            {
                view.initWaitScreen();
                questionTimer.Stop();
                view.stopLabelTimer();
                busy = false;
            }
        }
Ejemplo n.º 36
0
 public void TestIfTimerIsNotRunning_WhenQuestionTimeIs0()
 {
     Model.Question question = new Model.Question();
     question.Time = 0;
     Assert.AreEqual(question.Time, 0);
 }
Ejemplo n.º 37
0
 void when_i_create_a_question_the_created_date()
 {
     Model.Question q = new Model.Question();
     it["should be roughly now"] = () => q.CreatedDate.should_be(DateTime.Now);
 }
Ejemplo n.º 38
0
 public QuestionVM(Model.Question question)
 {
     // TODO: Complete member initialization
     this.question = question;
 }
Ejemplo n.º 39
0
 public QuestionVM()
 {
     this.question = new Model.Question();
 }
Ejemplo n.º 40
0
 public void ValidQuestionQuestionTextTest()
 {
     Model.Question q = new Model.Question { QuestionText = "Valid Value" };
     Assert.AreEqual(GetValidationResultsForField(q, "QuestionText").Count(), 0);
 }
Ejemplo n.º 41
0
 public void InvalidQuestionNullQuestionTextTest()
 {
     Model.Question q = new Model.Question { QuestionText = null };
     Assert.AreEqual(GetValidationResultsForField(q, "QuestionText").Count(), 1);
 }
Ejemplo n.º 42
0
 public void InvalidQuestionEmptyQuestionTextTest()
 {
     Model.Question q = new Model.Question { QuestionText = string.Empty };
     Assert.AreEqual(GetValidationResultsForField(q, "QuestionText").Count(), 1);
 }
Ejemplo n.º 43
0
 public void CreatedDateRoughlyNowTest()
 {
     Model.Question q = new Model.Question();
     Assert.AreEqual(q.CreatedDate, DateTime.Now);
 }
Ejemplo n.º 44
0
        private async Task <Model.MapStory> JSONtoModels(Windows.Storage.StorageFile file)
        {
            Model.Story storyModel = new Model.Story();
            Model.Map   mapModel   = new Model.Map();

            var dialog = new MessageDialog("");

            if (file != null)
            {
                string data = await Windows.Storage.FileIO.ReadTextAsync(file);

                JsonObject jsonObj = new JsonObject();
                jsonObj = JsonObject.Parse(data);

                MapStory.Story.Title       = jsonObj.GetNamedString("title");
                MapStory.Story.Description = jsonObj.GetNamedString("description");
                MapStory.Story.Author      = jsonObj.GetNamedString("author");

                //JsonObject, to access Json Api for Interactable Object.
                JsonObject interactableObjects = new JsonObject();

                interactableObjects = jsonObj.GetNamedObject("interactableobjects");
                //Multiple Interactable Objects usually. Has to dismantle and save them all into objects of the major Model: MapStory Model.
                foreach (var obj in interactableObjects)
                {
                    Model.InteractableObject interactableObjectModel = new Model.InteractableObject();

                    //Interactable Object (characters, enemies, bosses, friends, talking chair, etc)
                    interactableObjectModel.Name = obj.Key;
                    JsonObject jsonInteracatbleObject = new JsonObject();
                    jsonInteracatbleObject = JsonObject.Parse(obj.Value.ToString());
                    // Each interactable Objects has multiple branches, options, states, feelings etc...
                    foreach (var branch in jsonInteracatbleObject)
                    {
                        //Branch has a name.
                        Model.Branch branchModel = new Model.Branch();
                        branchModel.Messages = new List <Model.Message>();
                        branchModel.Name     = branch.Key;
                        JsonObject jsonObjBranch = new JsonObject();
                        jsonObjBranch = JsonObject.Parse(branch.Value.ToString());



                        //BranchModel added into the InteractableObjectModel. This process will repeatedly for the other branches.
                        interactableObjectModel.Branches.Add(branchModel);
                        //var dialogJson is not really a true JsonObject, it has only 2 properties (Key and Value).
                        //Those values have to be converted to Strings from a so called: "KeyValuePair".
                        foreach (var dialogJson in jsonObjBranch)
                        {
                            JsonObject dialogJsonObject = JsonObject.Parse(dialogJson.Value.ToString());

                            if (dialogJsonObject.ContainsKey("question"))
                            {
                                Model.Question questionModel = new Model.Question();
                                questionModel.Choices = new List <Model.Choice>();
                                questionModel.Name    = dialogJsonObject.GetNamedValue("name").ToString();
                                questionModel.Text    = dialogJsonObject.GetNamedValue("question").ToString();
                                if (dialogJsonObject.ContainsKey("emote"))
                                {
                                    questionModel.Emote = dialogJsonObject.GetNamedValue("emote").ToString();
                                }
                                JsonObject jsonObjChoices = new JsonObject();

                                if (JsonObject.TryParse(dialogJsonObject.GetNamedValue("choices").ToString(), out jsonObjChoices))
                                {
                                    foreach (var choiceJson in jsonObjChoices)
                                    {
                                        JsonObject   jsonObjectChoice = JsonObject.Parse(choiceJson.Value.ToString());
                                        Model.Choice choiceModel      = new Model.Choice();
                                        choiceModel.Name = jsonObjectChoice.GetNamedValue("name").ToString();

                                        //Recommend to have this... if it's empty, make a notification in the GUI.
                                        if (jsonObjChoices.ContainsKey("description"))
                                        {
                                            choiceModel.Description = jsonObjectChoice.GetNamedValue("description").ToString();
                                        }
                                        //Target is optional.
                                        if (jsonObjectChoice.ContainsKey("target"))
                                        {
                                            choiceModel.Function = jsonObjectChoice.GetNamedValue("target").ToString();
                                        }
                                        //Branch is optional... what's the real difference tho?
                                        if (jsonObjectChoice.ContainsKey("branch"))
                                        {
                                            choiceModel.Branch = jsonObjectChoice.GetNamedValue("branch").ToString();
                                        }
                                        questionModel.Choices.Add(choiceModel);
                                    }
                                    branchModel.Messages.Add(questionModel);
                                }
                                else
                                {
                                    MessageDialog msgbox = new MessageDialog("Error! There should be Choices jsonObject in the question JsonObject.");
                                    await msgbox.ShowAsync();
                                }
                            }

                            else
                            {
                                Model.Message message = new Model.Message();
                                if (dialogJsonObject.ContainsKey("name"))
                                {
                                    message.Name = dialogJsonObject.GetNamedValue("name").ToString();
                                }
                                else
                                {
                                    message.Name = "No name found?!";
                                }

                                if (dialogJsonObject.ContainsKey("message"))
                                {
                                    message.Text = dialogJsonObject.GetNamedValue("message").ToString();
                                }
                                else
                                {
                                    message.Text = "";
                                }
                                if (dialogJsonObject.ContainsKey("emote"))
                                {
                                    message.Emote = dialogJsonObject.GetNamedValue("emote").ToString();
                                }
                                branchModel.Messages.Add(message);
                            }

                            if (int.TryParse(dialogJson.Key, out int dialognumber))
                            {
                            }

                            else
                            {
                            }
                        }
                        //has chain of messages that the player has to go through.
                        //continue here ->
                        //extra info: go through another foreach. This time for the real dialogs.
                    }

                    //Interactable Object is filled... now it gets added into the MapStory.
                    this.MapStory.Story.InteractableObjects.Add(interactableObjectModel);
                }
            }



            else
            {
                dialog = new MessageDialog("Error, file is null!");
                await dialog.ShowAsync();
            }



            if (MapStory != null)
            {
                return(this.MapStory);
            }
            else
            {
                dialog = new MessageDialog("Error, MapStory is null!");
                await dialog.ShowAsync();

                MapStory = new Model.MapStory();
                return(MapStory);
            }
        }
Ejemplo n.º 45
0
 void when_validating_the_QuestionText_field_with_a_valid_value()
 {
     Model.Question q = new Model.Question { QuestionText = "Valid Value" };
     it["of Valid Value, should be no errors"] = () => this.Validate(q, "QuestionText").should_be_empty();
 }
Ejemplo n.º 46
0
 void when_validating_the_CreatedBy_property_with_a_valid_value()
 {
     Model.Question q = new Model.Question { CreatedBy = "jameshughes" };
     it["should be valid"] = () => this.Validate(q, "CreatedBy").should_be_empty();
 }
Ejemplo n.º 47
0
        protected void rbtnSubmit_Click(object sender, EventArgs e)
        {
            string title = RTB_Title.Text;
            if (title.Trim().Equals(""))
            {
                RadScriptManager.RegisterStartupScript(this.Page, this.GetType(), "c1", "OpenAlert('抱歉,标题不能为空!');", true);
                return;
            }
            SmartLaw.Model.Questionary qnModel = new Model.Questionary();
            List<SmartLaw.Model.Question> qsModelList = new List<Model.Question>();
            if (!RadButton2.Checked)
            {
                qnModel.IsValid = true;
                for (int i = 0; i < RadGrid1.Items.Count; i++)
                {
                    SmartLaw.Model.Question qsM = new Model.Question();
                    qsM.Orders = i;
                    RadTextBox box = (RadTextBox)RadGrid1.Items[i].FindControl("content");
                    string Content = box.Text;
                    if (Content.Trim() == "")
                    {
                        RadScriptManager.RegisterStartupScript(this.Page, this.GetType(), "c1", "OpenAlert('抱歉,问题不能为空!');", true);
                        return;
                    }
                    qsM.Content = Content;
                    RadTextBox box1 = (RadTextBox)RadGrid1.Items[i].FindControl("answer1");
                    string Answer1 = box1.Text;
                    RadTextBox box2 = (RadTextBox)RadGrid1.Items[i].FindControl("answer2");
                    string Answer2 = box2.Text;
                    RadTextBox box3 = (RadTextBox)RadGrid1.Items[i].FindControl("answer3");
                    string Answer3 = box3.Text;
                    RadTextBox box4 = (RadTextBox)RadGrid1.Items[i].FindControl("answer4");
                    string Answer4 = box4.Text;
                    StringBuilder ansSb = new StringBuilder();
                    if (Answer1.Trim() != "")
                    {
                        ansSb.Append(Answer1.Trim() + "|");
                    }
                    if (Answer2.Trim() != "")
                    {
                        ansSb.Append(Answer2.Trim() + "|");
                    }
                    if (Answer3.Trim() != "")
                    {
                        ansSb.Append(Answer3.Trim() + "|");
                    }
                    if (Answer4.Trim() != "")
                    {
                        ansSb.Append(Answer4.Trim() + "|");
                    }
                    if (ansSb.ToString().Equals(""))
                    {
                        RadScriptManager.RegisterStartupScript(this.Page, this.GetType(), "c1", "OpenAlert('抱歉,一个问题至少有一个选项!');", true);
                        return;
                    }
                    string[] ans = ansSb.ToString().Substring(0, ansSb.ToString().Length - 1).Split('|');
                    qsM.Answer = ans;
                    RadButton rbt = RadGrid1.Items[i].FindControl("RadButton3") as RadButton;
                    qsM.IsSingle = rbt.Checked;
                    qsModelList.Add(qsM);
                }
            }
            else
            {
                qnModel.IsValid = false;
            }
            SmartLaw.Model.Log logM = new Model.Log();
            logM.OperationItem = "新增调查问卷";
            logM.OperationDetail = "标题:"+title;
            logM.OperationTime = DateTime.Now;
            logM.Operator = user.UserInfo.UserID;
            logM.Memo = "";
            long idAdd = 0;
            try
            {
                qnModel.Title = title;

                if (qnModel.IsValid)
                {
                    idAdd = qn.AddQuestionary(qnModel, qsModelList.ToArray());
                }
                else
                {
                    idAdd = qn.AddEmptyQuestionary(qnModel);
                }
                if (idAdd != 0)
                {
                    logM.Memo += "成功";
                }
                else
                {
                    logM.Memo += "失败";
                }
            }
            catch (Exception ex)
            {
                logM.Memo += ex.Message;
            }
            finally
            {
                log.Add(logM);
                if (idAdd!=0)
                {
                    RadScriptManager.RegisterStartupScript(this.Page, this.GetType(), "c", "OpenAlert('恭喜!添加成功!');", true);
                }
                else
                {
                    RadScriptManager.RegisterStartupScript(this.Page, this.GetType(), "c3", "OpenAlert('抱歉!添加失败!');", true);
                }
            }
        }
Ejemplo n.º 48
0
        private void btnConnect_Click(object sender, EventArgs e)
        {
            if (checkConnect)
            {
                return;
            }
            if (validate())
            {
                int size;
                sck = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
                try
                {
                    sck.Connect(IPAddress.Parse(txtIpServer.Text), Convert.ToInt32(txtPort.Text));
                }
                catch (SocketException ex)
                {
                    MessageBox.Show(ex.ToString(), "Có lỗi xảy ra", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    sck.Close();
                    return;
                }

                this.Width        = 620;
                btnClose.Location = new Point(290, 4);
                PanelTransition.ShowSync(panelProcess);
                checkConnect = true;

                try
                {
                    data = new byte[1024];

                    size = sck.Receive(data);//size server transfer

                    processBar.MaxValue = Convert.ToInt32(Encoding.ASCII.GetString(data, 0, size));

                    sendDone();

                    data = new byte[1024];
                    size = sck.Receive(data);//object para
                    Controller.ParaObject para = new Controller.ParaObject(data);
                    Controller.Constant.time = para.Time * 60;

                    processBar.Value += size;
                    processBar.Update();

                    sendDone();

                    if (para.GetDB > 0)
                    {
                        for (int i = 0; i < para.GetDB; i++)
                        {
                            data = new byte[1024];
                            size = sck.Receive(data);
                            Model.Question ques = new Model.Question(data);
                            lsquesDB.Add(ques);
                            processBar.Value += size;
                            processBar.Update();
                            sendDone();
                        }
                        size = sck.Receive(data);
                        int countAns = Convert.ToInt32(Encoding.ASCII.GetString(data, 0, size));
                        sendDone();

                        for (int i = 0; i < countAns; i++)
                        {
                            data = new byte[1024];
                            size = sck.Receive(data);
                            Model.Answer ans = new Model.Answer(data);
                            lsansDB.Add(ans);
                            processBar.Value += size;
                            processBar.Update();
                            sendDone();
                        }
                    }

                    if (para.GetFile > 0)
                    {
                        for (int i = 0; i < para.GetFile; i++)
                        {
                            data = new byte[1024];
                            size = sck.Receive(data);
                            Model.Question ques = new Model.Question(data);
                            lsquesFile.Add(ques);
                            processBar.Value += size;
                            processBar.Update();
                            sendDone();
                        }
                        size = sck.Receive(data);
                        int countAns = Convert.ToInt32(Encoding.ASCII.GetString(data, 0, size));
                        sendDone();

                        for (int i = 0; i < countAns; i++)
                        {
                            data = new byte[1024];
                            size = sck.Receive(data);
                            Model.Answer ans = new Model.Answer(data);
                            lsansFile.Add(ans);
                            processBar.Value += size;
                            processBar.Update();
                            sendDone();
                        }
                    }
                }
                catch (SocketException ex)
                {
                    MessageBox.Show(ex.ToString(), "Có lỗi xảy ra", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    sck.Close();
                    return;
                }

                var ls = joinList();
                this.quesList = ls.Item1;
                this.ansList  = ls.Item2;

                btnStartQuiz.Visible = true;

                listen = new Thread(new ThreadStart(threadListen));
                listen.IsBackground = true;
                listen.Start();
            }
            else
            {
                MessageBox.Show("Bạn phải điền đủ thông tin!", "Thông Báo", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }
Ejemplo n.º 49
0
        protected void post_Btn_Click(object sender, EventArgs e)
        {
            DBCramming db = new DBCramming();

            Model.Question _q = new Model.Question();

            var id = from q in db.Questions
                     select q.QuestionID;

            string[] tags = tag.Text.Split(' ');
            if (tags.Length <= 3)
            {
                if (tag.Text == "")
                {
                    valid.Text = "Vui lòng nhập tối thiểu 1 tag";
                }
                else
                {
                    foreach (string t in tags)
                    {
                        var check = from tg in db.Tags
                                    where tg.TagName == t
                                    select tg.TagID;
                        if (check.Count() < 1)
                        {
                            var new_id = from tg in db.Tags

                                         select tg.TagID;
                            Tag new_tag = new Tag();
                            new_tag.TagID   = new_id.Max() + 1;
                            new_tag.TagName = t;
                            db.Tags.Add(new_tag);
                            db.SaveChanges();
                        }
                    }
                    if (title.Text == "")
                    {
                        valid.Text = "Tiêu đề không được rỗng";
                    }
                    else
                    {
                        if (body.Text == "")
                        {
                            valid.Text = "Nội dung không được rỗng";
                        }
                        else
                        {
                            _q.UserID     = Session["id"].ToString();
                            _q.QuestionID = id.Max() + 1;
                            _q.Title      = title.Text;
                            _q.Body       = body.Text;
                            _q.viewcount  = 0;
                            _q.Likes      = 0;
                            _q.Posttime   = DateTime.Now;

                            db.Questions.Add(_q);
                            int res = db.SaveChanges();

                            foreach (string t in tags)
                            {
                                QuestionTag new_qt = new QuestionTag();
                                var         new_id = from qt in db.QuestionTags
                                                     select qt.QTID;
                                var tag_id = from b in db.Tags
                                             where b.TagName == t
                                             select b.TagID;
                                new_qt.QTID       = new_id.Max() + 1;
                                new_qt.TagID      = tag_id.FirstOrDefault();
                                new_qt.QuestionID = _q.QuestionID;

                                db.QuestionTags.Add(new_qt);
                                db.SaveChanges();
                            }
                            if (res > 0)
                            {
                                Response.Redirect("Question.aspx");
                            }
                            else
                            {
                                valid.Text = "Đã có lỗi xảy ra vui lòng thử lại";
                            }
                        }
                    }
                }
            }
            else
            {
                valid.Text = "Vui lòng nhập ít hơn 3 tag";
            }
        }
Ejemplo n.º 50
0
 void when_validating_the_CreatedBy_property_with_an_unset_value()
 {
     Model.Question q = new Model.Question();
     it["should be invalid"] = () => this.Validate(q, "CreatedBy").should_not_be_empty();
 }
Ejemplo n.º 51
0
        /// <summary>
        /// 得到一个对象实体
        /// </summary>
        public Model.Question GetModel(long ID)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select ID,QuestionaryID,Content,Answer,Orders,IsSingle from Question");
            strSql.Append(" where ID=@ID limit 1");
            MySqlParameter[] parameters = {
                    new MySqlParameter("@ID", MySqlDbType.Int64)
            };
            parameters[0].Value = ID;

            Model.Question model = new Model.Question();
            DataSet ds = DbHelperMySQL.Query(strSql.ToString(), parameters);
            if (ds.Tables[0].Rows.Count > 0)
            {
                return DataRowToModel(ds.Tables[0].Rows[0]);

            }
            else
            {
                return null;
            }
        }
Ejemplo n.º 52
0
 public void GivenIHaveCreatedANewQuestion()
 {
     _question = new Model.Question();
 }