public void DeleteExam(int examId) { Contract.Requires<ArgumentOutOfRangeException>(examId > 0, "The examId must be > 0!"); using (var context = new SchoolContext()) { var examToBeDeleted = new Exam() { ExamId = examId }; try { context.Exams.Attach(examToBeDeleted); context.Exams.Remove(examToBeDeleted); if (context.SaveChanges() != 0) { /* Logger.Write("The exam " + examToBeDeleted + " was successfully removed!", "General", 2, 2, TraceEventType.Information); * */ }/* else { Logger.Write("The exam " + examToBeDeleted + " was not removed!", "Important", 1, 1, TraceEventType.Error); }*/ } catch { throw new NoSuchEntityException("The semester with the id=" + examToBeDeleted + " does not exist in the database"); } } }
public ActionResult AddNewWorkSchedule(Schedule schedule) { if (ModelState.IsValid) { db.Schedules.Add(schedule); db.SaveChanges(); IList<Shift> currentShift = db.Shifts.Where(x => x.ShiftId == schedule.ShiftId).ToList(); string dateAndTimeStart = schedule.Date.ToString("dd/MM/yyyy") + " " + currentShift[0].ShiftStart; DateTime shiftStart = Convert.ToDateTime(dateAndTimeStart); string dateAndTimeEnd = schedule.Date.ToString("dd/MM/yyyy") + " " + currentShift[0].ShiftEnd; DateTime shiftEnd = Convert.ToDateTime(dateAndTimeEnd); double minutestDifference = (shiftEnd - shiftStart).TotalMinutes; double examLines = minutestDifference / 20; for (int i = 0; i < examLines; i++) { Exam exam = new Exam { DoctorId = schedule.DoctorId, ExamTime = shiftStart }; shiftStart = shiftStart.AddMinutes(20); db.Exams.Add(exam); db.SaveChanges(); } return RedirectToAction("AddNewWorkSchedule","Home"); } ViewBag.Doctors = db.Doctors.ToList().Select(x => new SelectListItem { Text = x.DoctorName, Value = x.DoctorId.ToString() }); ViewBag.Shifts = db.Shifts.ToList().Select(x => new SelectListItem { Text = x.ShiftStart + "-" + x.ShiftEnd, Value = x.ShiftId.ToString() }); return View(); }
protected void btn_Go_Click(object sender, EventArgs e) { try { //if (!dr_SelectExam.Text.Equals("[Select One]") && (rdo_SelectConstraint.SelectedValue.Equals("Partial Marking") || rdo_SelectConstraint.SelectedValue.Equals("Negative Marking"))) if (!dr_SelectExam.SelectedValue.Equals("[Select One]")) { int iSelectedExamIndex = dr_SelectExam.SelectedIndex - 1; Exam oExam = new Exam(); List<Exam> oListExam = new List<Exam>(); oListExam = (List<Exam>)Utils.GetSession(SessionManager.csStoredExam); oExam = oListExam[iSelectedExamIndex]; //oExam.ExamConstraint = rdo_SelectConstraint.SelectedIndex + 1; //0=Full Marking,1=Partial Marking, 2=Negative Marking Utils.SetSession(SessionManager.csSelectedExam, oExam); Response.Redirect(ContainerManager.csMasterContainer + "?option=" + OptionManager.csQuestionSetup); } else { lbl_error.ForeColor = Color.Red; lbl_error.Text = "Please Select an Exam."; } } catch (Exception oEx) { } }
static void Main(string[] args) { XmlDocument doc = new XmlDocument(); doc.Load("C:/Users/khalefa/Downloads/exam.xml"); string dirname = @"c:\Users\khalefa\Downloads\exam\"; string batch = dirname + "compile.bat"; string combined = dirname + "c.tex"; string com_str = header; string batch_str = ""; for (int i = 0; i < 120; i++) { int version = i; shuffable.r = new Random(version); string filename = dirname + "a_" + version.ToString() + ".tex"; Exam e = new Exam(doc["exam"], version); e.Shuffle(); e.ToString(); System.IO.File.WriteAllText(filename, e.ToString()); batch_str = batch_str + "pdflatex a_" + version.ToString() + "\n"; com_str = com_str + " \\includepdf[pages=-]{a_" + version.ToString() + ".pdf}" + "\n"; } batch_str = batch_str + "pdflatex " + "c.tex"; com_str = com_str + "\\end{document}"; System.IO.File.WriteAllText(batch, batch_str); System.IO.File.WriteAllText(combined, com_str); }
public ExamWindow(Exam input) { local = input; InitializeComponent(); Title = input.Name; nadpisLabel.Content = input.Name; popisTextBox.Text = input.Description; doLabel.Content = input.Date.ToShortDateString(); předmětLabel.Content = input.Subject; if (input.Group != 0) skupinaLabel.Content = input.Group + "."; else skupinaLabel.Content = "1. a 2."; if (input.AdditionalInfo != "") { additionalInfo.NavigateUri = new Uri(input.AdditionalInfo); } else { additionalInfo.IsEnabled = false; } //nahrát odloženo ze soubvoru if (File.Exists(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Info", "Testy", local.Id + ".dat"))) using (StreamReader sr = new StreamReader(System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Info", "Testy", local.Id + ".dat"))) { done = Convert.ToBoolean(sr.ReadLine()); } else done = false; //set checkboxes hotovoCheckBox.IsChecked = this.Done; }
public string Add(string name, string comment, string date) { int school_id = SessionHandler.GetSchoolID(); Exam s = new Exam() { name = name, comment = comment, date = date, school_id = school_id }; bool result = _ed.Insert(s); return result.ToJSON(); }
public void Exam_WhenDeleted_StatusIsFalse() { Exam exam = new Exam() { Instructions = new string('a', 3500), Title = "here is the title", Value = 100 }; db.Exams.InsertOnSubmit(exam); db.SubmitChanges(); db.DeleteExam(exam.ExamId); Assert.AreEqual(false, exam.Status); }
public ActionResult CreateExam(Exam exam) { string username = User.Identity.Name; exam.LecturerID = username; db.Exams.AddObject(exam); db.SaveChanges(); return RedirectToAction("CreateExamCont", "Exam", new { ID = exam.ID }); }
public ActionResult CreateExam(int classID=0) { Class c = db.Classes.FirstOrDefault(cl => cl.ID == classID); Exam ex = new Exam(); //ex.Class = c;//Da bo exam ViewBag.ClassID = classID; return View(ex); }
// // GET: /Exam/Create public ActionResult Create() { var courses = _repo.Courses.All; var exam = new Exam(); var vm = new ExamInputModel(exam, courses); return View(vm); }
public static bool Equals(Exam a, Exam b) { if (a != null && b != null) { return a.Equals(b); } return a == b; }
private void StoreDefaultExamResult(string emailAddress = "emailaddress") { var exam = new Exam() { Instructions = "instructions", Title = "title" }; db.Exams.InsertOnSubmit(exam); var userProfile = new UserProfile() { EmailAddress = emailAddress, FirstName = "firstname", LastName = "lastname", Password = "******", GradeLevel = "12", UserType = 'M', Status = true }; db.UserProfiles.InsertOnSubmit(userProfile); userProfile.ExamResults.Add(new ExamResult() { Exam = exam, UserProfile = userProfile, Status = "not started", MaxScore = 100 }); db.SubmitChanges(); }
public void FillListFilter(Exam ex) { // deze functie voegt één afnamemoment toe aan de listview, wordt aangeroepen in de filter functie voor elk afnamemoment dat door de filters heen komt listView1.Items.Add(ex.Questionnaire.Name); listView1.Items[listView1.Items.Count - 1].SubItems.Add(Convert.ToString(ex.Questionnaire.Subject)); listView1.Items[listView1.Items.Count - 1].SubItems.Add(Convert.ToString(ex.Starttime)); listView1.Items[listView1.Items.Count - 1].SubItems.Add(Convert.ToString(ex.Endtime)); listView1.Items[listView1.Items.Count - 1].Tag = ex; }
public ActionResult CheckAnswer() { ExamViewModel examViewModel = new ExamViewModel(); examViewModel.SideBarData = new SideBarViewModel(); examViewModel.SideBarData.CurrentIndex = 2; int ProblemTotal = 0; int[] Ans = new int[200]; int[] ProblemScore = new int[200]; // string examname=RouteData.Values["examName"].ToString(); ExamBusinessLayer examBusinessLayer = new ExamBusinessLayer(); List<Exam> exam = examBusinessLayer.GetExamList(); // 获取考试题目分数和答案 string examName = Request.Form["examName"].ToString(); if (examName != null) { foreach (Exam t in exam) { if (t.ExamName == examName) { Exam userexam = new Exam(); Ans[ProblemTotal] = t.Answer; ProblemScore[ProblemTotal] = t.Score; ProblemTotal++; } } } int TotalScore = -1; int cnt = 0; for (int i = 0; i < ProblemTotal;i++) { if (Request.Form["examInfo[" + i + "].userAnswer"] == null) { cnt++; continue; } if (Request.Form["examInfo[" + i + "].userAnswer"].ToString()[0] - 'A'+1 == Ans[i]) TotalScore += ProblemScore[i]; } if (cnt == ProblemTotal) TotalScore = 65535; examViewModel.ExamScore = TotalScore; if (HttpContext.Session["User"] != null && Session["User"].ToString() != "") { examViewModel.NavStatusData = new NavStatusViewModel(); examViewModel.NavStatusData.LeftLink = "/User/Profile/" + HttpContext.Session["User"].ToString(); examViewModel.NavStatusData.LeftText = Session["User"].ToString(); examViewModel.NavStatusData.RightLink = "/User/Logout"; examViewModel.NavStatusData.RightText = "Log out"; } return View("Content", examViewModel); }
public ExamOverviewTeacherDetailDialog(ExamOverviewTeacherController teacherController, CustomEvent @event) { TeacherController = teacherController; Event = @event; Exam = (Exam)Event.Tag; //Stop de gegevens van de geselecteerde exam in een nieuw object, zodat deze wel bewaard blijven. LocallyEditedExam = new Exam(Exam.Examnr, Exam.Questionnaire, Exam.Starttime, Exam.Endtime, Exam.Lecture); InitializeComponent(); UpdateView(); }
public MainWindow() { exam = new Exam(); InitializeComponent(); EnableControls = false; CategoryTabs.SelectionChanged -= CategoryTabs_OnSelectionChanged; QuestionTabs.SelectionChanged -= QuestionTabs_OnSelectionChanged; C1.IsSelected = true; Q1.IsSelected = true; SetEventHandlers(); loadedQuestion = exam.Categories[ 0 ].Questions[ 0 ]; currentCategory = C1; currentQuestion = Q1; }
protected void GridView1_RowDeleting1(object sender, GridViewDeleteEventArgs e) { Exam exam = new Exam(); exam.ExamID = Convert.ToInt32(GridView1.DataKeys[e.RowIndex].Values[0]); try { examService.DelExam(exam.ExamID); lblMessger.Text = "删除成功!"; Response.Redirect("ExamManage.aspx"); } catch (Exception) { Response.Redirect("ExamManage.aspx"); } }
public ActionResult Delete(int id, Exam exam) { try { // TODO: Add delete logic here var item = _repo.Exams.All.Single(e => e.Id == id); _repo.Exams.Remove(exam); _repo.SaveChanges(); return RedirectToAction("Index"); } catch { return View(); } }
public ActionResult Create(Exam exam) { var examsNames = from exam2 in db.ExamNames select exam2.Name; ViewData["currentExamName"] = new SelectList(examsNames.ToList()); if (ModelState.IsValid) { db.Exams.Add(exam); db.SaveChanges(); return RedirectToAction("Create", "Exam"); } return View(exam); }
public ActionResult Create(Exam exam) { try { // TODO: Add insert logic here if (ModelState.IsValid) { _repo.Exams.Add(exam); _repo.SaveChanges(); } return RedirectToAction("Index"); } catch (Exception ex) { throw ex; } }
public bool AddExam(Exam exam) { string sql = @"insert into Exam (CourseID, PaperID, StartTime, EndTime) VALUES (@CourseID, @PaperID, @StartTime, @EndTime)"; SqlParameter[] para = new SqlParameter[] { new SqlParameter("@CourseID", exam.CourseID), new SqlParameter("@PaperID", exam.PaperID), new SqlParameter("@StartTime", exam.StartTime), new SqlParameter("@EndTime", exam.EndTime) }; int i = DBHelp.ExecuteCommand(sql, para); if (i > 0) { return true; } else { return false; } }
public Exam GetExam(int examID) { using (SqlConnection con = DBHelp.GetConnection()) { string sql = "select * from Exam where ExamID = " + examID.ToString(); SqlCommand cmd = new SqlCommand(sql, con); con.Open(); Exam e = new Exam(); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()) { e.ExamID = Convert.ToInt32(dr["ExamID"].ToString()); e.CourseID = Convert.ToInt32(dr["CourseID"].ToString()); e.PaperID = Convert.ToInt32(dr["PaperID"].ToString()); e.StartTime = Convert.ToDateTime(dr["StartTime"]); e.EndTime = Convert.ToDateTime(dr["EndTime"]); } dr.Close(); con.Close(); return e; } }
protected void imgBtnSave_Click(object sender, ImageClickEventArgs e) { Exam exam = new Exam(); exam.CourseID = Convert.ToInt32(ddlCourse.Text); exam.PaperID = Convert.ToInt32(ddlPaper.Text); try { exam.StartTime = new DateTime(Convert.ToInt32(txtStartYear.Text), Convert.ToInt32(txtStartMonth.Text), Convert.ToInt32(txtStartDay.Text), Convert.ToInt32(txtStartHour.Text), Convert.ToInt32(txtStartMinute.Text), 0); } catch (ArgumentOutOfRangeException) { lblMessage.Text = "请输入合法的开始时间!"; return; } exam.EndTime = exam.StartTime.AddMinutes(60 * Convert.ToInt32(txtHour.Text) + Convert.ToInt32(txtMinute.Text)); if (examService.AddExam(exam)) { lblMessage.Text = "添加成功!"; } else { lblMessage.Text = "添加失败!"; } }
protected void addquestion_Click(object sender, EventArgs e) { if (Session["handexam"] != null) exam1 = (Exam)Session["handexam"]; if (qutype.SelectedValue == "select") { foreach (GridViewRow row in GVShowQ.Rows) { if (row.RowType == DataControlRowType.DataRow) { CheckBox cb = (CheckBox)row.Cells[0].FindControl("cbAdd"); if (cb.Checked) { TextBox txt = (TextBox)row.Cells[1].FindControl("mark"); exam1.aAddId(Convert.ToInt32(GVShowQ.DataKeys[row.RowIndex].Value), Convert.ToInt32(txt.Text)); } } } } else if (qutype.SelectedValue == "ask") { foreach (GridViewRow row in GVShowQ2.Rows) { if (row.RowType == DataControlRowType.DataRow) { CheckBox cb = (CheckBox)row.Cells[0].FindControl("cbAdd2"); if (cb.Checked) { TextBox txt = (TextBox)row.Cells[1].FindControl("mark2"); exam1.bAddId(Convert.ToInt32(GVShowQ2.DataKeys[row.RowIndex].Value), Convert.ToInt32(txt.Text)); } } } } Session["handexam"] = exam1; }
public ActionResult CheckAnswer() { ExamViewModel examViewModel = new ExamViewModel(); examViewModel.SideBarData = new SideBarViewModel(); examViewModel.SideBarData.CurrentIndex = 2; int ProblemTotal = 0; int[] Ans = new int[200]; int[] ProblemScore = new int[200]; // string examname=RouteData.Values["examName"].ToString(); ExamBusinessLayer examBusinessLayer = new ExamBusinessLayer(); List <Exam> exam = examBusinessLayer.GetExamList(); // 获取考试题目分数和答案 string examName = Request.Form["examName"].ToString(); if (examName != null) { foreach (Exam t in exam) { if (t.ExamName == examName) { Exam userexam = new Exam(); Ans[ProblemTotal] = t.Answer; ProblemScore[ProblemTotal] = t.Score; ProblemTotal++; } } } int TotalScore = -1; int cnt = 0; for (int i = 0; i < ProblemTotal; i++) { if (Request.Form["examInfo[" + i + "].userAnswer"] == null) { cnt++; continue; } if (Request.Form["examInfo[" + i + "].userAnswer"].ToString()[0] - 'A' + 1 == Ans[i]) { TotalScore += ProblemScore[i]; } } if (cnt == ProblemTotal) { TotalScore = 65535; } examViewModel.ExamScore = TotalScore; if (HttpContext.Session["User"] != null && Session["User"].ToString() != "") { examViewModel.NavStatusData = new NavStatusViewModel(); examViewModel.NavStatusData.LeftLink = "/User/Profile/" + HttpContext.Session["User"].ToString(); examViewModel.NavStatusData.LeftText = Session["User"].ToString(); examViewModel.NavStatusData.RightLink = "/User/Logout"; examViewModel.NavStatusData.RightText = "Log out"; } return(View("Content", examViewModel)); }
public static void AddExam(Exam e) { var newExam = proxy.AddExam(e); AddExamNotification?.Invoke(typeof(ServiceDataProvider), new ExamEventArgs(newExam)); }
public static void EditExam(Exam editE) { proxy.EditExam(editE); }
public ActionResult Edit(int id, Exam exam) { try { // TODO: Add update logic here var item = _repo.Exams.All.Single(e => e.Id == id); item.Name = exam.Name; item.Where = exam.Where; item.When = exam.When; item.CourseId = exam.CourseId; _repo.SaveChanges(); return RedirectToAction("Index"); } catch { return View(); } }
public ActionResult Course(String CourseId) { CourseDetail CourseDes = new CourseDetail(); DataTable dtc = DataAccess.daobj("select Top(1) * from Courses where Course_Id = " + CourseId + " and Teacher_Id = '" + ((User)Session["CurrentUser"]).Id.ToString() + "'"); DataTable dte = DataAccess.daobj("select * from Exam where Course_Id = " + CourseId); DataTable dts = DataAccess.daobj("select * from Enrollement as En Join Student as St on En.Student_Id = St.id where Course_Id = " + CourseId + " and St.Blocked = 0"); if (dtc.Rows.Count > 0) { CourseDes.Course = new Course { Course_Id = Int32.Parse(dtc.Rows[0]["Course_Id"].ToString()), Name = dtc.Rows[0]["Course_name"].ToString(), Date = dtc.Rows[0]["Date_Created"].ToString(), Status = dtc.Rows[0]["Status"].ToString(), Enroll_id = dtc.Rows[0]["Enroll_Id"].ToString(), Enroll_Password = dtc.Rows[0]["Enroll_Password"].ToString() }; if (dte.Rows.Count > 0) { Exam[] Exams = new Exam[dte.Rows.Count]; for (int i = 0; i < dte.Rows.Count; i++) { Exams[i] = new Exam { Exam_Id = Int32.Parse(dte.Rows[i]["Exam_Id"].ToString()), Exam_Name = dte.Rows[i]["Exam_Name"].ToString(), Exam_Date = DateTime.Parse(dte.Rows[i]["Exam_Date"].ToString()), Start_Time = DateTime.Parse(dte.Rows[i]["Start_Time"].ToString()), End_Time = DateTime.Parse(dte.Rows[i]["End_Time"].ToString()), Total_Marks = Int32.Parse(dte.Rows[i]["Total_Marks"].ToString()), Duration = DateTime.Parse(dte.Rows[i]["End_Time"].ToString()).Subtract(DateTime.Parse(dte.Rows[i]["Start_Time"].ToString())) }; } CourseDes.Course.exam = Exams; } if (dts.Rows.Count > 0) { EnrolledStudent[] Students = new EnrolledStudent[dts.Rows.Count]; for (int i = 0; i < dts.Rows.Count; i++) { Students[i] = new EnrolledStudent { Id = dts.Rows[i]["Student_Id"].ToString(), Fullname = dts.Rows[i]["full_name"].ToString(), Username = dts.Rows[i]["username"].ToString(), Gender = dts.Rows[i]["Gender"].ToString(), Emailaddress = dts.Rows[i]["Email"].ToString(), ImageLocation = dts.Rows[i]["image"].ToString(), Status = dts.Rows[i]["Status"].ToString(), Enrollement_Date = DateTime.Parse(dts.Rows[i]["Enrollement_Date"].ToString()), Course_Id = Int32.Parse(CourseId) }; } CourseDes.Students = Students; } TempData["Cid"] = CourseId; } else { return(RedirectToAction("Dashboard", "Teacher")); } return(View(CourseDes)); }
public ActionResult PreviewResult(String ResultId) { String Tid = ((Teacher)Session["CurrentUser"]).Id; Int32 AutherizeAccess = (Int32)DataAccess.Reader("select Count(R.Result_Id) from Result as R Join Exam as E on E.Exam_Id = R.Exam_Id Join Courses as C on C.Course_Id = E.Course_Id where C.Teacher_Id = '" + Tid + "' and R.Result_Id = " + ResultId + "", false, false); if (AutherizeAccess > 0) { DataTable dtexam = DataAccess.daobj("select E.* from Result as R Join Exam as E on E.Exam_Id = R.Exam_Id where R.Result_Id = " + ResultId, false); Exam exam = new Exam(); if (dtexam.Rows.Count > 0) { exam.Exam_Id = (int)dtexam.Rows[0]["Exam_Id"]; exam.Course_Id = (int)dtexam.Rows[0]["Course_Id"]; exam.Exam_Name = dtexam.Rows[0]["Exam_Name"].ToString(); exam.Exam_Date = (DateTime)dtexam.Rows[0]["Exam_Date"]; exam.Start_Time = exam.Exam_Date.Date.Add((TimeSpan)dtexam.Rows[0]["Start_Time"]); exam.End_Time = exam.Exam_Date.Date.Add((TimeSpan)dtexam.Rows[0]["End_Time"]); exam.Total_Marks = (Double)dtexam.Rows[0]["Total_Marks"]; exam.Passing_Marks = (Double)dtexam.Rows[0]["Passing_Marks"]; exam.Duration = TimeSpan.FromMinutes(Int32.Parse(dtexam.Rows[0]["Duration"].ToString())); exam.AutoSubmit = (Boolean)dtexam.Rows[0]["AutoSubmit"]; exam.Temp = ResultId; DataTable dtparts = DataAccess.daobj("select * from Section where Exam_Id = " + exam.Exam_Id.ToString() + " order by Section_Order Asc"); if (dtparts.Rows.Count > 0) { exam.Sections = new Section[dtparts.Rows.Count]; for (int i = 0; i < dtparts.Rows.Count; i++) { Section section = new Section(); section.Section_Id = (int)dtparts.Rows[i]["Section_Id"]; section.Exam_Id = (int)dtparts.Rows[i]["Exam_Id"]; section.Section_Text = dtparts.Rows[i]["Section_Text"].ToString(); section.Section_Marks = (double)dtparts.Rows[i]["Section_Marks"]; section.Section_Order = (int)dtparts.Rows[i]["Section_Order"]; exam.Sections[i] = section; DataTable dtquestion = DataAccess.daobj("select Q.* , A.* from Question as Q Join Answer as A on Q.Question_Id = A.Question_Id Join Section as S on S.Section_Id = Q.Section_Id Join Exam as E on E.Exam_Id = S.Exam_Id Join Result as R on R.Exam_Id = E.Exam_Id where R.Result_Id = " + ResultId + " and S.Section_Id = " + section.Section_Id + " Order by Q.Question_Order Asc"); if (dtquestion.Rows.Count > 0) { exam.Sections[i].Questions = new Question[dtquestion.Rows.Count]; for (int j = 0; j < dtquestion.Rows.Count; j++) { Question question = new Question(); question.Question_Id = (int)dtquestion.Rows[j]["Question_Id"]; if (dtquestion.Rows[j]["Question_Type"].ToString().Equals("FB")) { question.QuestionText = StudentController.ConvertintoFB(dtquestion.Rows[j]["Question"].ToString()); } else { question.QuestionText = dtquestion.Rows[j]["Question"].ToString(); } question.Type = dtquestion.Rows[j]["Question_Type"].ToString(); question.Question_Marks = (double)dtquestion.Rows[j]["Question_Marks"]; question.Question_Order = (int)dtquestion.Rows[j]["Question_Order"]; question.Sample_Answer = (String)dtquestion.Rows[j]["Answer"]; question.Obtained_Marks = (double)dtquestion.Rows[j]["Obtain_Marks"]; exam.Sections[i].Questions[j] = question; if (question.Type.Equals("MCQ")) { DataTable dtchoices = DataAccess.daobj("select * from Choice where Question_Id = " + question.Question_Id.ToString() + " order by Choice_Id Asc"); if (dtchoices.Rows.Count > 0) { exam.Sections[i].Questions[j].Options = new String[dtchoices.Rows.Count]; for (int k = 0; k < dtchoices.Rows.Count; k++) { String Choice = dtchoices.Rows[k]["Choice"].ToString(); exam.Sections[i].Questions[j].Options[k] = Choice; } } } } } } } return(View(exam)); } else { ViewBag.ErrorHeading = "Invalid Exam Access"; return(View("~/Views/Shared/Error.cshtml")); } } else { ViewBag.ErrorHeading = "Invalid Result Access"; return(View("~/Views/Shared/Error.cshtml")); } }
public async Task <bool> CreateMissingAnswers(string username, Exam exam) { using (var conn = await GetDbConnectionForUser(username)) { //This transaction will automatically rollback if anything happens //https://github.com/aspnet/Microsoft.Data.Sqlite/blob/dev/src/Microsoft.Data.Sqlite.Core/SqliteTransaction.cs#L113 using (var transaction = conn.BeginTransaction(IsolationLevel.Serializable)) { var answers = (await GetAll(username, exam.Id)).ToList(); var maximumQuestions = Math.Min(exam.MaximumQuestions, exam.Questions.Count()); if (answers.Count >= maximumQuestions) { return(false); } var userQuestions = answers.Select(a => a.Question); var allQuestions = exam.Questions .OrderBy(q => q.Group) .ThenBy(q => Guid.NewGuid().ToString()) .Select(q => q.Id) .ToList(); var difference = maximumQuestions - answers.Count; var questionsToCreate = allQuestions.Except(userQuestions).Take(difference).ToList(); if (questionsToCreate.Count > 0) { answers = questionsToCreate .Select(q => new Answer { Exam = exam.Id, Question = q }) .ToList(); } else { answers.Clear(); } if (answers.Count > 0) { int number = 0; using (var cmd = conn.CreateCommand()) { cmd.CommandText = "SELECT COALESCE(MAX(Number), 0) FROM Answers WHERE Exam=@exam;"; cmd.AddParameter("exam", exam.Id); number = Convert.ToInt32(await cmd.ExecuteScalarAsync()); } foreach (var answer in answers) { using (var cmd = conn.CreateCommand()) { number++; answer.Number = number; cmd.CommandText = "INSERT INTO Answers (Exam, Question, Number, Created, IsCorrectAnswer, IsCompleteAnswer, IsBookmarked) VALUES (@exam, @question, @number, @created, @isCorrectAnswer, @isCompleteAnswer, @isBookmarked)"; cmd.AddParameter("exam", answer.Exam); cmd.AddParameter("question", answer.Question); cmd.AddParameter("number", answer.Number); cmd.AddParameter("created", answer.Created); cmd.AddParameter("isCorrectAnswer", false); cmd.AddParameter("isCompleteAnswer", false); cmd.AddParameter("isBookmarked", false); await cmd.ExecuteNonQueryAsync(); } } } transaction.Commit(); return(answers.Count > 0); } } }
public async Task <Exam> CreateAsync(Exam entity) { await _examsRepository.AddAsync(entity); return(entity); }
public IEnumerable <Student> GetByExam(Exam exam) { exam.ThrowIfNull("exam"); return(GetByExam(exam.ID)); }
async void OpenFileAsync(object sender, RoutedEventArgs e) { var ofd = new OpenFileDialog { Filter = "Text Files (*.txt)|*.txt" }; if ( ofd.ShowDialog() != true ) { return; } using ( new WaitCursor() ) { exam = new Exam(); await ExamParser.ReadExamFileAsync(ofd.FileName, exam); LoadQuestion(); EnableControls = true; foreach ( var tabItem in CategoryTabs.Items.Cast< object >(). Where (tabItem => !string.IsNullOrEmpty(exam.Categories[ CategoryTabs.Items.IndexOf(tabItem) ].Name)) ) { ( (TabItem) tabItem ).Header = exam.Categories[ CategoryTabs.Items.IndexOf(tabItem) ].Name.Trim(); } } }
public static Exam CreateExamFromXml(string xmlFilePath) { if (string.IsNullOrWhiteSpace(xmlFilePath)) { throw new ArgumentException("Empty xml file path"); } else { Exam exam = new Exam(); // XPathDocument doc = new XPathDocument(xmlFilePath); XPathNavigator navigator = doc.CreateNavigator(); XPathExpression expression = navigator.Compile("//FileVersion"); XPathNodeIterator iterator = navigator.Select(expression); while (iterator.MoveNext()) { exam.Properties.Version = (int)float.Parse(iterator.Current.Value); } expression = navigator.Compile("//ExamTitle"); iterator = navigator.Select(expression); while (iterator.MoveNext()) { exam.Properties.Title = iterator.Current.Value; } expression = navigator.Compile("//TimeAllowed"); iterator = navigator.Select(expression); while (iterator.MoveNext()) { exam.Properties.TimeLimit = Convert.ToInt32(iterator.Current.Value); } expression = navigator.Compile("//PassingScore"); iterator = navigator.Select(expression); while (iterator.MoveNext()) { exam.Properties.Passmark = Convert.ToInt32(iterator.Current.Value); } expression = navigator.Compile("//ExamCode"); iterator = navigator.Select(expression); while (iterator.MoveNext()) { exam.Properties.Code = iterator.Current.Value; } expression = navigator.Compile("//ExamInstructions"); iterator = navigator.Select(expression); while (iterator.MoveNext()) { exam.Properties.Instructions = iterator.Current.Value; } // expression = navigator.Compile("//Section"); iterator = navigator.Select(expression); while (iterator.MoveNext()) { Section section = new Section(); section.Title = iterator.Current.GetAttribute("Title", ""); // XPathNodeIterator subIterator = iterator.Current.SelectChildren(XPathNodeType.Element); while (subIterator.MoveNext()) { Question question = new Question(); question.No = Convert.ToInt32(subIterator.Current.GetAttribute("No", "")); // XPathNodeIterator subIter = subIterator.Current.SelectChildren(XPathNodeType.Element); while (subIter.MoveNext()) { if (subIter.Current.LocalName == "Text") { question.Text = subIter.Current.Value; } else if (subIter.Current.LocalName == "Image") { string examFolderPath = Path.GetDirectoryName(xmlFilePath); try { question.Image = new Bitmap(Path.Combine(examFolderPath, subIter.Current.Value)); } catch (ArgumentException) { } } else if (subIter.Current.LocalName == "Answer") { question.Answer = Convert.ToChar(subIter.Current.Value); } // if (subIter.Current.LocalName == "Options") { XPathNodeIterator ite = subIter.Current.SelectChildren(XPathNodeType.Element); while (ite.MoveNext()) { Option option = new Option(); string tempp = ite.Current.GetAttribute("Title", ""); option.Alphabet = Convert.ToChar(tempp); option.Text = ite.Current.Value; question.Options.Add(option); } } if (exam.Properties.Version == 1.0F) { question.Explanation = "Version 1.0 files do not support explanations"; } else { if (iterator.Current.LocalName == "AnswerExplanation") { question.Explanation = iterator.Current.Value; } } } section.Questions.Add(question); } exam.Sections.Add(section); } return(exam); } }
private static void GradeExamQuestion(ref RichTextBox rtb, bool addLogs, string studentPass, string instructorPassword, Exam anExam) { var id = AESGCM.SimpleDecryptWithPassword(anExam.RequiredStudentDetails.StudentID, studentPass); var name = AESGCM.SimpleDecryptWithPassword(anExam.RequiredStudentDetails.StudentName, studentPass); rtb.AppendText($"{anExam.ExamDescription}\n", new System.Drawing.Font("Courier New", 16, System.Drawing.FontStyle.Bold)); rtb.AppendText($"Student Name: {name}\n", new System.Drawing.Font("Courier New", 16, System.Drawing.FontStyle.Bold)); rtb.AppendText($"Student ID: {id}\n", new System.Drawing.Font("Courier New", 16, System.Drawing.FontStyle.Bold)); rtb.AppendText($"Grade: {anExam.GetExamGrade(instructorPassword)}\n", new System.Drawing.Font("Courier New", 18, System.Drawing.FontStyle.Underline)); // rtb.AppendText($"Exam Sent to Student Date and Comment:{list[i].weSentHimExamDateAndDetails}", new System.Drawing.Font("Courier New", 12, System.Drawing.FontStyle.Italic)); // rtb.AppendText($"Student Exam Submission Date And Comment:{list[i].weSentHimExamDateAndDetails}", new System.Drawing.Font("Courier New", 12, System.Drawing.FontStyle.Italic)); foreach (var q in anExam.QuestionsList) { QuizHelper.AddGradedQuestionToRtb(ref rtb, q.QuestionNumber, q, instructorPassword, true, true); } if (addLogs) { rtb.AppendText(System.Environment.NewLine); rtb.AppendText($"***** Student Exam Logs *****\n", new System.Drawing.Font("Courier New", 18, System.Drawing.FontStyle.Italic)); foreach (var s in anExam?.ExamLog) { rtb.AppendText($"{s}\n", new System.Drawing.Font("Courier New", 8, System.Drawing.FontStyle.Regular)); } } rtb.AppendText($"***** END OF STUDENT {name} EXAM *****\n", new System.Drawing.Font("Courier New", 18, System.Drawing.FontStyle.Italic)); rtb.AddNewPage(); }
public async Task <decimal> StartExam(Exam exam) { try { DataContext dataContext = new DataContext(); List <Answer> answers = new List <Answer>(); while (true) { if (!await F****r.StartExam(exam)) { return(0); } if (exam.Papers == null || exam.Papers.Count == 0) { return(0); } var paper = exam.Papers[exam.Papers.Count - 1]; answers.Clear(); foreach (var item in paper.Questions) { var question = await dataContext.GetRow(item.TmID); Answer answer = new Answer(); answer.TmID = item.TmID; answers.Add(answer); if (question == null) { answer.AnswerContent = ""; } else { answer.AnswerContent = question.Answers.Replace(";", ","); } } if (!await F****r.HandIn(paper, exam, answers)) { continue; } await F****r.GetResult(paper.Result); if (paper.Result.ErrorQuestionCount != 0) //答题失败 { await UpdateQuestionBank(paper.Result); continue; } else { return(paper.Result.Integral); } } } catch (Exception ex) { F****r.Worker.ReportError(ex.Message); Stop(); return(0); } }
private void AllotStudentsInSessionWritingExamToRoom(Session session, Exam exam1, Exam exam2, List <Department> DeptList1, List <Department> DeptList2) { foreach (var room in db.Rooms.ToList()) { List <Student> stud1 = new List <Student>(); List <Student> stud2 = new List <Student>(); if (exam1 != null) { stud1 = exam1.Students.ToList(); List <Student> temp = db.Students.Where(x => x.RoomStudents.Where(t => t.exam_id == exam1.Id && t.Session_Id == session.Id).Count() == 0).ToList(); stud1.RemoveAll(x => temp.Contains(x) == false); } if (exam2 != null) { stud2 = exam2.Students.ToList(); List <Student> temp = db.Students.Where(x => x.RoomStudents.Where(t => t.exam_id == exam2.Id && t.Session_Id == session.Id).Count() == 0).ToList(); stud2.RemoveAll(x => temp.Contains(x) == false); } int capacity = (room.Capacity.GetValueOrDefault() - db.RoomStudents.Where(x => x.Room_Id == room.Id && x.Session_Id == session.Id).ToList().Count()) / 2; if (room.RoomStatus == 1 && capacity != 0) { if (stud1.Count() != 0) { if (room.Exams.Where(x => x.Code == exam1.Code).Count() == 0) { foreach (var dept in DeptList1) { if (stud1.Where(x => x.Department.Id == dept.Id).ToList().Count() >= capacity) { UpdateRoomStudents(session, room, exam1, stud1.Where(x => x.Department.Id == dept.Id).ToList(), capacity); break; } } } } if (stud2.Count() != 0) { if (room.Exams.Where(x => x.Code == exam2.Code).Count() == 0) { foreach (var dept in DeptList2) { if (stud2.Where(x => x.Department.Id == dept.Id).ToList().Count() >= capacity) { UpdateRoomStudents(session, room, exam2, stud2.Where(x => x.Department.Id == dept.Id).ToList(), capacity); break; } } } } } capacity = (room.Capacity.GetValueOrDefault() - db.RoomStudents.Where(x => x.Room_Id == room.Id && x.Session_Id == session.Id).ToList().Count()); if (capacity == 0) { room.RoomStatus = 0; } if (stud1.Count() == 0 && stud2.Count() == 0) { return; } } }
partial void UpdateExams(Exam instance);
public ActionResult AddStudent([FromRoute] int classId, [FromRoute] int studentId, [FromBody] Exam request) { this.classService.AddExam(classId, studentId, request); return(this.Accepted()); }
public async Task <IActionResult> WriteAnswer(WriteAnswersDto writeAnswersDto) { //Вземане на studentId и testId от header - exam ExamDto examDto = JsonConvert.DeserializeObject <ExamDto>(Request.Headers["Exam"]); if (examDto.TestId == 0 || examDto.StudentId == 0 || String.IsNullOrEmpty(examDto.Token)) { return(NotFound()); } var student = await _context.Students .Include(stt => stt.StudentToTest) .FirstOrDefaultAsync(s => s.Id == examDto.StudentId && s.StudentToTest.TestId == examDto.TestId && s.StudentToTest.Id == examDto.Token); if (student == null) { return(Unauthorized()); } var question = await _context.TestQuestions .Include(tqa => tqa.TestQuestionAnswers) .Include(tqt => tqt.TestQuestionType) .FirstOrDefaultAsync(tq => tq.Id == writeAnswersDto.Id); int studentAnswers = writeAnswersDto.Answers.Count(); //Проверява дали броят на отговорите не превишата с този на типът тест if (question.TestQuestionType.NumberOfAnswers < studentAnswers) { return(BadRequest("You cheat!")); } var examAnswersForStudent = await _context.Exams .Include(ea => ea.ExamAnswer) .Where(e => e.StudentId == examDto.StudentId && e.TestQuestionId == writeAnswersDto.Id) .ToListAsync(); //Изтриване на старите отговори ако съществуват if (examAnswersForStudent.Count() != 0) { _context.RemoveRange(examAnswersForStudent); } //Entities за запис в базата ExamAnswer examAnswerToAdd = new ExamAnswer(); Exam examToAdd = new Exam(); foreach (var answer in writeAnswersDto.Answers) { //Мапване с въпрос var testQuestionAnswerForAdd = await _context.TestQuestionAnswers .FirstOrDefaultAsync(q => q.Id == answer); examAnswerToAdd = new ExamAnswer { TestQuestionAnswer = testQuestionAnswerForAdd }; //Проверява дали ид на отговорите дадени от студентът отговарят на тези в базата за въпроса var questionsToCheck = question.TestQuestionAnswers.ToList(); if (!questionsToCheck.Contains(testQuestionAnswerForAdd)) { return(BadRequest("You cheat")); } await _context.ExamAnswers.AddAsync(examAnswerToAdd); examToAdd = new Exam { ExamAnswer = examAnswerToAdd, Student = student, TestQuestion = question }; await _context.Exams.AddAsync(examToAdd); } if (await _context.SaveChangesAsync() > 0) { return(Ok()); } return(BadRequest()); }
/* * public static string AddWebinarRecordToCart(this HtmlHelper helper, Course course, bool withoutDialog = false) * { * return helper.AddToCart(x => x.AddWebinarRecord(course.Course_TC), * withoutDialog: withoutDialog); * } */ public static string AddToCart(this HtmlHelper helper, Exam exam) { return(AddToCart(helper, exam, false)); }
public ActionResult AddExam(Exam exam) { int eid = 0; int sid = 0; int qid = 0; Boolean Of = false; Boolean Fbf = false; DateTime EndTime = new DateTime(exam.Exam_Date.Year, exam.Exam_Date.Month, exam.Exam_Date.Day, exam.End_Time.Hour, exam.End_Time.Minute, exam.End_Time.Second); DateTime StartTime = new DateTime(exam.Exam_Date.Year, exam.Exam_Date.Month, exam.Exam_Date.Day, exam.Start_Time.Hour, exam.Start_Time.Minute, exam.Start_Time.Second); try { double t_marks = 0; if (exam.Sections != null && DateTime.Compare(EndTime, StartTime) > 0) { foreach (Section item in exam.Sections) { if (item.Questions != null) { foreach (Question Ques in item.Questions) { t_marks = t_marks + Ques.Question_Marks; } } } } else { throw new Exception(""); } DataAccess.clearparam(); DataAccess.addParam("title", exam.Exam_Name.ToString()); DataAccess.addParam("date", exam.Exam_Date.ToString("yyyy-MMMM-dd")); DataAccess.addParam("stime", StartTime.ToString("hh:mm:ss")); DataAccess.addParam("etime", EndTime.ToString("hh:mm:ss")); DataAccess.addParam("tmarks", t_marks); DataAccess.addParam("pmarks", exam.Passing_Marks); DataAccess.addParam("duration", (EndTime - StartTime).TotalMinutes); DataAccess.addParam("autosubmit", exam.AutoSubmit); DataAccess.addParam("instruction", ""); DataAccess.addParam("cid", exam.Course_Id); eid = (int)DataAccess.Reader("select (Isnull(Max(Exam_Id),0)+1) as Id from Exam"); DataAccess.addParam("eid", eid); DataAccess.Execute("insert into Exam (Exam_id,Course_Id,Exam_Name,Exam_Date,Start_Time,End_Time,Total_Marks,Passing_Marks,Duration,AutoSubmit,Instructions) values (@eid,@cid,@title,@date,@stime,@etime,@tmarks,@pmarks,@duration,@autosubmit,@instruction)", true, true); if (exam.Sections != null) { foreach (Section item in exam.Sections) { DataAccess.clearparam(); sid = (int)DataAccess.Reader("select (Isnull(Max(Section_Id),0)+1) as Id from Section"); DataAccess.addParam("sid", sid); DataAccess.addParam("eid", eid); DataAccess.addParam("stext", item.Section_Text); DataAccess.addParam("smarks", item.Section_Marks); DataAccess.addParam("sorder", item.Section_Order); DataAccess.Execute("insert into Section (Section_Id,Exam_Id,Section_Text,Section_Marks,Section_Order) values (@sid,@eid,@stext,@smarks,@sorder)", true, true); if (item.Questions != null) { foreach (Question Ques in item.Questions) { DataAccess.clearparam(); qid = (int)DataAccess.Reader("select (Isnull(Max(Question_Id),0)+1) as Id from Question"); DataAccess.addParam("qid", qid); DataAccess.addParam("sid", sid); DataAccess.addParam("question", Ques.QuestionText); DataAccess.addParam("marks", Ques.Question_Marks); DataAccess.addParam("order", Ques.Question_Order); DataAccess.addParam("type", Ques.Type); switch (Ques.Type) { case "Descriptive": DataAccess.addParam("answer", Ques.Sample_Answer); break; case "FB": DataAccess.addParam("answer", ExtractAnswer(Ques.QuestionText)); Fbf = true; break; case "MCQ": DataAccess.addParam("answer", Ques.Sample_Answer); Of = true; break; case "TF": DataAccess.addParam("answer", Ques.Sample_Answer); break; } DataAccess.Execute("insert into Question (Question_Id,Section_Id,Question,Question_Type,Question_Marks,Sample_Answer,Question_Order) values (@qid,@sid,@question,@type,@marks,@answer,@order)", true, true); if (Of && Ques.Options != null && Ques.Options.Length > 0) { foreach (String Options in Ques.Options) { DataAccess.clearparam(); DataAccess.addParam("qid", qid); DataAccess.addParam("choice", Options); if (Ques.Sample_Answer.Equals(Options)) { DataAccess.addParam("correct", true); } else { DataAccess.addParam("correct", false); } DataAccess.Execute("insert into Choice (Choice_Id,Question_Id,Choice,IsCorrect) values ((select (Isnull(Max(Choice_Id),0)+1) as Id from Choice),@qid,@choice,@correct)", true, true); } } else if (Fbf) { List <String> answers = ExtractAnswerList(Ques.QuestionText); if (answers.Count > 0) { foreach (String ans in answers) { DataAccess.clearparam(); DataAccess.addParam("qid", qid); DataAccess.addParam("answer", ans); DataAccess.Execute("insert into FB_Answers (FB_Answer_Id,Question_Id,Answer) values ((select (Isnull(Max(FB_Answer_Id),0)+1) as Id from FB_Answers),@qid,@answer)", true, true); } } } Fbf = false; Of = false; } } } } DataAccess.TransactionCommit(); return(new HttpStatusCodeResult(200, eid.ToString())); } catch (Exception e) { DataAccess.TransactionRollback(); return(new HttpStatusCodeResult(400)); } }
public Result CheckResult(Exam exam) { return(resultAccess.GetResultOfStudent(student.studentID, exam.id)); }
public ActionResult PreviewExam(String ExamId, String Type = "Solved") { String Tid = ((Teacher)Session["CurrentUser"]).Id; DataTable dtexam = DataAccess.daobj("select E.* from Exam as E Join Courses as C on E.Course_Id = C.Course_Id where C.Teacher_Id = '" + Tid + "' and E.Exam_Id = " + ExamId, false); Exam exam = new Exam(); if (dtexam.Rows.Count > 0) { exam.Exam_Id = (int)dtexam.Rows[0]["Exam_Id"]; exam.Course_Id = (int)dtexam.Rows[0]["Course_Id"]; exam.Exam_Name = dtexam.Rows[0]["Exam_Name"].ToString(); exam.Exam_Date = (DateTime)dtexam.Rows[0]["Exam_Date"]; exam.Start_Time = exam.Exam_Date.Date.Add((TimeSpan)dtexam.Rows[0]["Start_Time"]); exam.End_Time = exam.Exam_Date.Date.Add((TimeSpan)dtexam.Rows[0]["End_Time"]); exam.Total_Marks = (Double)dtexam.Rows[0]["Total_Marks"]; exam.Passing_Marks = (Double)dtexam.Rows[0]["Passing_Marks"]; exam.Duration = TimeSpan.FromMinutes(Int32.Parse(dtexam.Rows[0]["Duration"].ToString())); exam.AutoSubmit = (Boolean)dtexam.Rows[0]["AutoSubmit"]; DataTable dtparts = DataAccess.daobj("select * from Section where Exam_Id = " + ExamId + " order by Section_Order Asc"); if (dtparts.Rows.Count > 0) { exam.Sections = new Section[dtparts.Rows.Count]; for (int i = 0; i < dtparts.Rows.Count; i++) { Section section = new Section(); section.Section_Id = (int)dtparts.Rows[i]["Section_Id"]; section.Exam_Id = (int)dtparts.Rows[i]["Exam_Id"]; section.Section_Text = dtparts.Rows[i]["Section_Text"].ToString(); section.Section_Marks = (double)dtparts.Rows[i]["Section_Marks"]; section.Section_Order = (int)dtparts.Rows[i]["Section_Order"]; exam.Sections[i] = section; DataTable dtquestion = DataAccess.daobj("select * from Question where Section_Id = " + section.Section_Id.ToString() + " order by Question_Order Asc"); if (dtquestion.Rows.Count > 0) { exam.Sections[i].Questions = new Question[dtquestion.Rows.Count]; for (int j = 0; j < dtquestion.Rows.Count; j++) { Question question = new Question(); question.Question_Id = (int)dtquestion.Rows[j]["Question_Id"]; if (dtquestion.Rows[j]["Question_Type"].ToString().Equals("FB")) { question.QuestionText = StudentController.ConvertintoFB(dtquestion.Rows[j]["Question"].ToString()); } else { question.QuestionText = dtquestion.Rows[j]["Question"].ToString(); } question.Type = dtquestion.Rows[j]["Question_Type"].ToString(); question.Question_Marks = (double)dtquestion.Rows[j]["Question_Marks"]; question.Question_Order = (int)dtquestion.Rows[j]["Question_Order"]; if (Type.Equals("Solved")) { question.Sample_Answer = (String)dtquestion.Rows[j]["Sample_Answer"]; } else { question.Sample_Answer = ""; } exam.Sections[i].Questions[j] = question; if (question.Type.Equals("MCQ")) { DataTable dtchoices = DataAccess.daobj("select * from Choice where Question_Id = " + question.Question_Id.ToString() + " order by Choice_Id Asc"); if (dtchoices.Rows.Count > 0) { exam.Sections[i].Questions[j].Options = new String[dtchoices.Rows.Count]; for (int k = 0; k < dtchoices.Rows.Count; k++) { String Choice = dtchoices.Rows[k]["Choice"].ToString(); exam.Sections[i].Questions[j].Options[k] = Choice; } } } } } } } return(View(exam)); } else { ViewBag.ErrorHeading = "Invalid Exam Access"; return(View("~/Views/Shared/Error.cshtml")); } }
public ResolveFilterSpecification(Exam exam) : base(item => !item.Removed && exam.QuestionIds.Contains(item.QuestionId)) { }
public async Task <Guid> CreateOralExam(OralExamCreate oralExamForm) { var errors = new List <string>(); if (!(await context.Course.AnyAsync(_ => _.Id == oralExamForm.CourseId))) { errors.Add("Odabran je nepostojeći predmet!"); } if (!(await context.Semester.AnyAsync(_ => _.Id == oralExamForm.SemesterId))) { errors.Add("Odabran je nepostojeći semestar!"); } if (!(await context.CourseInstance.AnyAsync(_ => _.CourseId == oralExamForm.CourseId && _.SemesterId == oralExamForm.SemesterId))) { errors.Add("Odabrani predmet se ne održava u odabranom semestru!"); } if (!(await context.Enrolment.AnyAsync(_ => _.Id == oralExamForm.EnrolmentId))) { errors.Add("Odabrani student nije upisan na odabranu instancu predmeta!"); } if (oralExamForm.ExamId.HasValue) { if (!(await context.Exam.AnyAsync(_ => _.Id == oralExamForm.ExamId.Value))) { errors.Add("Odabran je nepostojeći ispit!"); } } else if (oralExamForm.Exam == null) { errors.Add("Nevaljali podaci za kreiranje usmenog ispita!"); } if (context.StudentExam.Any(_ => _.ExamId == oralExamForm.ExamId && _.EnrolmentId == oralExamForm.EnrolmentId)) { var student = context.StudentExam .Include(_ => _.Enrolment) .ThenInclude(_ => _.Student) .FirstOrDefault(_ => _.ExamId == oralExamForm.ExamId && _.EnrolmentId == oralExamForm.EnrolmentId) .Enrolment .Student; throw new ValidationException(string.Format($"Odabrani student {student.Firstname} {student.Lastname} već je prijavljen na dani ispit.")); } if (errors.Any()) { throw new ValidationException(errors); } if (!oralExamForm.ExamId.HasValue) { var exam = new Exam { Type = (int)ExamType.Oral, Date = GetDateTime(oralExamForm.Exam.Date, oralExamForm.Exam.Time), CourseId = oralExamForm.CourseId, SemesterId = oralExamForm.SemesterId }; await context.Exam.AddAsync(exam); oralExamForm.ExamId = exam.Id; } if (oralExamForm.ExistingExamDateTime != null) { var exam = await context.Exam.FirstOrDefaultAsync(_ => _.Id == oralExamForm.ExamId); exam.Date = GetDateTime(oralExamForm.ExistingExamDateTime.Date, oralExamForm.ExistingExamDateTime.Time); context.Exam.Update(exam); } var studentExam = new StudentExam { EnrolmentId = oralExamForm.EnrolmentId, ExamId = oralExamForm.ExamId.Value }; await context.StudentExam.AddAsync(studentExam); await context.SaveChangesAsync(); return(studentExam.Id); }
public Exam AddExam(Exam exam) { _context.Exams.Add(exam); _context.SaveChanges(); return(exam); }
public void Create_new_session_exam(int id_de_thi, IEnumerable <CAUHOI> cau_hois) { Session["Exam"] = new Exam(id_de_thi, cau_hois); }
public void PopulateExamDetails(int examID) { OnlineExamAppDBEntities3 dbContext = new OnlineExamAppDBEntities3(); _exam = dbContext.Exams.Where(qpa => qpa.ID == examID).FirstOrDefault(); }
public PartialViewResult Render_list_button_quiz() { Exam exam = Session["Exam"] as Exam; return(PartialView(exam)); }
bool IRepository <Exam> .Add(Exam o) { throw new NotImplementedException(); }
/// <summary> /// 批卷 /// </summary> /// <param nickname="questions"></param> /// <param nickname="studentAnswers"></param> /// <param nickname="rightCount"></param> /// <param nickname="value"></param> public static TestResult CalTestResult(Exam exam, string studentAnswers) { int value = 0, rightCount = 0; string[] user_ans = studentAnswers.Split('|'); string[] true_ans = exam.AnswerCache.Split('|'); if (true_ans.Length != user_ans.Length) { throw new Exception("答案与题数不符"); } for (int i = 0; i < user_ans.Length; i++) { var true_an = true_ans[i].Split('-'); var q_value = int.Parse(true_an[0]); var q_an = true_an[1]; if (exam.MultipleQuestionCelValue) { //第一种方式 全答对满分,少答错答0分 if (q_an == user_ans[i]) { //完全正确 value += q_value; rightCount++; } } else { //第二部方式计算:多选题满分必须大于等于正确答案数,每答对一个给1分,全部答对给满分,打错一个不计分 if (true_an[1] != "") { //不是问答题 if (q_an == user_ans[i]) { //完全正确 value += q_value; rightCount++; } else { if (true_an[1].IndexOf(",") > -1) { //多选 计分 var q_ans = true_an[1].Split(','); var ans = user_ans[i].Split(','); if (q_ans.Length > ans.Length) {//可能存答对一部分 int _value = 0; foreach (var a in ans) { if (q_ans.Contains(a)) { _value++; } else { _value = 0; break; } } value += _value; } } } } } } return(new TestResult() { Value = value, RightCount = rightCount, }); }
/* Create by Mimikami 2015-13-3 14:50 */ private List <Exam> FileTrans(HttpPostedFileBase examFile) { if (!System.IO.Directory.Exists(Server.MapPath("../Upload/"))) { System.IO.Directory.CreateDirectory(Server.MapPath("../Upload/")); } string filePath = Server.MapPath("../Upload/") + System.IO.Path.GetFileName(examFile.FileName); /* Delete the suffix */ char[] temp = examFile.FileName.ToCharArray(0, examFile.FileName.Length); int i = 0; for (i = temp.Length - 1; i >= 0; i--) { if (temp[i] == '.') { temp[i] = '\0'; break; } } string filename = new string(temp); filename = filename.Split('\0')[0]; examFile.SaveAs(filePath); List <Exam> questionList = new List <Exam>(); try { Excel.Application xlApp; Excel.Workbook xlWorkBook; Excel.Worksheet xlWorkSheet; Excel.Range range; int rCnt; xlApp = new Excel.Application(); xlWorkBook = xlApp.Workbooks.Open(filePath, 0, true, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0); xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1); range = xlWorkSheet.UsedRange; for (rCnt = 2; rCnt <= range.Rows.Count; rCnt++) { Exam question = new Exam(); question.ExamName = filename; question.Problem = (range.Cells[rCnt, 2] as Excel.Range).Value2.ToString(); question.Score = (int)(range.Cells[rCnt, 8] as Excel.Range).Value2; switch ((int)(range.Cells[rCnt, 1] as Excel.Range).Value2) { case 0: question.First = (range.Cells[rCnt, 3] as Excel.Range).Value2.ToString(); question.Second = (range.Cells[rCnt, 4] as Excel.Range).Value2.ToString(); question.Answer = (int)(range.Cells[rCnt, 7] as Excel.Range).Value2; break; case 1: question.First = (range.Cells[rCnt, 3] as Excel.Range).Value2.ToString(); question.Second = (range.Cells[rCnt, 4] as Excel.Range).Value2.ToString(); question.Third = (range.Cells[rCnt, 5] as Excel.Range).Value2.ToString(); question.Fourth = (range.Cells[rCnt, 6] as Excel.Range).Value2.ToString(); question.Answer = (int)(range.Cells[rCnt, 7] as Excel.Range).Value2; break; } question.ProblemProperty = (int)(range.Cells[rCnt, 1] as Excel.Range).Value2; questionList.Add(question); } xlWorkBook.Close(true, null, null); xlApp.Quit(); releaseObject(xlWorkSheet); releaseObject(xlWorkBook); releaseObject(xlApp); } catch (Exception ex) { //Response.Write(ex.ToString()); questionList = null; } finally { if (System.IO.File.Exists(filePath)) { System.IO.File.Delete(filePath); } } return(questionList); }
void SetEventHandlers() { CategoryTabs.SelectionChanged += CategoryTabs_OnSelectionChanged; QuestionTabs.SelectionChanged += QuestionTabs_OnSelectionChanged; foreach ( TabItem tabItem in CategoryTabs.Items ) { tabItem.MouseDoubleClick += EditCategoryNameAsync; } CategoryGrid.MultiSelectRadioButton.Checked += delegate { loadedQuestion.QuestionType = QuestionType.MultiSelect; }; CategoryGrid.MultiSingleRadioButton.Checked += delegate { loadedQuestion.QuestionType = QuestionType.MultiSingle; }; CategoryGrid.TrueFalseRadioButton.Checked += delegate { loadedQuestion.QuestionType = QuestionType.TrueFalse; }; CategoryGrid.MultiSingleNoShuffleRadioButton.Checked += delegate { loadedQuestion.QuestionType = QuestionType.MultiSingleNoShuffle; }; CategoryGrid.Answer1CheckBox.Checked += delegate { if ( CategoryGrid.Answer1CheckBox.IsChecked == null || loadedQuestion.QuestionType == QuestionType.MultiSelect || !(bool) CategoryGrid.Answer1CheckBox.IsChecked ) { return; } CategoryGrid.Answer2CheckBox.IsChecked = false; CategoryGrid.Answer3CheckBox.IsChecked = false; CategoryGrid.Answer4CheckBox.IsChecked = false; CategoryGrid.Answer5CheckBox.IsChecked = false; }; CategoryGrid.Answer2CheckBox.Checked += delegate { if ( CategoryGrid.Answer2CheckBox.IsChecked == null || loadedQuestion.QuestionType == QuestionType.MultiSelect || !(bool) CategoryGrid.Answer2CheckBox.IsChecked ) { return; } CategoryGrid.Answer1CheckBox.IsChecked = false; CategoryGrid.Answer3CheckBox.IsChecked = false; CategoryGrid.Answer4CheckBox.IsChecked = false; CategoryGrid.Answer5CheckBox.IsChecked = false; }; CategoryGrid.Answer3CheckBox.Checked += delegate { if ( CategoryGrid.Answer3CheckBox.IsChecked == null || loadedQuestion.QuestionType == QuestionType.MultiSelect || !(bool) CategoryGrid.Answer3CheckBox.IsChecked ) { return; } CategoryGrid.Answer1CheckBox.IsChecked = false; CategoryGrid.Answer2CheckBox.IsChecked = false; CategoryGrid.Answer4CheckBox.IsChecked = false; CategoryGrid.Answer5CheckBox.IsChecked = false; }; CategoryGrid.Answer4CheckBox.Checked += delegate { if ( CategoryGrid.Answer4CheckBox.IsChecked == null || loadedQuestion.QuestionType == QuestionType.MultiSelect || !(bool) CategoryGrid.Answer4CheckBox.IsChecked ) { return; } CategoryGrid.Answer1CheckBox.IsChecked = false; CategoryGrid.Answer2CheckBox.IsChecked = false; CategoryGrid.Answer3CheckBox.IsChecked = false; CategoryGrid.Answer5CheckBox.IsChecked = false; }; CategoryGrid.Answer5CheckBox.Checked += delegate { if ( CategoryGrid.Answer5CheckBox.IsChecked == null || loadedQuestion.QuestionType == QuestionType.MultiSelect || !(bool) CategoryGrid.Answer5CheckBox.IsChecked ) { return; } CategoryGrid.Answer1CheckBox.IsChecked = false; CategoryGrid.Answer2CheckBox.IsChecked = false; CategoryGrid.Answer3CheckBox.IsChecked = false; CategoryGrid.Answer4CheckBox.IsChecked = false; }; NewExamFlyout.IsCreatingExam += delegate { exam = new Exam { Name = NewExamFlyout.ExamNameTextbox.Text }; EnableControls = true; CategoryGrid.Answer1CheckBox.Unchecked += CheckForNoSelectedAnswers; CategoryGrid.Answer2CheckBox.Unchecked += CheckForNoSelectedAnswers; CategoryGrid.Answer3CheckBox.Unchecked += CheckForNoSelectedAnswers; CategoryGrid.Answer4CheckBox.Unchecked += CheckForNoSelectedAnswers; CategoryGrid.Answer5CheckBox.Unchecked += CheckForNoSelectedAnswers; }; }
public IList <Exam> GetExamsInfoByOrgID(string examName, int CategoryId, DateTime beginDateTime, DateTime endDateTime, int orgID, string isServerCenter) { IList <Exam> exams = new List <Exam>(); try { Database db = DatabaseFactory.CreateDatabase(); string sqlCommand; //路局服务器 或 次服务器(有两台服务器) if (Convert.ToBoolean(isServerCenter)) { sqlCommand = "USP_EXAM_GRADE_LIST_ORG1"; } else { sqlCommand = "USP_EXAM_GRADE_LIST_ORG_Ser"; } DbCommand dbCommand = db.GetStoredProcCommand(sqlCommand); db.AddInParameter(dbCommand, "p_exam_type_id", DbType.Int32, 1); if (examName != null) { db.AddInParameter(dbCommand, "p_exam_name", DbType.String, examName); } else { db.AddInParameter(dbCommand, "p_exam_name", DbType.String, string.Empty); } db.AddInParameter(dbCommand, "p_categoryId", DbType.Int32, CategoryId); if (beginDateTime > DateTime.MinValue) { db.AddInParameter(dbCommand, "p_begin_time", DbType.DateTime, beginDateTime); } if (endDateTime > DateTime.MinValue) { db.AddInParameter(dbCommand, "p_end_time", DbType.DateTime, endDateTime); } db.AddInParameter(dbCommand, "p_org_id", DbType.Int32, orgID); //db.AddOutParameter(dbCommand, "p_count", DbType.Int32, 4); using (IDataReader dataReader = db.ExecuteReader(dbCommand)) { Exam exam = null; while (dataReader.Read()) { exam = CreateModelObject(dataReader); exam.ExamineeCount = int.Parse(dataReader[GetMappingFieldName("ExamineeCount")].ToString()); exam.ExamAverageScore = (decimal)dataReader[GetMappingFieldName("ExamAverageScore")]; exam.ExamType = Convert.ToInt32(dataReader[GetMappingFieldName("ExamType")].ToString()); exams.Add(exam); } } } catch { } return(exams); }
partial void InsertExams(Exam instance);
public void Exam_Object_Creation_Test(int id, int groupID, int sessionId, int subjectId, DateTime examDate, bool iscredit, Exam ex_exam) { Exam t_exam = new Exam() { ID = id, GroupId = groupID, SessionID = sessionId, SubjectID = subjectId, ExamDate = examDate, IsCredit = iscredit }; Assert.True(ex_exam.Equals(t_exam)); }
partial void DeleteExams(Exam instance);
public static void AddExamToSandbox(Exam exam) { Exams.Add(exam); }