public async Task <IActionResult> DisableGrade(int id) { grade b = _context.grades.FirstOrDefault(u => u.id == id && u.status == true); if (b != null) { b.status = false; } else { b = null; } try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!gradeExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
//Get the grade list info public List <grade> getGradeList() { MySqlConnection conn = new MySqlConnection(connectString); string sql = "select id, name, school_id from grade"; MySqlCommand cmd = new MySqlCommand(sql, conn); MySqlDataReader dr; List <grade> GradeList = new List <grade>(); try { conn.Open(); dr = cmd.ExecuteReader(); while (dr.Read()) { grade grade = new grade(); grade.Id = Convert.ToInt32(dr["id"]); grade.Name = Convert.ToString(dr["name"]); grade.School_id = Convert.ToInt32(dr["school_id"]); GradeList.Add(grade); } } catch (Exception ex) { Console.WriteLine(ex); } finally { conn.Close(); Console.WriteLine("finally!"); } return(GradeList); }
public async Task <ActionResult <grade> > Postgrade(grade grade) { _context.grades.Add(grade); await _context.SaveChangesAsync(); return(CreatedAtAction("Getgrade", new { id = grade.id }, grade)); }
public async Task <IActionResult> Putgrade(int id, grade grade) { if (id != grade.id) { return(BadRequest()); } _context.Entry(grade).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!gradeExists(id)) { return(NotFound()); } else { throw; } } return(NoContent()); }
public ActionResult DeleteConfirmed(int id) { grade grade = db.grades.Find(id); db.grades.Remove(grade); db.SaveChanges(); return(RedirectToAction("Index")); }
public ActionResult UploadGrade(grade grade) { if ((string)Session["user"] != null) { //Debug.WriteLine(grade.quiz2); data.grade.Add(grade); // Debug.WriteLine(grade.quiz1); data.SaveChanges(); } return(View("Grades")); }
public ActionResult UploadGrade(grade grade) { if ((string)Session["user"] != null) { RedirectToAction("ViewGrade", "Student"); Debug.WriteLine(grade.quiz2); data.grade.Add(grade); Debug.WriteLine(grade.quiz1); data.SaveChanges(); } return(View("Grades")); }
public ActionResult Edit(grade grade) { if (ModelState.IsValid) { var crs = DB.courses.FirstOrDefault(s => s.ID.Equals(grade.CourseID)); DateTime datenow = DateTime.Now; DateTime ExamA = crs.ExamA; DateTime ExamB = crs.ExamB; int valueA = DateTime.Compare(ExamA, datenow); int valueB = DateTime.Compare(ExamB, datenow); // checking /* if (valueA < 0) * { * ModelState.AddModelError("GradeA", "you can update the grade of moed A after the date of the exam"); * } * if (valueB < 0) * { * ModelState.AddModelError("GradeB", "you can update the grade of moed B after the date of the exam"); * }*/ if (valueA < 0 || grade.GradeA == null) { if (valueB < 0 || grade.GradeB == null) { try { var grad = DB.grades.FirstOrDefault(s => s.CourseID.Equals(grade.CourseID) && s.StudentID.Equals(grade.StudentID)); grad.CourseID = grade.CourseID; grad.GradeA = grade.GradeA; grad.GradeB = grade.GradeB; grad.StudentID = grade.StudentID; DB.SaveChanges(); return(RedirectToAction("show")); } catch (Exception ex) { } } else { ModelState.AddModelError("GradeB", "you can update the grade of moed B after the date of the exam"); } } else { ModelState.AddModelError("GradeA", "you can update the grade of moed A after the date of the exam"); } } return(View(grade)); }
public ActionResult Edit([Bind(Include = "gradeID,finalpont,letterpoint,studentID,courseID")] grade grade) { if (ModelState.IsValid) { db.Entry(grade).State = EntityState.Modified; db.SaveChanges(); return(RedirectToAction("Index")); } int y = int.Parse(Session["instructorID"].ToString()); ViewBag.courseID = new SelectList(db.courses.Where(x => x.instructorID == y), "courseID", "coursename", grade.courseID); ViewBag.studentID = new SelectList(db.students, "studentID", "username", grade.studentID); return(View(grade)); }
public ActionResult Details(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } grade grade = db.grades.Find(id); if (grade == null) { return(HttpNotFound()); } return(View(grade)); }
public grade getGrade(decimal marks) { grade grade = new grade(); var Gradeinfo = db.GradeInfoes.Where(t => t.MarksFrom <= marks && t.MarksTo >= marks).SingleOrDefault(); grade.Grade = Gradeinfo.GradeName; grade.GradePoint = Convert.ToDouble(Gradeinfo.GradePoint); //new grade(); //if (marks >= 80) //{ // grade.Grade = "A+"; // grade.GradePoint = 5; //} //else if(marks >=70){ // grade.Grade = "A"; // grade.GradePoint = 4; //} //else if (marks >= 60) //{ // grade.Grade = "A-"; // grade.GradePoint = 3.5; //} //else if (marks >= 50) //{ // grade.Grade = "B"; // grade.GradePoint = 3; //} //else if (marks >= 40) //{ // grade.Grade = "C"; // grade.GradePoint = 2; //} //else if (marks >= 33 && marks<=39) //{ // grade.Grade = "D"; // grade.GradePoint = 1; //} //else //{ // grade.Grade = "F"; // grade.GradePoint = 0; //} return(grade); }
public static List <grade> fillgrade(int grade) { List <grade> grd = new List <grade>(); bus_eleave_ugc1 bus = new bus_eleave_ugc1(); bus.id = grade; DataTable dt = bus.fetchgrade(); for (int i = 0; i < dt.Rows.Count; i++) { grade _grade = new grade(); _grade.grade_id = int.Parse(dt.Rows[i]["grade_id"].ToString()); _grade.grade_desc = dt.Rows[i]["grade_desc"].ToString(); _grade.category = dt.Rows[i]["category"].ToString(); grd.Add(_grade); } return(grd); }
/// <summary> /// Description: Valida el estudiante agregado /// </summary> private void _addButton_btn_Click(object sender, RoutedEventArgs e) { if ((_textMilitarCode_tex.Text != "") && (_textFirstName_tex.Text != "") && (_textLastName_tex.Text != "")) { pilot pilot = new pilot(); pilot.militar_code = _textMilitarCode_tex.Text; pilot.first_name = _textFirstName_tex.Text; pilot.last_name = _textLastName_tex.Text; grade grade = _comboGrade_com.SelectedItem as grade; pilot.grade_id = grade.grade_id; if (_idEdit_boo == false) { pilotLogic.CreatePilot(pilot); } else { pilotLogic.UpdatePilot(pilot); } if (SelectInstructor.instance != null) { SelectInstructor.instance.UpdateData(); } if (SelectStudent.instance != null) { SelectStudent.instance.UpdateData(); } this.Close(); } else { RadWindow.Alert(new DialogParameters { Header = "Alert", Content = "Complete all fields and press Add", OkButtonContent = "Ok", Owner = this }); } }
public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } grade grade = db.grades.Find(id); if (grade == null) { return(HttpNotFound()); } int y = int.Parse(Session["instructorID"].ToString()); ViewBag.courseID = new SelectList(db.courses.Where(x => x.instructorID == y), "courseID", "coursename", grade.courseID); ViewBag.studentID = new SelectList(db.students, "studentID", "username", grade.studentID); return(View(grade)); }
public GradeViewModel(int _id) { gradeName = DataProvider.Ins.DB.grades.Where(x => x.id == _id).ToArray()[0].name; SaveCommand = new RelayCommand <MetroWindow>((p) => { return(true); }, async(p) => { var mySettings = new MetroDialogSettings() { AffirmativeButtonText = "Ok", ColorScheme = p.MetroDialogOptions.ColorScheme }; grade EditingGrade = DataProvider.Ins.DB.grades.Where(x => x.id == _id).ToArray()[0]; EditingGrade.name = gradeName; DataProvider.Ins.DB.SaveChanges(); await p.ShowMessageAsync("Hello!", "Saved successfully.", MessageDialogStyle.Affirmative, mySettings); p.Close(); LoadData(); ClassViewModel.LoadGrades(); }); }
public ActionResult EditGrades(int id) { if ((string)Session["user"] != null) { grade s = data.grade.Where(a => a.gradeid == id).FirstOrDefault(); s.gradeid = id; // Debug.WriteLine(s.gradeid); grade[] grade = data.grade.ToArray(); ViewData["grade"] = grade; //var cls = new SelectList([email protected](), "classname", "classname"); //var stu = new SelectList(data.student.ToList(), "studentname", "studentname"); //var sec = new SelectList(data.section.ToList(), "sectionname", "sectionname"); //var sub = new SelectList(data.subject.ToList(), "subjectname", "subjectname"); //ViewData["classlist"] = cls; //ViewData["studentlist"] = stu; //ViewData["sectionlist"] = sec; //ViewData["subjectlist"] = sub; return(View(s)); } return(RedirectToAction("Login", "User")); }
static void Main(string[] args) { grade s1; s1.name = "Lachlan"; s1.paper1mark = 40; s1.paper2mark = 50; Console.WriteLine("{0} got {1}", s1.name, s1.paper1mark + s1.paper2mark); // We can even create an array of structs grade[] structOFgrades = new grade[12]; structOFgrades[0].name = "Tom"; structOFgrades[0].paper1mark = 30; structOFgrades[0].paper2mark = 20; structOFgrades[1].name = "Nathan"; structOFgrades[1].paper1mark = 35; structOFgrades[1].paper2mark = 40; // Add 4 other students to the array and iterate arounfd the array printing out each students // name and total mark. Use a for loop // create a bubble sort to sort the array in order of paper1mark // write your array of structures out to a file. }
public ActionResult EditGrades(grade g, int id) { if ((string)Session["user"] != null) { grade gradeUpdate = data.grade.Where(a => a.gradeid == id).FirstOrDefault(); gradeUpdate.gradeid = id; gradeUpdate.classname = g.classname; gradeUpdate.sectionname = g.sectionname; gradeUpdate.subjectname = g.subjectname; gradeUpdate.studentname = g.studentname; gradeUpdate.quiz1 = g.quiz1; gradeUpdate.quiz2 = g.quiz2; gradeUpdate.quiz3 = g.quiz3; gradeUpdate.quiz4 = g.quiz4; gradeUpdate.assignment1 = g.assignment1; gradeUpdate.assignment2 = g.assignment2; gradeUpdate.halfyearlygrade = g.halfyearlygrade; gradeUpdate.finalexamgrade = g.finalexamgrade; data.SaveChanges(); return(RedirectToAction("Grades")); } return(RedirectToAction("Login", "User")); }
TranscriptEntry te = new TranscriptEntry(Student s, grade, this);
static List <Personnel> LecturePersonnel(StreamReader monStreamReader, List <Attraction> liste_attraction) { List <Personnel> liste_personnel = new List <Personnel>(); string ligne = monStreamReader.ReadLine(); //on stock la premiere ligne for (int j = 0; j < 17; j++) // tant qu'il y a pas d'espace vide { string[] temp = ligne.Split(';'); Typesexe type_sex = Typesexe.none; int matricule = -1; try { matricule = int.Parse(temp[1]); } catch (InvalidCastException e) { Console.WriteLine(e.Message); } try { type_sex = (Typesexe)Enum.Parse(typeof(Typesexe), temp[4]); } catch (InvalidCastException e) { Console.WriteLine(e.Message); } int c = -1; Attraction monAttraction = null; if (temp[0] != "Sorcier") { try { c = int.Parse(temp[7]); } catch (FormatException e) { Console.WriteLine(e.Message); } monAttraction = QuelEstAttraction(liste_attraction, c); } switch (temp[0]) { case "Sorcier": grade G = grade.none; try { G = (grade)Enum.Parse(typeof(grade), temp[6]); } catch (InvalidCastException e) { Console.WriteLine(e.Message); } List <string> liste_p = new List <string>(); string[] temp2 = temp[7].Split('-'); for (int i = 0; i < temp2.Length; i++) { liste_p.Add(temp2[i]); } Sorcier monSorcier = new Sorcier(matricule, temp[2], temp[3], type_sex, temp[5], G, liste_p); liste_personnel.Add(monSorcier); break; case "Monstre": int cagnotte_monstre = 0; try { cagnotte_monstre = int.Parse(temp[6]); } catch (InvalidCastException e) { Console.WriteLine(e.Message); } Monstre monMonstre = new Monstre(matricule, temp[2], temp[3], type_sex, temp[5], cagnotte_monstre, monAttraction); liste_personnel.Add(monMonstre); break; case "Demon": int cagnotte_demon = int.Parse(temp[6]); int force = int.Parse(temp[8]); Demon monDemon = new Demon(matricule, temp[2], temp[3], type_sex, temp[5], cagnotte_demon, monAttraction, force); liste_personnel.Add(monDemon); break; case "Fantome": int cagnotte_fantome = int.Parse(temp[6]); Fantome monFantome = new Fantome(matricule, temp[2], temp[3], type_sex, temp[5], cagnotte_fantome, monAttraction); liste_personnel.Add(monFantome); break; case "LoupGarou": int cagnotte_loup = int.Parse(temp[6]); float indiceCruaute = float.Parse(temp[8]); LoupGarou monLoup = new LoupGarou(matricule, temp[2], temp[3], type_sex, temp[5], cagnotte_loup, monAttraction, indiceCruaute); liste_personnel.Add(monLoup); break; case "Vampire": int cagnotte_vamp = int.Parse(temp[6]); float indiceLuminosite = float.Parse(temp[8]); Vampire monVamp = new Vampire(matricule, temp[2], temp[3], type_sex, temp[5], cagnotte_vamp, monAttraction, indiceLuminosite); liste_personnel.Add(monVamp); break; case "Zombie": CouleurZ maCouleur = (CouleurZ)Enum.Parse(typeof(CouleurZ), temp[8]); int degreDecomposition = int.Parse(temp[9]); int cagnotte_zomb = int.Parse(temp[6]); Zombie monZomb = new Zombie(matricule, temp[2], temp[3], type_sex, temp[5], cagnotte_zomb, monAttraction, maCouleur, degreDecomposition); liste_personnel.Add(monZomb); break; } ligne = monStreamReader.ReadLine(); } monStreamReader.Close(); return(liste_personnel); }
public ActionResult Submit(grade model) { if (ModelState.IsValid) { course temp1 = null; course temp2 = null; int flag = 0; List <course> courss = new List <course>(); List <string> user_courses = new List <string>(); string studentid = model.StudentID; string courseid = model.CourseID; foreach (grade g in DB.grades) { if (g.StudentID.Equals(studentid)) { user_courses.Add(g.CourseID); } } foreach (string s in user_courses) { temp1 = DB.courses.Find(s); temp2 = DB.courses.Find(courseid); if (temp1 != null && temp2 != null) { if (temp1.Day.Equals(temp2.Day) && temp1.startlec.Equals(temp2.startlec) && temp1 != temp2) { flag = 1; } } } var crs = DB.courses.FirstOrDefault(s => s.ID.Equals(model.CourseID)); var std = DB.users.FirstOrDefault(s => s.ID.Equals(model.StudentID)); var grad = DB.grades.FirstOrDefault(s => s.CourseID.Equals(model.CourseID) && s.StudentID.Equals(model.StudentID)); if (crs != null && std != null) { if (grad == null) { if (flag == 0) { if (std.UserTyper == 0) { DB.grades.Add(model); DB.SaveChanges(); return(RedirectToAction("AddCourseToStudent")); } else { ModelState.AddModelError("StudentID", "student id is incorrect"); } } else { ModelState.AddModelError("CourseID", "There are conflict with onther course at the same time"); } } else { ModelState.AddModelError("CourseID", "Already having this Course"); } } else { ModelState.AddModelError("StudentID", "The student id is incorrect"); ModelState.AddModelError("CourseID", "The course id is incorrect"); } } else { ModelState.AddModelError("StudentID", "The course id or student id is incorrect"); } return(View("AddCourseToStudent", model)); }
public GradeViewModel() { LoadData(); AddGradeCommand = new RelayCommand <UserControl>((p) => { return(true); }, async(p) => { MetroWindow CurrentWindow = Application.Current.MainWindow as MetroWindow; var mySettings = new MetroDialogSettings() { AffirmativeButtonText = "Ok", ColorScheme = CurrentWindow.MetroDialogOptions.ColorScheme }; var mySettings2 = new MetroDialogSettings() { AffirmativeButtonText = "Yes", NegativeButtonText = "No", ColorScheme = CurrentWindow.MetroDialogOptions.ColorScheme }; if (gradeName == null || gradeName == "") { await CurrentWindow.ShowMessageAsync("Hello!", "Please fill in every blanks.", MessageDialogStyle.Affirmative, mySettings); return; } MessageDialogResult mr = await CurrentWindow.ShowMessageAsync("Hello!", "Do you want to add grade " + gradeName + " ?", MessageDialogStyle.AffirmativeAndNegative, mySettings2); if (mr == MessageDialogResult.Affirmative) { if (DataProvider.Ins.DB.grades.Where(x => x.name == gradeName).Count() > 0) { await CurrentWindow.ShowMessageAsync("Hello!", "This grade existed.", MessageDialogStyle.Affirmative, mySettings); return; } else { grade AddingGrade = new grade(); AddingGrade.name = gradeName; DataProvider.Ins.DB.grades.Add(AddingGrade); DataProvider.Ins.DB.SaveChanges(); await CurrentWindow.ShowMessageAsync("Hello!", "Added successfully.", MessageDialogStyle.Affirmative, mySettings); LoadData(); ClassViewModel.LoadGrades(); } } }); DeleteCommand = new RelayCommand <int>((p) => { return(true); }, async(p) => { MetroWindow CurrentWindow = Application.Current.MainWindow as MetroWindow; var mySettings = new MetroDialogSettings() { AffirmativeButtonText = "Ok", ColorScheme = CurrentWindow.MetroDialogOptions.ColorScheme }; var mySettings2 = new MetroDialogSettings() { AffirmativeButtonText = "Yes", NegativeButtonText = "No", ColorScheme = CurrentWindow.MetroDialogOptions.ColorScheme }; grade DeletingGrade = DataProvider.Ins.DB.grades.Where(x => x.id == p).ToArray()[0]; MessageDialogResult mr = await CurrentWindow.ShowMessageAsync("Hello!", "Do you want to delete grade " + DeletingGrade.name + "?", MessageDialogStyle.AffirmativeAndNegative, mySettings2); if (mr == MessageDialogResult.Affirmative) { if (DeletingGrade.classes.Count() > 0) { await CurrentWindow.ShowMessageAsync("Hello!", "This grade has more than one class. Please delete its classes first.", MessageDialogStyle.Affirmative, mySettings); return; } DataProvider.Ins.DB.grades.Remove(DeletingGrade); DataProvider.Ins.DB.SaveChanges(); await CurrentWindow.ShowMessageAsync("Hello!", "Deleted successfully.", MessageDialogStyle.Affirmative, mySettings); LoadData(); ClassViewModel.LoadGrades(); } }); EditCommand = new RelayCommand <Button>((p) => { return(true); }, (p) => { int id = Convert.ToInt32(p.Tag); EditGrade editGrade = new EditGrade(id); editGrade.ShowDialog(); }); SearchCommand = new RelayCommand <string>((p) => { return(true); }, (p) => { List <grade> SearchedGrade = DataProvider.Ins.DB.grades.Where(x => x.name.Contains(p)).ToList(); LoadData(SearchedGrade); }); }
public Sorcier(int matricule, string nom, string prenom, Typesexe sexe, string function, grade tatouage, List <string> pouvoirs) : base(function, matricule, nom, prenom, sexe) { this.Pouvoirs = pouvoirs; this.Tatouage = tatouage; }
private void btnPrint_Click(object sender, EventArgs e) { if (K12.Presentation.NLDPanels.Student.SelectedSource.Count < 1) { FISCA.Presentation.Controls.MsgBox.Show("請先選擇學生"); return; } btnPrint.Enabled = false; filter f = new filter { GradeType = comboBoxEx2.Text }; Document document = new Document(); BackgroundWorker bgw = new BackgroundWorker(); Dictionary <StudentRecord, List <string> > errCheck = new Dictionary <StudentRecord, List <string> >(); bgw.DoWork += delegate { #region DoWork Byte[] template; if (K12.Presentation.NLDPanels.Student.SelectedSource.Count <= 0) { return; } List <string> sids = K12.Presentation.NLDPanels.Student.SelectedSource; Dictionary <string, SemesterHistoryRecord> dshr = SemesterHistory.SelectByStudentIDs(sids).ToDictionary(x => x.RefStudentID, x => x); Dictionary <string, StudentRecord> dsr = Student.SelectByIDs(sids).ToDictionary(x => x.ID, x => x); Dictionary <string, SemesterScoreRecord> dssr = SemesterScore.SelectByStudentIDs(sids).ToDictionary(x => x.RefStudentID + "#" + x.SchoolYear + "#" + x.Semester, x => x); DataTable dt = tool._Q.Select("select ref_student_id,entrance_date,leaving_date from $jhcore_bilingual.studentrecordext where ref_student_id in ('" + string.Join("','", sids) + "')"); Dictionary <string, edld> dedld = new Dictionary <string, edld>(); DateTime tmp; foreach (DataRow row in dt.Rows) { if (!dedld.ContainsKey("" + row["ref_student_id"])) { dedld.Add("" + row["ref_student_id"], new edld() { }); } if (DateTime.TryParse("" + row["entrance_date"], out tmp)) { dedld["" + row["ref_student_id"]].entrance_date = tmp; } if (DateTime.TryParse("" + row["leaving_date"], out tmp)) { dedld["" + row["ref_student_id"]].leaving_date = tmp; } } List <string> gradeYearList; int domainDicKey; switch (f.GradeType) { case "3~6": case "6": gradeYearList = new List <string> { "3", "4", "5", "6" }; domainDicKey = 6; template = (ReportConfiguration3_6.Template != null) //單頁範本 ? ReportConfiguration3_6.Template.ToBinary() : new Campus.Report.ReportTemplate(Properties.Resources._6樣版, Campus.Report.TemplateType.Word).ToBinary(); Choose3to6Grade = true; break; case "7~8": case "8": gradeYearList = new List <string> { "7", "8" }; domainDicKey = 8; template = (ReportConfiguration7_8.Template != null) //單頁範本 ? ReportConfiguration7_8.Template.ToBinary() : new Campus.Report.ReportTemplate(Properties.Resources._8樣版, Campus.Report.TemplateType.Word).ToBinary(); Choose7to8Grade = true; break; case "9~12": case "12": gradeYearList = new List <string> { "9", "10", "11", "12" }; domainDicKey = 12; template = (ReportConfiguration9_12.Template != null) //單頁範本 ? ReportConfiguration9_12.Template.ToBinary() : new Campus.Report.ReportTemplate(Properties.Resources._9_12_grade樣板, Campus.Report.TemplateType.Word).ToBinary(); break; default: return; } List <CourseGradeB.Tool.Domain> cgbdl = CourseGradeB.Tool.DomainDic[domainDicKey]; // 2016/5/18 穎驊新增功能,因原本3~6年級其Domain 並無English、Western Social Studies ,會造成如果沒有成績,而不顯示N/A直接空白的問題 if (Choose3to6Grade) { English.Hours = 6; English.Name = "English"; English.ShortName = "English"; WesternSocialStudies.Hours = 2; WesternSocialStudies.Name = "Western Social Studies"; WesternSocialStudies.ShortName = "W.S.S"; cgbdl.Add(English); cgbdl.Add(WesternSocialStudies); } // 2016/5/20(蔡英文上任)穎驊新增功能,因原本7~8年級其Domain 並無Elective ,會造成如果沒有成績,而不顯示N/A直接空白的問題 if (Choose7to8Grade) { Elective.Hours = 2; Elective.Name = "Elective"; Elective.ShortName = "Elective"; cgbdl.Add(Elective); } cgbdl.Sort(delegate(CourseGradeB.Tool.Domain x, CourseGradeB.Tool.Domain y) { return(x.DisplayOrder.CompareTo(y.DisplayOrder)); }); //int domainCount; Dictionary <string, string> NationalityMapping = K12.EduAdminDataMapping.Utility.GetNationalityMappingDict(); Dictionary <string, object> mailmerge = new Dictionary <string, object>(); GradeCumulateGPA gcgpa = new GradeCumulateGPA(); foreach (var studentID in dshr.Keys) {//學生 System.IO.Stream docStream = new System.IO.MemoryStream(template); Document each = new Document(docStream); //DocumentBuilder db = new DocumentBuilder(each); //Table table = (Table)each.GetChild(NodeType.Table, 1, true); //table.AllowAutoFit = true; //not work,why ? // 2016/4/28 取得樣板上,所有的功能變數,以利以後核對使用。 string[] fieldNames = each.MailMerge.GetFieldNames(); grade lastGrade = null; mailmerge.Clear(); mailmerge.Add("列印日期", DateTime.Today.ToString("MMMM d, yyyy", new System.Globalization.CultureInfo("en-US"))); #region 學生資料 StudentRecord sr = dsr[studentID]; mailmerge.Add("學生系統編號", sr.ID); mailmerge.Add("學號", sr.StudentNumber); mailmerge.Add("姓名", sr.Name); mailmerge.Add("英文名", sr.EnglishName); string gender; switch (sr.Gender) { case "男": gender = "Male"; break; case "女": gender = "Female"; break; default: gender = sr.Gender; break; } mailmerge.Add("性別", gender); mailmerge.Add("國籍", sr.Nationality); if (NationalityMapping.ContainsKey(sr.Nationality)) { mailmerge["國籍"] = NationalityMapping[sr.Nationality]; } mailmerge.Add("生日", sr.Birthday.HasValue ? sr.Birthday.Value.ToString("d-MMMM-yyyy", new System.Globalization.CultureInfo("en-US")) : ""); string esy = "", edog = ""; if (dedld.ContainsKey(studentID)) { if (dedld[studentID].entrance_date != null) { esy = dedld[studentID].entrance_date.Value.ToString("MMMM-yyyy", new System.Globalization.CultureInfo("en-US")); } if (dedld[studentID].leaving_date != null) { edog = dedld[studentID].leaving_date.Value.ToString("MMMM-yyyy", new System.Globalization.CultureInfo("en-US")); } } mailmerge.Add("入學日期", esy); mailmerge.Add("預計畢業日期", edog); //mailmerge.Add("Registrar", row.Value[0].SeatNo); //mailmerge.Add("Dean", row.Value[0].SeatNo); //mailmerge.Add("Principal", row.Value[0].SeatNo); #endregion #region 學生成績 Dictionary <int, grade> dgrade = new Dictionary <int, grade>(); #region 整理學生成績及年級 foreach (SemesterHistoryItem shi in dshr[studentID].SemesterHistoryItems) { if (!gradeYearList.Contains("" + shi.GradeYear)) { continue; } int _gradeYear = shi.GradeYear; string key = shi.RefStudentID + "#" + shi.SchoolYear + "#" + shi.Semester; if (!dgrade.ContainsKey(_gradeYear)) { dgrade.Add(_gradeYear, new grade() { grade_year = shi.GradeYear, school_year = shi.SchoolYear }); } if (shi.Semester == 1) { dgrade[_gradeYear].semester = 1; if (dssr.ContainsKey(key)) { dgrade[_gradeYear].sems1 = dssr[key]; } } else if (shi.Semester == 2) { dgrade[_gradeYear].semester = 2; if (dssr.ContainsKey(key)) { dgrade[_gradeYear].sems2 = dssr[key]; } } } #endregion mailmerge.Add("GPA", ""); int gradeCount = 1; foreach (string gy in gradeYearList) {//級別_ //群 , 科目 , 分數 //Dictionary<string, Dictionary<string, course>> dcl = new Dictionary<string, Dictionary<string, course>>(); Dictionary <string, List <SubjectScore> > dcl = new Dictionary <string, List <SubjectScore> >(); mailmerge.Add(string.Format("級別{0}", gradeCount), gy); mailmerge.Add(string.Format("學年度{0}", gradeCount), ""); if (dgrade.ContainsKey(int.Parse(gy))) { grade g = dgrade[int.Parse(gy)]; mailmerge[string.Format("學年度{0}", gradeCount)] = (g.school_year + 1911) + "-" + (g.school_year + 1912); foreach (var semScore in new SemesterScoreRecord[] { g.sems1, g.sems2 }) { if (semScore != null) { foreach (var subjectScore in semScore.Subjects.Values) { //if (!dcl.ContainsKey(subjectScore.Domain)) // dcl.Add(subjectScore.Domain, new Dictionary<string, course>()); //if (!dcl[subjectScore.Domain].ContainsKey(subjectScore.Subject)) // dcl[subjectScore.Domain].Add(subjectScore.Subject, new course()); //switch (subjectScore.Semester) //{ // case 1: // dcl[subjectScore.Domain][subjectScore.Subject].sems1_title = subjectScore.Subject; // dcl[subjectScore.Domain][subjectScore.Subject].sems1_score = subjectScore.Score.HasValue ? Math.Round(subjectScore.Score.Value, 0, MidpointRounding.AwayFromZero) : 0; // break; // case 2: // dcl[subjectScore.Domain][subjectScore.Subject].sems2_title = subjectScore.Subject; // dcl[subjectScore.Domain][subjectScore.Subject].sems2_score = subjectScore.Score.HasValue ? Math.Round(subjectScore.Score.Value, 0, MidpointRounding.AwayFromZero) : 0; // break; //} if (!dcl.ContainsKey(subjectScore.Domain)) { dcl.Add(subjectScore.Domain, new List <SubjectScore>()); } subjectScore.Score = subjectScore.Score.HasValue ? Math.Round(subjectScore.Score.Value, 0, MidpointRounding.AwayFromZero) : 0; dcl[subjectScore.Domain].Add(subjectScore); } } } //使用學期歷程最後一筆的學年度學期 if (g.sems1 != null) { mailmerge["GPA"] = g.sems1.CumulateGPA; } if (g.sems2 != null) { mailmerge["GPA"] = g.sems2.CumulateGPA; } lastGrade = g; } //檢查預設清單,缺漏處補回空資料 foreach (CourseGradeB.Tool.Domain domain in cgbdl) { //if (!dcl.ContainsKey(domain.Name)) // dcl.Add(domain.Name, new Dictionary<string, course>()); if (!dcl.ContainsKey(domain.Name)) { dcl.Add(domain.Name, new List <SubjectScore>()); } } foreach (var domain in dcl.Keys) { foreach (var semester in new int[] { 1, 2 }) { //群 int courseCount = 1; dcl[domain].Sort((SubjectScore s1, SubjectScore s2) => { return((s1.Subject + " (" + s1.Credit + ")").CompareTo(s2.Subject + " (" + s2.Credit + ")")); }); foreach (var item in dcl[domain]) { if (item.Semester == semester) { mailmerge.Add(string.Format("{0}_級{1}_學期{2}_科目{3}", domain.FixFieldName(), gradeCount, semester, courseCount), item.Subject + " (" + item.Credit + ")"); mailmerge.Add(string.Format("{0}_級{1}_學期{2}_科目級別{3}", domain.FixFieldName(), gradeCount, semester, courseCount), "Level:" + item.Level); mailmerge.Add(string.Format("{0}_級{1}_學期{2}_科目成績{3}", domain.FixFieldName(), gradeCount, semester, courseCount), "" + item.Score); // 2016/4/28 穎驊筆記,下面為檢察功能,fieldName為目前樣板的所有功能變數,假如樣版沒有完整的對應功能變數,會加入錯誤訊息提醒。 if (!fieldNames.Contains(string.Format("{0}_級{1}_學期{2}_科目成績{3}", domain.FixFieldName(), gradeCount, semester, courseCount))) { if (!errCheck.ContainsKey(sr)) { errCheck.Add(sr, new List <string>()); } errCheck[sr].Add("合併欄位「" + string.Format("{0}_級{1}_學期{2}_科目成績{3}", domain.FixFieldName(), gradeCount, semester, courseCount) + "」在樣板中不存在(" + item.SchoolYear + "學年度第" + item.Semester + "學期 科目名稱 " + item.Subject + ")。"); } courseCount++; //mailmerge.Add(string.Format("{0}_級{1}_學期1_科目{2}", domain.FixFieldName(), gradeCount, courseCount), item.sems1_title); //mailmerge.Add(string.Format("{0}_級{1}_學期2_科目{2}", domain.FixFieldName(), gradeCount, courseCount), item.sems2_title); ////都存在且相同才需要合併 //if (item.sems1_title != null && item.sems2_title != null && item.sems1_title == item.sems2_title) //{ // mailmerge[string.Format("{0}_級{1}_學期1_科目{2}", domain.FixFieldName(), gradeCount, courseCount)] = new mailmergeSpecial() { cellmerge = Aspose.Words.Tables.CellMerge.First, value = item.sems1_title }; // mailmerge[string.Format("{0}_級{1}_學期2_科目{2}", domain.FixFieldName(), gradeCount, courseCount)] = new mailmergeSpecial() { cellmerge = Aspose.Words.Tables.CellMerge.Previous, value = item.sems2_title }; //} //mailmerge.Add(string.Format("{0}_級{1}_學期1_科目成績{2}", domain.FixFieldName(), gradeCount, courseCount), // item.sems1_title != null ? "" + item.sems1_score : "N/A"); //mailmerge.Add(string.Format("{0}_級{1}_學期2_科目成績{2}", domain.FixFieldName(), gradeCount, courseCount), // item.sems2_title != null ? "" + item.sems2_score : "N/A"); //courseCount++; } } for (; courseCount <= 3; courseCount++) { mailmerge.Add(string.Format("{0}_級{1}_學期{2}_科目{3}", domain.FixFieldName(), gradeCount, semester, courseCount), ""); mailmerge.Add(string.Format("{0}_級{1}_學期{2}_科目級別{3}", domain.FixFieldName(), gradeCount, semester, courseCount), ""); mailmerge.Add(string.Format("{0}_級{1}_學期{2}_科目成績{3}", domain.FixFieldName(), gradeCount, semester, courseCount), "N/A"); //mailmerge.Add(string.Format("{0}_級{1}_學期1_科目{2}", domain.FixFieldName(), gradeCount, courseCount), new mailmergeSpecial() { cellmerge = Aspose.Words.Tables.CellMerge.First, value = "" }); //mailmerge.Add(string.Format("{0}_級{1}_學期2_科目{2}", domain.FixFieldName(), gradeCount, courseCount), new mailmergeSpecial() { cellmerge = Aspose.Words.Tables.CellMerge.Previous, value = "" }); //mailmerge.Add(string.Format("{0}_級{1}_學期1_科目成績{2}", domain.FixFieldName(), gradeCount, courseCount), "N/A"); //mailmerge.Add(string.Format("{0}_級{1}_學期2_科目成績{2}", domain.FixFieldName(), gradeCount, courseCount), "N/A"); } } for (var courseCount = 1; courseCount <= 3; courseCount++) { var subjName1 = "" + mailmerge[string.Format("{0}_級{1}_學期{2}_科目{3}", domain.FixFieldName(), gradeCount, 1, courseCount)]; var subjName2 = "" + mailmerge[string.Format("{0}_級{1}_學期{2}_科目{3}", domain.FixFieldName(), gradeCount, 2, courseCount)]; if (subjName1 == subjName2 || subjName1 == "" || subjName2 == "") { mailmerge[string.Format("{0}_級{1}_學期1_科目{2}", domain.FixFieldName(), gradeCount, courseCount)] = new mailmergeSpecial() { cellmerge = Aspose.Words.Tables.CellMerge.First, value = subjName1 }; mailmerge[string.Format("{0}_級{1}_學期2_科目{2}", domain.FixFieldName(), gradeCount, courseCount)] = new mailmergeSpecial() { cellmerge = Aspose.Words.Tables.CellMerge.Previous, value = subjName1 }; } if (subjName1 != "" && subjName2 == "") { mailmerge[string.Format("{0}_級{1}_學期1_科目{2}", domain.FixFieldName(), gradeCount, courseCount)] = new mailmergeSpecial() { cellmerge = Aspose.Words.Tables.CellMerge.First, value = subjName1 }; mailmerge[string.Format("{0}_級{1}_學期2_科目{2}", domain.FixFieldName(), gradeCount, courseCount)] = new mailmergeSpecial() { cellmerge = Aspose.Words.Tables.CellMerge.Previous, value = subjName1 }; } if (subjName1 == "" && subjName2 != "") { mailmerge[string.Format("{0}_級{1}_學期1_科目{2}", domain.FixFieldName(), gradeCount, courseCount)] = new mailmergeSpecial() { cellmerge = Aspose.Words.Tables.CellMerge.First, value = subjName2 }; mailmerge[string.Format("{0}_級{1}_學期2_科目{2}", domain.FixFieldName(), gradeCount, courseCount)] = new mailmergeSpecial() { cellmerge = Aspose.Words.Tables.CellMerge.Previous, value = subjName2 }; } var subjLevel1 = "" + mailmerge[string.Format("{0}_級{1}_學期{2}_科目級別{3}", domain.FixFieldName(), gradeCount, 1, courseCount)]; var subjLevel2 = "" + mailmerge[string.Format("{0}_級{1}_學期{2}_科目級別{3}", domain.FixFieldName(), gradeCount, 2, courseCount)]; if (subjLevel1 == subjLevel2) { mailmerge[string.Format("{0}_級{1}_學期1_科目級別{2}", domain.FixFieldName(), gradeCount, courseCount)] = new mailmergeSpecial() { cellmerge = Aspose.Words.Tables.CellMerge.First, value = subjLevel1 }; mailmerge[string.Format("{0}_級{1}_學期2_科目級別{2}", domain.FixFieldName(), gradeCount, courseCount)] = new mailmergeSpecial() { cellmerge = Aspose.Words.Tables.CellMerge.Previous, value = subjLevel1 }; } if (subjLevel1 != "" && subjLevel2 == "") { mailmerge[string.Format("{0}_級{1}_學期1_科目級別{2}", domain.FixFieldName(), gradeCount, courseCount)] = new mailmergeSpecial() { cellmerge = Aspose.Words.Tables.CellMerge.First, value = subjLevel1 }; mailmerge[string.Format("{0}_級{1}_學期2_科目級別{2}", domain.FixFieldName(), gradeCount, courseCount)] = new mailmergeSpecial() { cellmerge = Aspose.Words.Tables.CellMerge.Previous, value = subjLevel1 }; } if (subjLevel1 == "" && subjLevel2 != "") { mailmerge[string.Format("{0}_級{1}_學期1_科目級別{2}", domain.FixFieldName(), gradeCount, courseCount)] = new mailmergeSpecial() { cellmerge = Aspose.Words.Tables.CellMerge.First, value = subjLevel2 }; mailmerge[string.Format("{0}_級{1}_學期2_科目級別{2}", domain.FixFieldName(), gradeCount, courseCount)] = new mailmergeSpecial() { cellmerge = Aspose.Words.Tables.CellMerge.Previous, value = subjLevel2 }; } } } gradeCount++; } GradeCumulateGPARecord gcgpar; mailmerge.Add("級最高GPA", ""); mailmerge.Add("級平均GPA", ""); if (lastGrade != null && sr.Class != null) { //if (lastGrade.semester != null) //{ gcgpar = gcgpa.GetGradeCumulateGPARecord(lastGrade.school_year, lastGrade.semester, lastGrade.grade_year); if (gcgpar != null) { mailmerge["級最高GPA"] = decimal.Round(gcgpar.MaxGPA, 2, MidpointRounding.AwayFromZero); mailmerge["級平均GPA"] = decimal.Round(gcgpar.AvgGPA, 2, MidpointRounding.AwayFromZero); } //} } #endregion // 正式把MailMerge資料 給填上去,2015/4/27 驊紀錄 each.MailMerge.FieldMergingCallback = new MailMerge_MergeField(); each.MailMerge.Execute(mailmerge.Keys.ToArray(), mailmerge.Values.ToArray()); each.MailMerge.DeleteFields(); document.Sections.Add(document.ImportNode(each.FirstSection, true)); //2016/4/28 以下是恩正給穎驊的程式碼,可以輸出本程式MergeField 所有功能變數的縮寫成一個獨立Doc檔 // 在未來如果要要大量更動新增表格很方便可以直接複製貼上使用,如要使用,將上方原本的輸出MergeField、下面的//document.Sections.RemoveAt(0);註解掉即可。 //{ // Document doc = new Document(); // DocumentBuilder bu = new DocumentBuilder(doc); // bu.MoveToDocumentStart(); // bu.CellFormat.Borders.LineStyle = LineStyle.Single; // bu.CellFormat.VerticalAlignment = CellVerticalAlignment.Center; // Table table = bu.StartTable(); // foreach (String col in mailmerge.Keys) // { // bu.InsertCell(); // bu.CellFormat.Width = 15; // bu.InsertField("MERGEFIELD " + col + @" \* MERGEFORMAT", "«.»"); // bu.ParagraphFormat.Alignment = ParagraphAlignment.Center; // bu.InsertCell(); // bu.CellFormat.Width = 125; // bu.Write(col); // bu.ParagraphFormat.Alignment = ParagraphAlignment.Left; // bu.EndRow(); // } // table.AllowAutoFit = false; // bu.EndTable(); // document = doc; // break; //} } document.Sections.RemoveAt(0); #endregion }; bgw.RunWorkerCompleted += delegate { if (errCheck.Count > 0) { StringBuilder sb = new StringBuilder(); foreach (var stuRec in errCheck.Keys) { foreach (var err in errCheck[stuRec]) { sb.AppendLine(string.Format("{0} {1}({2}) {3}:{4}", stuRec.StudentNumber, stuRec.Class != null ? stuRec.Class.Name : "", stuRec.SeatNo, stuRec.Name, err)); } } MessageBox.Show(sb.ToString()); } #region Completed btnPrint.Enabled = true; //if (e.Error != null) //{ // MessageBox.Show(e.Error.Message); // return; //} Document inResult = document; try { SaveFileDialog SaveFileDialog1 = new SaveFileDialog(); SaveFileDialog1.Filter = "Word (*.doc)|*.doc|所有檔案 (*.*)|*.*"; SaveFileDialog1.FileName = "國外成績單"; if (SaveFileDialog1.ShowDialog() == DialogResult.OK) { inResult.Save(SaveFileDialog1.FileName); Process.Start(SaveFileDialog1.FileName); FISCA.Presentation.MotherForm.SetStatusBarMessage(SaveFileDialog1.FileName + ",列印完成!!"); //Update_ePaper ue = new Update_ePaper(new List<Document> { inResult }, current, PrefixStudent.學號); //ue.ShowDialog(); } else { FISCA.Presentation.Controls.MsgBox.Show("檔案未儲存"); return; } } catch (Exception exp) { string msg = "檔案儲存錯誤,請檢查檔案是否開啟中!!"; FISCA.Presentation.Controls.MsgBox.Show(msg + "\n" + exp.Message); FISCA.Presentation.MotherForm.SetStatusBarMessage(msg + "\n" + exp.Message); } #endregion }; bgw.RunWorkerAsync(); }
public ActionResult IndividualGradeSheet(int?examId, int?Roll, int?DeparmentId) { try { double totalGPA = 0; int flag = 1; var getResult = DDL.GetSingleResult(Roll.Value, examId, DeparmentId, null); StudentInfo student = db.StudentInfoes.Where(t => t.RollNo == Roll).SingleOrDefault(); FacultyInfo facinfo = db.FacultyInfoes.Where(t => t.Id == DeparmentId).SingleOrDefault(); List <result> result = new List <result>(); // get total Subject from StudentInfoSubject Except optional = Y int StudentSubject = db.StudentInfoSubjects.Where(t => t.OptionalSubject != "Y" && t.StudentId == student.Id).Count(); if (getResult != null) { foreach (var item in getResult) { //get is this subjectId is Optional grade _grade = new grade(); if (item.PassStatus == "F") { _grade.Grade = "F"; _grade.GradePoint = 0; } else { _grade = getGrade(item.MarksObtain); } if (item.OptionalSubject == "Y") { totalGPA += (_grade.GradePoint - 2) > 0 ? (_grade.GradePoint - 2) : 0; } else { if (flag == 1 && _grade.GradePoint < 1) { flag = 0; } totalGPA += _grade.GradePoint; } result.Add(new result { SubjectName = item.SubjectName, Grade = _grade.Grade, GradePoint = Convert.ToString(_grade.GradePoint) }); } if (flag == 0) { totalGPA = 0; } else { totalGPA = totalGPA / StudentSubject; } } string GPA = ""; if (totalGPA < 1) { GPA = "0 " + "(F)"; } else if (totalGPA < 2) { GPA = totalGPA.ToString("0.##") + " (D)"; } else if (totalGPA < 3) { GPA = totalGPA.ToString("0.##") + " (C)"; } else if (totalGPA < 3.5) { GPA = totalGPA.ToString("0.##") + " (B)"; } else if (totalGPA < 4) { GPA = totalGPA.ToString("0.##") + " (A-)"; } else if (totalGPA < 5) { GPA = totalGPA.ToString("0.##") + " (A)"; } else if (totalGPA < 6) { GPA = totalGPA.ToString("0.##") + " (A+)"; } LocalReport lr = new LocalReport(); ReportDataSource rd = new ReportDataSource(); lr.ReportPath = Server.MapPath("~/ReporFile/IndividualGradeSheet.rdlc"); DataTable dtFDRStatement = ConvertToDataTable(result.ToList()); rd.Name = "SingleResult"; rd.Value = dtFDRStatement; ReportParameter[] parameters = new ReportParameter[] { new ReportParameter("Name", student.StudentName), new ReportParameter("ClassRoll", Convert.ToString(student.RollNo)), new ReportParameter("Faculty", Convert.ToString(facinfo.FacultyName)), new ReportParameter("GPA", GPA) // returns "0" when decimalVar == 0 }; lr.SetParameters(parameters); lr.DataSources.Add(rd); string reportType = "PDF"; string mimeType; string encoding; string fileNameExtension; string deviceInfo = "<DeviceInfo>" + " <OutputFormat>PDF</OutputFormat>" + " <PageWidth>10.5in</PageWidth>" + " <PageHeight>11in</PageHeight>" + " <MarginTop>0.5in</MarginTop>" + " <MarginLeft>1in</MarginLeft>" + " <MarginRight>1in</MarginRight>" + " <MarginBottom>0.5in</MarginBottom>" + "</DeviceInfo>"; Warning[] warnings; string[] streams; byte[] renderedBytes; renderedBytes = lr.Render( reportType, deviceInfo, out mimeType, out encoding, out fileNameExtension, out streams, out warnings); renderedBytes = lr.Render(reportType); string reportName = "IndGradeSheet-Roll" + Convert.ToString(student.RollNo) + ".pdf"; return(File(renderedBytes, mimeType, reportName)); } catch (Exception ex) { ViewBag.Error = ex.Message; return(View("Error")); } }