public IHttpActionResult PutAnswer(int id, Answer answer) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != answer.Id) { return(BadRequest()); } db.Entry(answer).State = EntityState.Modified; try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!AnswerExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public ActionResult Create(CauHoi cauHoi, DapAn dapan1, DapAn dapan2, DapAn dapan3, DapAn dapan4, HttpPostedFileBase file) { try { cauHoi.MaCauHoiMoi = cauHoi.MaCauHoi; cauHoi.DapAns = new List <DapAn>(); if (db.CauHois.Any(x => x.MaCauHoiMoi == cauHoi.MaCauHoi)) { ModelState.AddModelError("MaCauHoi", "Mã câu hỏi này đã tồn tại. Bạn hãy kiểm tra lại."); } else { if (!string.IsNullOrEmpty(dapan1.NoiDung)) { cauHoi.DapAns.Add(dapan1); } if (!string.IsNullOrEmpty(dapan2.NoiDung)) { cauHoi.DapAns.Add(dapan2); } if (!string.IsNullOrEmpty(dapan3.NoiDung)) { cauHoi.DapAns.Add(dapan3); } if (!string.IsNullOrEmpty(dapan4.NoiDung)) { cauHoi.DapAns.Add(dapan4); } if (cauHoi.DapAns.Count > 0 && cauHoi.DapAns.Any(x => x.DapAnDung == true) == false) { ModelState.AddModelError("", "Bạn cần chỉ định ít nhất 1 đáp án là đáp án đúng!"); } } if (ModelState.IsValid) { if (file != null && file.ContentLength > 0) { string fileName = DateTime.Now.Ticks.ToString() + System.IO.Path.GetExtension(file.FileName); cauHoi.Hinh = fileName; file.SaveAs(Server.MapPath("~/Content/images/" + fileName)); } db.CauHois.Add(cauHoi); db.SaveChanges(); return(RedirectToAction("Index", new { MaChuyenMuc = cauHoi.MaChuyenMuc })); } ViewBag.MaChuyenMuc = new SelectList(db.ChuyenMucCauHois, "MaChuyenMuc", "TenChuyenMuc", cauHoi.MaChuyenMuc); return(View(cauHoi)); } catch (Exception ex) { ModelState.AddModelError("", ex.Message); ViewBag.MaChuyenMuc = new SelectList(db.ChuyenMucCauHois, "MaChuyenMuc", "TenChuyenMuc", cauHoi.MaChuyenMuc); return(View(cauHoi)); } }
public DataModel.Quiz Add(DataModel.Quiz obj) { try { var existing = context.tblQuizs.Where(x => x.Name == obj.Name).FirstOrDefault(); if (obj.ID != 0) { return(Update(obj)); } tblQuiz quiz = new tblQuiz(); quiz.Name = obj.Name; quiz.Description = obj.Description; quiz.AllowReAttempt = obj.AllowReAttempt; quiz.Hours = obj.Hours; quiz.Minutes = obj.Minutes; quiz.ReAttemptDuration = obj.ReAttemptDuration; quiz.Timer = obj.Time; quiz.PassMarks = obj.PassMarks; quiz.QuizUrl = obj.QuizUrl; quiz.CreatedBy = obj.CreatedBy; quiz.CreatedAt = DateTime.Now; quiz.Type = obj.Type; quiz.UpdatedAt = DateTime.Now; quiz.IsActive = obj.IsActive; quiz.QuizNotes = obj.QuizNotes; quiz.RequiresLogin = obj.RequiresLogin; if (existing != null) { obj.ErrorMessage = "Quiz with same name already exists"; return(obj); } context.tblQuizs.Add(quiz); context.SaveChanges(); //Assuming the database is generating your Id's for you obj.ID = quiz.ID; obj.Success = true; obj.ErrorMessage = "Quiz saved successfully."; return(obj); } catch (DbEntityValidationException ex) { foreach (var validationErrors in ex.EntityValidationErrors) { foreach (var validationError in validationErrors.ValidationErrors) { Trace.TraceInformation("Property: {0} Error: {1}", validationError.PropertyName, validationError.ErrorMessage); } } throw; } }
public ActionResult Edit(CauHoi cauHoiLiet, DapAn dapan1, DapAn dapan2, DapAn dapan3, DapAn dapan4, HttpPostedFileBase file) { try { cauHoiLiet.MaChuyenMuc = 8; List <DapAn> dapAns = new List <DapAn>(); if (dapan1.MaDapAn != 0) { dapAns.Add(dapan1); } if (dapan2.MaDapAn != 0) { dapAns.Add(dapan2); } if (dapan3.MaDapAn != 0) { dapAns.Add(dapan3); } if (dapan4.MaDapAn != 0) { dapAns.Add(dapan4); } if (dapAns.Any(x => x.DapAnDung == true) == false) { ModelState.AddModelError("", "Bạn cần chỉ định ít nhất 1 đáp án là đáp án đúng!"); } if (ModelState.IsValid) { foreach (DapAn dapAnItem in dapAns) { db.Entry(dapAnItem).State = System.Data.Entity.EntityState.Modified; } if (file != null && file.ContentLength > 0) { string fileName = DateTime.Now.Ticks.ToString() + System.IO.Path.GetExtension(file.FileName); cauHoiLiet.Hinh = fileName; file.SaveAs(Server.MapPath("~/Content/images/" + fileName)); } db.Entry(cauHoiLiet).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Edit", new { Id = cauHoiLiet.MaCauHoi, message = "Sửa thành công" })); } return(View(cauHoiLiet)); } catch (Exception ex) { ModelState.AddModelError("", ex.Message); return(View(cauHoiLiet)); } }
public DataModel.Users Add(DataModel.Users obj) { try { //CustomResponse response = new CustomResponse(); var existing = context.tblUsers.Where(u => u.UserName == obj.UserName).FirstOrDefault(); if (obj.UserId != 0) { return(Update(obj)); } tblUser user = new tblUser(); user.UserName = obj.UserName; user.FirstName = obj.FirstName; user.LastName = obj.LastName; user.UserEmail = obj.Email; user.CreatedBy = obj.CreatedBy; user.CreatedAt = DateTime.Now; user.UpdatedAt = DateTime.Now; user.UserRole = obj.Role; user.IsActive = true; user.Password = obj.Password; user.UpdatedBy = obj.CreatedBy; if (existing != null) { obj.ErrorMessage = "User with same name already exists"; obj.Success = false; obj.CreatedAt = existing.CreatedAt.Value; obj.UpdatedAt = existing.UpdatedAt.Value; return(obj); } context.tblUsers.Add(user); context.SaveChanges(); //Assuming the database is generating your Id's for you obj.UserId = user.UserId; obj.Success = true; obj.CreatedAt = DateTime.Now; obj.UpdatedAt = DateTime.Now; obj.ErrorMessage = "User saved successfully"; } catch (Exception ex) { obj.ErrorMessage = ex.Message; obj.Success = false; } return(obj); }
public ActionResult Create([Bind(Include = "Id,Name,DataInHttpPostedFileBase")] AvatarViewModel avatarViewModel) { if (ModelState.IsValid) { Avatar avatar = new Avatar() { Name = avatarViewModel.Name, Data = ConvertHttpPostedFileBaseToByteArray(avatarViewModel.DataInHttpPostedFileBase) }; db.Avatar.Add(avatar); db.SaveChanges(); return(RedirectToAction("Index")); } return(View(avatarViewModel)); }
public ActionResult Register(UserViewModel user) { User userIntoDatabase = new User(); try { if (ModelState.IsValid) { userIntoDatabase.NickName = user.NickName; userIntoDatabase.Password = user.PlainPassword; userIntoDatabase.Email = user.Email; userIntoDatabase.UserTypeId = 2; userIntoDatabase.AvatarId = user.AvatarId; } db.User.Add(userIntoDatabase); db.SaveChanges(); return(RedirectToAction("Index", "Home")); } catch (Exception exception) { ModelState.AddModelError("", exception.Message.ToString()); } return(View(user)); }
private void SaveTest() { try { using (var context = new QuizDBEntities()) { var questionIdx = context.Questions.ToList().Select(t => t.id).Max() + 1; var variantIdx = context.Variants.ToList().Select(t => t.id).Max() + 1; context.Tests.Add(_currentTest); foreach (var itemQuestion in _testQuestions) { var question = new Questions(); question.id = questionIdx++; question.testId = this._currentTest.id; question.question = itemQuestion.QuestionText; //TODO: list variants foreach (var itemVariant in itemQuestion.Variants) { var variant = new Variants(); variant.id = variantIdx++; variant.variant = itemVariant.VariantText; variant.imgPath = itemVariant.ImageUri; variant.variant_type = itemVariant.Type; variant.questionId = question.id; if (itemVariant.IsCorrect == true) { var answer = new Answers(); answer.questionId = question.id; answer.variantId = variant.id; context.Answers.Add(answer); } question.Variants.Add(variant); } // context.Questions.Add(question); } context.SaveChanges(); } // Your code... // Could also be before try if you know the exception occurs in SaveChanges } catch (DbEntityValidationException e) { foreach (var eve in e.EntityValidationErrors) { var error = String.Format("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State); foreach (var ve in eve.ValidationErrors) { error += string.Format("\n- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage); } } throw; } }
public void UpdateOutput(Participant model) { using (QuizDBEntities db = new QuizDBEntities()) { db.Entry(model).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); } }
public Participant Insert(Participant model) { using (QuizDBEntities db = new QuizDBEntities()) { db.Participants.Add(model); db.SaveChanges(); return(model); } }
public ActionResult Edit(ThongTinChung thongTinChung) { if (ModelState.IsValid) { db.Entry(thongTinChung).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); return(Redirect("Edit")); } return(View(thongTinChung)); }
public ActionResult Create([Bind(Include = "Id,Email,PlainPassword,AvatarId,AvatarImage,UserTypeId,UserType,NickName,NumberOfFinishedQuiz,TotalScore")] UserViewModel userViewModel) { if (ModelState.IsValid) { User user = new User() { Id = userViewModel.Id, Email = userViewModel.Email, Password = userViewModel.PlainPassword, AvatarId = userViewModel.AvatarId, NickName = userViewModel.NickName }; db.User.Add(user); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.AvatarId = new SelectList(db.Avatar, "Id", "Name", userViewModel.AvatarId); ViewBag.UserTypeId = new SelectList(db.UserType, "Id", "Name", userViewModel.UserTypeId); return(View(userViewModel)); }
public DataModel.Questions Add(DataModel.Questions obj) { if (obj.QuestionId != 0) { return(UpdateQuestion(obj)); } var existing = context.tblQuizQuestions.Where(x => x.QuestionText == obj.QuestionText && x.QuizId == obj.QuizId).FirstOrDefault(); tblQuizQuestion Question = new tblQuizQuestion(); Question.QuizId = obj.QuizId; Question.QuestionText = obj.QuestionText; Question.IsActive = obj.IsActive; Question.CreatedAt = DateTime.Now; Question.CreatedBy = obj.CreatedBy; Question.UpdatedAt = DateTime.Now; if (existing != null) { obj.ErrorMessage = "Question with same text already exists"; obj.Success = false; obj.CreatedAt = Question.CreatedAt.Value; obj.UpdatedAt = Question.UpdatedAt.Value; return(obj); } context.tblQuizQuestions.Add(Question); context.SaveChanges(); //Assuming the database is generating your Id's for you obj.QuestionId = Question.QuestionId; obj.CreatedAt = Question.CreatedAt.Value; obj.UpdatedAt = Question.UpdatedAt.Value; obj.Success = true; obj.ErrorMessage = "Question saved successfully."; return(obj); }
public IHttpActionResult PutQuestion(int id, Question question) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != question.Id) { return(BadRequest()); } db.Entry(question).State = EntityState.Modified; foreach (var answer in question.Answers) { db.Entry(answer).State = EntityState.Modified; } try { db.SaveChanges(); } catch (DbUpdateConcurrencyException) { if (!QuestionExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public void AgregarDatosPersonales() { Datos_Personales DP = new Datos_Personales(); DP.ID = 1; DP.Nombre = "XXX"; DP.Apellido = "ZZZ"; DP.Telefono = "12345678"; using (QuizDBEntities context = new QuizDBEntities()) { // me agrega ala base datos context.Datos_Personales.Add(DP); context.SaveChanges();// guarda. } }
public ActionResult ChangePassword(ChangePasswordViewModel changePasswordViewModel) { QuanTriVien quanTriVien = Session["UserLogged"] as QuanTriVien; if (changePasswordViewModel.OldPassword != quanTriVien.MatKhau) { ModelState.AddModelError("OldPassword", "Mật khẩu hiện tại không đúng!"); } if (ModelState.IsValid) { quanTriVien.MatKhau = changePasswordViewModel.NewPassword; db.Entry(quanTriVien).State = System.Data.Entity.EntityState.Modified; db.SaveChanges(); Session["UserLogged"] = quanTriVien; return(RedirectToAction("Index", "Dashboard")); } return(View(changePasswordViewModel)); }
public void AgregarDirecciones() { Direcciones DP = new Direcciones(); DP.ID_Direcciones = 234; DP.ID = 1; DP.Pais = "C.R "; DP.Provincia = " Heredia"; DP.Canton = "Central "; DP.Distrito = "Ulloa "; DP.Detalle = "WWWWWWWWWWW"; using (QuizDBEntities context = new QuizDBEntities()) { // me agrega ala base datos context.Direcciones.Add(DP); context.SaveChanges();// guarda. } }
public ActionResult ScoresOnBoard(Quiz scoreboard) { List <ScoreBoard> leaderboard = new List <ScoreBoard>(); if (ModelState.IsValid) { db.ScoreBoards.Add(scoreboard.ScoreEntry); db.SaveChanges(); var scores = from s in db.ScoreBoards orderby s.Score descending select s; leaderboard = scores.Take(10).ToList(); scoreboard.LeaderBoard = leaderboard; return(View(scoreboard)); } scoreboard = (Quiz)Session["quiz"]; return(View(scoreboard)); }
public void Add(TEntity item) { _dbSet.Add(item); _context.SaveChanges(); }
public ActionResult NewQuizStart(QuizTestViewModel quiz) { // Create a list what is used for counting the total score per User per Quiz List <Question> questionList = db.Question.Include(q => q.Answer).AsEnumerable().Where(x => x.QuizId == quiz.Question[0].QuizId).ToList(); var quizId = quiz.Question.FirstOrDefault().QuizId; var quizName = db.Quiz.Where(x => x.Id == quizId).Select(x => x.Name).FirstOrDefault(); var userId = quiz.Question.FirstOrDefault().UserId; var userNickName = db.User.Where(x => x.Id == userId).Select(x => x.NickName).FirstOrDefault(); // Create unique model instance CompletedQuiz completedQuiz = new CompletedQuiz(); // Create database list to save User's answers var dbList = db.FinishedQuizByUser.ToList(); int totalScore = 0; for (int i = 0; i < quiz.Question.Count; i++) { completedQuiz = new CompletedQuiz { UserId = userId, UserNickName = userNickName, QuizId = quizId, QuizName = quizName, QuestionId = quiz.Question[i].QuestionId, Date = quiz.Question[i].Date, }; if (quiz.Question[i].QuestionType == 1) { if (quiz.Question[i].SelectedAnswer == questionList[i].Answer.Where(x => x.AnswerCheck == true).FirstOrDefault().Id) { totalScore += questionList[i].Point; completedQuiz.Score = questionList[i].Point; } } if (quiz.Question[i].QuestionType == 2) { int trueAnswerCounterInDatabase = 0; int correctAnswerCounterFromUser = 0; foreach (var item in questionList[i].Answer) { if (item.AnswerCheck == true) { trueAnswerCounterInDatabase++; } } for (int j = 0; j < quiz.Question[i].AnswerList.Count; j++) { if (quiz.Question[i].AnswerList[j].AnswerCheck == questionList[i].Answer.ElementAt(j).AnswerCheck&& questionList[i].Answer.ElementAt(j).AnswerCheck == true) { correctAnswerCounterFromUser++; if (correctAnswerCounterFromUser == trueAnswerCounterInDatabase) { completedQuiz.Score = questionList[i].Point; totalScore += questionList[i].Point; break; } } } } FinishedQuizByUser result = new FinishedQuizByUser(); result.UserId = completedQuiz.UserId; result.QuizId = completedQuiz.QuizId; result.QuestionId = completedQuiz.QuestionId; result.Score = completedQuiz.Score; result.Date = completedQuiz.Date; var finishedQuiz = db.FinishedQuizByUser?.Where(q => q.QuestionId == completedQuiz.QuestionId && q.UserId == completedQuiz.UserId)?.FirstOrDefault(); if (finishedQuiz == null) { db.FinishedQuizByUser.Add(result); db.SaveChanges(); } else { finishedQuiz.QuestionId = completedQuiz.QuestionId; finishedQuiz.Score = completedQuiz.Score; finishedQuiz.Date = completedQuiz.Date; db.Entry(finishedQuiz).State = EntityState.Modified; db.SaveChanges(); } } completedQuiz.TotalScore = totalScore; return(View("FinishedQuizView", completedQuiz)); }