public async Task <IActionResult> Post([FromRoute] int voteID, [FromRoute] int optionID) { var voteExist = _context.Votes.Include(x => x.Options).FirstOrDefault(x => x.Id == voteID); if (voteExist == null) { return(BadRequest(new { result = "This vote not exist" })); } var voteOption = voteExist.Options.FirstOrDefault(x => x.Id == optionID); if (voteOption == null) { return(BadRequest(new { result = "Option in that vote not exist" })); } var userIP = _accessor.HttpContext.Connection.RemoteIpAddress.ToString(); var answerExist = _context.VoteOptions.Where(x => x.Vote == voteExist).Include(x => x.Answers).SelectMany(x => x.Answers).Where(x => x.IpAdress == userIP); if (answerExist != null) { _context.VoteOpionAnswer.RemoveRange(answerExist); await _context.SaveChangesAsync(); } var newAnswer = new Models.Answer(); newAnswer.IpAdress = userIP; newAnswer.VoteOption = voteOption; newAnswer.VoteOptionId = voteOption.Id; await _context.VoteOpionAnswer.AddAsync(newAnswer); await _context.SaveChangesAsync(); var option = new { Id = voteExist.Id, CreateDate = voteExist.CreateDate, Name = voteExist.Name, Options = voteExist.Options.Select(c => new { Id = c.Id, Name = c.Name, Answers = _context.VoteOpionAnswer.Where(x => x.VoteOption == c).Count(), Answered = _context.VoteOpionAnswer.Any(x => x.VoteOption == c && x.IpAdress == userIP) }) }; await _hubContext.Clients.Group(voteID.ToString()).SendAsync("sendToGroup", option); return(Ok()); }
WCF.Service1Client client = new WCF.Service1Client(); //readonly suggeseted #region TODO // TODO: Test each method inside this controller // TODO: Change Return type to HTTPResponse // TODO:Add NLog to each method inside the entire controller (not just this region). Each Controller should have its own log file // TODO:Add Unit Tests for each method inside this controller. There is already a Unit Test Library in this project with a class already made for this controller /// <summary> /// Gets a specific Subquestion's Answer List /// </summary> /// <param name="SubquestionID">int QuestionID (NOT Exam Question)</param> /// <endpoint>GET: api/Answer/id</endpoint> /// <returns>The List of Answers correlating to that quesiton</returns> public List <Answer> Get(int SubquestionID) { var results = client.GetAnswersQuestion(SubquestionID).ToList(); List <Answer> ans = new List <Answer>(); foreach (WCF.Answers item in results) { Answer a = new Models.Answer(); a.DisplayedAnswer = item.Answer1; a.IsCorrect = item.correct.isCorrect; a.PKID = item.PKID; ans.Add(a); } return(ans); }
//called when user wants to delete all questions they've answered and start the quiz over public bool RestartQuiz() { using (_context) { var dbAnswer = new Models.Answer(); //New instance of Answer class, representing one row in the DB's Answer table //update answer table, marking which question was answered var answers = _context.Answers.ToList(); answers.ForEach(a => a.WasSelected = null); //update question table, marking this question as answered var questions = _context.Questions.ToList(); questions.ForEach(q => q.IsComplete = false); _context.SaveChanges(); //Applies changes to DB } return(true); }
//this is called when user submits a POST request of the answer they selected public string ProcessAnswer([FromBody] AnswerResult answer) { string returnText = ""; try { using (_context) { Answer dbAnswer = new Models.Answer(); //New instance of Answer class, representing one row in the DB's Answer table //make sure the question id given is actually an int value potentially in the DB if (Int32.Parse(answer.optionId) < 1) { throw new System.ArgumentException("Parameter must be greater than 0"); } //update answer table, marking which question was answered dbAnswer = _context.Answers.FirstOrDefault(a => a.Id == Int32.Parse(answer.optionId)); dbAnswer.WasSelected = true; _context.Answers.Update(dbAnswer); if (Int32.Parse(answer.questionId) < 1) { throw new System.ArgumentException("Parameter must be greater than 0"); } //update question table, marking this question as answered Question dbQuestion = new Models.Question(); dbQuestion = _context.Questions.FirstOrDefault(q => q.Id == Int32.Parse(answer.questionId)); dbQuestion.IsComplete = true; _context.Questions.Update(dbQuestion); _context.SaveChanges(); //Applies changes to DB } } catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.ToString()); Response.StatusCode = 400; returnText = e.ToString(); } return(returnText); }
/// <summary> /// Insert the <paramref name="newAnswer"/> in database /// </summary> /// <param name="newAnswer">The answer object to insert</param> /// <param name="ID">The ID of the strawpoll linked with this answer</param> public void sendAnswerInDatabase(Models.Answer newAnswer, int ID) { String queryAddAnswer; ConnectionQuery newDataBaseTask = new ConnectionQuery(); queryAddAnswer = "INSERT INTO Answer(Answer, NbrVotes, NumStrawPoll) " + "VALUES(@Answer, @NbrVotes, @NumStrawPoll)"; newDataBaseTask.OpenConnection(); SqlCommand cmd = new SqlCommand(queryAddAnswer, newDataBaseTask.getSqlConnection()); cmd.Parameters.AddWithValue("@Answer", newAnswer.getAnswer()); cmd.Parameters.AddWithValue("@NbrVotes", newAnswer.getNbrVotesByAnswer()); cmd.Parameters.AddWithValue("@NumStrawPoll", ID); newDataBaseTask.setMySqlCommand(cmd); newDataBaseTask.ExecuteNonQuery(); newDataBaseTask.CloseConnection(); }
/// <summary> /// Get the <paramref name="question"/>, <paramref name="answerOne"/>, <paramref name="answerTwo"/>, /// <paramref name="answerThree"/>, <paramref name="answerFour"/> and the <paramref name="questionChoice"/>, /// make objects out of it and add them to the database /// </summary> /// <param name="question">The label of the question</param> /// <param name="answerOne">The label of the first question</param> /// <param name="answerTwo">The label of the second question</param> /// <param name="answerThree">The label of the third question</param> /// <param name="answerFour">The label of the fourth question</param> /// <param name="questionChoice">The type of strawpoll (simple or multiple answers allowed)</param> /// <returns>View URLGeneration.cshtml</returns> public ActionResult CreateStrawPoll(String question, String answerOne, String answerTwo, String answerThree, String answerFour, String questionChoice) { bool multipleChoices; if (questionChoice == "uniqueChoice") { multipleChoices = false; } else { multipleChoices = true; } //Create question Models.StrawPoll myStrawPoll = new Models.StrawPoll(question, multipleChoices, 0, false); //Create answers Models.Answer myAnswerOne = new Models.Answer(answerOne, 0); Models.Answer myAnswerTwo = new Models.Answer(answerTwo, 0); Models.Answer myAnswerThree = new Models.Answer(answerThree, 0); Models.Answer myAnswerFour = new Models.Answer(answerFour, 0); //Send StrawPoll in database int IDStrawPoll = addStrawPollInDataBase(myStrawPoll); //Send URL in database sendURLsInDataBase(myStrawPoll, IDStrawPoll); //Send Answers in database and assign them to the corresponding strawpoll sendAnswerInDatabase(myAnswerOne, IDStrawPoll); sendAnswerInDatabase(myAnswerTwo, IDStrawPoll); sendAnswerInDatabase(myAnswerThree, IDStrawPoll); sendAnswerInDatabase(myAnswerFour, IDStrawPoll); ViewBag.URLStrawPoll = myStrawPoll.getURLStrawPoll(); ViewBag.URLDeletion = myStrawPoll.getURLDeletion(); ViewBag.URLResult = myStrawPoll.getURLResults(); //return URL page return(View("URLGeneration")); }
public ActionResult VotePage(int ID)//parameters inside http --> ?ID=5 { //get corresponding strawpoll and answers in database and create object Models.StrawPoll myStrawPoll = new Models.StrawPoll(); Models.Answer myAnswerOne = new Models.Answer(); Models.Answer myAnswerTwo = new Models.Answer(); Models.Answer myAnswerThree = new Models.Answer(); Models.Answer myAnswerFour = new Models.Answer(); //TODO - Get Values in Database and set objects below's attributes myStrawPoll.setStrawPollQuestion("EGZKSJLBNRGSFJ GULDI"); //SEND TO THE VIEW ViewBag.StrawPoll = myStrawPoll; ViewBag.answerOne = myAnswerOne; ViewBag.answerTwo = myAnswerTwo; ViewBag.answerThree = myAnswerThree; ViewBag.answerFour = myAnswerFour; return(View()); }
/// <summary> /// 新回答 /// </summary> /// <param name="body"></param> /// <returns></returns> public bool PostnewAnswer(Models.Answer answer) { SqlConnection sqlConnection = new SqlConnection(connectionstring); string datetime = DateTime.Now.ToString(); string PutAns = "insert into AnswerTable (Qusitonid,Userid,AnswerTime,UpAnsTime,AnswerContent)values" + "(@Qusitonid,@Userid,@AnswerTime,@UpAnsTime,@AnswerContent);" + "update UserTable set Answernum =Answernum+1 " + "where Userid = @Userid;update QusitonTable set Answerednum =Answerednum+1 " + "where Qusitonid = @Qusitonid"; sqlConnection.Open(); using (SqlCommand sqlCommand = sqlConnection.CreateCommand()) { SqlTransaction sqlTransaction = sqlConnection.BeginTransaction(); try { sqlCommand.CommandText = PutAns; sqlCommand.Transaction = sqlTransaction; sqlCommand.Parameters.AddWithValue("@Qusitonid", answer.Qusitionid); sqlCommand.Parameters.AddWithValue("@Userid", answer.Userid); sqlCommand.Parameters.AddWithValue("@AnswerTime", datetime); sqlCommand.Parameters.AddWithValue("@UpAnsTime", datetime); sqlCommand.Parameters.AddWithValue("@AnswerContent", answer.AnswerContent); int rows = sqlCommand.ExecuteNonQuery(); sqlTransaction.Commit(); return(true); } catch (SqlException) { sqlTransaction.Rollback(); return(false); } finally { sqlConnection.Close(); } } }
/// <summary> /// Increment the number of votes of the strawpoll and the answers chosen. /// Display the result page then (multiple answers only). /// </summary> /// <param name="ID">The ID of the strawpoll</param> /// <param name="checkbox">A list of String holding the label of each chosen answer</param> /// <returns>View Result.cshtml</returns> public ActionResult VoteCheckBoxes(int ID, List <String> checkbox) { //Increment database String queryIncrementNbrVotes; ConnectionQuery newDataBaseTask = new ConnectionQuery(); queryIncrementNbrVotes = "UPDATE StrawPoll " + "SET NbrVotes = NbrVotes + 1 " + "WHERE NumStrawPoll=@ID; " + "UPDATE Answer " + "SET NbrVotes = NbrVotes + 1 " + "WHERE NumStrawPoll = @IDAnswer AND Answer = @LabelAnswer;"; newDataBaseTask.OpenConnection(); foreach (String answerChosen in checkbox) { SqlCommand newcmd = new SqlCommand(queryIncrementNbrVotes, newDataBaseTask.getSqlConnection()); newcmd.Parameters.AddWithValue("@ID", ID); newcmd.Parameters.AddWithValue("@IDAnswer", ID); newcmd.Parameters.AddWithValue("@LabelAnswer", answerChosen); newDataBaseTask.setMySqlCommand(newcmd); newDataBaseTask.ExecuteNonQuery(); } newDataBaseTask.CloseConnection(); createCookies(ID); //RETURN RESULT Models.StrawPoll myStrawPoll = new Models.StrawPoll(); Models.Answer myAnswerOne = new Models.Answer(); Models.Answer myAnswerTwo = new Models.Answer(); Models.Answer myAnswerThree = new Models.Answer(); Models.Answer myAnswerFour = new Models.Answer(); //Get strawpoll in database String queryGetStrawPoll = "SELECT * FROM StrawPoll WHERE NumStrawPoll = @ID;"; newDataBaseTask.OpenConnection(); SqlCommand cmd = new SqlCommand(queryGetStrawPoll, newDataBaseTask.getSqlConnection()); cmd.Parameters.AddWithValue("@ID", ID); SqlDataReader newReader = cmd.ExecuteReader(); while (newReader.Read()) { myStrawPoll.setStrawPollQuestion((String)newReader["Question"]); myStrawPoll.setMultipleChoices((bool)newReader["MultipleChoices"]); myStrawPoll.setNbrVotesStrawPoll((int)newReader["NbrVotes"]); myStrawPoll.setURLStrawPoll((String)newReader["URLStrawPoll"]); myStrawPoll.setURLDeletion((String)newReader["URLDeletion"]); myStrawPoll.setURLResults((String)newReader["URLResult"]); myStrawPoll.setIsActive((bool)newReader["IsActive"]); } newReader.Close(); String queryGetAnswers = "SELECT * FROM Answer WHERE NumStrawPoll = @ID;"; SqlCommand cmdAnswer = new SqlCommand(queryGetAnswers, newDataBaseTask.getSqlConnection()); cmdAnswer.Parameters.AddWithValue("@ID", ID); SqlDataReader newReaderAnswer = cmdAnswer.ExecuteReader(); List <Models.Answer> answers = new List <Models.Answer>(); while (newReaderAnswer.HasRows) { while (newReaderAnswer.Read()) { Models.Answer newAnswer = new Models.Answer((String)newReaderAnswer["Answer"], (int)newReaderAnswer["NbrVotes"]); answers.Add(newAnswer); } newReaderAnswer.NextResult(); } newReaderAnswer.Close(); newDataBaseTask.CloseConnection(); //Set answers with database datas myAnswerOne = answers.ElementAt(0); myAnswerTwo = answers.ElementAt(1); myAnswerThree = answers.ElementAt(2); myAnswerFour = answers.ElementAt(3); //SEND TO THE VIEW ViewBag.StrawPoll = myStrawPoll; ViewBag.aOne = myAnswerOne.getAnswer(); ViewBag.vOne = myAnswerOne.getNbrVotesByAnswer(); ViewBag.aTwo = myAnswerTwo.getAnswer(); ViewBag.vTwo = myAnswerTwo.getNbrVotesByAnswer(); ViewBag.aThree = myAnswerThree.getAnswer(); ViewBag.vThree = myAnswerThree.getNbrVotesByAnswer(); ViewBag.aFour = myAnswerFour.getAnswer(); ViewBag.vFour = myAnswerFour.getNbrVotesByAnswer(); return(View("Result")); }
/// <summary> /// Display the result page of a specific strawpoll using its <paramref name="ID"/> /// </summary> /// <param name="ID">The ID of the strawpoll</param> /// <returns>View Result.cshtml</returns> public ActionResult ResultPage(int ID) { Models.StrawPoll myStrawPoll = new Models.StrawPoll(); Models.Answer myAnswerOne = new Models.Answer(); Models.Answer myAnswerTwo = new Models.Answer(); Models.Answer myAnswerThree = new Models.Answer(); Models.Answer myAnswerFour = new Models.Answer(); //Get strawpoll in database String queryGetStrawPoll; ConnectionQuery newDataBaseTask = new ConnectionQuery(); queryGetStrawPoll = "SELECT * FROM StrawPoll WHERE NumStrawPoll = @ID;"; newDataBaseTask.OpenConnection(); SqlCommand cmd = new SqlCommand(queryGetStrawPoll, newDataBaseTask.getSqlConnection()); cmd.Parameters.AddWithValue("@ID", ID); SqlDataReader newReader = cmd.ExecuteReader(); while (newReader.Read()) { myStrawPoll.setStrawPollQuestion((String)newReader["Question"]); myStrawPoll.setMultipleChoices((bool)newReader["MultipleChoices"]); myStrawPoll.setNbrVotesStrawPoll((int)newReader["NbrVotes"]); myStrawPoll.setURLStrawPoll((String)newReader["URLStrawPoll"]); myStrawPoll.setURLDeletion((String)newReader["URLDeletion"]); myStrawPoll.setURLResults((String)newReader["URLResult"]); myStrawPoll.setIsActive((bool)newReader["IsActive"]); } newReader.Close(); String queryGetAnswers = "SELECT * FROM Answer WHERE NumStrawPoll = @ID;"; SqlCommand cmdAnswer = new SqlCommand(queryGetAnswers, newDataBaseTask.getSqlConnection()); cmdAnswer.Parameters.AddWithValue("@ID", ID); SqlDataReader newReaderAnswer = cmdAnswer.ExecuteReader(); List <Models.Answer> answers = new List <Models.Answer>(); while (newReaderAnswer.HasRows) { while (newReaderAnswer.Read()) { Models.Answer newAnswer = new Models.Answer((String)newReaderAnswer["Answer"], (int)newReaderAnswer["NbrVotes"]); answers.Add(newAnswer); } newReaderAnswer.NextResult(); } newReaderAnswer.Close(); newDataBaseTask.CloseConnection(); //Set answers with database datas myAnswerOne = answers.ElementAt(0); myAnswerTwo = answers.ElementAt(1); myAnswerThree = answers.ElementAt(2); myAnswerFour = answers.ElementAt(3); //Send data to the views ViewBag.StrawPoll = myStrawPoll; ViewBag.aOne = myAnswerOne.getAnswer(); ViewBag.vOne = myAnswerOne.getNbrVotesByAnswer(); ViewBag.aTwo = myAnswerTwo.getAnswer(); ViewBag.vTwo = myAnswerTwo.getNbrVotesByAnswer(); ViewBag.aThree = myAnswerThree.getAnswer(); ViewBag.vThree = myAnswerThree.getNbrVotesByAnswer(); ViewBag.aFour = myAnswerFour.getAnswer(); ViewBag.vFour = myAnswerFour.getNbrVotesByAnswer(); return(View("Result")); }
/// <summary> /// Check if the strawpoll is either deleted or allready answered by the current user (using cookies). /// If not, display the vote page /// </summary> /// <param name="ID">The strawpoll's unique ID</param> /// <returns> /// <list type="bullet"> /// <item> /// <description>View Error_404.cshtml</description> /// </item> /// <item> /// <description>View CookieError.cshtml</description> /// </item> /// <item> /// <description>View UniqueChoice.cshtml</description> /// </item> /// <item> /// <description>View MultipleChoices.cshtml</description> /// </item> /// </list> /// </returns> public ActionResult VotePage(int ID) { Models.StrawPoll myStrawPoll = new Models.StrawPoll(); Models.Answer myAnswerOne = new Models.Answer(); Models.Answer myAnswerTwo = new Models.Answer(); Models.Answer myAnswerThree = new Models.Answer(); Models.Answer myAnswerFour = new Models.Answer(); //Get strawpoll in database String queryGetStrawPoll; ConnectionQuery newDataBaseTask = new ConnectionQuery(); queryGetStrawPoll = "SELECT * FROM StrawPoll WHERE NumStrawPoll = @ID;"; newDataBaseTask.OpenConnection(); SqlCommand cmd = new SqlCommand(queryGetStrawPoll, newDataBaseTask.getSqlConnection()); cmd.Parameters.AddWithValue("@ID", ID); SqlDataReader newReader = cmd.ExecuteReader(); while (newReader.Read()) { myStrawPoll.setStrawPollQuestion((String)newReader["Question"]); myStrawPoll.setMultipleChoices((bool)newReader["MultipleChoices"]); myStrawPoll.setNbrVotesStrawPoll((int)newReader["NbrVotes"]); myStrawPoll.setURLStrawPoll((String)newReader["URLStrawPoll"]); myStrawPoll.setURLDeletion((String)newReader["URLDeletion"]); myStrawPoll.setURLResults((String)newReader["URLResult"]); myStrawPoll.setIsActive((bool)newReader["IsActive"]); } newReader.Close(); String queryGetAnswers = "SELECT * FROM Answer WHERE NumStrawPoll = @ID;"; SqlCommand cmdAnswer = new SqlCommand(queryGetAnswers, newDataBaseTask.getSqlConnection()); cmdAnswer.Parameters.AddWithValue("@ID", ID); SqlDataReader newReaderAnswer = cmdAnswer.ExecuteReader(); List <Models.Answer> answers = new List <Models.Answer>(); while (newReaderAnswer.HasRows) { while (newReaderAnswer.Read()) { Models.Answer newAnswer = new Models.Answer((String)newReaderAnswer["Answer"], (int)newReaderAnswer["NbrVotes"]); answers.Add(newAnswer); } newReaderAnswer.NextResult(); } newReaderAnswer.Close(); newDataBaseTask.CloseConnection(); myAnswerOne = answers.ElementAt(0); myAnswerTwo = answers.ElementAt(1); myAnswerThree = answers.ElementAt(2); myAnswerFour = answers.ElementAt(3); //Send data to the views ViewBag.StrawPoll = myStrawPoll; ViewBag.answerOne = myAnswerOne; ViewBag.answerTwo = myAnswerTwo; ViewBag.answerThree = myAnswerThree; ViewBag.answerFour = myAnswerFour; ViewBag.IDStrawPoll = ID; bool hasVoted = getCookies(ID); if (myStrawPoll.getIsActive() == false) { return(View("Error_404")); } else if (hasVoted) { return(View("CookieError")); } else if (myStrawPoll.getMultipleChoices() == false) { return(View("UniqueChoice")); } else { return(View("MultipleChoices")); } }
public ActionResult SimulateExamStart() { JxLib.ExamController examController = new JxLib.ExamController(); JxLib.UserExamController userExamController = new JxLib.UserExamController(); CacheLib.Cookie cookie = new CacheLib.Cookie(); System.Collections.Hashtable data = new System.Collections.Hashtable(); string user_id = cookie.GetCookie("user_id"); //深大驾校测试代码 //data.Add("SchoolID", "1"); //data.Add("StudentID", "00001"); data.Add("StudentID", user_id); //插入数据,考试结束 string strExamID = userExamController.ExamStart(data); List<System.Collections.Hashtable> list = examController.getTestExam(); System.Text.StringBuilder strExams = new System.Text.StringBuilder(); int index = 1; foreach (System.Collections.Hashtable item in list) { Models.ExamA exam_a = null; Models.ExamB exam_b = null; if (CommonLib.Common.Validate.IsNullString(item["OptionC"]) == "") { Models.Answer answerA = null; if (item["Answer"].ToString().IndexOf("A") > -1) { answerA = new Models.Answer { title = item["OptionA"].ToString(), correct = true }; } else { answerA = new Models.Answer { title = item["OptionA"].ToString(), correct = false }; } string strAnswerA = Newtonsoft.Json.JsonConvert.SerializeObject(answerA); Models.Answer answerB = null; if (item["Answer"].ToString().IndexOf("B") > -1) { answerB = new Models.Answer { title = item["OptionB"].ToString(), correct = true }; } else { answerB = new Models.Answer { title = item["OptionB"].ToString(), correct = false }; } Models.AnswersA answers = new Models.AnswersA { A = answerA, B = answerB }; exam_a = new Models.ExamA { no = index.ToString(), exam_id = item["ExamID"].ToString(), total = this.EXAMCOUNT.ToString(), title = item["ExamText"].ToString(), img = CommonLib.Common.ConfigReader.Read("ResourceUrl") + CommonLib.Common.Validate.IsNullString(item["ImgUrl"]), video = CommonLib.Common.ConfigReader.Read("ResourceUrl") + CommonLib.Common.Validate.IsNullString(item["VideoUrl"]), answers = answers }; if (index > 1) strExams.Append(","); strExams.Append(Newtonsoft.Json.JsonConvert.SerializeObject(exam_a)); } else { Models.Answer answerA = null; if (item["Answer"].ToString().IndexOf("A") > -1) { answerA = new Models.Answer { title = item["OptionA"].ToString(), correct = true }; } else { answerA = new Models.Answer { title = item["OptionA"].ToString(), correct = false }; } Models.Answer answerB = null; if (item["Answer"].ToString().IndexOf("B") > -1) { answerB = new Models.Answer { title = item["OptionB"].ToString(), correct = true }; } else { answerB = new Models.Answer { title = item["OptionB"].ToString(), correct = false }; } Models.Answer answerC = null; if (item["Answer"].ToString().IndexOf("C") > -1) { answerC = new Models.Answer { title = item["OptionC"].ToString(), correct = true }; } else { answerC = new Models.Answer { title = item["OptionC"].ToString(), correct = false }; } Models.Answer answerD = null; if (item["Answer"].ToString().IndexOf("D") > -1) { answerD = new Models.Answer { title = item["OptionD"].ToString(), correct = true }; } else { answerD = new Models.Answer { title = item["OptionD"].ToString(), correct = false }; } Models.AnswersB answers = new Models.AnswersB { A = answerA, B = answerB, C = answerC, D = answerD }; exam_b = new Models.ExamB { no = index.ToString(), exam_id = item["ExamID"].ToString(), total = this.EXAMCOUNT.ToString(), title = item["ExamText"].ToString(), img = CommonLib.Common.ConfigReader.Read("ResourceUrl") + CommonLib.Common.Validate.IsNullString(item["ImgUrl"]), video = CommonLib.Common.ConfigReader.Read("ResourceUrl") + CommonLib.Common.Validate.IsNullString(item["VideoUrl"]), answers = answers }; if (index > 1) strExams.Append(","); strExams.Append(Newtonsoft.Json.JsonConvert.SerializeObject(exam_b)); } index++; } string tmp = strExams.ToString().Replace("[", "{").Replace("]", "}"); ViewData["exams"] = tmp; ViewData["exam_id"] = strExamID; ViewData["title"] = "开始考试"; return View(); }
public string GetExam() { JxLib.ExamController examController = new JxLib.ExamController(); HttpContextBase context = (HttpContextBase)Request.Properties["MS_HttpContext"]; Models.Result result = new Models.Result(); string id = context.Request.Params["id"]; if (id == null) { result.code = "0"; result.message = "参数不能为空!"; result.data = ""; return Newtonsoft.Json.JsonConvert.SerializeObject(result).Replace("\"", "'"); } int tmp_id = Int32.Parse(id) + 1; string strResult = ""; System.Collections.Hashtable item = examController.load(tmp_id.ToString()); System.Collections.Hashtable count = examController.getCount(); Models.ExamA exam_a = null; Models.ExamB exam_b = null; if (CommonLib.Common.Validate.IsNullString(item["OptionC"]) == "") { Models.Answer answerA = null; if (item["Answer"].ToString().IndexOf("A") > -1) { answerA = new Models.Answer { title = item["OptionA"].ToString(), correct = true }; } else { answerA = new Models.Answer { title = item["OptionA"].ToString(), correct = false }; } string strAnswerA = Newtonsoft.Json.JsonConvert.SerializeObject(answerA); Models.Answer answerB = null; if (item["Answer"].ToString().IndexOf("B") > -1) { answerB = new Models.Answer { title = item["OptionB"].ToString(), correct = true }; } else { answerB = new Models.Answer { title = item["OptionB"].ToString(), correct = false }; } Models.AnswersA answers = new Models.AnswersA { A = answerA, B = answerB }; exam_a = new Models.ExamA { no = tmp_id.ToString(), exam_id = item["ExamID"].ToString(), total = count["Count"].ToString(), title = item["ExamText"].ToString(), img = CommonLib.Common.ConfigReader.Read("ResourceUrl") + CommonLib.Common.Validate.IsNullString(item["ImgUrl"]), video = CommonLib.Common.ConfigReader.Read("ResourceUrl") + CommonLib.Common.Validate.IsNullString(item["VideoUrl"]), answers = answers }; strResult = Newtonsoft.Json.JsonConvert.SerializeObject(exam_a); } else { Models.Answer answerA = null; if (item["Answer"].ToString().IndexOf("A") > -1) { answerA = new Models.Answer { title = item["OptionA"].ToString(), correct = true }; } else { answerA = new Models.Answer { title = item["OptionA"].ToString(), correct = false }; } Models.Answer answerB = null; if (item["Answer"].ToString().IndexOf("B") > -1) { answerB = new Models.Answer { title = item["OptionB"].ToString(), correct = true }; } else { answerB = new Models.Answer { title = item["OptionB"].ToString(), correct = false }; } Models.Answer answerC = null; if (item["Answer"].ToString().IndexOf("C") > -1) { answerC = new Models.Answer { title = item["OptionC"].ToString(), correct = true }; } else { answerC = new Models.Answer { title = item["OptionC"].ToString(), correct = false }; } Models.Answer answerD = null; if (item["Answer"].ToString().IndexOf("D") > -1) { answerD = new Models.Answer { title = item["OptionD"].ToString(), correct = true }; } else { answerD = new Models.Answer { title = item["OptionD"].ToString(), correct = false }; } Models.AnswersB answers = new Models.AnswersB { A = answerA, B = answerB, C = answerC, D = answerD }; exam_b = new Models.ExamB { no = tmp_id.ToString(), exam_id = item["ExamID"].ToString(), total = count["Count"].ToString(), title = item["ExamText"].ToString(), img = CommonLib.Common.ConfigReader.Read("ResourceUrl") + CommonLib.Common.Validate.IsNullString(item["ImgUrl"]), video = CommonLib.Common.ConfigReader.Read("ResourceUrl") + CommonLib.Common.Validate.IsNullString(item["VideoUrl"]), answers = answers }; strResult = Newtonsoft.Json.JsonConvert.SerializeObject(exam_b); } result.code = "200"; result.message = "success!"; result.data = strResult.ToString().Replace("[", "{").Replace("]", "}"); return Newtonsoft.Json.JsonConvert.SerializeObject(result).Replace("\"", "'"); }
protected override void Seed(MyStackOverFlow.Models.ApplicationDbContext context) { var passwordHash = new PasswordHasher(); string password1 = passwordHash.HashPassword("1!Qwer"); var User1 = new Models.ApplicationUser { Id = "1", Email = "*****@*****.**", EmailConfirmed = false, PasswordHash = password1, SecurityStamp = Guid.NewGuid().ToString("D"), PhoneNumber = null, PhoneNumberConfirmed = false, TwoFactorEnabled = false, LockoutEndDateUtc = null, LockoutEnabled = false, AccessFailedCount = 0, UserName = "******", Reputation = 180 }; string password2 = passwordHash.HashPassword("2!John"); var User2 = new Models.ApplicationUser { Id = "2", UserName = "******", Email = "*****@*****.**", PasswordHash = password2, Reputation = 150 }; string password3 = passwordHash.HashPassword("3!Mike"); var User3 = new Models.ApplicationUser { Id = "3", UserName = "******", Email = "*****@*****.**", PasswordHash = password3, Reputation = 100 }; context.Users.AddOrUpdate(x => x.Id, User1); context.Users.AddOrUpdate(x => x.Id, User2); context.Users.AddOrUpdate(x => x.Id, User3); context.SaveChanges(); var tag1 = new Models.Tag { TagId = 1, Title = "MVC" }; var tag2 = new Models.Tag { TagId = 2, Title = "C#" }; var tag3 = new Models.Tag { TagId = 3, Title = "EF Model" }; var tag4 = new Models.Tag { TagId = 4, Title = "Asp.net" }; var tag5 = new Models.Tag { TagId = 5, Title = ".net Core" }; var tag6 = new Models.Tag { TagId = 6, Title = "String" }; context.Tags.AddOrUpdate(t => t.TagId, tag1); context.Tags.AddOrUpdate(t => t.TagId, tag2); context.Tags.AddOrUpdate(t => t.TagId, tag3); context.Tags.AddOrUpdate(t => t.TagId, tag4); context.Tags.AddOrUpdate(t => t.TagId, tag5); context.Tags.AddOrUpdate(t => t.TagId, tag6); var Q1 = new Models.Question { Id = 1, Tilte = "Introducing FOREIGN KEY constraint 'FK_dbo.Comments_dbo.Questions_QuestionId' " + "on table may cause cycles or multiple cascade paths. in mvc ASP.net", Description = "ve been wrestling with this for a while and can't quite figure out what's happening. " + "I have a Card entity which contains Sides (usually 2) - and both Cards and Sides have a Stage. " + "I'm using EF Codefirst migrations and the migrations are failing with this error:", Qdate = DateTime.Parse("2016-05-02"), UserId = "1", QVoteCount = 45 }; var Q2 = new Models.Question { Id = 2, Tilte = "check which user is login asp.net mvc.", Description = "I want to show some div at the view only if user has logged in. " + "But Request.IsAuthenticated(and User.Identity.IsAuthenticated) is always true even in the very beginning," + "right after I start the website from Visual Studio.Apparently," + "it gets me as the user logged in Windows(because User.Identity.Name returns my Windows login)," + "but I need it to check if user has authenticated on website via FormsAuthentication.", Qdate = DateTime.Parse("2016-08-15"), UserId = "2", QVoteCount = 20 }; var Q3 = new Models.Question { Id = 3, Tilte = "pagedList doesnt show ordered data on 2nd page mvc c# EF code first?", Description = "My problem is that the search string is 'lost' when I page to the second page," + " so instead of a filtered set of results, I'm shown all the records.", Qdate = DateTime.Parse("2017-02-21"), UserId = "2", QVoteCount = 10 }; var Q4 = new Models.Question { Id = 4, Tilte = "Differnce between string And String c#", Description = "What is the difference between String and string in C# mvc .net?", Qdate = DateTime.Parse("2015-12-11"), UserId = "1", QVoteCount = 37 }; var Q5 = new Models.Question { Id = 5, Tilte = "How to properly write seed method in Entity Framework mvc?", Description = "ve been wrestling with this for a while and can't quite figure out what's happening. " + "I have a Card entity which contains Sides (usually 2) - and both Cards and Sides have a Stage. " + "I'm using EF Codefirst migrations and the migrations are failing with this error:", Qdate = DateTime.Parse("2018-09-10"), UserId = "3", QVoteCount = 61 }; var Q6 = new Models.Question { Id = 6, Tilte = "Displaying Multiple Image Links instead of Text in WebGrid?", Description = "I have a WebGrid definition and three links in a single " + "column by using Html.ActionLink. But, when I do not use " + "LinkText property, the applicantId property is passed as null value to the Controller.", Qdate = DateTime.Parse("2018-10-13"), UserId = "4", QVoteCount = 25 }; var Q7 = new Models.Question { Id = 7, Tilte = "How to speed up large data in reactjs?", Description = "I am trying to get million of data " + "and showing the data tables. Now, I am trying to check static data instead of" + "getting from database . class UL extends React.Compontent { state = { data: [],..", Qdate = DateTime.Parse("2018-02-18"), UserId = "2", QVoteCount = 21 }; var Q8 = new Models.Question { Id = 8, Tilte = "Android Studio, cannot see anymore warnings, errors and println in “4:Run”?", Description = "i cant see anymore my warning, errors and println in my console, but i need it]", Qdate = DateTime.Parse("2016-01-07"), UserId = "2", QVoteCount = 10 }; var Q9 = new Models.Question { Id = 9, Tilte = "Push unique objects into array in JAVASCRIPT", Description = "I want to push object that only have unique id1 into array." + " Example: let array = [], obj = {}, access = true if(access){ obj['id1'] = 1 obj['id2'] = 2 if(array.indexOf(obj.id1) ", Qdate = DateTime.Parse("2017-02-01"), UserId = "1", QVoteCount = 18 }; var Q10 = new Models.Question { Id = 10, Tilte = "Access File System of a WSL as a seperate Drive", Description = "I have installed Ubuntu 20.04 from Microsoft Store as " + "a Windows Subsystem for Linux (WSL) and I need to access the system files of it " + "from Windows Explorer and access it as a separate Partition ", Qdate = DateTime.Parse("2015-02-11"), UserId = "1", QVoteCount = 18 }; var Q11 = new Models.Question { Id = 11, Tilte = "I have installed Ubuntu 20.04 from Microsoft Store as a Windows Subsystem for Linux (WSL)" + "and I need to access the system files of it from Windows Explorer and access it as a separate Partition", Description = "I have a question about Kotlin error messages. Let's say I have a simple error caused by not " + "closing a print statement: fun main() { println('Hello.' } and the error returned is: Hello.kt:2:54:", Qdate = DateTime.Parse("2016-08-07"), UserId = "1", QVoteCount = 18 }; context.Questions.AddOrUpdate(q => q.Id, Q1); context.Questions.AddOrUpdate(q => q.Id, Q2); context.Questions.AddOrUpdate(q => q.Id, Q3); context.Questions.AddOrUpdate(q => q.Id, Q4); context.Questions.AddOrUpdate(q => q.Id, Q5); Q1.Tag.Add(tag1); Q1.Tag.Add(tag2); Q1.Tag.Add(tag3); Q2.Tag.Add(tag4); Q2.Tag.Add(tag5); Q2.Tag.Add(tag6); Q3.Tag.Add(tag1); Q3.Tag.Add(tag3); Q3.Tag.Add(tag5); Q4.Tag.Add(tag1); Q4.Tag.Add(tag2); Q4.Tag.Add(tag4); Q5.Tag.Add(tag2); Q5.Tag.Add(tag3); Q5.Tag.Add(tag5); var Ans1 = new Models.Answer { Id = 1, UserId = "2", Description = "Owned entity types are never included by EF Core in the model by convention. You can use the " + "OwnsOne method in OnModelCreating or annotate the type with OwnedAttribute (new in EF Core 2.1) " + "to configure the type as an owned type in mvc", Ansdate = DateTime.Parse("2016-05-08"), QuestionId = 1, AnsVoteCount = 122 }; var Ans2 = new Models.Answer { Id = 2, UserId = "3", Description = "When using a relational database, the database provider selects a data type based on the .NET " + "type of the property.It also takes into account other metadata, such as the configured maximum length, " + "whether the property is part of a primary key, etc.", Ansdate = DateTime.Parse("2016-05-09"), QuestionId = 1, AnsVoteCount = 327 }; var Ans3 = new Models.Answer { Id = 3, UserId = "1", Description = "Owned entity types are never included by EF Core in the model by convention. You can use the " + "OwnsOne method in OnModelCreating or annotate the type with OwnedAttribute (new in EF Core 2.1) " + "to configure the type as an owned type in mvc", Ansdate = DateTime.Parse("2016-08-16"), QuestionId = 2, AnsVoteCount = 87 }; var Ans4 = new Models.Answer { Id = 4, UserId = "3", Description = "When using a relational database, the database provider selects a data type based on the .NET " + "type of the property.It also takes into account other metadata, such as the configured maximum length, " + "whether the property is part of a primary key, etc.", Ansdate = DateTime.Parse("2016-09-01"), QuestionId = 2, AnsVoteCount = 267 }; var Ans5 = new Models.Answer { Id = 5, UserId = "3", Description = "The problem is your PagedList entry doesn't include your sort order nor your current filter.+" + "In addition to adding ViewBag.CurrentSort as suggested by Vasanth," + " you also need to change your PagedListPager to:", Ansdate = DateTime.Parse("2017-02-22"), QuestionId = 3, AnsVoteCount = 89 }; var Ans6 = new Models.Answer { Id = 6, UserId = "2", Description = "string is an alias in C# for System.String.So technically, " + "there is no difference. It's like int vs. System.Int32.", Ansdate = DateTime.Parse("2015-12-12"), QuestionId = 4, AnsVoteCount = 101 }; var Ans7 = new Models.Answer { Id = 7, UserId = "2", Description = "Alternatively, you can use context.Database.EnsureCreated() to create a new database " + "containing the seed data, for example for a test database or when using the in-memory provider or any " + "non-relation database. Note that if the database already exists, EnsureCreated() will neither update the " + "schema nor seed data in the database. " + "For relational databases you shouldn't call EnsureCreated() if you plan to use Migrations.", Ansdate = DateTime.Parse("2015-12-12"), QuestionId = 5, AnsVoteCount = 332 }; context.Answers.AddOrUpdate(A => A.Id, Ans1); context.Answers.AddOrUpdate(A => A.Id, Ans2); context.Answers.AddOrUpdate(A => A.Id, Ans3); context.Answers.AddOrUpdate(A => A.Id, Ans4); context.Answers.AddOrUpdate(A => A.Id, Ans5); context.Answers.AddOrUpdate(A => A.Id, Ans6); context.Answers.AddOrUpdate(A => A.Id, Ans7); var QCom1 = new Models.QComment { Id = 1, QuestionId = 1, UserId = "2", Comdate = DateTime.Parse("2017-02-21"), Description = "This Question can be found in another place" }; var QCom2 = new Models.QComment { Id = 2, QuestionId = 1, UserId = "3", Comdate = DateTime.Parse("2017-08-12"), Description = "This is the 2nd Comment on Question 1" }; var QCom3 = new Models.QComment { Id = 3, QuestionId = 2, UserId = "3", Comdate = DateTime.Parse("2016-09-18"), Description = "This is the 1st Comment on Question 2" }; var QCom4 = new Models.QComment { Id = 4, QuestionId = 3, UserId = "1", Comdate = DateTime.Parse("2017-09-03"), Description = "This is the Ist Comment on Question 3" }; var QCom5 = new Models.QComment { Id = 5, QuestionId = 5, UserId = "3", Comdate = DateTime.Parse("2018-08-12"), Description = "This is the 1st Comment on Question 5" }; context.QComments.AddOrUpdate(QC => QC.Id, QCom1); context.QComments.AddOrUpdate(QC => QC.Id, QCom2); context.QComments.AddOrUpdate(QC => QC.Id, QCom3); context.QComments.AddOrUpdate(QC => QC.Id, QCom4); context.QComments.AddOrUpdate(QC => QC.Id, QCom5); var Acom1 = new Models.AComment { Id = 1, AnswerId = 1, UserId = "1", Comdate = DateTime.Parse("2018-08-13"), Description = "Found this answer very informative" }; var Acom2 = new Models.AComment { Id = 2, AnswerId = 2, UserId = "1", Description = "This is the Comment on the given answer", Comdate = DateTime.Parse("2019-06-17"), }; var Acom3 = new Models.AComment { Id = 3, AnswerId = 2, UserId = "1", Comdate = DateTime.Parse("2019-03-31"), Description = "This is the Comment on the given answer" }; var Acom4 = new Models.AComment { Id = 4, AnswerId = 3, UserId = "1", Comdate = DateTime.Parse("2019-07-08"), Description = "That works" }; var Acom5 = new Models.AComment { Id = 5, AnswerId = 4, UserId = "2", Comdate = DateTime.Parse("2020-01-12"), Description = "Aah... Doesn't help" }; var Acom6 = new Models.AComment { Id = 6, AnswerId = 5, UserId = "1", Comdate = DateTime.Parse("2020-02-23"), Description = "This is the comment on answer 5" }; context.AComments.AddOrUpdate(AC => AC.Id, Acom1); context.AComments.AddOrUpdate(AC => AC.Id, Acom2); context.AComments.AddOrUpdate(AC => AC.Id, Acom3); context.AComments.AddOrUpdate(AC => AC.Id, Acom4); context.AComments.AddOrUpdate(AC => AC.Id, Acom5); context.AComments.AddOrUpdate(AC => AC.Id, Acom6); var vote1 = new Models.Vote { Id = 1, QuestionId = 1, UpVote = true }; var vote2 = new Models.Vote { Id = 2, QuestionId = 2, DownVote = true }; var vote3 = new Models.Vote { Id = 3, QuestionId = 2, UpVote = true }; var vote4 = new Models.Vote { Id = 4, QuestionId = 2, UpVote = false }; context.Votes.AddOrUpdate(v => v.Id, vote1); context.Votes.AddOrUpdate(v => v.Id, vote2); context.Votes.AddOrUpdate(v => v.Id, vote3); context.Votes.AddOrUpdate(v => v.Id, vote4); context.SaveChanges(); // This method will be called after migrating to the latest version. // You can use the DbSet<T>.AddOrUpdate() helper extension method // to avoid creating duplicate seed data. }