Beispiel #1
0
 protected override void OnPrimaryKeyChanged(EventArgs e)
 {
     JHCourse.RemoveByIDs(new string[] { PrimaryKey });
     DisplayRecord(JHCourse.SelectByID(PrimaryKey));
     SaveButtonVisible   = false;
     CancelButtonVisible = false;
 }
Beispiel #2
0
        protected override void OnSaveButtonClick(EventArgs e)
        {
            if (!IsValid())
            {
                return;
            }

            JHCourseRecord record = JHCourse.SelectByID(PrimaryKey);

            //CourseRecordEditor editor = record.GetEditor();

            if (rdoCalcTrue.Checked)
            {
                record.CalculationFlag = "1";
            }
            else
            {
                record.CalculationFlag = "2";
            }

            record.RefAssessmentSetupID = string.Empty;

            if (cboAssessmentSetup.SelectedItem != null)
            {
                ComboBoxItem item = (cboAssessmentSetup.SelectedItem as ComboBoxItem);
                if (item.Tag != null && (item.Tag + "") != string.Empty)
                {
                    record.RefAssessmentSetupID = (item.Tag as JHAssessmentSetupRecord).ID;
                }
            }

            JHCourse.Update(record);
        }
Beispiel #3
0
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            StudentAttendInfo info = new StudentAttendInfo();

            Worker.ReportProgress(0);
            //快取指定學期的課程清單,查詢用。
            Dictionary <string, JHCourseRecord> courseDict = new Dictionary <string, JHCourseRecord>();

            foreach (JHCourseRecord course in JHCourse.SelectBySchoolYearAndSemester(SchoolYear, Semester))
            {
                courseDict.Add(course.ID, course);
            }

            Worker.ReportProgress(30);
            foreach (JHSCAttendRecord sc in JHSCAttend.SelectByStudentIDs(Students.AsKeyList()))
            {
                //修習的課程必須是指定學期的課程
                if (courseDict.ContainsKey(sc.RefCourseID))
                {
                    info.Add(sc.RefStudentID, courseDict[sc.RefCourseID]);
                }
            }

            Worker.ReportProgress(80);
            info.RemoveRegular();
            Worker.ReportProgress(100);
            e.Result = info;
        }
        private Dictionary <string, JHCourseRecord> ReadCourse()
        {
            Reporter.Feedback("讀取課程資料...", 0);

            Dictionary <string, JHCourseRecord> courses = new Dictionary <string, JHCourseRecord>();

            JHCourse.RemoveAll();
            List <JHCourseRecord> lstCourses = JHCourse.SelectBySchoolYearAndSemester(SchoolYear, Semester);

            foreach (JHCourseRecord each in lstCourses)
            {
                //過慮掉不計算的科目。
                if (!IsValidSubject(each))
                {
                    continue;
                }

                if (!courses.ContainsKey(each.ID))
                {
                    courses.Add(each.ID, each);
                }
            }

            return(courses);
        }
Beispiel #5
0
        private void InitializeCourses()
        {
            _allcourses = new Dictionary <SemesterInfo, List <JHSchool.Data.JHCourseRecord> >();
            List <int> schoolYearList = new List <int>();

            cboSchoolYear.Items.Clear();
            cboSemester.Items.Clear();

            SemesterInfo last = new SemesterInfo();

            foreach (JHCourseRecord course in JHCourse.SelectAll())
            {
                SemesterInfo info = new SemesterInfo();

                if (course.SchoolYear.HasValue)
                {
                    info.SchoolYear = course.SchoolYear.Value;
                }

                if (course.Semester.HasValue)
                {
                    info.Semester = course.Semester.Value;
                }

                //info.SchoolYear = (int)course.SchoolYear;
                //info.Semester = (int)course.Semester;


                if (!_allcourses.ContainsKey(info))
                {
                    _allcourses.Add(info, new List <JHSchool.Data.JHCourseRecord>());
                }
                _allcourses[info].Add(course);

                if (!schoolYearList.Contains(info.SchoolYear))
                {
                    schoolYearList.Add(info.SchoolYear);
                }

                if (info > last)
                {
                    last = info;
                }
            }

            schoolYearList.Sort();
            foreach (int sy in schoolYearList)
            {
                cboSchoolYear.Items.Add(sy);
            }

            cboSemester.Items.Add(1);
            cboSemester.Items.Add(2);

            cboCourseName.DisplayMember = "Name";

            cboSchoolYear.SelectedItem = last.SchoolYear;
            cboSemester.SelectedItem   = last.Semester;
        }
Beispiel #6
0
        public void Add(JHSCETakeRecord score)
        {
            string subject = JHCourse.SelectByID(score.RefCourseID).Subject;

            if (!Scores.ContainsKey(subject))
            {
                Scores.Add(subject, score);
            }
        }
Beispiel #7
0
        public void Add(JHSCAttendRecord attend)
        {
            string subject = JHCourse.SelectByID(attend.RefCourseID).Subject;

            if (!Attends.ContainsKey(subject))
            {
                Attends.Add(subject, attend);
            }
        }
        /// <summary>
        /// 根據單筆課程系統編號取得課程
        /// </summary>
        /// <param name="CourseID"></param>
        /// <returns></returns>
        public static AssignmentExamCourseRecord SelectByID(string CourseID)
        {
            JHCourse.RemoveByIDs(new List <string>()
            {
                CourseID
            });

            return(SelectByID <AssignmentExamCourseRecord>(CourseID));
        }
Beispiel #9
0
        public static Dictionary <string, JHCourseRecord> GetCourseDict(int SchoolYear, int Semester)
        {
            Dictionary <string, JHCourseRecord> dictCourses = new Dictionary <string, JHCourseRecord>();

            foreach (JHCourseRecord course in JHCourse.SelectBySchoolYearAndSemester(SchoolYear, Semester))
            {
                dictCourses.Add(course.ID, course);
            }
            return(dictCourses);
        }
        /// <summary>
        /// (Network Access)將目前學期的資料填入到 Courses、SCAttends 變數中。
        /// </summary>
        private void FillCurrentSemesterData()
        {
            Courses   = new Dictionary <string, JHCourseRecord>();
            SCAttends = new Dictionary <string, JHSCAttendRecord>();

            if (Students.Count <= 0)
            {
                return;                      //沒有學生當然就沒有任何資料了。
            }
            //Network Access
            int t1 = Environment.TickCount;
            List <JHCourseRecord> listCourses = JHCourse.SelectBySchoolYearAndSemester(Sems.SelectedSchoolYear, Sems.SelectedSemester);

            Console.WriteLine(string.Format("JHCourse.SelectBySchoolYearAndSemester Time:{0}", Environment.TickCount - t1));

            if (listCourses.Count <= 0)
            {
                return;                         //沒有任何課程也不會有成績資料了。
            }
            #region 建立 Course Dictionary
            foreach (JHCourseRecord each in listCourses)
            {
                Courses.Add(each.ID, each);
            }
            #endregion

            //Network Access
            t1 = Environment.TickCount;
            List <JHSCAttendRecord> listSCAttends = JHSCAttend.SelectByStudentIDAndCourseID(Students.ToKeys(), Courses.Values.ToKeys());

            Console.WriteLine(string.Format("JHSCAttend.SelectByStudentIDAndCourseID Time:{0}", Environment.TickCount - t1));

            t1 = Environment.TickCount;
            #region 建立 SCAttend Dictionary
            int selSchoolYear = Sems.SelectedSchoolYear;
            int selSemester   = Sems.SelectedSemester;
            foreach (JHSCAttendRecord each in listSCAttends)
            {
                JHCourseRecord course = Courses[each.RefCourseID];
                if (course.SchoolYear != selSchoolYear || course.Semester != selSemester)
                {
                    continue;
                }

                SCAttends.Add(each.ID, each);
            }
            #endregion
            Console.WriteLine(string.Format("建立 SCAttend Dictionary Time:{0}", Environment.TickCount - t1));
        }
Beispiel #11
0
        private void CourseWorker_DoWork(object sender, DoWorkEventArgs e)
        {
            CourseWorker.ReportProgress(0, "讀取學生資料...");
            Event.WaitOne();
            CourseWorker.ReportProgress(100, "讀取學生資料...");

            List <string> studentIDs = Students.AsKeyList();
            FunctionSpliter <string, JHSCAttendRecord> spliter = new FunctionSpliter <string, JHSCAttendRecord>(100, Util.MaxThread);

            spliter.Function = delegate(List <string> part)
            {
                return(JHSCAttend.Select(part, null, null, "" + RunningSchoolYear, "" + RunningSemester));
            };
            spliter.ProgressChange = delegate(int progress)
            {
                CourseWorker.ReportProgress(Util.CalculatePercentage(studentIDs.Count, progress), "讀取修課記錄...");
            };
            List <JHSCAttendRecord> AllAttends = spliter.Execute(studentIDs);

            AttendManager.Instance.Set(Students, AllAttends);

            List <string> validCourseIDs = new List <string>();

            foreach (JHSCAttendRecord sca in AllAttends)
            {
                if (!validCourseIDs.Contains(sca.RefCourseID))
                {
                    validCourseIDs.Add(sca.RefCourseID);
                }
            }

            //CourseWorker.ReportProgress(0, "讀取課程...");

            JHCourse.RemoveAll();

            FunctionSpliter <string, JHCourseRecord> spliter2 = new FunctionSpliter <string, JHCourseRecord>(100, Util.MaxThread);

            spliter2.Function = delegate(List <string> part)
            {
                return(JHCourse.SelectByIDs(part));
            };
            spliter2.ProgressChange = delegate(int progress)
            {
                CourseWorker.ReportProgress(Util.CalculatePercentage(validCourseIDs.Count, progress), "讀取課程...");
            };
            Courses = spliter2.Execute(validCourseIDs);
        }
        /// <summary>
        /// (Network Access)將目前學期的資料填入到 Courses、SCAttends 變數中。
        /// </summary>
        private void FillCurrentSemesterData()
        {
            Courses   = new Dictionary <string, JHCourseRecord>();
            SCAttends = new Dictionary <string, JHSCAttendRecord>();

            if (Students.Count <= 0)
            {
                return;                      //沒有學生當然就沒有任何資料了。
            }
            //Network Access
            List <JHCourseRecord> listCourses = JHCourse.SelectBySchoolYearAndSemester(Sems.SelectedSchoolYear, Sems.SelectedSemester);

            if (listCourses.Count <= 0)
            {
                return;                         //沒有任何課程也不會有成績資料了。
            }
            #region 建立 Course Dictionary
            foreach (JHCourseRecord each in listCourses)
            {
                Courses.Add(each.ID, each);
            }
            #endregion

            //Network Access
            List <JHSCAttendRecord> listSCAttends = JHSCAttend.SelectByStudentIDAndCourseID(Students.ToKeys(), Courses.Values.ToKeys());

            #region 建立 SCAttend Dictionary
            foreach (JHSCAttendRecord each in listSCAttends)
            {
                JHCourseRecord course = Courses[each.RefCourseID];
                if (course.SchoolYear != Sems.SelectedSchoolYear || course.Semester != Sems.SelectedSemester)
                {
                    continue;
                }

                SCAttends.Add(each.ID, each);
            }
            #endregion
        }
        private void InitializeBackgroundWorker()
        {
            _worker         = new BackgroundWorker();
            _worker.DoWork += delegate(object sender, DoWorkEventArgs e)
            {
                JHStudentRecord student = JHStudent.SelectByID(PrimaryKey);

                List <string> courseIDs = new List <string>();
                foreach (JHSCAttendRecord record in JHSCAttend.SelectByStudentIDAndCourseID(new string[] { student.ID }, new string[] { }))
                {
                    if (!courseIDs.Contains(record.RefCourseID))
                    {
                        courseIDs.Add(record.RefCourseID);
                    }
                }
                List <JHCourseRecord> courses = JHCourse.SelectByIDs(courseIDs);
                courses.Sort(delegate(JHCourseRecord x, JHCourseRecord y)
                {
                    return(x.Name.CompareTo(y.Name));
                });

                e.Result = courses;
            };
            _worker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
            {
                if (_RunningID != PrimaryKey)
                {
                    _RunningID = PrimaryKey;
                    _worker.RunWorkerAsync(_RunningID);
                    return;
                }

                ResetListView();
                PrefillItems(e.Result as List <JHCourseRecord>);
            };
        }
Beispiel #14
0
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            #region DoWork

            SelectSemesterForm opt = e.Argument as SelectSemesterForm;

            Worker.ReportProgress(0, "正在進行開課...");

            double totalClass = K12.Presentation.NLDPanels.Class.SelectedSource.Count;
            if (totalClass <= 0)
            {
                totalClass = 0;
            }
            double classCount = 0;

            Dictionary <string, JHCourseRecord> subjectCourseDict = new Dictionary <string, JHCourseRecord>();

            foreach (JHClassRecord cla in JHClass.SelectByIDs(K12.Presentation.NLDPanels.Class.SelectedSource))
            {
                #region 班級開課

                classCount++;

                int gradeYear = 0; //取得班級年級
                if (!cla.GradeYear.HasValue)
                {
                    continue;
                }
                gradeYear = cla.GradeYear.Value;

                // TODO: 先寫著,之後再討論…
                if (gradeYear >= 7)
                {
                    gradeYear -= 6;
                }

                #region 取得班級內每個學生的課程規劃表
                List <JHProgramPlanRecord> programPlanList = new List <JHProgramPlanRecord>();

                List <JHStudentRecord> studentsInSchool = GetInSchoolStudents(cla.Students);
                if (studentsInSchool.Count > 0) //班級有學生,抓學生課程規劃表
                {
                    foreach (JHStudentRecord stu in studentsInSchool)
                    {
                        //取得學生的課程規劃表
                        JHProgramPlanRecord record = PPCollection.GetProgramPlanRecord(stu);
                        if (record != null)
                        {
                            if (!programPlanList.Contains(record))
                            {
                                programPlanList.Add(record);
                            }
                        }
                    }
                }
                else //班級沒有學生,也是要開課的!
                {
                    JHProgramPlanRecord record = PPCollection.GetProgramPlanRecord(cla);
                    if (record != null)
                    {
                        if (!programPlanList.Contains(record))
                        {
                            programPlanList.Add(record);
                        }
                    }
                }
                #endregion

                #region 所有課程規劃表中要開的課程
                Dictionary <string, K12.Data.ProgramSubject> courseDict = new Dictionary <string, K12.Data.ProgramSubject>();

                foreach (JHProgramPlanRecord record in programPlanList)
                {
                    foreach (K12.Data.ProgramSubject subject in record.Subjects)
                    {
                        if (subject.GradeYear == gradeYear &&
                            subject.Semester == opt.Semester &&
                            subject.Period.HasValue &&
                            subject.Credit.HasValue)
                        {
                            string key = subject.SubjectName.Trim();
                            if (!courseDict.ContainsKey(key))
                            {
                                courseDict.Add(key, subject);
                            }
                        }
                    }
                }
                #endregion

                //快取來源學期課程先放這
                Dictionary <string, JHCourseRecord> copySourceCourses = new Dictionary <string, JHCourseRecord>();

                #region 取得本學期已開的課程
                Dictionary <string, JHCourseRecord> existSubjects = new Dictionary <string, JHCourseRecord>();

                foreach (JHCourseRecord course in JHCourse.SelectAll())
                {
                    #region 取得複製來源學期的課程,智慧型開課需要
                    if (opt.CopyOptionEnabled && (opt.CopyTeacher || opt.CopyAssessmentSetup))
                    {
                        if (course.SchoolYear == opt.CopySchoolYear && course.Semester == opt.CopySemester && course.RefClassID == cla.ID)
                        {
                            if (!copySourceCourses.ContainsKey(course.Subject))
                            {
                                copySourceCourses.Add(course.Subject, course);
                            }
                        }
                    }
                    #endregion

                    //取得本學期的課程
                    if (course.SchoolYear == opt.SchoolYear && course.Semester == opt.Semester && course.RefClassID == cla.ID)
                    {
                        if (!existSubjects.ContainsKey(course.Subject))
                        {
                            existSubjects.Add(course.Subject, course);
                        }
                    }
                }
                #endregion

                #region 開課(加入新課程)
                List <JHCourseRecord> insertCourseList = new List <JHCourseRecord>();
                foreach (string key in courseDict.Keys)
                {
                    //是原來沒有的課程
                    if (!existSubjects.ContainsKey(key))
                    {
                        K12.Data.ProgramSubject subject   = courseDict[key];
                        JHCourseRecord          newCourse = new JHCourseRecord();

                        newCourse.Credit          = subject.Credit;
                        newCourse.Period          = subject.Period;
                        newCourse.Domain          = subject.Domain;
                        newCourse.Name            = cla.Name + " " + subject.SubjectName;
                        newCourse.SchoolYear      = opt.SchoolYear;
                        newCourse.Semester        = opt.Semester;
                        newCourse.Subject         = subject.SubjectName.Trim();
                        newCourse.RefClassID      = cla.ID;
                        newCourse.CalculationFlag = subject.CalcFlag ? "1" : "2";

                        insertCourseList.Add(newCourse);
                    }
                }
                if (insertCourseList.Count > 0)
                {
                    JHCourse.Insert(insertCourseList);
                }
                #endregion

                #region 重新取得本學期已開的課程(包含這次新開的課程)
                JHCourse.RemoveAll();
                Dictionary <string, JHCourseRecord> reloadedExistSubjects = new Dictionary <string, JHCourseRecord>();
                List <string> courseIDs = new List <string>();
                foreach (JHCourseRecord course in JHCourse.SelectAll())
                {
                    if (course.SchoolYear == opt.SchoolYear &&
                        course.Semester == opt.Semester &&
                        course.RefClassID == cla.ID)
                    {
                        string key = course.Subject;
                        if (!reloadedExistSubjects.ContainsKey(key))
                        {
                            reloadedExistSubjects.Add(key, course);
                        }

                        courseIDs.Add(course.ID);
                    }
                }
                #endregion

                #region 加入學生修課
                CourseAttendCollection caCollection = new CourseAttendCollection();
                foreach (JHSCAttendRecord sca in JHSCAttend.SelectByCourseIDs(courseIDs))
                {
                    if (!caCollection.ContainsKey(sca.RefCourseID))
                    {
                        caCollection.Add(sca.RefCourseID, new List <JHSCAttendRecord>());
                    }
                    caCollection[sca.RefCourseID].Add(sca);
                }

                List <JHSCAttendRecord> insertSCAttendList = new List <JHSCAttendRecord>();

                foreach (JHStudentRecord student in GetInSchoolStudents(cla.Students))
                {
                    if (PPCollection.GetProgramPlanRecord(student) == null)
                    {
                        continue;
                    }

                    foreach (K12.Data.ProgramSubject subject in PPCollection.GetProgramPlanRecord(student).Subjects)
                    {
                        string key = subject.SubjectName.Trim();

                        if (subject.GradeYear == gradeYear &&
                            subject.Semester == opt.Semester &&
                            reloadedExistSubjects.ContainsKey(key))
                        {
                            bool found = false;
                            foreach (JHStudentRecord attendStudent in caCollection.GetAttendStudents(reloadedExistSubjects[key]))
                            {
                                if (attendStudent.ID == student.ID)
                                {
                                    found = true;
                                    break;
                                }
                            }
                            if (found == false)
                            {
                                JHSCAttendRecord newSCAttend = new JHSCAttendRecord();
                                newSCAttend.RefStudentID = student.ID;
                                newSCAttend.RefCourseID  = reloadedExistSubjects[key].ID;
                                insertSCAttendList.Add(newSCAttend);
                            }
                        }
                    }
                }
                if (insertSCAttendList.Count > 0)
                {
                    int t1 = Environment.TickCount;

                    JHSCAttend.Insert(insertSCAttendList);

                    Trace.WriteLine("寫入修課記錄時間:" + (Environment.TickCount - t1).ToString());
                }
                #endregion

                #region 判斷是否進行智慧型開課
                if (opt.CopyOptionEnabled)
                {
                    CourseInstructCollection ciCollection        = new CourseInstructCollection();
                    CourseInstructCollection currentCICollection = new CourseInstructCollection();
                    List <string>            copyCourseIDs       = new List <string>();
                    foreach (JHCourseRecord course in copySourceCourses.Values)
                    {
                        copyCourseIDs.Add(course.ID);
                    }
                    foreach (JHTCInstructRecord tc in JHTCInstruct.SelectByTeacherIDAndCourseID(new string[] { }, copyCourseIDs))
                    {
                        if (!ciCollection.ContainsKey(tc.RefCourseID))
                        {
                            ciCollection.Add(tc.RefCourseID, new List <JHTCInstructRecord>());
                        }
                        ciCollection[tc.RefCourseID].Add(tc);
                    }
                    foreach (JHTCInstructRecord tc in JHTCInstruct.SelectByTeacherIDAndCourseID(new string[] { }, courseIDs))
                    {
                        if (!currentCICollection.ContainsKey(tc.RefCourseID))
                        {
                            currentCICollection.Add(tc.RefCourseID, new List <JHTCInstructRecord>());
                        }
                        currentCICollection[tc.RefCourseID].Add(tc);
                    }

                    List <JHTCInstructRecord> insertTCList = new List <JHTCInstructRecord>();
                    List <JHTCInstructRecord> updateTCList = new List <JHTCInstructRecord>();

                    List <JHCourseRecord> updateCourseList = new List <JHCourseRecord>();

                    //針對目前這個班級在開課學年度學期的所有課程
                    foreach (JHCourseRecord course in reloadedExistSubjects.Values)
                    {
                        //如果課程不存在課程規劃表中,則不處理
                        if (!courseDict.ContainsKey(course.Subject))
                        {
                            continue;
                        }

                        //複製來源課程中,如果有相同科目名稱,則進行複製
                        if (copySourceCourses.ContainsKey(course.Subject))
                        {
                            JHCourseRecord copyCourseRecord = copySourceCourses[course.Subject];

                            #region 自動加入授課教師
                            if (opt.CopyTeacher == true)
                            {
                                for (int i = 1; i <= 3; i++)
                                {
                                    //取得來源課程的授課教師
                                    JHTeacherRecord teacherRecord = ciCollection.GetTeacher(copyCourseRecord, i);
                                    if (teacherRecord != null)
                                    {
                                        //取得開課課程的授課記錄
                                        JHTCInstructRecord tc = currentCICollection.GetInstruct(course, i);
                                        if (tc == null)
                                        {
                                            tc              = new JHTCInstructRecord();
                                            tc.RefCourseID  = course.ID;
                                            tc.RefTeacherID = teacherRecord.ID;
                                            tc.Sequence     = i;
                                            insertTCList.Add(tc);
                                        }
                                        else
                                        {
                                            tc.RefTeacherID = teacherRecord.ID;
                                            updateTCList.Add(tc);
                                        }
                                    }
                                }
                            }
                            #endregion

                            #region 自動加入評量設定
                            if (opt.CopyAssessmentSetup == true)
                            {
                                course.RefAssessmentSetupID = copyCourseRecord.RefAssessmentSetupID;
                                updateCourseList.Add(course);
                            }
                            #endregion
                        }
                    }

                    if (insertTCList.Count > 0)
                    {
                        JHTCInstruct.Insert(insertTCList);
                    }
                    if (updateTCList.Count > 0)
                    {
                        JHTCInstruct.Update(updateTCList);
                    }
                    if (updateCourseList.Count > 0)
                    {
                        JHCourse.Update(updateCourseList);
                    }
                }
                #endregion

                #endregion

                //回報進度
                Worker.ReportProgress((int)(classCount * 100d / totalClass), "正在進行開課...");
            }
            #endregion
        }
        public override void InitializeImport(SmartSchool.API.PlugIn.Import.ImportWizard wizard)
        {
            //學生資訊 key: studentID
            Dictionary <string, JHStudentRecord> students = new Dictionary <string, JHSchool.Data.JHStudentRecord>();
            //學生修課資訊 studentID -> List:SCAttendRecord
            Dictionary <string, List <JHSCAttendRecord> > scattends = new Dictionary <string, List <JHSchool.Data.JHSCAttendRecord> >();
            //學生修習的課程 courseID -> CourseRecord
            Dictionary <string, JHCourseRecord> courses = new Dictionary <string, JHSchool.Data.JHCourseRecord>();
            //所有課程(依學年度學期分開) schoolYear_semester -> (courseName -> CourseRecord)
            Dictionary <string, Dictionary <string, JHCourseRecord> > allcourses = new Dictionary <string, Dictionary <string, JHSchool.Data.JHCourseRecord> >();
            //學生修習的課程對應的評量設定細節
            Dictionary <string, List <HC.JHAEIncludeRecord> > courseAe = new Dictionary <string, List <HC.JHAEIncludeRecord> >();
            //學生的評量成績記錄
            Dictionary <string, List <HC.JHSCETakeRecord> > existSces = new Dictionary <string, List <HC.JHSCETakeRecord> >();
            //所有試別
            Dictionary <string, JHExamRecord> exams = new Dictionary <string, JHSchool.Data.JHExamRecord>();

            wizard.PackageLimit = 3000;
            wizard.ImportableFields.AddRange("學年度", "學期", "課程名稱", "評量名稱", "定期分數", "平時分數", "文字描述");
            wizard.RequiredFields.AddRange("學年度", "學期", "課程名稱", "評量名稱");

            wizard.ValidateStart += delegate(object sender, SmartSchool.API.PlugIn.Import.ValidateStartEventArgs e)
            {
                #region 取得學生資訊
                foreach (JHStudentRecord stu in JHStudent.SelectByIDs(e.List))
                {
                    if (!students.ContainsKey(stu.ID))
                    {
                        students.Add(stu.ID, stu);
                    }
                }
                #endregion

                #region 取得修課記錄
                MultiThreadWorker <string> loader1 = new MultiThreadWorker <string>();
                loader1.MaxThreads     = 3;
                loader1.PackageSize    = 250;
                loader1.PackageWorker += delegate(object sender1, PackageWorkEventArgs <string> e1)
                {
                    foreach (JHSCAttendRecord record in JHSCAttend.SelectByStudentIDAndCourseID(e1.List, new string[] { }))
                    {
                        if (!scattends.ContainsKey(record.RefStudentID))
                        {
                            scattends.Add(record.RefStudentID, new List <JHSCAttendRecord>());
                        }
                        scattends[record.RefStudentID].Add(record);

                        if (!courses.ContainsKey(record.RefCourseID))
                        {
                            courses.Add(record.RefCourseID, null);
                        }
                    }
                };
                loader1.Run(e.List);
                #endregion

                #region 取得課程資訊
                MultiThreadWorker <string> loader2 = new MultiThreadWorker <string>();
                loader2.MaxThreads     = 3;
                loader2.PackageSize    = 250;
                loader2.PackageWorker += delegate(object sender2, PackageWorkEventArgs <string> e2)
                {
                    foreach (JHCourseRecord record in JHCourse.SelectByIDs(new List <string>(e2.List)))
                    {
                        if (courses.ContainsKey(record.ID))
                        {
                            courses[record.ID] = record;
                        }
                    }
                };
                loader2.Run(courses.Keys);

                foreach (JHCourseRecord course in JHCourse.SelectAll())
                {
                    string key = course.SchoolYear + "_" + course.Semester;
                    if (!allcourses.ContainsKey(key))
                    {
                        allcourses.Add(key, new Dictionary <string, JHCourseRecord>());
                    }
                    if (!allcourses[key].ContainsKey(course.Name))
                    {
                        allcourses[key].Add(course.Name, course);
                    }
                }
                #endregion

                #region 取得目前評量成績記錄

                MultiThreadWorker <string> loader3 = new MultiThreadWorker <string>();
                loader3.MaxThreads     = 3;
                loader3.PackageSize    = 250;
                loader3.PackageWorker += delegate(object sender3, PackageWorkEventArgs <string> e3)
                {
                    foreach (HC.JHSCETakeRecord sce in JHSCETake.SelectByStudentIDs(e3.List).AsHCJHSCETakeRecords())
                    {
                        if (!existSces.ContainsKey(sce.RefSCAttendID))
                        {
                            existSces.Add(sce.RefSCAttendID, new List <HC.JHSCETakeRecord>());
                        }
                        existSces[sce.RefSCAttendID].Add(sce);
                    }
                };
                loader3.Run(e.List);
                #endregion

                #region 取得評量設定
                foreach (HC.JHAEIncludeRecord ae in JHAEInclude.SelectAll().AsHCJHAEIncludeRecords())
                {
                    if (!courseAe.ContainsKey(ae.RefAssessmentSetupID))
                    {
                        courseAe.Add(ae.RefAssessmentSetupID, new List <HC.JHAEIncludeRecord>());
                    }
                    courseAe[ae.RefAssessmentSetupID].Add(ae);
                }
                #endregion

                #region 取得試別
                foreach (JHExamRecord exam in JHExam.SelectAll())
                {
                    if (!exams.ContainsKey(exam.ID))
                    {
                        exams.Add(exam.ID, exam);
                    }
                }
                #endregion
            };

            wizard.ValidateRow += delegate(object sender, SmartSchool.API.PlugIn.Import.ValidateRowEventArgs e)
            {
                int     i;
                decimal d;

                #region 檢查學生是否存在
                JHStudentRecord student = null;
                if (students.ContainsKey(e.Data.ID))
                {
                    student = students[e.Data.ID];
                }
                else
                {
                    e.ErrorMessage = "壓根就沒有這個學生" + e.Data.ID;
                    return;
                }
                #endregion

                #region 驗證各個欄位格式
                bool inputFormatPass = true;
                foreach (string field in e.SelectFields)
                {
                    string value = e.Data[field];
                    switch (field)
                    {
                    default:
                        break;

                    case "學年度":
                    case "學期":
                        if (value == "" || !int.TryParse(value, out i))
                        {
                            inputFormatPass &= false;
                            e.ErrorFields.Add(field, "必須填入整數");
                        }
                        break;

                    case "課程名稱":
                        if (value == "")
                        {
                            inputFormatPass &= false;
                            e.ErrorFields.Add(field, "必須填入課程名稱");
                        }
                        break;

                    case "評量名稱":
                        if (value == "")
                        {
                            inputFormatPass &= false;
                            e.ErrorFields.Add(field, "必須填入評量名稱");
                        }
                        break;

                    case "定期分數":
                    case "平時分數":
                        if (value != "" && !decimal.TryParse(value, out d))
                        {
                            inputFormatPass &= false;
                            e.ErrorFields.Add(field, "必須填入空白或數值");
                        }
                        break;

                    //case "努力程度":
                    //    if (value != "" && !int.TryParse(value, out i))
                    //    {
                    //        inputFormatPass &= false;
                    //        e.ErrorFields.Add(field, "必須填入空白或整數");
                    //    }
                    //    break;
                    case "文字描述":
                        break;
                    }
                }
                #endregion

                //輸入格式正確才會針對情節做檢驗
                #region 驗證各種情節
                if (inputFormatPass)
                {
                    string errorMessage = "";

                    string sy         = e.Data["學年度"];
                    string se         = e.Data["學期"];
                    string key        = e.Data.ID + "_" + sy + "_" + se;
                    string courseName = e.Data["課程名稱"];
                    string semsKey    = sy + "_" + se;
                    string examName   = e.Data["評量名稱"];

                    //int schoolyear = Framework.Int.ParseInt(sy);
                    //int semester = Framework.Int.ParseInt(se);

                    #region 檢查課程是否存在系統中
                    bool noCourse = false;
                    if (!allcourses.ContainsKey(semsKey))
                    {
                        noCourse      = true;
                        errorMessage += (errorMessage == "" ? "" : "\n") + " 系統中找不到該課程";
                    }
                    else if (!allcourses[semsKey].ContainsKey(courseName))
                    {
                        noCourse      = true;
                        errorMessage += (errorMessage == "" ? "" : "\n") + " 系統中找不到該課程";
                    }
                    else
                    {
                    }
                    #endregion

                    #region 檢查學生是否有修此課程 & 評量是否存在
                    bool attended = false;

                    JHCourseRecord attendCourse = null;
                    if (scattends.ContainsKey(e.Data.ID))
                    {
                        foreach (JHSCAttendRecord record in scattends[e.Data.ID])
                        {
                            //if (courses[record.RefCourseID].Name == courseName)
                            //    attendCourse = courses[record.RefCourseID];
                            bool HasRec = false;

                            // 當有學年度學期課程名稱相同
                            if (courses[record.RefCourseID].Name == courseName && courses[record.RefCourseID].SchoolYear.HasValue && courses[record.RefCourseID].Semester.HasValue)
                            {
                                if ((courses[record.RefCourseID].SchoolYear.Value.ToString().Trim() == sy.Trim()) && courses[record.RefCourseID].Semester.Value.ToString().Trim() == se.Trim())
                                {
                                    HasRec = true;
                                }
                            }
                            if (HasRec && courses.ContainsKey(record.RefCourseID))
                            {
                                attendCourse = courses[record.RefCourseID];
                            }
                        }
                    }
                    else //學生沒修半堂課
                    {
                    }

                    if (attendCourse == null && !noCourse)
                    {
                        if (!e.ErrorFields.ContainsKey("無修課記錄"))
                        {
                            e.ErrorFields.Add("無修課記錄", "學生在此學期並無修習此課程");
                        }
                    }
                    else if (attendCourse != null)
                    {
                        #region 驗證評量是否存在
                        if (string.IsNullOrEmpty(attendCourse.RefAssessmentSetupID))
                        {
                            if (!e.ErrorFields.ContainsKey("無評量設定"))
                            {
                                e.ErrorFields.Add("無評量設定", "課程(" + attendCourse.Name + ")無評量設定");
                            }
                        }
                        else
                        {
                            if (!courseAe.ContainsKey(attendCourse.RefAssessmentSetupID))
                            {
                                if (!e.ErrorFields.ContainsKey("無評量設定"))
                                {
                                    e.ErrorFields.Add("無評量設定", "課程(" + attendCourse.Name + ")無評量設定");
                                }
                            }
                            else
                            {
                                bool examValid = false;
                                foreach (HC.JHAEIncludeRecord ae in courseAe[attendCourse.RefAssessmentSetupID])
                                {
                                    if (!exams.ContainsKey(ae.RefExamID))
                                    {
                                        continue;
                                    }

                                    if (exams[ae.RefExamID].Name == examName)
                                    {
                                        examValid = true;
                                    }
                                }

                                if (!examValid)
                                {
                                    if (!e.ErrorFields.ContainsKey("評量名稱無效"))
                                    {
                                        e.ErrorFields.Add("評量名稱無效", "評量名稱(" + examName + ")不存在系統中");
                                    }
                                }
                            }
                        }
                        #endregion
                    }
                    #endregion

                    e.ErrorMessage = errorMessage;
                }
                #endregion
            };

            wizard.ImportPackage += delegate(object sender, SmartSchool.API.PlugIn.Import.ImportPackageEventArgs e)
            {
                Dictionary <string, List <RowData> > id_Rows = new Dictionary <string, List <RowData> >();

                #region 分包裝
                foreach (RowData data in e.Items)
                {
                    if (!id_Rows.ContainsKey(data.ID))
                    {
                        id_Rows.Add(data.ID, new List <RowData>());
                    }
                    id_Rows[data.ID].Add(data);
                }
                #endregion

                List <HC.JHSCETakeRecord> insertList = new List <HC.JHSCETakeRecord>();
                List <HC.JHSCETakeRecord> updateList = new List <HC.JHSCETakeRecord>();

                //交叉比對各學生資料
                #region 交叉比對各學生資料
                foreach (string id in id_Rows.Keys)
                {
                    JHStudentRecord studentRec = students[id];

                    foreach (RowData data in id_Rows[id])
                    {
                        string examName   = data["評量名稱"];
                        string courseName = data["課程名稱"];
                        string SchoolYear = data["學年度"];
                        string Semester   = data["學期"];


                        if (!scattends.ContainsKey(id))
                        {
                            continue;
                        }

                        foreach (JHSCAttendRecord record in scattends[id])
                        {
                            if (!courses.ContainsKey(record.RefCourseID))
                            {
                                continue;
                            }
                            JHCourseRecord course = courses[record.RefCourseID];
                            //if (course.Name != courseName) continue;

                            HC.JHSCETakeRecord currentSCE = null;


                            string sy = "", ss = "";
                            if (course.SchoolYear.HasValue)
                            {
                                sy = course.SchoolYear.Value.ToString();
                            }
                            if (course.Semester.HasValue)
                            {
                                ss = course.Semester.Value.ToString();
                            }

                            if (SchoolYear != sy || Semester != ss || courseName != course.Name)
                            {
                                continue;
                            }


                            if (SchoolYear == sy && Semester == ss && course.Name == courseName)
                            {
                                if (existSces.ContainsKey(record.ID))
                                {
                                    foreach (HC.JHSCETakeRecord sce in existSces[record.ID])
                                    {
                                        if (!exams.ContainsKey(sce.RefExamID))
                                        {
                                            continue;
                                        }

                                        if (exams[sce.RefExamID].Name == examName)
                                        {
                                            currentSCE = sce;
                                        }
                                    }
                                }
                            }

                            if (currentSCE != null)
                            {
                                bool changed = false;

                                #region 填入資料
                                foreach (string field in e.ImportFields)
                                {
                                    string value = data[field];
                                    switch (field)
                                    {
                                    case "定期分數":
                                        if ("" + currentSCE.Score != value)
                                        {
                                            decimal d;
                                            if (decimal.TryParse(value, out d))
                                            {
                                                currentSCE.Score = d;
                                            }
                                            else
                                            {
                                                currentSCE.Score = null;
                                            }
                                            changed = true;
                                        }
                                        break;

                                    case "平時分數":
                                        if ("" + currentSCE.AssignmentScore != value)
                                        {
                                            decimal d;
                                            if (decimal.TryParse(value, out d))
                                            {
                                                currentSCE.AssignmentScore = d;
                                            }
                                            else
                                            {
                                                currentSCE.AssignmentScore = null;
                                            }
                                            changed = true;
                                        }
                                        break;

                                    //case "努力程度":
                                    //    if ("" + currentSCE.Effort != value)
                                    //    {
                                    //        int i;
                                    //        if (int.TryParse(value, out i))
                                    //            currentSCE.Effort = i;
                                    //        else
                                    //            currentSCE.Effort = null;
                                    //        changed = true;
                                    //    }
                                    //    break;
                                    case "文字描述":
                                        if (currentSCE.Text != value)
                                        {
                                            currentSCE.Text = value;
                                            changed         = true;
                                        }
                                        break;
                                    }
                                }
                                #endregion

                                if (changed)
                                {
                                    updateList.Add(currentSCE);
                                }
                            }
                            else
                            {
                                HC.JHSCETakeRecord newSCE = new HC.JHSCETakeRecord(new JHSCETakeRecord());
                                newSCE.RefStudentID  = id;
                                newSCE.RefSCAttendID = record.ID;
                                newSCE.RefCourseID   = record.RefCourseID;

                                foreach (JHExamRecord exam in exams.Values)
                                {
                                    if (exam.Name == examName)
                                    {
                                        newSCE.RefExamID = exam.ID;
                                    }
                                }

                                #region 填入資料
                                foreach (string field in e.ImportFields)
                                {
                                    string value = data[field];
                                    switch (field)
                                    {
                                    case "定期分數":
                                        if (value != "")
                                        {
                                            decimal d;
                                            if (decimal.TryParse(value, out d))
                                            {
                                                newSCE.Score = d;
                                            }
                                            else
                                            {
                                                newSCE.Score = null;
                                            }
                                        }
                                        else
                                        {
                                            newSCE.Score = null;
                                        }
                                        break;

                                    case "平時分數":
                                        if (value != "")
                                        {
                                            decimal d;
                                            if (decimal.TryParse(value, out d))
                                            {
                                                newSCE.AssignmentScore = d;
                                            }
                                            else
                                            {
                                                newSCE.AssignmentScore = null;
                                            }
                                        }
                                        else
                                        {
                                            newSCE.AssignmentScore = null;
                                        }
                                        break;

                                    case "文字描述":
                                        newSCE.Text = value;
                                        break;
                                    }
                                }
                                #endregion

                                if (newSCE.RefExamID != "")
                                {
                                    insertList.Add(newSCE);
                                }
                            }
                        }
                    }
                }

                try
                {
                    if (updateList.Count > 0)
                    {
                        #region 分批次兩路上傳
                        List <List <HC.JHSCETakeRecord> > updatePackages  = new List <List <HC.JHSCETakeRecord> >();
                        List <List <HC.JHSCETakeRecord> > updatePackages2 = new List <List <HC.JHSCETakeRecord> >();
                        {
                            List <HC.JHSCETakeRecord> package = null;
                            int count = 0;
                            foreach (HC.JHSCETakeRecord var in updateList)
                            {
                                if (count == 0)
                                {
                                    package = new List <HC.JHSCETakeRecord>(30);
                                    count   = 30;
                                    if ((updatePackages.Count & 1) == 0)
                                    {
                                        updatePackages.Add(package);
                                    }
                                    else
                                    {
                                        updatePackages2.Add(package);
                                    }
                                }
                                package.Add(var);
                                count--;
                            }
                        }
                        Thread threadUpdateSemesterSubjectScore = new Thread(new ParameterizedThreadStart(Update));
                        threadUpdateSemesterSubjectScore.IsBackground = true;
                        threadUpdateSemesterSubjectScore.Start(updatePackages);
                        Thread threadUpdateSemesterSubjectScore2 = new Thread(new ParameterizedThreadStart(Update));
                        threadUpdateSemesterSubjectScore2.IsBackground = true;
                        threadUpdateSemesterSubjectScore2.Start(updatePackages2);

                        threadUpdateSemesterSubjectScore.Join();
                        threadUpdateSemesterSubjectScore2.Join();
                        #endregion
                    }
                }
                catch (Exception ex)
                {
                }

                if (insertList.Count > 0)
                {
                    #region 分批次兩路上傳

                    List <List <HC.JHSCETakeRecord> > insertPackages  = new List <List <HC.JHSCETakeRecord> >();
                    List <List <HC.JHSCETakeRecord> > insertPackages2 = new List <List <HC.JHSCETakeRecord> >();
                    {
                        List <HC.JHSCETakeRecord> package = null;
                        int count = 0;
                        foreach (HC.JHSCETakeRecord var in insertList)
                        {
                            if (count == 0)
                            {
                                package = new List <HC.JHSCETakeRecord>(30);
                                count   = 30;
                                if ((insertPackages.Count & 1) == 0)
                                {
                                    insertPackages.Add(package);
                                }
                                else
                                {
                                    insertPackages2.Add(package);
                                }
                            }
                            package.Add(var);
                            count--;
                        }
                    }
                    Thread threadInsertSemesterSubjectScore = new Thread(new ParameterizedThreadStart(Insert));
                    threadInsertSemesterSubjectScore.IsBackground = true;
                    threadInsertSemesterSubjectScore.Start(insertPackages);
                    Thread threadInsertSemesterSubjectScore2 = new Thread(new ParameterizedThreadStart(Insert));
                    threadInsertSemesterSubjectScore2.IsBackground = true;
                    threadInsertSemesterSubjectScore2.Start(insertPackages2);

                    threadInsertSemesterSubjectScore.Join();
                    threadInsertSemesterSubjectScore2.Join();
                    #endregion
                }

                FISCA.LogAgent.ApplicationLog.Log("成績系統.匯入匯出", "匯入評量成績", "總共匯入" + (insertList.Count + updateList.Count) + "筆評量成績。");
                #endregion
            };
        }
Beispiel #16
0
        public override void InitializeImport(SmartSchool.API.PlugIn.Import.ImportWizard wizard)
        {
            //學生資訊 key: studentID
            Dictionary <string, JHStudentRecord> students = new Dictionary <string, JHStudentRecord>();
            //學生修課資訊 studentID -> List:SCAttendRecord
            Dictionary <string, List <JHSCAttendRecord> > scattends = new Dictionary <string, List <JHSCAttendRecord> >();
            //學生修習的課程 courseID -> CourseRecord
            Dictionary <string, JHCourseRecord> courses = new Dictionary <string, JHCourseRecord>();
            //所有課程(依學年度學期分開) schoolYear_semester -> (courseName -> CourseRecord)
            Dictionary <string, Dictionary <string, JHCourseRecord> > allcourses = new Dictionary <string, Dictionary <string, JHSchool.Data.JHCourseRecord> >();
            //學生修習的課程對應的評量設定細節
            Dictionary <string, List <JHAEIncludeRecord> > courseAe = new Dictionary <string, List <JHSchool.Data.JHAEIncludeRecord> >();
            //學生的評量成績記錄
            Dictionary <string, List <JHSCETakeRecord> > existSces = new Dictionary <string, List <JHSchool.Data.JHSCETakeRecord> >();
            //所有試別
            Dictionary <string, JHExamRecord> exams = new Dictionary <string, JHSchool.Data.JHExamRecord>();

            // 取得努力程度對照
            K12.Data.Configuration.ConfigData cd = K12.Data.School.Configuration["努力程度對照表"];
            if (!string.IsNullOrEmpty(cd["xml"]))
            {
                XmlElement element = XmlHelper.LoadXml(cd["xml"]);

                foreach (XmlElement each in element.SelectNodes("Effort"))
                {
                    int     code = int.Parse(each.GetAttribute("Code"));
                    decimal score;
                    if (!decimal.TryParse(each.GetAttribute("Score"), out score))
                    {
                        score = 0;
                    }

                    if (!_EffortDict.ContainsKey(score))
                    {
                        _EffortDict.Add(score, code);
                    }
                }

                _ScoreList.AddRange(_EffortDict.Keys);
                _ScoreList.Reverse();
            }


            wizard.PackageLimit = 3000;
            // 2018.09.05 [ischoolKingdom] Vicky依據 [02-01][03] 匯入評量成績 項目,移除文字描述。
            wizard.ImportableFields.AddRange("學年度", "學期", "課程名稱", "評量名稱", "分數評量", "努力程度");
            wizard.RequiredFields.AddRange("學年度", "學期", "課程名稱", "評量名稱");

            wizard.ValidateStart += delegate(object sender, SmartSchool.API.PlugIn.Import.ValidateStartEventArgs e)
            {
                #region 取得學生資訊
                foreach (JHStudentRecord stu in JHStudent.SelectByIDs(e.List))
                {
                    if (!students.ContainsKey(stu.ID))
                    {
                        students.Add(stu.ID, stu);
                    }
                }
                #endregion

                #region 取得修課記錄
                MultiThreadWorker <string> loader1 = new MultiThreadWorker <string>();
                loader1.MaxThreads     = 3;
                loader1.PackageSize    = 250;
                loader1.PackageWorker += delegate(object sender1, PackageWorkEventArgs <string> e1)
                {
                    foreach (JHSCAttendRecord record in JHSCAttend.SelectByStudentIDAndCourseID(e1.List, new string[] { }))
                    {
                        if (!scattends.ContainsKey(record.RefStudentID))
                        {
                            scattends.Add(record.RefStudentID, new List <JHSchool.Data.JHSCAttendRecord>());
                        }
                        scattends[record.RefStudentID].Add(record);

                        if (!courses.ContainsKey(record.RefCourseID))
                        {
                            courses.Add(record.RefCourseID, null);
                        }
                    }
                };
                loader1.Run(e.List);
                #endregion

                #region 取得課程資訊
                MultiThreadWorker <string> loader2 = new MultiThreadWorker <string>();
                loader2.MaxThreads     = 3;
                loader2.PackageSize    = 250;
                loader2.PackageWorker += delegate(object sender2, PackageWorkEventArgs <string> e2)
                {
                    foreach (JHCourseRecord record in JHCourse.SelectByIDs(new List <string>(e2.List)))
                    {
                        if (courses.ContainsKey(record.ID))
                        {
                            courses[record.ID] = record;
                        }
                    }
                };
                loader2.Run(courses.Keys);

                foreach (JHCourseRecord course in JHCourse.SelectAll())
                {
                    string key = course.SchoolYear + "_" + course.Semester;
                    if (!allcourses.ContainsKey(key))
                    {
                        allcourses.Add(key, new Dictionary <string, JHSchool.Data.JHCourseRecord>());
                    }
                    if (!allcourses[key].ContainsKey(course.Name))
                    {
                        allcourses[key].Add(course.Name, course);
                    }
                }
                #endregion

                #region 取得目前評量成績記錄

                MultiThreadWorker <string> loader3 = new MultiThreadWorker <string>();
                loader3.MaxThreads     = 3;
                loader3.PackageSize    = 250;
                loader3.PackageWorker += delegate(object sender3, PackageWorkEventArgs <string> e3)
                {
                    foreach (JHSCETakeRecord sce in JHSCETake.SelectByStudentIDs(e3.List))
                    {
                        if (!existSces.ContainsKey(sce.RefSCAttendID))
                        {
                            existSces.Add(sce.RefSCAttendID, new List <JHSchool.Data.JHSCETakeRecord>());
                        }
                        existSces[sce.RefSCAttendID].Add(sce);
                    }
                };
                loader3.Run(e.List);
                #endregion

                #region 取得評量設定
                foreach (JHAEIncludeRecord ae in JHAEInclude.SelectAll())
                {
                    if (!courseAe.ContainsKey(ae.RefAssessmentSetupID))
                    {
                        courseAe.Add(ae.RefAssessmentSetupID, new List <JHSchool.Data.JHAEIncludeRecord>());
                    }
                    courseAe[ae.RefAssessmentSetupID].Add(ae);
                }
                #endregion

                #region 取得試別
                foreach (JHExamRecord exam in JHExam.SelectAll())
                {
                    if (!exams.ContainsKey(exam.ID))
                    {
                        exams.Add(exam.ID, exam);
                    }
                }
                #endregion
            };

            wizard.ValidateRow += delegate(object sender, SmartSchool.API.PlugIn.Import.ValidateRowEventArgs e)
            {
                int     i = -1;
                decimal d = -1;

                #region 檢查學生是否存在
                JHStudentRecord student = null;
                if (students.ContainsKey(e.Data.ID))
                {
                    student = students[e.Data.ID];
                }
                else
                {
                    e.ErrorMessage = "壓根就沒有這個學生" + e.Data.ID;
                    return;
                }
                #endregion

                #region 驗證各個欄位格式
                bool inputFormatPass = true;
                foreach (string field in e.SelectFields)
                {
                    string value = e.Data[field];
                    switch (field)
                    {
                    default:
                        break;

                    case "學年度":
                    case "學期":
                        if (value == "" || !int.TryParse(value, out i))
                        {
                            inputFormatPass &= false;
                            e.ErrorFields.Add(field, "必須填入整數");
                        }
                        break;

                    case "課程名稱":
                        if (value == "")
                        {
                            inputFormatPass &= false;
                            e.ErrorFields.Add(field, "必須填入課程名稱");
                        }
                        break;

                    case "評量名稱":
                        if (value == "")
                        {
                            inputFormatPass &= false;
                            e.ErrorFields.Add(field, "必須填入評量名稱");
                        }
                        break;

                    case "分數評量":
                        if (value != "" && !decimal.TryParse(value, out d))
                        {
                            inputFormatPass &= false;
                            e.ErrorFields.Add(field, "必須填入空白或數值");
                        }
                        break;

                    case "努力程度":
                        if (value != "" && !int.TryParse(value, out i))
                        {
                            inputFormatPass &= false;
                            e.ErrorFields.Add(field, "必須填入空白或整數");
                        }
                        else
                        {
                            // 2020/10/15 加入檢查,當分數與努力轉換後努力程度不同,需要顯示警告
                            if (value != "")
                            {
                                int x = ConvertEffort(d);
                                if (x != i)
                                {
                                    e.WarningFields.Add(field, "努力程度與使用分數轉換後不一致");
                                }
                            }
                        }
                        break;

                        // 2018.09.05 [ischoolKingdom] Vicky依據 [02-01][03] 匯入評量成績 項目,移除文字描述。
                        //case "文字描述":
                        //    break;
                    }
                }
                #endregion

                //輸入格式正確才會針對情節做檢驗
                #region 驗證各種情節
                if (inputFormatPass)
                {
                    string errorMessage = "";

                    string sy         = e.Data["學年度"];
                    string se         = e.Data["學期"];
                    string key        = e.Data.ID + "_" + sy + "_" + se;
                    string courseName = e.Data["課程名稱"];
                    string semsKey    = sy + "_" + se;
                    string examName   = e.Data["評量名稱"];

                    //int schoolyear = Framework.Int.ParseInt(sy);
                    //int semester = Framework.Int.ParseInt(se);

                    #region 檢查課程是否存在系統中
                    bool noCourse = false;
                    if (!allcourses.ContainsKey(semsKey))
                    {
                        noCourse      = true;
                        errorMessage += (errorMessage == "" ? "" : "\n") + " 系統中找不到該課程";
                    }
                    else if (!allcourses[semsKey].ContainsKey(courseName))
                    {
                        noCourse      = true;
                        errorMessage += (errorMessage == "" ? "" : "\n") + " 系統中找不到該課程";
                    }
                    else
                    {
                    }
                    #endregion

                    #region 檢查學生是否有修此課程 & 評量是否存在
                    bool attended = false;

                    JHCourseRecord attendCourse = null;
                    if (scattends.ContainsKey(e.Data.ID))
                    {
                        foreach (JHSCAttendRecord record in scattends[e.Data.ID])
                        {
                            bool HasRec = false;

                            // 當有學年度學期課程名稱相同
                            if (courses[record.RefCourseID].Name == courseName && courses[record.RefCourseID].SchoolYear.HasValue && courses[record.RefCourseID].Semester.HasValue)
                            {
                                if ((courses[record.RefCourseID].SchoolYear.Value.ToString().Trim() == sy.Trim()) && courses[record.RefCourseID].Semester.Value.ToString().Trim() == se.Trim())
                                {
                                    HasRec = true;
                                }
                            }
                            if (HasRec && courses.ContainsKey(record.RefCourseID))
                            {
                                attendCourse = courses[record.RefCourseID];
                            }
                        }
                    }
                    else //學生沒修半堂課
                    {
                    }

                    if (attendCourse == null && !noCourse)
                    {
                        if (!e.ErrorFields.ContainsKey("無修課記錄"))
                        {
                            e.ErrorFields.Add("無修課記錄", "學生在此學期並無修習此課程");
                        }
                    }
                    else if (attendCourse != null)
                    {
                        #region 驗證評量是否存在
                        if (string.IsNullOrEmpty(attendCourse.RefAssessmentSetupID))
                        {
                            if (!e.ErrorFields.ContainsKey("無評量設定"))
                            {
                                e.ErrorFields.Add("無評量設定", "課程(" + attendCourse.Name + ")無評量設定");
                            }
                        }
                        else
                        {
                            if (!courseAe.ContainsKey(attendCourse.RefAssessmentSetupID))
                            {
                                if (!e.ErrorFields.ContainsKey("無評量設定"))
                                {
                                    e.ErrorFields.Add("無評量設定", "課程(" + attendCourse.Name + ")無評量設定");
                                }
                            }
                            else
                            {
                                bool examValid = false;
                                foreach (JHAEIncludeRecord ae in courseAe[attendCourse.RefAssessmentSetupID])
                                {
                                    if (!exams.ContainsKey(ae.RefExamID))
                                    {
                                        continue;
                                    }

                                    // 2016/7/26,穎驊新增,由於高雄國中希望可以加入匯出匯入"平時評量的功能",因此必須要在原本的Exam.Name驗證
                                    // 加上 ||examName =="平時評量" ,避免平時評量的欄位被擋掉
                                    if (exams[ae.RefExamID].Name == examName || examName == "平時評量")
                                    {
                                        examValid = true;
                                    }
                                }

                                if (!examValid)
                                {
                                    if (!e.ErrorFields.ContainsKey("評量名稱無效"))
                                    {
                                        e.ErrorFields.Add("評量名稱無效", "評量名稱(" + examName + ")不存在系統中");
                                    }
                                }
                            }
                        }
                        #endregion
                    }
                    #endregion

                    e.ErrorMessage = errorMessage;
                }
                #endregion
            };

            wizard.ImportPackage += delegate(object sender, SmartSchool.API.PlugIn.Import.ImportPackageEventArgs e)
            {
                Dictionary <string, List <RowData> > id_Rows = new Dictionary <string, List <RowData> >();

                #region 分包裝
                foreach (RowData data in e.Items)
                {
                    if (!id_Rows.ContainsKey(data.ID))
                    {
                        id_Rows.Add(data.ID, new List <RowData>());
                    }
                    id_Rows[data.ID].Add(data);
                }
                #endregion

                List <KH.JHSCETakeRecord> insertList = new List <KH.JHSCETakeRecord>();
                List <KH.JHSCETakeRecord> updateList = new List <KH.JHSCETakeRecord>();


                // 檢查是否有努力程度欄位
                bool isHasEffortField = false;

                //交叉比對各學生資料
                #region 交叉比對各學生資料
                foreach (string id in id_Rows.Keys)
                {
                    JHStudentRecord studentRec = students[id];

                    foreach (RowData data in id_Rows[id])
                    {
                        string examName   = data["評量名稱"];
                        string courseName = data["課程名稱"];
                        string SchoolYear = data["學年度"];
                        string Semester   = data["學期"];

                        if (isHasEffortField == false)
                        {
                            if (data.ContainsKey("努力程度"))
                            {
                                // 有努力程度這欄位
                                isHasEffortField = true;
                            }
                        }

                        // 2016/7/26,穎驊新增bool值避免 在有"平時評量"的評量名稱Row 進入算評量成績的判斷式
                        bool isOrdinarilyScore = false;

                        if (!scattends.ContainsKey(id))
                        {
                            continue;
                        }

                        foreach (JHSCAttendRecord record in scattends[id])
                        {
                            if (!courses.ContainsKey(record.RefCourseID))
                            {
                                continue;
                            }
                            JHCourseRecord course = courses[record.RefCourseID];
                            //if (course.Name != courseName) continue;

                            string sy = "", ss = "";
                            if (course.SchoolYear.HasValue)
                            {
                                sy = course.SchoolYear.Value.ToString();
                            }
                            if (course.Semester.HasValue)
                            {
                                ss = course.Semester.Value.ToString();
                            }

                            if (SchoolYear != sy || Semester != ss || course.Name != courseName)
                            {
                                continue;
                            }


                            KH.JHSCETakeRecord currentSCE = null;

                            if (SchoolYear == sy && Semester == ss && course.Name == courseName)
                            {
                                // 2016/7/26,穎驊新增,由於高雄國中希望可以加入匯出匯入"平時評量的功能",在原本的Code努力尋找見縫插針的位子,
                                //因為"平時評量"與一般的"評量成績"處理邏輯要分開
                                //後來決定這邊是最佳位子,邏輯為,當程序在一條一條讀取Excel Row時,讀到欄位"評量名稱"值為 "平時評量"
                                //則進入我們處理平時評量的程序,如果欄位"評量名稱"值非為 "平時評量" 則使用它原本的邏輯處理
                                // 上面的CODE會幫忙進行學年、學期、課程的驗證,確保是同一門課程成績資料,
                                //而 JHSCAttendRecord record內意外發現剛好有 平時評量OrdinarilyScore的欄位
                                //因此只要指定欄位為新的Excel 內的值,最後 使用JHSCAttend.Update(record) 更新即可

                                if (data.ContainsKey("評量名稱"))
                                {
                                    if (data["評量名稱"] == "平時評量")
                                    {
                                        if (data.ContainsKey("分數評量"))
                                        {
                                            if (data["分數評量"] != null && data["分數評量"] != "")
                                            {
                                                decimal d;

                                                // 使用TryParse 的轉換,是因為可能會有Row 的分數評量欄位是空的(EX: 社團成績) ,直接Parse會爆
                                                if (decimal.TryParse(data["分數評量"], out d))
                                                {
                                                    record.OrdinarilyScore = d;
                                                }
                                            }

                                            // 當分數評量是空白
                                            if (data["分數評量"] != null && data["分數評量"].Trim() == "")
                                            {
                                                record.OrdinarilyScore = null;
                                            }
                                        }

                                        if (data.ContainsKey("努力程度"))
                                        {
                                            if (data["努力程度"] != null && data["努力程度"] != "")
                                            {
                                                int i;
                                                if (int.TryParse(data["努力程度"], out i))
                                                {
                                                    record.OrdinarilyEffort = i;
                                                }
                                            }

                                            if (data["努力程度"] != null && data["努力程度"].Trim() == "")
                                            {
                                                record.OrdinarilyEffort = null;
                                            }
                                        }

                                        // 2018.09.05 [ischoolKingdom] Vicky依據 [02-01][03] 匯入評量成績 項目,移除文字描述。
                                        //if (data["文字描述"] != null)
                                        //{
                                        //    record.Text = data["文字描述"].ToString();
                                        //}

                                        // 2020/10/15 宏安與小組會議討論,當沒有努力程度欄位,會使用成績轉換努力程度
                                        if (isHasEffortField == false)
                                        {
                                            if (record.OrdinarilyScore.HasValue)
                                            {
                                                record.OrdinarilyEffort = ConvertEffort(record.OrdinarilyScore.Value);
                                            }
                                            else
                                            {
                                                record.OrdinarilyEffort = null;
                                            }
                                        }


                                        JHSCAttend.Update(record);

                                        isOrdinarilyScore = true;

                                        currentSCE = null;
                                    }

                                    else
                                    {
                                        if (existSces.ContainsKey(record.ID))
                                        {
                                            foreach (KH.JHSCETakeRecord sce in existSces[record.ID].AsKHJHSCETakeRecords())
                                            {
                                                if (!exams.ContainsKey(sce.RefExamID))
                                                {
                                                    continue;
                                                }

                                                if (exams[sce.RefExamID].Name == examName)
                                                {
                                                    currentSCE = sce;
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                            // 2016/7/26,穎驊新增bool值避免 在有"平時評量"的評量名稱Row 進入算評量成績的判斷式
                            if (currentSCE != null && isOrdinarilyScore == false)
                            {
                                //bool changed = false;

                                #region 填入資料
                                foreach (string field in e.ImportFields)
                                {
                                    string value = data[field];
                                    switch (field)
                                    {
                                    case "分數評量":
                                        if ("" + currentSCE.Score != value)
                                        {
                                            decimal d;
                                            if (decimal.TryParse(value, out d))
                                            {
                                                currentSCE.Score = d;
                                            }
                                            else
                                            {
                                                currentSCE.Score = null;
                                            }
                                            //   changed = true;
                                        }
                                        break;

                                    case "努力程度":
                                        if ("" + currentSCE.Effort != value)
                                        {
                                            int i;
                                            if (int.TryParse(value, out i))
                                            {
                                                currentSCE.Effort = i;
                                            }
                                            else
                                            {
                                                currentSCE.Effort = null;
                                            }
                                            //  changed = true;
                                        }
                                        break;
                                        // 2018.09.05 [ischoolKingdom] Vicky依據 [02-01][03] 匯入評量成績 項目,移除文字描述。
                                        //case "文字描述":
                                        //    if (currentSCE.Text != value)
                                        //    {
                                        //        currentSCE.Text = value;
                                        //        changed = true;
                                        //    }
                                        //    break;
                                    }
                                }
                                #endregion

                                //    if (changed)
                                updateList.Add(currentSCE);
                            }

                            // 2016/7/26,穎驊新增bool值避免 在有"平時評量"的評量名稱Row 進入算評量成績的判斷式
                            if (currentSCE == null && isOrdinarilyScore == false)
                            {
                                KH.JHSCETakeRecord newSCE = new KH.JHSCETakeRecord(new JHSCETakeRecord());
                                newSCE.RefStudentID  = id;
                                newSCE.RefSCAttendID = record.ID;
                                newSCE.RefCourseID   = record.RefCourseID;

                                foreach (JHExamRecord exam in exams.Values)
                                {
                                    if (exam.Name == examName)
                                    {
                                        newSCE.RefExamID = exam.ID;
                                        break;
                                    }
                                }

                                #region 填入資料
                                foreach (string field in e.ImportFields)
                                {
                                    string value = data[field];
                                    switch (field)
                                    {
                                    case "分數評量":
                                        if (value != "")
                                        {
                                            decimal d;
                                            if (decimal.TryParse(value, out d))
                                            {
                                                newSCE.Score = d;
                                            }
                                            else
                                            {
                                                newSCE.Score = null;
                                            }
                                        }
                                        else
                                        {
                                            newSCE.Score = null;
                                        }
                                        break;

                                    case "努力程度":
                                        if (value != "")
                                        {
                                            int i;
                                            if (int.TryParse(value, out i))
                                            {
                                                newSCE.Effort = i;
                                            }
                                            else
                                            {
                                                newSCE.Effort = null;
                                            }
                                        }
                                        else
                                        {
                                            newSCE.Effort = null;
                                        }
                                        break;

                                        // 2018.09.05 [ischoolKingdom] Vicky依據 [02-01][03] 匯入評量成績 項目,移除文字描述。
                                        //case "文字描述":
                                        //    newSCE.Text = value;
                                        //    break;
                                    }
                                }
                                #endregion

                                if (newSCE.RefExamID != "")
                                {
                                    insertList.Add(newSCE);
                                }
                            }
                        }
                    }
                }

                try
                {
                    // 解析並填入轉換空白的努力程度
                    // 2020/10/15 透過宏安討論,當沒有努力程度欄位才會使用成績轉換,如果有努力程度欄位不會使用成績轉換。
                    foreach (KH.JHSCETakeRecord rec in updateList)
                    {
                        //// 當努力程度沒有值卻有成績。
                        //if ((rec.Effort.HasValue == false) && rec.Score.HasValue)
                        //{
                        //    rec.Effort = ConvertEffort(rec.Score.Value);
                        //}

                        if (isHasEffortField == false)
                        {
                            if (rec.Score.HasValue)
                            {
                                rec.Effort = ConvertEffort(rec.Score.Value);
                            }
                            else
                            {
                                rec.Effort = null;
                            }
                        }
                    }

                    foreach (KH.JHSCETakeRecord rec in insertList)
                    {
                        //// 當努力程度沒有值卻有成績。
                        //if ((rec.Effort.HasValue == false) && rec.Score.HasValue)
                        //{
                        //    rec.Effort = ConvertEffort(rec.Score.Value);
                        //}

                        if (isHasEffortField == false)
                        {
                            if (rec.Score.HasValue)
                            {
                                rec.Effort = ConvertEffort(rec.Score.Value);
                            }
                            else
                            {
                                rec.Effort = null;
                            }
                        }
                    }



                    if (updateList.Count > 0)
                    {
                        #region 分批次兩路上傳
                        List <List <KH.JHSCETakeRecord> > updatePackages  = new List <List <KH.JHSCETakeRecord> >();
                        List <List <KH.JHSCETakeRecord> > updatePackages2 = new List <List <KH.JHSCETakeRecord> >();
                        {
                            List <KH.JHSCETakeRecord> package = null;
                            int count = 0;
                            foreach (KH.JHSCETakeRecord var in updateList)
                            {
                                if (count == 0)
                                {
                                    package = new List <KH.JHSCETakeRecord>(30);
                                    count   = 30;
                                    if ((updatePackages.Count & 1) == 0)
                                    {
                                        updatePackages.Add(package);
                                    }
                                    else
                                    {
                                        updatePackages2.Add(package);
                                    }
                                }
                                package.Add(var);
                                count--;
                            }
                        }
                        Thread threadUpdateSemesterSubjectScore = new Thread(new ParameterizedThreadStart(Update));
                        threadUpdateSemesterSubjectScore.IsBackground = true;
                        threadUpdateSemesterSubjectScore.Start(updatePackages);
                        Thread threadUpdateSemesterSubjectScore2 = new Thread(new ParameterizedThreadStart(Update));
                        threadUpdateSemesterSubjectScore2.IsBackground = true;
                        threadUpdateSemesterSubjectScore2.Start(updatePackages2);

                        threadUpdateSemesterSubjectScore.Join();
                        threadUpdateSemesterSubjectScore2.Join();
                        #endregion
                    }
                }
                catch (Exception ex)
                {
                }

                if (insertList.Count > 0)
                {
                    #region 分批次兩路上傳

                    List <List <KH.JHSCETakeRecord> > insertPackages  = new List <List <KH.JHSCETakeRecord> >();
                    List <List <KH.JHSCETakeRecord> > insertPackages2 = new List <List <KH.JHSCETakeRecord> >();
                    {
                        List <KH.JHSCETakeRecord> package = null;
                        int count = 0;
                        foreach (KH.JHSCETakeRecord var in insertList)
                        {
                            if (count == 0)
                            {
                                package = new List <KH.JHSCETakeRecord>(30);
                                count   = 30;
                                if ((insertPackages.Count & 1) == 0)
                                {
                                    insertPackages.Add(package);
                                }
                                else
                                {
                                    insertPackages2.Add(package);
                                }
                            }
                            package.Add(var);
                            count--;
                        }
                    }
                    Thread threadInsertSemesterSubjectScore = new Thread(new ParameterizedThreadStart(Insert));
                    threadInsertSemesterSubjectScore.IsBackground = true;
                    threadInsertSemesterSubjectScore.Start(insertPackages);
                    Thread threadInsertSemesterSubjectScore2 = new Thread(new ParameterizedThreadStart(Insert));
                    threadInsertSemesterSubjectScore2.IsBackground = true;
                    threadInsertSemesterSubjectScore2.Start(insertPackages2);

                    threadInsertSemesterSubjectScore.Join();
                    threadInsertSemesterSubjectScore2.Join();
                    #endregion
                }

                FISCA.LogAgent.ApplicationLog.Log("成績系統.匯入匯出", "匯入評量成績", "總共匯入" + (insertList.Count + updateList.Count) + "筆評量成績。");
                #endregion
            };
        }
Beispiel #17
0
        public override void InitializeExport(SmartSchool.API.PlugIn.Export.ExportWizard wizard)
        {
            // 2018.09.05 [ischoolKingdom] Vicky依據 [02-01][03] 匯入評量成績 項目,移除文字描述。
            // 2018.09.05 [ischoolKingdom] Vicky依據 [12-01][01] 多學期成績排名 項目,增加 "領域", "科目", "節數(權重)", "學分" 。
            // 2018.09.07 [ischoolKingdom] Vicky依據新需求調整項目位置。
            wizard.ExportableFields.AddRange("學年度", "學期", "課程名稱", "領域", "科目", "節數(權重)", "學分", "評量名稱", "分數評量", "努力程度");

            wizard.ExportPackage += delegate(object sender, SmartSchool.API.PlugIn.Export.ExportPackageEventArgs e)
            {
                //學生資訊
                List <JHStudentRecord> students = JHStudent.SelectByIDs(e.List);
                //學生修課資訊
                Dictionary <string, List <JHSCAttendRecord> > scattends = new Dictionary <string, List <JHSchool.Data.JHSCAttendRecord> >();
                //學生修習的課程
                Dictionary <string, JHCourseRecord> courses = new Dictionary <string, JHSchool.Data.JHCourseRecord>();
                //評量成績 key: SCAttendID
                Dictionary <string, List <KH.JHSCETakeRecord> > sces = new Dictionary <string, List <KH.JHSCETakeRecord> >();
                //試別資訊
                Dictionary <string, JHExamRecord> exams = new Dictionary <string, JHSchool.Data.JHExamRecord>();

                #region 取得修課記錄
                foreach (JHSCAttendRecord record in JHSCAttend.SelectByStudentIDAndCourseID(e.List, new string[] { }))
                {
                    if (!scattends.ContainsKey(record.RefStudentID))
                    {
                        scattends.Add(record.RefStudentID, new List <JHSchool.Data.JHSCAttendRecord>());
                    }
                    scattends[record.RefStudentID].Add(record);

                    if (!courses.ContainsKey(record.RefCourseID))
                    {
                        courses.Add(record.RefCourseID, null);
                    }
                }
                #endregion

                #region 取得課程資訊
                foreach (JHCourseRecord record in JHCourse.SelectByIDs(new List <string>(courses.Keys)))
                {
                    if (courses.ContainsKey(record.ID))
                    {
                        courses[record.ID] = record;
                    }
                }
                #endregion

                #region 取得試別資訊
                foreach (JHExamRecord exam in JHExam.SelectAll())
                {
                    if (!exams.ContainsKey(exam.ID))
                    {
                        exams.Add(exam.ID, exam);
                    }
                }
                #endregion

                #region 取得評量成績
                foreach (KH.JHSCETakeRecord record in JHSCETake.SelectByStudentAndCourse(new List <string>(scattends.Keys), new List <string>(courses.Keys)).AsKHJHSCETakeRecords())
                {
                    if (!sces.ContainsKey(record.RefSCAttendID))
                    {
                        sces.Add(record.RefSCAttendID, new List <KH.JHSCETakeRecord>());
                    }
                    sces[record.RefSCAttendID].Add(record);
                }
                #endregion



                #region 產生 Row Data
                foreach (JHStudentRecord stu in students)
                {
                    if (!scattends.ContainsKey(stu.ID))
                    {
                        //學生沒有任何修課記錄。
                        continue;
                    }

                    foreach (JHSCAttendRecord record in scattends[stu.ID])
                    {
                        if (!sces.ContainsKey(record.ID))
                        {
                            continue;
                        }

                        sces[record.ID].Sort(delegate(KH.JHSCETakeRecord x, KH.JHSCETakeRecord y)
                        {
                            return(x.RefExamID.CompareTo(y.RefExamID));
                        });

                        foreach (KH.JHSCETakeRecord sce in sces[record.ID])
                        {
                            string examName = sce.RefExamID;
                            if (exams.ContainsKey(sce.RefExamID))
                            {
                                examName = exams[sce.RefExamID].Name;
                            }

                            RowData row = new RowData();
                            row.ID = stu.ID;
                            foreach (string field in e.ExportFields)
                            {
                                if (wizard.ExportableFields.Contains(field))
                                {
                                    switch (field)
                                    {
                                    case "學年度": row.Add(field, "" + courses[record.RefCourseID].SchoolYear); break;

                                    case "學期": row.Add(field, "" + courses[record.RefCourseID].Semester); break;

                                    case "課程名稱": row.Add(field, courses[record.RefCourseID].Name); break;

                                    // 2018.09.05 [ischoolKingdom] Vicky依據 [02-01][03] 匯入評量成績 項目,移除文字描述。
                                    // 2018.09.05 [ischoolKingdom] Vicky依據 [12-01][01] 多學期成績排名 項目,增加 "領域", "科目", "節數(權重)", "學分" 項目資料。
                                    //case "文字描述": row.Add(field, sce.Text); break;
                                    case "領域": row.Add(field, courses[record.RefCourseID].Domain); break;

                                    case "科目": row.Add(field, courses[record.RefCourseID].Subject); break;

                                    case "節數(權重)": row.Add(field, "" + courses[record.RefCourseID].Period); break;

                                    case "學分": row.Add(field, "" + courses[record.RefCourseID].Credit); break;

                                    case "評量名稱": row.Add(field, examName); break;

                                    case "分數評量": row.Add(field, "" + sce.Score); break;

                                    case "努力程度": row.Add(field, "" + sce.Effort); break;
                                    }
                                }
                            }
                            e.Items.Add(row);
                        }

                        //2016/7/26 穎驊新增,因應高雄國中希望能加入匯出匯入"平時成績"的功能,因此在原本的匯出評量成績報表Excel中增加平時成績的項目,
                        // 基本邏輯跟 SCEtake 的定期評量一樣,另外意外發現平時成績、努力程度、Text在 JHSCAttendRecord裏頭就有了,不必在另外下SQL 找UDT 在用XElement 去解析Xml 檔填成績
                        string  examName2 = "平時評量";
                        RowData row2      = new RowData();
                        row2.ID = stu.ID;
                        foreach (string field in e.ExportFields)
                        {
                            if (wizard.ExportableFields.Contains(field))
                            {
                                switch (field)
                                {
                                case "學年度": row2.Add(field, "" + courses[record.RefCourseID].SchoolYear); break;

                                case "學期": row2.Add(field, "" + courses[record.RefCourseID].Semester); break;

                                case "課程名稱": row2.Add(field, courses[record.RefCourseID].Name); break;

                                // 2018.09.05 [ischoolKingdom] Vicky依據 [02-01][03] 匯入評量成績 項目,移除文字描述。
                                // 2018.09.05 [ischoolKingdom] Vicky依據 [12-01][01] 多學期成績排名 項目,增加 "領域", "科目", "節數(權重)", "學分" 項目資料。
                                // case "文字描述": row2.Add(field, record.Text); break;
                                case "領域": row2.Add(field, courses[record.RefCourseID].Domain); break;

                                case "科目": row2.Add(field, courses[record.RefCourseID].Subject); break;

                                case "節數(權重)": row2.Add(field, "" + courses[record.RefCourseID].Period); break;

                                case "學分": row2.Add(field, "" + courses[record.RefCourseID].Credit); break;

                                case "評量名稱": row2.Add(field, examName2); break;

                                case "分數評量": row2.Add(field, "" + record.OrdinarilyScore); break;

                                case "努力程度": row2.Add(field, "" + record.OrdinarilyEffort); break;
                                }
                            }
                        }
                        e.Items.Add(row2);
                    }
                }
                #endregion

                FISCA.LogAgent.ApplicationLog.Log("成績系統.匯入匯出", "匯出評量成績", "總共匯出" + e.Items.Count + "筆評量成績。");
            };
        }
Beispiel #18
0
        private void wizard1_FinishButtonClick(object sender, CancelEventArgs e)
        {
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Title    = "另存新檔";
            saveFileDialog1.FileName = "" + _Title + ".xls";
            saveFileDialog1.Filter   = "Excel (*.xls)|*.xls|所有檔案 (*.*)|*.*";
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                List <string> idlist = new List <string>();
                #region 取得選取課程編號
                List <JHCourseRecord> selectedCourses = null;
                if (IDs != null)
                {
                    selectedCourses = JHCourse.SelectByIDs(IDs);
                }
                else
                {
                    selectedCourses = JHCourse.SelectByIDs(JHSchool.Course.Instance.SelectedKeys);
                }
                foreach (JHCourseRecord course in selectedCourses)
                {
                    if (!idlist.Contains(course.ID))
                    {
                        idlist.Add(course.ID);
                    }
                }
                #endregion

                List <string> courseFieldList = new List <string>();
                List <string> exportFieldList = new List <string>(_SelectedFields);
                #region 取得選取欄位
                for (int index = 0; index < listViewEx1.Items.Count; index++)
                {
                    if (listViewEx1.Items[index] != null && listViewEx1.Items[index].Checked)
                    {
                        courseFieldList.Add(listViewEx1.Items[index].Text.Trim());
                    }
                }
                #endregion

                List <List <string> > splitList = new List <List <string> >();
                //把全部課程以_PackageLimint人分一包
                #region 把全部課程以_PackageLimint人分一包
                int           count   = 0;
                List <string> package = new List <string>();
                foreach (string id in idlist)
                {
                    if (count == 0)
                    {
                        count   = (splitList.Count + 1) * 50;
                        count   = count > _PackageLimint ? _PackageLimint : count;
                        package = new List <string>(_PackageLimint);
                        splitList.Add(package);
                    }
                    package.Add(id);
                    count--;
                }
                #endregion
                //兩條獨立讀取
                Dictionary <List <string>, ManualResetEvent> Loader1 = new Dictionary <List <string>, ManualResetEvent>();
                Dictionary <List <string>, ManualResetEvent> Loader2 = new Dictionary <List <string>, ManualResetEvent>();
                //已讀取資料
                Dictionary <ManualResetEvent, List <RowData> > Filler = new Dictionary <ManualResetEvent, List <RowData> >();
                int i = 0;
                foreach (List <string> p in splitList)
                {
                    ManualResetEvent handleEvent = new ManualResetEvent(false);
                    if ((i & 1) == 0)
                    {
                        Loader1.Add(p, handleEvent);
                    }
                    else
                    {
                        Loader2.Add(p, handleEvent);
                    }
                    Filler.Add(handleEvent, new List <RowData>());
                    i++;
                }

                //在背景執行取得資料
                BackgroundWorker bkwDataLoader = new BackgroundWorker();
                bkwDataLoader.DoWork += new DoWorkEventHandler(bkwDataLoader_DoWork);
                bkwDataLoader.RunWorkerAsync(new object[] { Loader1, Filler, exportFieldList });
                bkwDataLoader         = new BackgroundWorker();
                bkwDataLoader.DoWork += new DoWorkEventHandler(bkwDataLoader_DoWork);
                bkwDataLoader.RunWorkerAsync(new object[] { Loader2, Filler, exportFieldList });
                //在背景計算不及格名單
                BackgroundWorker bkwNotPassComputer = new BackgroundWorker();
                bkwNotPassComputer.WorkerReportsProgress = true;
                bkwNotPassComputer.DoWork             += new DoWorkEventHandler(bkwNotPassComputer_DoWork);
                bkwNotPassComputer.ProgressChanged    += new ProgressChangedEventHandler(bkwNotPassComputer_ProgressChanged);
                bkwNotPassComputer.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bkwNotPassComputer_RunWorkerCompleted);
                bkwNotPassComputer.RunWorkerAsync(new object[] { saveFileDialog1.FileName, courseFieldList, exportFieldList, Filler });
                this.Close();
            }
        }
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            double total = _config.Students.Count;
            double count = 0;

            _worker.ReportProgress(0);

            List <string> student_ids = new List <string>();

            foreach (JHStudentRecord item in _config.Students)
            {
                student_ids.Add(item.ID);
            }

            #region 快取資料
            //獎勵
            Dictionary <string, List <JHMeritRecord> > meritCache = new Dictionary <string, List <JHMeritRecord> >();
            foreach (JHMeritRecord record in JHMerit.SelectByStudentIDs(student_ids))
            {
                if (record.OccurDate < _config.StartDate)
                {
                    continue;
                }
                if (record.OccurDate > _config.EndDate)
                {
                    continue;
                }

                if (!meritCache.ContainsKey(record.RefStudentID))
                {
                    meritCache.Add(record.RefStudentID, new List <JHMeritRecord>());
                }
                meritCache[record.RefStudentID].Add(record);
            }

            //懲戒
            Dictionary <string, List <JHDemeritRecord> > demeritCache = new Dictionary <string, List <JHDemeritRecord> >();
            foreach (JHDemeritRecord record in JHDemerit.SelectByStudentIDs(student_ids))
            {
                if (record.OccurDate < _config.StartDate)
                {
                    continue;
                }
                if (record.OccurDate > _config.EndDate)
                {
                    continue;
                }

                if (!demeritCache.ContainsKey(record.RefStudentID))
                {
                    demeritCache.Add(record.RefStudentID, new List <JHDemeritRecord>());
                }
                demeritCache[record.RefStudentID].Add(record);
            }

            //缺曠
            Dictionary <string, List <JHAttendanceRecord> > attendanceCache = new Dictionary <string, List <JHAttendanceRecord> >();
            foreach (JHAttendanceRecord record in JHAttendance.SelectByStudentIDs(student_ids))
            {
                if (record.OccurDate < _config.StartDate)
                {
                    continue;
                }
                if (record.OccurDate > _config.EndDate)
                {
                    continue;
                }

                if (!attendanceCache.ContainsKey(record.RefStudentID))
                {
                    attendanceCache.Add(record.RefStudentID, new List <JHAttendanceRecord>());
                }
                attendanceCache[record.RefStudentID].Add(record);
            }

            List <string> course_ids = new List <string>();
            foreach (JHSCAttendRecord record in JHSCAttend.SelectByStudentIDs(student_ids))
            {
                if (!course_ids.Contains(record.RefCourseID))
                {
                    course_ids.Add(record.RefCourseID);
                }
            }

            //課程
            JHCourse.RemoveAll();
            int schoolYear = _config.SchoolYear;
            int semester   = _config.Semester;
            Dictionary <string, JHCourseRecord> courseCache = new Dictionary <string, JHCourseRecord>();
            foreach (JHCourseRecord record in JHCourse.SelectByIDs(course_ids))
            {
                if ("" + record.SchoolYear != "" + schoolYear)
                {
                    continue;
                }
                if ("" + record.Semester != "" + semester)
                {
                    continue;
                }

                // 過濾使用者所選課程才放入
                if (Global._selectCourseIDList.Contains(record.ID))
                {
                    if (!courseCache.ContainsKey(record.ID))
                    {
                        courseCache.Add(record.ID, record);
                    }
                }
            }

            //修課記錄
            Dictionary <string, List <string> > scCache = new Dictionary <string, List <string> >();
            //foreach (JHSCAttendRecord sc in JHSCAttend.Select(student_ids, course_ids, new string[] { }, "" + _config.SchoolYear, "" + _config.Semester))
            foreach (JHSCAttendRecord sc in JHSCAttend.SelectByStudentIDAndCourseID(student_ids, course_ids))
            {
                if (!courseCache.ContainsKey(sc.RefCourseID))
                {
                    continue;
                }

                if (!scCache.ContainsKey(sc.RefStudentID))
                {
                    scCache.Add(sc.RefStudentID, new List <string>());
                }

                // 過濾使用者不選
                if (Global._selectCourseIDList.Contains(sc.RefCourseID))
                {
                    scCache[sc.RefStudentID].Add(sc.RefCourseID);
                }
            }

            //評量成績
            Dictionary <string, List <HC.JHSCETakeRecord> > sceScoreCache = new Dictionary <string, List <HC.JHSCETakeRecord> >();
            foreach (JHSCETakeRecord record in JHSCETake.SelectByStudentAndCourse(student_ids, course_ids))
            {
                if (record.RefExamID != _config.Exam.ID)
                {
                    continue;
                }

                if (!sceScoreCache.ContainsKey(record.RefStudentID))
                {
                    sceScoreCache.Add(record.RefStudentID, new List <HC.JHSCETakeRecord>());
                }
                sceScoreCache[record.RefStudentID].Add(new HC.JHSCETakeRecord(record));
            }

            //學期歷程
            Dictionary <string, K12.Data.SemesterHistoryItem> historyCache = new Dictionary <string, K12.Data.SemesterHistoryItem>();
            foreach (JHSemesterHistoryRecord record in JHSemesterHistory.SelectByStudentIDs(student_ids))
            {
                foreach (K12.Data.SemesterHistoryItem item in record.SemesterHistoryItems)
                {
                    if ("" + item.SchoolYear != K12.Data.School.DefaultSchoolYear)
                    {
                        continue;
                    }
                    if ("" + item.Semester != K12.Data.School.DefaultSemester)
                    {
                        continue;
                    }

                    if (!historyCache.ContainsKey(record.RefStudentID))
                    {
                        historyCache.Add(record.RefStudentID, item);
                    }
                }
            }

            //取得所有教師,為了Cache下來
            JHTeacher.SelectAll();
            #endregion

            #region 建立節次對照及假別列表
            Dictionary <string, string> periodMapping = new Dictionary <string, string>();
            foreach (JHPeriodMappingInfo info in JHPeriodMapping.SelectAll())
            {
                if (!periodMapping.ContainsKey(info.Name))
                {
                    periodMapping.Add(info.Name, info.Type);
                }
            }

            List <string> absenceList = new List <string>();
            foreach (JHAbsenceMappingInfo info in JHAbsenceMapping.SelectAll())
            {
                absenceList.Add(info.Name);
            }
            #endregion

            #region 判斷要列印的領域科目
            Dictionary <string, bool>           domains  = new Dictionary <string, bool>();
            Dictionary <string, List <string> > subjects = new Dictionary <string, List <string> >();

            List <JHCourseRecord> courseList = new List <JHCourseRecord>(courseCache.Values);
            courseList.Sort(delegate(JHCourseRecord x, JHCourseRecord y)
            {
                return(JHSchool.Evaluation.Subject.CompareSubjectOrdinal(x.Subject, y.Subject));
                //List<string> list = new List<string>(new string[] { "國語文", "國文", "英文", "英語", "數學", "歷史", "地理", "公民", "理化", "生物" });
                //int ix = list.IndexOf(x.Subject);
                //int iy = list.IndexOf(y.Subject);

                //if (ix >= 0 && iy >= 0)
                //    return ix.CompareTo(iy);
                //else if (ix >= 0)
                //    return -1;
                //else if (iy >= 0)
                //    return 1;
                //else
                //    return x.Subject.CompareTo(y.Subject);
            });

            string domainSubjectSetup = _rc.GetString("領域科目設定", "Domain");
            _config.DomainSubjectSetup = domainSubjectSetup;

            if (domainSubjectSetup == "Domain")
            {
                foreach (var domain in JHSchool.Evaluation.Subject.Domains)
                {
                    domains.Add(domain, true);
                }
                //domains.Add("彈性課程", false);

                if (domains.ContainsKey("語文"))
                {
                    domains["語文"] = false;
                }
                if (!domains.ContainsKey(""))
                {
                    domains.Add("", false);
                }
            }
            else if (domainSubjectSetup == "Subject")
            {
                foreach (var domain in JHSchool.Evaluation.Subject.Domains)
                {
                    domains.Add(domain, false);
                }
                //domains.Add("彈性課程", false);
                if (!domains.ContainsKey(""))
                {
                    domains.Add("", false);
                }
            }
            else
            {
                throw new Exception("請重新儲存一次列印設定");
            }

            foreach (var domain in JHSchool.Evaluation.Subject.Domains)
            {
                subjects.Add(domain, new List <string>());
            }
            //subjects.Add("彈性課程", new List<string>());
            subjects.Add("", new List <string>());

            //foreach (JHCourseRecord course in courseList)
            //{
            //    if (!domains.ContainsKey(course.Domain)) continue;

            //    if (!subjects.ContainsKey(course.Domain))
            //        subjects.Add(course.Domain, new List<string>());

            //    //很怪
            //    if (domains[course.Domain] == true) continue;

            //    if (!subjects[course.Domain].Contains(course.Subject))
            //        subjects[course.Domain].Add(course.Subject);
            //}

            _config.SetPrintDomains(domains);
            _config.SetPrintSubjects(subjects);
            #endregion

            DocumentBuilder templateBuilder = new DocumentBuilder(_template);

            #region 判斷是否列印文字評語

            templateBuilder.MoveToMergeField("文字評語");
            if (_rc.GetBoolean("列印文字評語", true))
            {
                templateBuilder.Write("文字評語");
            }
            else
            {
                Cell   first = templateBuilder.CurrentParagraph.ParentNode as Cell;
                double width = first.CellFormat.Width;
                Table  table = first.ParentRow.ParentTable;
                foreach (Row row in table.Rows)
                {
                    if (row.ChildNodes.Count == 1)
                    {
                        break;
                    }
                    row.RemoveChild(row.LastCell);
                    int lastIndex = row.ChildNodes.Count - 1;
                    row.Cells[lastIndex--].CellFormat.Width += (width / 3f);
                    row.Cells[lastIndex--].CellFormat.Width += (width / 3f);
                    row.Cells[lastIndex].CellFormat.Width   += (width / 3f);
                }
            }
            #endregion

            #region 依節權數設定,在畫面上顯示
            string pcDisplay = string.Empty;
            bool   p         = _rc.GetBoolean("列印節數", false);
            bool   c         = _rc.GetBoolean("列印權數", false);
            if (p && c)
            {
                pcDisplay = "節/權數";
            }
            else if (p)
            {
                pcDisplay = "節數";
            }
            else if (c)
            {
                pcDisplay = "權數";
            }

            while (templateBuilder.MoveToMergeField("節權數"))
            {
                templateBuilder.Write(pcDisplay);
            }
            #endregion

            #region 如果使用者不印定期評量,從畫面上將欄位拿掉
            templateBuilder.MoveToMergeField("定期評量");

            if (_rc.GetBoolean("列印定期評量", false) == false)
            {
                Cell   assignmentCell = templateBuilder.CurrentParagraph.ParentNode as Cell;
                double width          = assignmentCell.CellFormat.Width;
                bool   hasText        = false;
                if (assignmentCell.NextSibling != null)
                {
                    hasText = true;
                }
                Table scoreTable = assignmentCell.ParentRow.ParentTable;
                foreach (Row eachRow in scoreTable.Rows)
                {
                    if (eachRow.Cells.Count == 1)
                    {
                        break;
                    }

                    int lastIndex = 0;
                    if (hasText)
                    {
                        eachRow.RemoveChild(eachRow.Cells[eachRow.Count - 3]);
                        lastIndex = eachRow.ChildNodes.Count - 3;
                    }
                    else
                    {
                        eachRow.RemoveChild(eachRow.LastCell);
                        lastIndex = eachRow.ChildNodes.Count - 1;
                    }
                    eachRow.Cells[lastIndex--].CellFormat.Width += (width / 2f);
                    eachRow.Cells[lastIndex].CellFormat.Width   += (width / 2f);
                }
            }
            else
            {
                templateBuilder.Write("定期評量");
            }
            #endregion


            #region 如果使用者不印平時評量,從畫面上將欄位拿掉
            templateBuilder.MoveToMergeField("平時評量");

            if (_rc.GetBoolean("列印平時評量", false) == false)
            {
                Cell   assignmentCell = templateBuilder.CurrentParagraph.ParentNode as Cell;
                double width          = assignmentCell.CellFormat.Width;
                bool   hasText        = false;
                if (assignmentCell.NextSibling != null)
                {
                    hasText = true;
                }
                Table scoreTable = assignmentCell.ParentRow.ParentTable;
                foreach (Row eachRow in scoreTable.Rows)
                {
                    if (eachRow.Cells.Count == 1)
                    {
                        break;
                    }

                    int lastIndex = 0;
                    if (hasText)
                    {
                        eachRow.RemoveChild(eachRow.Cells[eachRow.Count - 2]);
                        lastIndex = eachRow.ChildNodes.Count - 2;
                    }
                    else
                    {
                        eachRow.RemoveChild(eachRow.LastCell);
                        lastIndex = eachRow.ChildNodes.Count - 1;
                    }
                    eachRow.Cells[lastIndex--].CellFormat.Width += (width / 2f);
                    eachRow.Cells[lastIndex].CellFormat.Width   += (width / 2f);
                }
            }
            else
            {
                templateBuilder.Write("平時評量");
            }
            #endregion

            #region 如果使用者不印定期學習評量總成績,從畫面上將欄位拿掉
            templateBuilder.MoveToMergeField("定期學習評量總成績");

            if (_rc.GetBoolean("列印定期學習評量總成績", false) == false)
            {
                Cell   assignmentCell = templateBuilder.CurrentParagraph.ParentNode as Cell;
                double width          = assignmentCell.CellFormat.Width;
                bool   hasText        = false;
                if (assignmentCell.NextSibling != null)
                {
                    hasText = true;
                }
                Table scoreTable = assignmentCell.ParentRow.ParentTable;
                foreach (Row eachRow in scoreTable.Rows)
                {
                    if (eachRow.Cells.Count == 1)
                    {
                        break;
                    }

                    int lastIndex = 0;
                    if (hasText)
                    {
                        eachRow.RemoveChild(eachRow.Cells[eachRow.Count - 2]);
                        lastIndex = eachRow.ChildNodes.Count - 2;
                    }
                    else
                    {
                        eachRow.RemoveChild(eachRow.LastCell);
                        lastIndex = eachRow.ChildNodes.Count - 1;
                    }
                    eachRow.Cells[lastIndex--].CellFormat.Width += (width / 2f);
                    eachRow.Cells[lastIndex].CellFormat.Width   += (width / 2f);
                }
            }
            else
            {
                templateBuilder.Write("定期學習評量總成績");
            }
            #endregion


            #region 取得學生成績計算規則
            ScoreCalculator defaultScoreCalculator = new ScoreCalculator(null);

            //key: ScoreCalcRuleID
            Dictionary <string, ScoreCalculator> calcCache = new Dictionary <string, ScoreCalculator>();
            //key: StudentID, val: ScoreCalcRuleID
            Dictionary <string, string> calcIDCache = new Dictionary <string, string>();
            List <string> scoreCalcRuleIDList       = new List <string>();
            foreach (JHStudentRecord student in _config.Students)
            {
                //calcCache.Add(student.ID, new ScoreCalculator(student.ScoreCalcRule));
                string calcID = string.Empty;
                if (!string.IsNullOrEmpty(student.OverrideScoreCalcRuleID))
                {
                    calcID = student.OverrideScoreCalcRuleID;
                }
                else if (student.Class != null && !string.IsNullOrEmpty(student.Class.RefScoreCalcRuleID))
                {
                    calcID = student.Class.RefScoreCalcRuleID;
                }

                if (!string.IsNullOrEmpty(calcID))
                {
                    calcIDCache.Add(student.ID, calcID);
                }
            }
            foreach (JHScoreCalcRuleRecord record in JHScoreCalcRule.SelectByIDs(calcIDCache.Values))
            {
                if (!calcCache.ContainsKey(record.ID))
                {
                    calcCache.Add(record.ID, new ScoreCalculator(record));
                }
            }
            //MsgBox.Show("" + (Environment.TickCount - t));
            #endregion

            #region 檢查學生成績是否超出可列印行數

            foreach (JHStudentRecord student in _config.Students)
            {
                if (scCache.ContainsKey(student.ID))
                {
                    int checkCount = 0;
                    if (_config.DomainSubjectSetup == "Subject")
                    {
                        checkCount = scCache[student.ID].Count;
                    }
                    else
                    {
                        List <string> checkDomains = new List <string>();
                        foreach (string courseID in scCache[student.ID])
                        {
                            JHCourseRecord course = courseCache[courseID];
                            if (string.IsNullOrEmpty(course.Domain))
                            {
                                checkCount++;
                            }
                            else if (!checkDomains.Contains(course.Domain))
                            {
                                checkDomains.Add(course.Domain);
                            }
                        }
                        checkCount += checkDomains.Count;
                    }

                    if (checkCount > _rowCount)
                    {
                        _overStudentList.Add(student.ID);
                    }
                }
            }

            //有學生資料超出範圍
            if (_overStudentList.Count > 0)
            {
                //K12.Presentation.NLDPanels.Student.AddToTemp(overStudentList);
                System.Windows.Forms.DialogResult result = MsgBox.Show("有 " + _overStudentList.Count + " 位學生評量成績資料超出範本可列印範圍,已將學生加入待處理。\n是否繼續列印?", System.Windows.Forms.MessageBoxButtons.YesNo);
                if (result == System.Windows.Forms.DialogResult.No)
                {
                    e.Result = "Cancel";
                }
            }
            #endregion

            // 取得學生課程ID對照
            Dictionary <string, List <string> > studCourseID = new Dictionary <string, List <string> >();
            List <string> sid = (from stud in _config.Students select stud.ID).ToList();
            foreach (JHSCAttendRecord attend in JHSCAttend.SelectByStudentIDs(sid))
            {
                if (attend.Course.SchoolYear.HasValue && attend.Course.Semester.HasValue)
                {
                    if (attend.Course.SchoolYear == _config.SchoolYear && attend.Course.Semester == _config.Semester)
                    {
                        if (studCourseID.ContainsKey(attend.RefStudentID))
                        {
                            studCourseID[attend.RefStudentID].Add(attend.RefCourseID);
                        }
                        else
                        {
                            List <string> coid = new List <string>();
                            coid.Add(attend.RefCourseID);
                            studCourseID.Add(attend.RefStudentID, coid);
                        }
                    }
                }
            }

            // 取得學期歷程
            Config._StudSemesterHistoryItemDict.Clear();

            List <JHSemesterHistoryRecord> semHisRec = JHSemesterHistory.SelectByStudents(_config.Students);
            // 當畫面學期歷程內的學年度學期與畫面上設定相同,加入
            foreach (JHSemesterHistoryRecord rec in semHisRec)
            {
                foreach (K12.Data.SemesterHistoryItem shi in rec.SemesterHistoryItems)
                {
                    if (shi.SchoolYear == _config.SchoolYear && shi.Semester == _config.Semester)
                    {
                        if (!Config._StudSemesterHistoryItemDict.ContainsKey(shi.RefStudentID))
                        {
                            Config._StudSemesterHistoryItemDict.Add(shi.RefStudentID, shi);
                        }
                    }
                }
            }

            // 取得評量比例
            Utility.ScorePercentageHSDict.Clear();
            Utility.ScorePercentageHSDict = Utility.GetScorePercentageHS();


            #region 產生
            foreach (JHStudentRecord student in _config.Students)
            {
                count++;
                if (_overStudentList.Contains(student.ID))
                {
                    continue;
                }
                Document        each    = (Document)_template.Clone(true);
                DocumentBuilder builder = new DocumentBuilder(each);

                #region 學生基本資料
                StudentBasicInfo basicInfo = new StudentBasicInfo(builder);
                basicInfo.SetStudent(student);
                #endregion

                #region 班導師
                builder.MoveToMergeField("班導師");
                if (historyCache.ContainsKey(student.ID))
                {
                    builder.Write(historyCache[student.ID].Teacher);
                }
                else
                {
                    builder.Write(string.Empty);
                }
                #endregion

                #region 成績
                List <HC.JHSCETakeRecord> sceScoreList = null;
                if (sceScoreCache.ContainsKey(student.ID))
                {
                    sceScoreList = sceScoreCache[student.ID];
                }
                else
                {
                    sceScoreList = new List <HC.JHSCETakeRecord>();
                }
                ScoreCalculator studentCalculator = defaultScoreCalculator;
                if (calcIDCache.ContainsKey(student.ID) && calcCache.ContainsKey(calcIDCache[student.ID]))
                {
                    studentCalculator = calcCache[calcIDCache[student.ID]];
                }

                // 過濾 courseCache studid
                Dictionary <string, JHCourseRecord> courseCache1 = new Dictionary <string, JHCourseRecord>();

                foreach (KeyValuePair <string, JHCourseRecord> val in courseCache)
                {
                    // 從學生修課來對應到課程
                    if (studCourseID.ContainsKey(student.ID))
                    {
                        if (studCourseID[student.ID].Contains(val.Value.ID))
                        {
                            courseCache1.Add(val.Key, val.Value);
                        }
                    }
                }

                StudentExamScore examScore = new StudentExamScore(builder, _config, courseCache1);
                examScore.PrintPeriod     = _rc.GetBoolean("列印節數", false);
                examScore.PrintCredit     = _rc.GetBoolean("列印權數", false);
                examScore.PrintText       = _rc.GetBoolean("列印文字評語", true);
                examScore.PrintScore      = _rc.GetBoolean("列印定期評量", true);
                examScore.PrintAssScore   = _rc.GetBoolean("列印平時評量", true);
                examScore.PrintTotalScore = _rc.GetBoolean("列印定期學習評量總成績", true);

                examScore.SetScoreCalculator(studentCalculator);
                if (scCache.ContainsKey(student.ID))
                {
                    examScore.SetSubjects(scCache[student.ID]);
                }
                examScore.SetData(sceScoreList);

                #endregion

                if (_config.DomainSubjectSetup == "Subject")
                {
                    // 科目定期評量加權平均
                    if (builder.MoveToMergeField("加權平均") || builder.MoveToMergeField("定期評量加權平均"))
                    {
                        if (examScore.SubjAvgScore > 0)
                        {
                            builder.Write(examScore.SubjAvgScore.ToString());
                        }
                        else
                        {
                            builder.Write("");
                        }
                    }

                    // 科目平時評量加權平均
                    if (builder.MoveToMergeField("平時評量加權平均"))
                    {
                        if (examScore.SubjAvgAssignmentScore > 0)
                        {
                            builder.Write(examScore.SubjAvgAssignmentScore.ToString());
                        }
                        else
                        {
                            builder.Write("");
                        }
                    }

                    // 科目學習總分加權平均
                    if (builder.MoveToMergeField("定期學習評量總成績加權平均"))
                    {
                        if (examScore.SubjAvgFinalScore > 0)
                        {
                            builder.Write(examScore.SubjAvgFinalScore.ToString());
                        }
                        else
                        {
                            builder.Write("");
                        }
                    }
                }
                else
                {
                    // 領域定期評量加權平均
                    if (builder.MoveToMergeField("加權平均") || builder.MoveToMergeField("定期評量加權平均"))
                    {
                        if (examScore.DomainAvgScore > 0)
                        {
                            builder.Write(examScore.DomainAvgScore.ToString());
                        }
                        else
                        {
                            builder.Write("");
                        }
                    }

                    // 領域平時評量加權平均
                    if (builder.MoveToMergeField("平時評量加權平均"))
                    {
                        if (examScore.DomainAvgAssignmentScore > 0)
                        {
                            builder.Write(examScore.DomainAvgAssignmentScore.ToString());
                        }
                        else
                        {
                            builder.Write("");
                        }
                    }

                    // 領域學習總分加權平均
                    if (builder.MoveToMergeField("定期學習評量總成績加權平均"))
                    {
                        if (examScore.DomainAvgFinalScore > 0)
                        {
                            builder.Write(examScore.DomainAvgFinalScore.ToString());
                        }
                        else
                        {
                            builder.Write("");
                        }
                    }
                }

                #region 日常表現
                List <JHMeritRecord>      meritList      = null;
                List <JHDemeritRecord>    demeritList    = null;
                List <JHAttendanceRecord> attendanceList = null;

                meritList      = (meritCache.ContainsKey(student.ID)) ? meritCache[student.ID] : new List <JHMeritRecord>();
                demeritList    = (demeritCache.ContainsKey(student.ID)) ? demeritCache[student.ID] : new List <JHDemeritRecord>();
                attendanceList = (attendanceCache.ContainsKey(student.ID)) ? attendanceCache[student.ID] : new List <JHAttendanceRecord>();

                StudentMoralScore moral = new StudentMoralScore(builder, _config, periodMapping, absenceList);
                moral.SetData(meritList, demeritList, attendanceList);
                #endregion

                foreach (Section sec in each.Sections)
                {
                    _doc.Sections.Add(_doc.ImportNode(sec, true));
                }

                //回報進度
                _worker.ReportProgress((int)(count * 100.0 / total));
            }

            List <string> globalFieldName  = new List <string>();
            List <object> globalFieldValue = new List <object>();

            globalFieldName.Add("學校名稱");
            globalFieldValue.Add(K12.Data.School.ChineseName);

            globalFieldName.Add("學年度");
            globalFieldValue.Add(_config.SchoolYear);

            globalFieldName.Add("學期");
            globalFieldValue.Add(_config.Semester);

            globalFieldName.Add("評量名稱");
            globalFieldValue.Add(_config.Exam.Name);

            globalFieldName.Add("統計期間");
            globalFieldValue.Add(_config.StartDate.ToShortDateString() + " ~ " + _config.EndDate.ToShortDateString());

            globalFieldName.Add("列印日期");
            globalFieldValue.Add(DateConvert.CDate(DateTime.Now.ToString("yyyy/MM/dd")) + " " + DateTime.Now.ToString("HH:mm:ss"));

            string chancellor, eduDirector, stuDirector;
            chancellor = eduDirector = stuDirector = string.Empty;

            XmlElement schoolInfo         = K12.Data.School.Configuration["學校資訊"].PreviousData;
            XmlElement chancellorElement  = (XmlElement)schoolInfo.SelectSingleNode("ChancellorChineseName");
            XmlElement eduDirectorElement = (XmlElement)schoolInfo.SelectSingleNode("EduDirectorName");

            if (chancellorElement != null)
            {
                chancellor = chancellorElement.InnerText;
            }
            if (eduDirectorElement != null)
            {
                eduDirector = eduDirectorElement.InnerText;
            }

            globalFieldName.Add("教務主任");
            globalFieldValue.Add(eduDirector);

            globalFieldName.Add("校長");
            globalFieldValue.Add(chancellor);

            globalFieldName.Add("成績校正日期");
            globalFieldValue.Add(_rc.GetString("成績校正日期", string.Empty));

            if (_config.Students.Count > _overStudentList.Count)
            {
                _doc.MailMerge.Execute(globalFieldName.ToArray(), globalFieldValue.ToArray());
            }

            #endregion
        }
Beispiel #20
0
        public ImportStartupForm()
        {
            InitializeComponent();
            InitializeSemesters();

            _effortMapper = new EffortMapper();

            // 載入預設儲存值
            LoadConfigData();

            _worker = new BackgroundWorker();
            _worker.WorkerReportsProgress = true;
            _worker.ProgressChanged      += delegate(object sender, ProgressChangedEventArgs e)
            {
                lblMessage.Text = "" + e.UserState;
            };
            _worker.DoWork += delegate(object sender, DoWorkEventArgs e)
            {
                #region Worker DoWork
                _worker.ReportProgress(0, "檢查讀卡文字格式…");

                #region 檢查文字檔
                ValidateTextFiles  vtf      = new ValidateTextFiles(intStudentNumberLenght.Value);
                ValidateTextResult vtResult = vtf.CheckFormat(_files);
                if (vtResult.Error)
                {
                    e.Result = vtResult;
                    return;
                }
                #endregion

                //文字檔轉 RawData
                RawDataCollection rdCollection = new RawDataCollection();
                rdCollection.ConvertFromFiles(_files);

                //RawData 轉 DataRecord
                DataRecordCollection drCollection = new DataRecordCollection();
                drCollection.ConvertFromRawData(rdCollection);

                _rawDataValidator    = new DataValidator <RawData>();
                _dataRecordValidator = new DataValidator <DataRecord>();

                #region 取得驗證需要的資料
                JHCourse.RemoveAll();
                _worker.ReportProgress(0, "取得學生資料…");
                List <JHStudentRecord> studentList = GetInSchoolStudents();

                List <string> s_ids = new List <string>();
                Dictionary <string, List <string> > studentNumberToStudentIDs = new Dictionary <string, List <string> >();
                foreach (JHStudentRecord student in studentList)
                {
                    string sn = SCValidatorCreator.GetStudentNumberFormat(student.StudentNumber);
                    if (!studentNumberToStudentIDs.ContainsKey(sn))
                    {
                        studentNumberToStudentIDs.Add(sn, new List <string>());
                    }
                    studentNumberToStudentIDs[sn].Add(student.ID);
                }
                foreach (var dr in drCollection)
                {
                    if (studentNumberToStudentIDs.ContainsKey(dr.StudentNumber))
                    {
                        s_ids.AddRange(studentNumberToStudentIDs[dr.StudentNumber]);
                    }
                }

                studentList.Clear();

                _worker.ReportProgress(0, "取得課程資料…");
                List <JHCourseRecord>    courseList = JHCourse.SelectBySchoolYearAndSemester(SchoolYear, Semester);
                List <JHAEIncludeRecord> aeList     = JHAEInclude.SelectAll();

                //List<JHSCAttendRecord> scaList = JHSCAttend.SelectAll();
                var c_ids = from course in courseList select course.ID;
                _worker.ReportProgress(0, "取得修課資料…");
                //List<JHSCAttendRecord> scaList2 = JHSCAttend.SelectByStudentIDAndCourseID(s_ids, c_ids.ToList<string>());
                List <JHSCAttendRecord> scaList = new List <JHSCAttendRecord>();
                FunctionSpliter <string, JHSCAttendRecord> spliter = new FunctionSpliter <string, JHSCAttendRecord>(300, 3);
                spliter.Function = delegate(List <string> part)
                {
                    return(JHSCAttend.Select(part, c_ids.ToList <string>(), null, SchoolYear.ToString(), Semester.ToString()));
                };
                scaList = spliter.Execute(s_ids);

                _worker.ReportProgress(0, "取得試別資料…");
                List <JHExamRecord> examList = JHExam.SelectAll();
                #endregion

                #region 註冊驗證
                _worker.ReportProgress(0, "載入驗證規則…");
                _rawDataValidator.Register(new SubjectCodeValidator());
                _rawDataValidator.Register(new ClassCodeValidator());
                _rawDataValidator.Register(new ExamCodeValidator());

                SCValidatorCreator scCreator = new SCValidatorCreator(JHStudent.SelectByIDs(s_ids), courseList, scaList);
                _dataRecordValidator.Register(scCreator.CreateStudentValidator());
                _dataRecordValidator.Register(new ExamValidator(examList));
                _dataRecordValidator.Register(scCreator.CreateSCAttendValidator());
                _dataRecordValidator.Register(new CourseExamValidator(scCreator.StudentCourseInfo, aeList, examList));
                #endregion

                #region 進行驗證
                _worker.ReportProgress(0, "進行驗證中…");
                List <string> msgList = new List <string>();

                foreach (RawData rawData in rdCollection)
                {
                    List <string> msgs = _rawDataValidator.Validate(rawData);
                    msgList.AddRange(msgs);
                }
                if (msgList.Count > 0)
                {
                    e.Result = msgList;
                    return;
                }

                foreach (DataRecord dataRecord in drCollection)
                {
                    List <string> msgs = _dataRecordValidator.Validate(dataRecord);
                    msgList.AddRange(msgs);
                }
                if (msgList.Count > 0)
                {
                    e.Result = msgList;
                    return;
                }
                #endregion

                #region 取得學生的評量成績
                _deleteScoreList.Clear();
                _addScoreList.Clear();

                //var student_ids = from student in scCreator.StudentNumberDictionary.Values select student.ID;
                //List<string> course_ids = scCreator.AttendCourseIDs;

                var scaIDs = from sca in scaList select sca.ID;

                Dictionary <string, JHSCETakeRecord>      sceList    = new Dictionary <string, JHSCETakeRecord>();
                FunctionSpliter <string, JHSCETakeRecord> spliterSCE = new FunctionSpliter <string, JHSCETakeRecord>(300, 3);
                spliterSCE.Function = delegate(List <string> part)
                {
                    return(JHSCETake.Select(null, null, null, null, part));
                };
                foreach (JHSCETakeRecord sce in spliterSCE.Execute(scaIDs.ToList()))
                {
                    string key = GetCombineKey(sce.RefStudentID, sce.RefCourseID, sce.RefExamID);
                    if (!sceList.ContainsKey(key))
                    {
                        sceList.Add(key, sce);
                    }
                }

                Dictionary <string, JHExamRecord>     examTable = new Dictionary <string, JHExamRecord>();
                Dictionary <string, JHSCAttendRecord> scaTable  = new Dictionary <string, JHSCAttendRecord>();

                foreach (JHExamRecord exam in examList)
                {
                    if (!examTable.ContainsKey(exam.Name))
                    {
                        examTable.Add(exam.Name, exam);
                    }
                }

                foreach (JHSCAttendRecord sca in scaList)
                {
                    string key = GetCombineKey(sca.RefStudentID, sca.RefCourseID);
                    if (!scaTable.ContainsKey(key))
                    {
                        scaTable.Add(key, sca);
                    }
                }

                foreach (DataRecord dr in drCollection)
                {
                    JHStudentRecord       student = student = scCreator.StudentNumberDictionary[dr.StudentNumber];
                    JHExamRecord          exam    = examTable[dr.Exam];
                    List <JHCourseRecord> courses = new List <JHCourseRecord>();
                    foreach (JHCourseRecord course in scCreator.StudentCourseInfo.GetCourses(dr.StudentNumber))
                    {
                        if (dr.Subjects.Contains(course.Subject))
                        {
                            courses.Add(course);
                        }
                    }

                    foreach (JHCourseRecord course in courses)
                    {
                        string key = GetCombineKey(student.ID, course.ID, exam.ID);

                        if (sceList.ContainsKey(key))
                        {
                            _deleteScoreList.Add(sceList[key]);
                        }

                        JHSCETakeRecord    jh     = new JHSCETakeRecord();
                        KH.JHSCETakeRecord sceNew = new KH.JHSCETakeRecord(jh);
                        sceNew.RefCourseID   = course.ID;
                        sceNew.RefExamID     = exam.ID;
                        sceNew.RefSCAttendID = scaTable[GetCombineKey(student.ID, course.ID)].ID;
                        sceNew.RefStudentID  = student.ID;
                        sceNew.Score         = dr.Score;
                        sceNew.Effort        = _effortMapper.GetCodeByScore(dr.Score);
                        _addScoreList.Add(sceNew.AsJHSCETakeRecord());
                    }
                }
                #endregion

                e.Result = null;
                #endregion
            };
            _worker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
            {
                #region Worker Completed
                if (e.Error == null && e.Result == null)
                {
                    if (!_upload.IsBusy)
                    {
                        //如果學生身上已有成績,則提醒使用者
                        if (_deleteScoreList.Count > 0)
                        {
                            _warn.RunWorkerAsync();
                        }
                        else
                        {
                            lblMessage.Text = "成績上傳中…";
                            FISCA.Presentation.MotherForm.SetStatusBarMessage("成績上傳中…", 0);
                            counter = 0;
                            _upload.RunWorkerAsync();
                        }
                    }
                }
                else
                {
                    ControlEnable = true;

                    if (e.Error != null)
                    {
                        MsgBox.Show("匯入失敗。" + e.Error.Message);
                        SmartSchool.ErrorReporting.ReportingService.ReportException(e.Error);
                    }
                    else if (e.Result != null && e.Result is ValidateTextResult)
                    {
                        ValidateTextResult    result = e.Result as ValidateTextResult;
                        ValidationErrorViewer viewer = new ValidationErrorViewer();
                        viewer.SetTextFileError(result.LineIndexes, result.ErrorFormatLineIndexes, result.DuplicateLineIndexes);
                        viewer.ShowDialog();
                    }
                    else if (e.Result != null && e.Result is List <string> )
                    {
                        ValidationErrorViewer viewer = new ValidationErrorViewer();
                        viewer.SetErrorLines(e.Result as List <string>);
                        viewer.ShowDialog();
                    }
                }
                #endregion
            };

            _upload = new BackgroundWorker();
            _upload.WorkerReportsProgress = true;
            _upload.ProgressChanged      += new ProgressChangedEventHandler(_upload_ProgressChanged);
            //_upload.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e)
            //{
            //    counter += double.Parse("" + e.ProgressPercentage);
            //    FISCA.Presentation.MotherForm.SetStatusBarMessage("成績上傳中…", (int)(counter * 100f / (double)_addScoreList.Count));
            //};
            _upload.DoWork += new DoWorkEventHandler(_upload_DoWork);

            //_upload.DoWork += delegate
            //{


            //#region Upload DoWork
            //Framework.MultiThreadWorker<JHSCETakeRecord> multi = new Framework.MultiThreadWorker<JHSCETakeRecord>();
            //multi.MaxThreads = 3;
            //multi.PackageSize = 500;
            //multi.PackageWorker += delegate(object sender, Framework.PackageWorkEventArgs<JHSCETakeRecord> e)
            //{
            //    JHSCETake.Delete(e.List);
            //};
            //multi.Run(_deleteScoreList);

            //Framework.MultiThreadWorker<JHSCETakeRecord> multi2 = new Framework.MultiThreadWorker<JHSCETakeRecord>();
            //multi2.MaxThreads = 3;
            //multi2.PackageSize = 500;
            //multi2.PackageWorker += delegate(object sender, Framework.PackageWorkEventArgs<JHSCETakeRecord> e)
            //{
            //    JHSCETake.Insert(e.List);
            //    lock (_upload)
            //    {
            //        _upload.ReportProgress(e.List.Count);
            //    }
            //};
            //multi2.Run(_addScoreList);
            //#endregion
            //};


            _upload.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_upload_RunWorkerCompleted);

            _warn = new BackgroundWorker();
            _warn.WorkerReportsProgress = true;
            _warn.DoWork += delegate(object sender, DoWorkEventArgs e)
            {
                _warn.ReportProgress(0, "產生警告訊息...");

                Dictionary <string, string> examDict = new Dictionary <string, string>();
                foreach (JHExamRecord exam in JHExam.SelectAll())
                {
                    if (!examDict.ContainsKey(exam.ID))
                    {
                        examDict.Add(exam.ID, exam.Name);
                    }
                }

                WarningForm form  = new WarningForm();
                int         count = 0;
                foreach (JHSCETakeRecord sce in _deleteScoreList)
                {
                    // 當成績資料是空值跳過
                    if (sce.Score.HasValue == false && sce.Effort.HasValue == false && string.IsNullOrEmpty(sce.Text))
                    {
                        continue;
                    }

                    count++;

                    JHStudentRecord student = JHStudent.SelectByID(sce.RefStudentID);
                    JHCourseRecord  course  = JHCourse.SelectByID(sce.RefCourseID);
                    string          exam    = (examDict.ContainsKey(sce.RefExamID) ? examDict[sce.RefExamID] : "<未知的試別>");

                    string s = "";
                    if (student.Class != null)
                    {
                        s += student.Class.Name;
                    }
                    if (!string.IsNullOrEmpty("" + student.SeatNo))
                    {
                        s += " " + student.SeatNo + "號";
                    }
                    if (!string.IsNullOrEmpty(student.StudentNumber))
                    {
                        s += " (" + student.StudentNumber + ")";
                    }
                    s += " " + student.Name;

                    form.Add(student.ID, s, string.Format("學生在「{0}」課程「{1}」中已有成績。", course.Name, exam));
                    _warn.ReportProgress((int)(count * 100 / _deleteScoreList.Count), "產生警告訊息...");
                }

                e.Result = form;
            };
            _warn.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
            {
                WarningForm form = e.Result as WarningForm;

                if (form.ShowDialog() == DialogResult.OK)
                {
                    lblMessage.Text = "成績上傳中…";
                    FISCA.Presentation.MotherForm.SetStatusBarMessage("成績上傳中…", 0);
                    counter = 0;
                    _upload.RunWorkerAsync();
                }
                else
                {
                    this.DialogResult = DialogResult.Cancel;
                }
            };
            _warn.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e)
            {
                FISCA.Presentation.MotherForm.SetStatusBarMessage("" + e.UserState, e.ProgressPercentage);
            };

            _files           = new List <FileInfo>();
            _addScoreList    = new List <JHSCETakeRecord>();
            _deleteScoreList = new List <JHSCETakeRecord>();
        }
        /// <summary>
        /// 檢查
        /// </summary>
        public DataRationalityMessage Execute()
        {
            RATRecords.Clear();
            AssnciationDic.Clear();
            CourseDic.Clear();

            DataRationalityMessage Message = new DataRationalityMessage();

            List <AssnAddress> AssnciationAddressList = _accessHelper.Select <AssnAddress>();

            List <string> CourseIDList = new List <string>();

            foreach (AssnAddress each in AssnciationAddressList)
            {
                if (each.Address == "")
                {
                    //目的是後續要取得該課程
                    if (!CourseIDList.Contains(each.AssociationID))
                    {
                        CourseIDList.Add(each.AssociationID);
                    }

                    //建立對照清單
                    if (!AssnciationDic.ContainsKey(each.UID))
                    {
                        AssnciationDic.Add(each.UID, each);
                    }
                }
            }

            foreach (JHCourseRecord each in JHCourse.SelectByIDs(CourseIDList))
            {
                if (!CourseDic.ContainsKey(each.ID))
                {
                    CourseDic.Add(each.ID, each);
                }
            }

            foreach (AssnAddress each in AssnciationAddressList)
            {
                if (each.Address == "")
                {
                    AssociationAddressRATRecord AArat = new AssociationAddressRATRecord();
                    AArat.社團系統編號 = each.AssociationID;
                    AArat.課學年度   = each.SchoolYear;
                    AArat.課學期    = each.Semester;
                    AArat.課地點    = each.Address;
                    AArat.課地點UID = each.UID;
                    if (CourseDic.ContainsKey(each.AssociationID))
                    {
                        AArat.社團名稱  = CourseDic[each.AssociationID].Name;
                        AArat.社團學年度 = CourseDic[each.AssociationID].SchoolYear.HasValue ? CourseDic[each.AssociationID].SchoolYear.Value.ToString() : "";
                        AArat.社團學期  = CourseDic[each.AssociationID].Semester.HasValue ? CourseDic[each.AssociationID].Semester.Value.ToString() : "";
                    }
                    RATRecords.Add(AArat);
                }
            }

            //錯誤說明
            StringBuilder strBuilder = new StringBuilder();

            strBuilder.AppendLine("檢查(上課地點)筆數:" + _accessHelper.Select <AssnAddress>().Count);
            strBuilder.AppendLine("空值(上課地點)筆數:" + RATRecords.Count);
            strBuilder.AppendLine("(您可以匯出Excel以保存資料,再進行自動修正!!)");

            var SortedRATRecords = from RATRecord in RATRecords orderby RATRecord.社團名稱, RATRecord.社團系統編號, RATRecord.課學年度, RATRecord.課學期 select RATRecord;

            Message.Data    = SortedRATRecords.ToList();
            Message.Message = strBuilder.ToString();

            if (RATRecords.Count == 0)
            {
                MsgBox.Show("未檢查到錯誤資料!!");
            }

            return(Message);
        }
Beispiel #22
0
        public MainForm()
        {
            //GetSubjectList();
            InitializeComponent();
            InitializeSemester();
            this.Text        = Global.ReportName;
            this.MinimumSize = this.Size;
            this.MaximumSize = this.Size;

            _config = new Config(Global.ReportName);

            _data       = new List <ClassExamScoreData>();
            _courseDict = new Dictionary <string, JHCourseRecord>();
            _exams      = new List <JHExamRecord>();
            //_ecMapping = new Dictionary<string, List<string>>();
            _courseList = new List <string>();

            cbExam.DisplayMember = "Name";
            cbSource.Items.Add("定期");
            cbSource.Items.Add("定期加平時");
            cbSource.SelectedIndex = 0;

            cbExam.Items.Add("");
            _exams = JHExam.SelectAll();
            foreach (var exam in _exams)
            {
                cbExam.Items.Add(exam);
            }
            cbExam.SelectedIndex = 0;

            _worker         = new BackgroundWorker();
            _worker.DoWork += delegate(object sender, DoWorkEventArgs e)
            {
                JHExamRecord exam = e.Argument as JHExamRecord;
                #region 取得試別
                //_ecMapping.Clear();
                //_exams = JHExam.SelectAll();
                //List<string> examIDs = new List<string>();
                //foreach (JHExamRecord exam in _exams)
                //{
                //    examIDs.Add(exam.ID);
                //_ecMapping.Add(exam.ID, new List<string>());
                //}
                #endregion

                #region 取得課程
                _courseDict.Clear();
                List <JHCourseRecord> courseList = JHCourse.SelectBySchoolYearAndSemester(_runningSchoolYear, _runningSemester);
                List <string>         courseIDs  = new List <string>();
                foreach (JHCourseRecord course in courseList)
                {
                    courseIDs.Add(course.ID);
                    _courseDict.Add(course.ID, course);
                }
                #endregion

                #region 取得評量成績
                //StudentID -> ClassExamScoreData
                Dictionary <string, ClassExamScoreData> scMapping = new Dictionary <string, ClassExamScoreData>();
                List <string> ids = new List <string>();
                _classes = JHClass.SelectByIDs(K12.Presentation.NLDPanels.Class.SelectedSource);

                // 排序
                if (_classes.Count > 1)
                {
                    _classes = DAL.DALTransfer.ClassRecordSortByDisplayOrder(_classes);
                }

                // TODO: 這邊要排序
                //List<K12.Data.ClassRecord> c = new List<K12.Data.ClassRecord>(_classes);
                //c.Sort();
                //_classes = new List<JHClassRecord>(c);
                //((List<K12.Data.ClassRecord>)_classes).Sort();

                _data.Clear();
                foreach (JHClassRecord cla in _classes)
                {
                    ClassExamScoreData classData = new ClassExamScoreData(cla);
                    foreach (JHStudentRecord stu in classData.Students)
                    {
                        scMapping.Add(stu.ID, classData);
                    }
                    _data.Add(classData);
                }

                //foreach (string examID in examIDs)
                //{

                _courseList.Clear();
                if (courseIDs.Count > 0)
                {
                    // TODO: JHSCETake 需要提供 SelectBy 課程IDs and 試別IDs 嗎?
                    foreach (JHSCETakeRecord sce in JHSCETake.SelectByCourseAndExam(courseIDs, exam.ID))
                    {
                        // TODO: 下面前兩個判斷應該可以拿掉
                        //if (!examIDs.Contains(sce.RefExamID)) continue; //試別無效
                        //if (!courseIDs.Contains(sce.RefCourseID)) continue; //課程無效
                        if (!scMapping.ContainsKey(sce.RefStudentID))
                        {
                            continue;                                           //學生編號無效
                        }
                        if (string.IsNullOrEmpty(_courseDict[sce.RefCourseID].RefAssessmentSetupID))
                        {
                            continue;                                                                          //課程無評量設定
                        }
                        if (!_courseList.Contains(sce.RefCourseID))
                        {
                            _courseList.Add(sce.RefCourseID);
                        }
                        //if (!_ecMapping[sce.RefExamID].Contains(sce.RefCourseID))
                        //    _ecMapping[sce.RefExamID].Add(sce.RefCourseID);

                        ClassExamScoreData classData = scMapping[sce.RefStudentID];
                        classData.AddScore(sce);
                    }
                }
                //}
                #endregion
            };
            _worker.RunWorkerCompleted += delegate
            {
                string running = _runningSchoolYear + "_" + _runningSemester;
                string current = (int)cboSchoolYear.SelectedItem + "_" + (int)cboSemester.SelectedItem;
                if (running != current)
                {
                    if (!_worker.IsBusy)
                    {
                        _runningSchoolYear = (int)cboSchoolYear.SelectedItem;
                        _runningSemester   = (int)cboSemester.SelectedItem;

                        RunWorker();
                    }
                }
                else
                {
                    FillData();
                    ControlEnabled = true;
                }
            };

            RunWorker();
        }
Beispiel #23
0
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            #region DoWork
            object[] objs         = (object[])e.Argument;
            int      schoolyear   = Framework.Int.Parse(objs[0] as string);
            int      semester     = Framework.Int.Parse(objs[1] as string);
            string   domain       = objs[2] as string;
            string   subject      = objs[3] as string;
            string   periodcredit = objs[4] as string;
            string   required     = objs[5] as string;

            PeriodCredit pc = new PeriodCredit();
            pc.Parse(periodcredit);

            double total   = _classes.Count;
            double counter = 0;
            if (total == 0)
            {
                total = 1;
            }
            else
            {
                total *= 2;
            }
            _worker.ReportProgress(1, "正在檢查班級課程…");

            _classes.Sort(SortClassesByClassName);

            #region 檢查重複開課
            List <string> errors = new List <string>();

            List <string> classIDs = new List <string>();
            foreach (JHClassRecord cla in _classes)
            {
                classIDs.Add(cla.ID);
            }

            Dictionary <string, List <JHCourseRecord> > classExistCourses = new Dictionary <string, List <JHCourseRecord> >();
            List <JHCourseRecord> orphanCourse = new List <JHCourseRecord>();

            foreach (JHCourseRecord course in JHCourse.SelectBySchoolYearAndSemester(schoolyear, semester))
            {
                if (!classIDs.Contains(course.RefClassID))
                {
                    orphanCourse.Add(course);
                    continue;
                }

                if (!classExistCourses.ContainsKey(course.RefClassID))
                {
                    classExistCourses.Add(course.RefClassID, new List <JHCourseRecord>());
                }
                classExistCourses[course.RefClassID].Add(course);
            }

            foreach (JHClassRecord cla in _classes)
            {
                if (!classExistCourses.ContainsKey(cla.ID))
                {
                    continue;
                }

                foreach (JHCourseRecord course in classExistCourses[cla.ID])
                {
                    if (course.Subject == subject)
                    {
                        errors.Add(cla.Name + ":已有相同科目(" + subject + ")的課程。");
                    }
                }

                foreach (JHCourseRecord course in orphanCourse)
                {
                    if (course.Name == cla.Name + " " + subject)
                    {
                        errors.Add(cla.Name + ":已有相同課程名稱(" + course.Name + ")的課程。");
                    }
                }
            }

            if (errors.Count > 0)
            {
                e.Result = errors;
                return;
            }
            #endregion

            #region 開課
            Dictionary <string, string> classNewCourse = new Dictionary <string, string>();

            DSXmlHelper req = new DSXmlHelper("UpdateRequest");

            foreach (JHClassRecord cla in _classes)
            {
                JHCourseRecord newCourse = new JHCourseRecord();
                newCourse.CalculationFlag = "1";
                newCourse.Period          = pc.Period;
                newCourse.Credit          = pc.Credit;
                newCourse.Domain          = domain;
                newCourse.Subject         = subject;
                newCourse.Name            = cla.Name + " " + subject;
                newCourse.SchoolYear      = schoolyear;
                newCourse.Semester        = semester;
                newCourse.RefClassID      = cla.ID;

                //建立Course時也將CourseExtendRecord建立
                string             course_id = JHCourse.Insert(newCourse);
                CourseExtendRecord courseEx  = new CourseExtendRecord();
                courseEx.Ref_course_id = int.Parse(course_id);
                courseEx.GradeYear     = cla.GradeYear == null ? -1 : int.Parse(cla.GradeYear + "");
                courseEx.Save();

                classNewCourse.Add(cla.ID, course_id);
                req.AddElement("Course");
                req.AddElement("Course", "Field");
                req.AddElement("Course/Field", "IsRequired", required.Replace("修", ""));
                req.AddElement("Course", "Condition");
                req.AddElement("Course/Condition", "ID", classNewCourse[cla.ID]);

                counter++;
                _worker.ReportProgress((int)(counter * 100d / total), "正在進行開課…");
            }

            //更新必選修
            if (classNewCourse.Count > 0)
            {
                JHSchool.Feature.Legacy.EditCourse.UpdateCourse(new DSRequest(req));
            }

            #endregion

            #region 加入學生修課

            foreach (JHClassRecord cla in _classes)
            {
                List <JHSCAttendRecord> scattends = new List <JHSchool.Data.JHSCAttendRecord>();
                foreach (JHStudentRecord stu in cla.Students)
                {
                    JHSCAttendRecord scattend = new JHSchool.Data.JHSCAttendRecord();
                    scattend.RefCourseID  = classNewCourse[cla.ID];
                    scattend.RefStudentID = stu.ID;

                    scattends.Add(scattend);
                }

                if (scattends.Count > 0)
                {
                    JHSCAttend.Insert(scattends);
                }

                counter++;
                _worker.ReportProgress((int)(counter * 100d / total), "正在加入學生修課…");
            }
            #endregion

            // 加這主要是重新整理
            Course.Instance.SyncDataBackground(classNewCourse.Values);

            e.Result = string.Empty;

            #endregion
        }
Beispiel #24
0
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            double total = Students.Count;
            double count = 0;

            _worker.ReportProgress(0);

            List <string> studentIDs = Students.Select(x => x.ID).ToList();

            //List<string> student_ids = new List<string>();
            //foreach (JHStudentRecord item in Students)
            //    student_ids.Add(item.ID);

            #region 快取資料

            //獎勵
            // 1.依學生編號、開始日期、結束日期,取得學生獎勵紀錄
            // 2.依學生編號進行分群
            Dictionary <string, List <JHMeritRecord> > meritCache = new Dictionary <string, List <JHMeritRecord> >();
            foreach (JHMeritRecord record in JHMerit.Select(studentIDs, _config.StartDate, _config.EndDate, null, null, null, null))
            {
                if (!meritCache.ContainsKey(record.RefStudentID))
                {
                    meritCache.Add(record.RefStudentID, new List <JHMeritRecord>());
                }
                meritCache[record.RefStudentID].Add(record);
            }
            //Dictionary<string, List<JHMeritRecord>> meritCache = new Dictionary<string, List<JHMeritRecord>>();
            //foreach (JHMeritRecord record in JHMerit.SelectByStudentIDs(student_ids))
            //{
            //    if (record.OccurDate < _config.StartDate) continue;
            //    if (record.OccurDate > _config.EndDate) continue;

            //    if (!meritCache.ContainsKey(record.RefStudentID))
            //        meritCache.Add(record.RefStudentID, new List<JHMeritRecord>());
            //    meritCache[record.RefStudentID].Add(record);
            //}

            //懲戒
            // 1.依學生編號、開始日期、結束日期,取得學生懲戒紀錄
            // 2.依學生編號進行分群
            Dictionary <string, List <JHDemeritRecord> > demeritCache = new Dictionary <string, List <JHDemeritRecord> >();
            foreach (JHDemeritRecord record in JHDemerit.Select(studentIDs, _config.StartDate, _config.EndDate, null, null, null, null))
            {
                if (!demeritCache.ContainsKey(record.RefStudentID))
                {
                    demeritCache.Add(record.RefStudentID, new List <JHDemeritRecord>());
                }
                demeritCache[record.RefStudentID].Add(record);
            }

            //Dictionary<string, List<JHDemeritRecord>> demeritCache = new Dictionary<string, List<JHDemeritRecord>>();
            //foreach (JHDemeritRecord record in JHDemerit.SelectByStudentIDs(student_ids))
            //{
            //    if (record.OccurDate < _config.StartDate) continue;
            //    if (record.OccurDate > _config.EndDate) continue;

            //    if (!demeritCache.ContainsKey(record.RefStudentID))
            //        demeritCache.Add(record.RefStudentID, new List<JHDemeritRecord>());
            //    demeritCache[record.RefStudentID].Add(record);
            //}


            ////缺曠
            //// 1.依學生編號、開始日期、結束日期,取得學生缺曠紀錄
            //// 2.依學生編號進行分群
            //Dictionary<string, List<JHAttendanceRecord>> attendanceCache = new Dictionary<string, List<JHAttendanceRecord>>();
            //foreach (JHAttendanceRecord record in JHAttendance.Select(studentIDs, _config.StartDate, _config.EndDate, null, null, null))
            //{
            //    if (!attendanceCache.ContainsKey(record.RefStudentID))
            //        attendanceCache.Add(record.RefStudentID, new List<JHAttendanceRecord>());
            //    attendanceCache[record.RefStudentID].Add(record);
            //}
            //Dictionary<string, List<JHAttendanceRecord>> attendanceCache = new Dictionary<string, List<JHAttendanceRecord>>();
            //foreach (JHAttendanceRecord record in JHAttendance.SelectByStudentIDs(student_ids))
            //{
            //    if (record.OccurDate < _config.StartDate) continue;
            //    if (record.OccurDate > _config.EndDate) continue;

            //    if (!attendanceCache.ContainsKey(record.RefStudentID))
            //        attendanceCache.Add(record.RefStudentID, new List<JHAttendanceRecord>());
            //    attendanceCache[record.RefStudentID].Add(record);
            //}

            //List<string> studentIDs = new List<string>();
            //foreach (var stu in _config.Students)
            //    studentIDs.Add(stu.ID);

            //缺曠
            // 1.依學生編號、開始日期、結束日期,取得學生缺曠紀錄
            // 2.依學生編號進行分群
            Dictionary <string, List <JHAttendanceRecord> > attendanceCache = new Dictionary <string, List <JHAttendanceRecord> >();
            foreach (JHAttendanceRecord record in JHAttendance.Select(studentIDs, _config.StartDate, _config.EndDate, null, null, null))
            {
                if (!attendanceCache.ContainsKey(record.RefStudentID))
                {
                    attendanceCache.Add(record.RefStudentID, new List <JHAttendanceRecord>());
                }
                attendanceCache[record.RefStudentID].Add(record);
            }



            //修課紀錄
            // 1.依學生編號、學年度、學期,取得修課紀錄
            // 2.
            List <string> courseIDs = new List <string>();
            List <string> attendIDs = new List <string>();
            Dictionary <string, List <string> > scCache = new Dictionary <string, List <string> >();
            foreach (var attend in JHSCAttend.Select(studentIDs, null, null, "" + _config.SchoolYear, "" + _config.Semester))
            {
                attendIDs.Add(attend.ID);
                if (!scCache.ContainsKey(attend.RefStudentID))
                {
                    scCache.Add(attend.RefStudentID, new List <string>());
                }
                scCache[attend.RefStudentID].Add(attend.RefCourseID);
                if (!courseIDs.Contains(attend.RefCourseID))
                {
                    courseIDs.Add(attend.RefCourseID);
                }
            }

            //課程
            // 1.依課程編號取得課程紀錄
            // 2.略過不列入成績計算的課程
            JHCourse.RemoveByIDs(courseIDs);
            Dictionary <string, JHCourseRecord> courseCache = JHCourse.SelectByIDs(courseIDs).Where(x => x.CalculationFlag != "2").ToDictionary(x => x.ID);

            //試別資訊: 取得所有試別
            Dictionary <string, JHExamRecord> examCache = JHExam.SelectAll().ToDictionary(x => x.ID);

            // 取得社團ExamID
            List <string> NExamIDList = new List <string>();
            foreach (JHExamRecord rec in JHExam.SelectAll())
            {
                if (rec.Name.IndexOf("社團") > -1)
                {
                    NExamIDList.Add(rec.ID);
                }
            }

            //評量成績
            // 1.依修課記錄及所有試別取得評量成績
            // 2.依第1點的評量成績取得試別編號 (實際學生評量成績中的試別編號)
            // 3.依學生編號進行分群
            Dictionary <string, List <HC.JHSCETakeRecord> > sceScoreCache = new Dictionary <string, List <HC.JHSCETakeRecord> >();
            List <string> validExamIDs = new List <string>();

            //  檢查當有修課紀錄才取成績資料
            if (attendIDs.Count > 0 && examCache.Count > 0)
            {
                foreach (JHSCETakeRecord record in JHSCETake.Select(null, null, examCache.Keys, null, attendIDs))
                {
                    if (!NExamIDList.Contains(record.RefExamID))
                    {
                        if (!validExamIDs.Contains(record.RefExamID))
                        {
                            validExamIDs.Add(record.RefExamID);
                        }
                    }

                    if (!sceScoreCache.ContainsKey(record.RefStudentID))
                    {
                        sceScoreCache.Add(record.RefStudentID, new List <HC.JHSCETakeRecord>());
                    }
                    sceScoreCache[record.RefStudentID].Add(new HC.JHSCETakeRecord(record));
                }
            }

            //將『所有試別編號』與『實際學生評量成績中的試別編號』做交集,以取得使用管理的試別次序
            //假設『所有試別編號』為1,4,3,5
            //假設『實際學生評量成績中的試別編號』為3,4,1
            //交集後的結果為1,4,3
            validExamIDs = examCache.Keys.Intersect(validExamIDs).ToList();



            // 取得學生成績計算規則
            // 如果學生沒有計算規則一律用預設,預設進位方式取到小數點第2位
            ScoreCalculator defaultScoreCalculator = new ScoreCalculator(null);
            //key: ScoreCalcRuleID
            Dictionary <string, ScoreCalculator> calcCache = new Dictionary <string, ScoreCalculator>();
            //key: StudentID, val: ScoreCalcRuleID
            Dictionary <string, string> calcIDCache = new Dictionary <string, string>();

            List <string> scoreCalcRuleIDList = new List <string>();

            // 取得學生計算規則的ID,建立對照表
            // 如果學生身上有指定成績計算規則,就以學生身上成績計算規則為主
            // 如果學生身上沒有指定成績計算規則,就以學生所屬班級成績計算規則為主
            foreach (JHStudentRecord student in _config.Students)
            {
                string calcID = string.Empty;
                if (!string.IsNullOrEmpty(student.OverrideScoreCalcRuleID))
                {
                    calcID = student.OverrideScoreCalcRuleID;
                }
                else if (student.Class != null && !string.IsNullOrEmpty(student.Class.RefScoreCalcRuleID))
                {
                    calcID = student.Class.RefScoreCalcRuleID;
                }

                if (!string.IsNullOrEmpty(calcID))
                {
                    calcIDCache.Add(student.ID, calcID);
                }
            }
            // 取得計算規則建立成績進位器
            foreach (JHScoreCalcRuleRecord record in JHScoreCalcRule.SelectByIDs(calcIDCache.Values))
            {
                if (!calcCache.ContainsKey(record.ID))
                {
                    calcCache.Add(record.ID, new ScoreCalculator(record));
                }
            }


            ////修課紀錄
            //// 1.依學生編號、學年度、學期,取得修課紀錄
            //// 2.
            //List<string> courseIDs = new List<string>();
            //foreach (var attend in JHSCAttend.SelectByStudentIDs(studentIDs))
            //{
            //    if (!courseIDs.Contains(attend.RefCourseID))
            //        courseIDs.Add(attend.RefCourseID);
            //}

            //int schoolYear = _config.SchoolYear;
            //int semester = _config.Semester;
            //List<JHCourseRecord> courses = JHCourse.SelectByIDs(courseIDs);

            ////課程
            //Dictionary<string, JHCourseRecord> courseCache = new Dictionary<string, JHCourseRecord>();
            //foreach (JHCourseRecord record in JHCourse.SelectByIDs(courseIDs))
            //{
            //    if ("" + record.SchoolYear != "" + schoolYear) continue;
            //    if ("" + record.Semester != "" + semester) continue;
            //    if (record.CalculationFlag == "2") continue;
            //    //if (string.IsNullOrEmpty(record.Domain)) continue; //沒有填領域

            //    if (!courseCache.ContainsKey(record.ID))
            //        courseCache.Add(record.ID, record);
            //}

            ////試別資訊
            //Dictionary<string, JHExamRecord> examCache = new Dictionary<string, JHExamRecord>();
            //foreach (JHExamRecord exam in JHExam.SelectAll())
            //{
            //    if (!examCache.ContainsKey(exam.ID))
            //        examCache.Add(exam.ID, exam);
            //}
            //List<string> validExamIDs = new List<string>();

            ////評量成績
            //Dictionary<string, List<HC.JHSCETakeRecord>> sceScoreCache = new Dictionary<string, List<HC.JHSCETakeRecord>>();
            //foreach (JHSCETakeRecord record in JHSCETake.SelectByStudentIDs(student_ids))
            //{
            //    if (examCache.ContainsKey(record.RefExamID))
            //    {
            //        if (!validExamIDs.Contains(record.RefExamID))
            //            validExamIDs.Add(record.RefExamID);
            //    }
            //    else
            //        continue;

            //    if (!sceScoreCache.ContainsKey(record.RefStudentID))
            //        sceScoreCache.Add(record.RefStudentID, new List<HC.JHSCETakeRecord>());
            //    sceScoreCache[record.RefStudentID].Add(new HC.JHSCETakeRecord(record));
            //}
            //// TODO: 這邊的排序有可能再改
            //validExamIDs.Sort(delegate(string x, string y)
            //{
            //    int ix, iy;
            //    if (!int.TryParse(x, out ix))
            //        ix = int.MaxValue;
            //    if (!int.TryParse(y, out iy))
            //        iy = int.MaxValue;
            //    return ix.CompareTo(iy);
            //});

            //學期歷程
            //Dictionary<string, K12.Data.SemesterHistoryItem> historyCache = new Dictionary<string, K12.Data.SemesterHistoryItem>();
            //foreach (JHSemesterHistoryRecord record in JHSemesterHistory.SelectByStudentIDs(student_ids))
            //{
            //    foreach (K12.Data.SemesterHistoryItem item in record.SemesterHistoryItems)
            //    {
            //        if ("" + item.SchoolYear != K12.Data.School.DefaultSchoolYear) continue;
            //        if ("" + item.Semester != K12.Data.School.DefaultSemester) continue;

            //        if (!historyCache.ContainsKey(record.RefStudentID))
            //            historyCache.Add(record.RefStudentID, item);
            //    }
            //}
            #endregion

            #region 判斷領域是否需要展開
            //判斷領域是否展開對照表
            //Key:領域名稱
            //Value:false=展開,true=不展開
            //展開: 詳列該領域下所有科目成績
            //不展開: 只列該領域成績
            Dictionary <string, bool>           domains  = new Dictionary <string, bool>();
            Dictionary <string, List <string> > subjects = new Dictionary <string, List <string> >();

            List <JHCourseRecord> courseList = new List <JHCourseRecord>(courseCache.Values);
            courseList.Sort(delegate(JHCourseRecord x, JHCourseRecord y)
            {
                return(JHSchool.Evaluation.Subject.CompareSubjectOrdinal(x.Subject, y.Subject));
                //List<string> list = new List<string>(new string[] { "國語文", "國文", "英文", "英語", "數學", "歷史", "地理", "公民", "理化", "生物" });
                //int ix = list.IndexOf(x.Subject);
                //int iy = list.IndexOf(y.Subject);

                //if (ix >= 0 && iy >= 0)
                //    return ix.CompareTo(iy);
                //else if (ix >= 0)
                //    return -1;
                //else if (iy >= 0)
                //    return 1;
                //else
                //    return x.Subject.CompareTo(y.Subject);
            });

            DomainSubjectSetup domainSubjectSetup = _config.DomainSubjectSetup;
            //使用者設定"只列印領域"
            if (domainSubjectSetup == DomainSubjectSetup.Domain)
            {
                //預設從領域資料管理來的領域名稱皆不展開
                foreach (var domain in JHSchool.Evaluation.Subject.Domains)
                {
                    domains.Add(domain, DomainSubjectExpand.展開);
                }
                if (domains.ContainsKey("語文"))
                {
                    domains["語文"] = DomainSubjectExpand.展開;
                }

                //彈性課程一定展開
                if (!domains.ContainsKey(""))
                {
                    domains.Add("", DomainSubjectExpand.展開);
                }
                //if (!domains.ContainsKey("彈性課程")) domains.Add("彈性課程", false);
            }
            //使用者設定"只列印科目"
            else if (domainSubjectSetup == DomainSubjectSetup.Subject)
            {
                //預設從領域資料管理來的領域名稱皆展開
                foreach (var domain in JHSchool.Evaluation.Subject.Domains)
                {
                    domains.Add(domain, DomainSubjectExpand.展開);
                }
                //彈性課程一定展開
                if (!domains.ContainsKey(""))
                {
                    domains.Add("", DomainSubjectExpand.展開);
                }
                //if (!domains.ContainsKey("彈性課程")) domains.Add("彈性課程", false);
            }
            else
            {
                throw new Exception("請重新儲存一次列印設定");
            }

            //foreach (var domain in JHSchool.Evaluation.Subject.Domains)
            //    subjects.Add(domain, new List<string>());

            //if (!subjects.ContainsKey("")) subjects.Add("", new List<string>());
            //if (!subjects.ContainsKey("彈性課程")) subjects.Add("彈性課程", new List<string>());

            //foreach (var course in courseList)
            //{
            //    if (!subjects.ContainsKey(course.Domain))
            //        subjects.Add(course.Domain, new List<string>());
            //    if (!subjects[course.Domain].Contains(course.Subject))
            //        subjects[course.Domain].Add(course.Subject);
            //}

            //_config.SetPrintDomains(domains);
            //_config.SetPrintSubjects(subjects);
            _config.PrintDomains = domains;
            #endregion

            #region 建立節次對照
            Dictionary <string, string> periodMapping = JHPeriodMapping.SelectAll().ToDictionary(x => x.Name, y => y.Type);
            //Dictionary<string, string> periodMapping = new Dictionary<string, string>();
            //foreach (JHPeriodMappingInfo info in JHPeriodMapping.SelectAll())
            //{
            //    if (!periodMapping.ContainsKey(info.Name))
            //        periodMapping.Add(info.Name, info.Type);
            //}
            #endregion

            #region 假別列表
            List <string> absenceList = JHAbsenceMapping.SelectAll().Select(x => x.Name).ToList();
            //List<string> absenceList = new List<string>();
            //foreach (JHAbsenceMappingInfo info in JHAbsenceMapping.SelectAll())
            //    absenceList.Add(info.Name);
            #endregion

            #region 依評量試別重新劃分範本
            int             rowCount        = 0;
            DocumentBuilder templateBuilder = new DocumentBuilder(_template);
            templateBuilder.MoveToMergeField("各次評量");
            Font   font       = templateBuilder.Font;
            Cell   examsCell  = templateBuilder.CurrentParagraph.ParentNode as Cell;
            Table  table      = examsCell.ParentRow.ParentTable;
            double width      = examsCell.CellFormat.Width;
            double examWidth  = width / (double)validExamIDs.Count;
            double scoreWidth = width / (double)validExamIDs.Count / 3.0;

            //計算有幾個 Score Row
            foreach (Row row in table.Rows)
            {
                if (row.Cells.Count > 3)
                {
                    rowCount++;
                }
            }

            #region Header Cell
            //建立評量欄位對照表
            Dictionary <string, int> columnMapping = new Dictionary <string, int>();
            int columnShift = 3;
            int columnIndex = 0;

            table.Rows[0].LastCell.Remove();
            table.Rows[1].LastCell.Remove();
            foreach (string examID in validExamIDs)
            {
                columnMapping.Add(examID, columnIndex + columnShift);

                Cell topHeaderCell = new Cell(_template);
                WordHelper.Write(topHeaderCell, font, examCache[examID].Name);
                table.Rows[0].Cells.Add(topHeaderCell);

                Cell subHeaderCell1 = new Cell(_template);
                WordHelper.Write(subHeaderCell1, font, "定期", "評量");
                table.Rows[1].Cells.Add(subHeaderCell1);
                columnIndex++;

                Cell subHeaderCell2 = new Cell(_template);
                WordHelper.Write(subHeaderCell2, font, "平時", "評量");
                table.Rows[1].Cells.Add(subHeaderCell2);
                columnIndex++;

                Cell subHeaderCell3 = new Cell(_template);
                WordHelper.Write(subHeaderCell3, font, "總成績");
                table.Rows[1].Cells.Add(subHeaderCell3);
                columnIndex++;

                topHeaderCell.CellFormat.Width  = examWidth;
                subHeaderCell1.CellFormat.Width = scoreWidth;
                subHeaderCell2.CellFormat.Width = scoreWidth;
                subHeaderCell3.CellFormat.Width = scoreWidth;

                topHeaderCell.CellFormat.VerticalAlignment  = CellVerticalAlignment.Center;
                subHeaderCell1.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
                subHeaderCell2.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
                subHeaderCell3.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
            }
            WordHelper.MergeVerticalCell(table.Rows[0].Cells[1], 2);
            #endregion

            #region Content Cell
            int shift = 2; //Header has 2 rows
            for (int i = 0; i < rowCount; i++)
            {
                table.Rows[i + shift].LastCell.Remove();

                for (int j = 0; j < validExamIDs.Count * 3; j++)
                {
                    Cell contentCell = new Cell(_template);
                    contentCell.CellFormat.Width             = scoreWidth;
                    contentCell.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;

                    table.Rows[i + shift].Cells.Add(contentCell);
                }
            }
            #endregion

            #endregion

            #region 依節權數設定,在畫面上顯示
            string pcDisplay = string.Empty;
            if (_config.PrintPeriod && _config.PrintCredit)
            {
                pcDisplay = "節/權數";
            }
            else if (_config.PrintPeriod)
            {
                pcDisplay = "節數";
            }
            else if (_config.PrintCredit)
            {
                pcDisplay = "權數";
            }

            templateBuilder.MoveToMergeField("節權數");
            templateBuilder.Write(pcDisplay);
            #endregion

            //#region 取得學生成績計算規則

            //ScoreCalculator defaultScoreCalculator = new ScoreCalculator(null);

            ////key: ScoreCalcRuleID
            //Dictionary<string, ScoreCalculator> calcCache = new Dictionary<string, ScoreCalculator>();
            ////key: StudentID, val: ScoreCalcRuleID
            //Dictionary<string, string> calcIDCache = new Dictionary<string, string>();

            //List<string> scoreCalcRuleIDList = new List<string>();

            //foreach (JHStudentRecord student in _config.Students)
            //{
            //    string calcID = string.Empty;
            //    if (!string.IsNullOrEmpty(student.OverrideScoreCalcRuleID))
            //        calcID = student.OverrideScoreCalcRuleID;
            //    else if (student.Class != null && !string.IsNullOrEmpty(student.Class.RefScoreCalcRuleID))
            //        calcID = student.Class.RefScoreCalcRuleID;

            //    if (!string.IsNullOrEmpty(calcID))
            //        calcIDCache.Add(student.ID, calcID);
            //}
            //foreach (JHScoreCalcRuleRecord record in JHScoreCalcRule.SelectByIDs(calcIDCache.Values))
            //{
            //    if (!calcCache.ContainsKey(record.ID))
            //        calcCache.Add(record.ID, new ScoreCalculator(record));
            //}
            //#endregion

            // 取得學期歷程
            Config._StudSemesterHistoryItemDict.Clear();

            List <JHSemesterHistoryRecord> semHisRec = JHSemesterHistory.SelectByStudents(Students);
            // 當畫面學期歷程內的學年度學期與畫面上設定相同,加入
            foreach (JHSemesterHistoryRecord rec in semHisRec)
            {
                foreach (K12.Data.SemesterHistoryItem shi in rec.SemesterHistoryItems)
                {
                    if (shi.SchoolYear == _config.SchoolYear && shi.Semester == _config.Semester)
                    {
                        if (!Config._StudSemesterHistoryItemDict.ContainsKey(shi.RefStudentID))
                        {
                            Config._StudSemesterHistoryItemDict.Add(shi.RefStudentID, shi);
                        }
                    }
                }
            }

            // 取得學生服務學習時數
            Config._SRDict.Clear();
            List <string> sidList = (from data in Students select data.ID).ToList();
            Config._SRDict = Utility.GetServiceLearningDetail(sidList, _config.SchoolYear, _config.Semester);

            #region 產生
            foreach (JHStudentRecord student in Students)
            {
                count++;

                Document        each    = (Document)_template.Clone(true);
                DocumentBuilder builder = new DocumentBuilder(each);

                #region 學生基本資料
                StudentBasicInfo basicInfo = new StudentBasicInfo(builder);
                basicInfo.SetStudent(student);
                #endregion

                //#region 班導師
                //builder.MoveToMergeField("班導師");
                //if (historyCache.ContainsKey(student.ID))
                //    builder.Write(historyCache[student.ID].Teacher);
                //else
                //    builder.Write(string.Empty);
                //#endregion

                #region 各評量成績
                List <HC.JHSCETakeRecord> sceScoreList = null;
                if (sceScoreCache.ContainsKey(student.ID))
                {
                    sceScoreList = sceScoreCache[student.ID];
                }
                else
                {
                    sceScoreList = new List <HC.JHSCETakeRecord>();
                }

                ScoreCalculator studentCalculator = defaultScoreCalculator;
                if (calcIDCache.ContainsKey(student.ID) && calcCache.ContainsKey(calcIDCache[student.ID]))
                {
                    studentCalculator = calcCache[calcIDCache[student.ID]];
                }

                try {
                    StudentExamScore examScore = new StudentExamScore(builder, _config, courseCache);
                    if (scCache.ContainsKey(student.ID))
                    {
                        examScore.SetSubjects(scCache[student.ID]);
                    }
                    examScore.SetColumnMap(columnMapping);
                    examScore.SetCalculator(studentCalculator);
                    examScore.SetData(sceScoreList);
                } catch (Exception erro)
                {
                    e.Cancel = true;
                }

                #endregion

                #region 缺曠獎懲
                List <JHMeritRecord>      meritList      = null;
                List <JHDemeritRecord>    demeritList    = null;
                List <JHAttendanceRecord> attendanceList = null;

                meritList      = (meritCache.ContainsKey(student.ID)) ? meritCache[student.ID] : new List <JHMeritRecord>();
                demeritList    = (demeritCache.ContainsKey(student.ID)) ? demeritCache[student.ID] : new List <JHDemeritRecord>();
                attendanceList = (attendanceCache.ContainsKey(student.ID)) ? attendanceCache[student.ID] : new List <JHAttendanceRecord>();

                StudentMoralScore moral = new StudentMoralScore(builder, _config, periodMapping, absenceList);
                moral.SetData(meritList, demeritList, attendanceList);
                #endregion

                foreach (Section sec in each.Sections)
                {
                    _doc.Sections.Add(_doc.ImportNode(sec, true));
                }

                //回報進度
                _worker.ReportProgress((int)(count * 100.0 / total));
            }

            #region 全域 MergeField
            List <string> globalFieldName  = new List <string>();
            List <object> globalFieldValue = new List <object>();

            globalFieldName.Add("學校名稱");
            globalFieldValue.Add(K12.Data.School.ChineseName);

            globalFieldName.Add("學年度");
            //globalFieldValue.Add(K12.Data.School.DefaultSchoolYear);
            globalFieldValue.Add(_config.SchoolYear.ToString());

            globalFieldName.Add("學期");
            //globalFieldValue.Add(K12.Data.School.DefaultSemester);
            globalFieldValue.Add(_config.Semester.ToString());

            globalFieldName.Add("統計期間");
            globalFieldValue.Add(_config.StartDate.ToShortDateString() + " ~ " + _config.EndDate.ToShortDateString());

            globalFieldName.Add("列印日期");
            globalFieldValue.Add(DateConvert.CDate(DateTime.Now.ToString("yyyy/MM/dd")) + " " + DateTime.Now.ToString("HH:mm:ss"));

            string chancellor, eduDirector, stuDirector;
            chancellor = eduDirector = stuDirector = string.Empty;

            XmlElement schoolInfo         = K12.Data.School.Configuration["學校資訊"].PreviousData;
            XmlElement chancellorElement  = (XmlElement)schoolInfo.SelectSingleNode("ChancellorChineseName");
            XmlElement eduDirectorElement = (XmlElement)schoolInfo.SelectSingleNode("EduDirectorName");
            XmlElement stuDirectorElement = (XmlElement)schoolInfo.SelectSingleNode("StuDirectorName");

            if (chancellorElement != null)
            {
                chancellor = chancellorElement.InnerText;
            }
            if (eduDirectorElement != null)
            {
                eduDirector = eduDirectorElement.InnerText;
            }
            if (stuDirectorElement != null)
            {
                stuDirector = stuDirectorElement.InnerText;
            }

            globalFieldName.Add("校長");
            globalFieldValue.Add(chancellor);

            globalFieldName.Add("教務主任");
            globalFieldValue.Add(eduDirector);

            globalFieldName.Add("學務主任");
            globalFieldValue.Add(stuDirector);

            _doc.MailMerge.Execute(globalFieldName.ToArray(), globalFieldValue.ToArray());
            #endregion

            #endregion
        }
Beispiel #25
0
        public override void InitializeExport(SmartSchool.API.PlugIn.Export.ExportWizard wizard)
        {
            // 2018.09.06 [ischoolKingdom] Vicky依據 [12-01][01] 多學期成績排名 項目,增加 "領域", "科目", "節數(權重)", "學分" 項目資料。
            // 2018.09.07 [ischoolKingdom] Vicky依據 [12-01][01] 多學期成績排名 新需求更動項目排序。
            wizard.ExportableFields.AddRange("學年度", "學期", "課程名稱", "領域", "科目", "節數(權重)", "學分", "評量名稱", "定期分數", "平時分數", "文字描述");
            wizard.ExportPackage += delegate(object sender, SmartSchool.API.PlugIn.Export.ExportPackageEventArgs e)
            {
                //學生資訊
                List <JHStudentRecord> students = JHStudent.SelectByIDs(e.List);
                //學生修課資訊
                Dictionary <string, List <JHSCAttendRecord> > scattends = new Dictionary <string, List <JHSchool.Data.JHSCAttendRecord> >();
                //學生修習的課程
                Dictionary <string, JHCourseRecord> courses = new Dictionary <string, JHSchool.Data.JHCourseRecord>();
                //評量成績 key: SCAttendID
                Dictionary <string, List <HC.JHSCETakeRecord> > sces = new Dictionary <string, List <HC.JHSCETakeRecord> >();
                //試別資訊
                Dictionary <string, JHExamRecord> exams = new Dictionary <string, JHSchool.Data.JHExamRecord>();

                #region 取得修課記錄
                foreach (JHSCAttendRecord record in JHSCAttend.SelectByStudentIDAndCourseID(e.List, new string[] { }))
                {
                    if (!scattends.ContainsKey(record.RefStudentID))
                    {
                        scattends.Add(record.RefStudentID, new List <JHSchool.Data.JHSCAttendRecord>());
                    }
                    scattends[record.RefStudentID].Add(record);

                    if (!courses.ContainsKey(record.RefCourseID))
                    {
                        courses.Add(record.RefCourseID, null);
                    }
                }
                #endregion

                #region 取得課程資訊
                foreach (JHCourseRecord record in JHCourse.SelectByIDs(new List <string>(courses.Keys)))
                {
                    if (courses.ContainsKey(record.ID))
                    {
                        courses[record.ID] = record;
                    }
                }
                #endregion

                #region 取得試別資訊
                foreach (JHExamRecord exam in JHExam.SelectAll())
                {
                    if (!exams.ContainsKey(exam.ID))
                    {
                        exams.Add(exam.ID, exam);
                    }
                }
                #endregion

                #region 取得評量成績
                foreach (HC.JHSCETakeRecord record in JHSCETake.SelectByStudentAndCourse(new List <string>(scattends.Keys), new List <string>(courses.Keys)).AsHCJHSCETakeRecords())
                {
                    if (!sces.ContainsKey(record.RefSCAttendID))
                    {
                        sces.Add(record.RefSCAttendID, new List <HC.JHSCETakeRecord>());
                    }
                    sces[record.RefSCAttendID].Add(record);
                }
                #endregion


                #region 取得評量成績缺考暨免試設定

                PluginMain.ScoreTextMap.Clear();
                PluginMain.ScoreValueMap.Clear();
                Framework.ConfigData cd = JHSchool.School.Configuration["評量成績缺考暨免試設定"];
                if (!string.IsNullOrEmpty(cd["評量成績缺考暨免試設定"]))
                {
                    XmlElement element = Framework.XmlHelper.LoadXml(cd["評量成績缺考暨免試設定"]);

                    foreach (XmlElement each in element.SelectNodes("Setting"))
                    {
                        var     UseText          = each.SelectSingleNode("UseText").InnerText;
                        var     AllowCalculation = bool.Parse(each.SelectSingleNode("AllowCalculation").InnerText);
                        decimal Score;
                        decimal.TryParse(each.SelectSingleNode("Score").InnerText, out Score);
                        var Active   = bool.Parse(each.SelectSingleNode("Active").InnerText);
                        var UseValue = decimal.Parse(each.SelectSingleNode("UseValue").InnerText);

                        if (Active)
                        {
                            if (!PluginMain.ScoreTextMap.ContainsKey(UseText))
                            {
                                PluginMain.ScoreTextMap.Add(UseText, new ScoreMap
                                {
                                    UseText          = UseText,
                                    AllowCalculation = AllowCalculation,
                                    Score            = Score,
                                    Active           = Active,
                                    UseValue         = UseValue,
                                });
                            }
                            if (!PluginMain.ScoreValueMap.ContainsKey(UseValue))
                            {
                                PluginMain.ScoreValueMap.Add(UseValue, new ScoreMap
                                {
                                    UseText          = UseText,
                                    AllowCalculation = AllowCalculation,
                                    Score            = Score,
                                    Active           = Active,
                                    UseValue         = UseValue,
                                });
                            }
                        }
                    }
                }

                #endregion

                #region 產生 Row Data
                try
                {
                    foreach (JHStudentRecord stu in students)
                    {
                        if (!scattends.ContainsKey(stu.ID))
                        {
                            continue;
                        }

                        foreach (JHSCAttendRecord record in scattends[stu.ID])
                        {
                            if (!sces.ContainsKey(record.ID))
                            {
                                continue;
                            }

                            sces[record.ID].Sort(delegate(HC.JHSCETakeRecord x, HC.JHSCETakeRecord y)
                            {
                                return(x.RefExamID.CompareTo(y.RefExamID));
                            });

                            foreach (HC.JHSCETakeRecord sce in sces[record.ID])
                            {
                                string examName = sce.RefExamID;
                                if (exams.ContainsKey(sce.RefExamID))
                                {
                                    examName = exams[sce.RefExamID].Name;
                                }

                                RowData row = new RowData();
                                row.ID = stu.ID;
                                foreach (string field in e.ExportFields)
                                {
                                    if (wizard.ExportableFields.Contains(field))
                                    {
                                        switch (field)
                                        {
                                        case "學年度": row.Add(field, "" + courses[record.RefCourseID].SchoolYear); break;

                                        case "學期": row.Add(field, "" + courses[record.RefCourseID].Semester); break;

                                        case "課程名稱": row.Add(field, courses[record.RefCourseID].Name); break;

                                        // 2018.09.06 [ischoolKingdom] Vicky依據 [12-01][01] 多學期成績排名 項目,增加 "領域", "科目", "節數(權重)", "學分" 項目資料。
                                        case "領域": row.Add(field, courses[record.RefCourseID].Domain); break;

                                        case "科目": row.Add(field, courses[record.RefCourseID].Subject); break;

                                        case "節數(權重)": row.Add(field, "" + courses[record.RefCourseID].Period); break;

                                        case "學分": row.Add(field, "" + courses[record.RefCourseID].Credit); break;

                                        case "評量名稱": row.Add(field, examName); break;

                                        case "定期分數":
                                            if (sce.Score.HasValue)
                                            {
                                                if (PluginMain.ScoreValueMap.ContainsKey(sce.Score.Value))
                                                {
                                                    row.Add(field, PluginMain.ScoreValueMap[sce.Score.Value].UseText);
                                                }
                                                else
                                                {
                                                    row.Add(field, sce.Score.Value + "");
                                                }
                                            }
                                            else
                                            {
                                                row.Add(field, "");
                                            }
                                            break;

                                        case "平時分數":
                                            if (sce.AssignmentScore.HasValue)
                                            {
                                                if (PluginMain.ScoreValueMap.ContainsKey(sce.AssignmentScore.Value))
                                                {
                                                    row.Add(field, PluginMain.ScoreValueMap[sce.AssignmentScore.Value].UseText);
                                                }
                                                else
                                                {
                                                    row.Add(field, sce.AssignmentScore.Value + "");
                                                }
                                            }
                                            else
                                            {
                                                row.Add(field, "");
                                            }
                                            break;

                                        case "文字描述": row.Add(field, sce.Text); break;
                                        }
                                    }
                                }
                                e.Items.Add(row);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    ;       // MessageBox.Show(ex.Message);
                }
                #endregion

                FISCA.LogAgent.ApplicationLog.Log("成績系統.匯入匯出", "匯出評量成績", "總共匯出" + e.Items.Count + "筆評量成績。");
            };
        }
Beispiel #26
0
        void bkwNotPassComputer_DoWork(object sender, DoWorkEventArgs e)
        {
            string        fileName        = (string)((object[])e.Argument)[0];
            List <string> courseFieldList = (List <string>)((object[])e.Argument)[1];
            List <string> exportFieldList = (List <string>)((object[])e.Argument)[2];
            Dictionary <ManualResetEvent, List <RowData> > Filler = (Dictionary <ManualResetEvent, List <RowData> >)((object[])e.Argument)[3];
            double   totleProgress   = 0.0;
            double   packageProgress = 100.0 / Filler.Count;
            Workbook report          = new Workbook();

            report.Worksheets[0].Name = _Title;
            ((BackgroundWorker)sender).ReportProgress(1, _Title + " 資料整理中...");
            int RowIndex = 0;
            int i        = 0;

            foreach (string field in exportFieldList)
            {
                if (courseFieldList.Contains(field))
                {
                    courseFieldList.Remove(field);
                }
            }
            //填表頭
            for (; i < courseFieldList.Count; i++)
            {
                report.Worksheets[0].Cells[0, i].PutValue(courseFieldList[i]);
            }
            for (int j = 0; j < exportFieldList.Count; j++)
            {
                report.Worksheets[0].Cells[0, i + j].PutValue(exportFieldList[j]);
            }
            RowIndex = 1;
            foreach (ManualResetEvent eve in Filler.Keys)
            {
                eve.WaitOne();
                if (RowIndex <= 65535)
                {
                    double miniProgress = Filler[eve].Count == 0 ? 1 : packageProgress / Filler[eve].Count;
                    double miniTotle    = 0;
                    foreach (RowData row in Filler[eve])
                    {
                        JHCourseRecord course = null;
                        if (row.ID != "")
                        {
                            course = JHCourse.SelectByID(row.ID);
                        }

                        if (course != null)
                        {
                            if (RowIndex <= 65535)
                            {
                                i = 0;
                                for (; i < courseFieldList.Count; i++)
                                {
                                    switch (courseFieldList[i])
                                    {
                                    case "課程系統編號": report.Worksheets[0].Cells[RowIndex, i].PutValue(course.ID); break;

                                    case "學年度": report.Worksheets[0].Cells[RowIndex, i].PutValue("" + course.SchoolYear); break;

                                    case "學期": report.Worksheets[0].Cells[RowIndex, i].PutValue("" + course.Semester); break;

                                    case "課程名稱": report.Worksheets[0].Cells[RowIndex, i].PutValue(course.Name); break;

                                    case "社團名稱": report.Worksheets[0].Cells[RowIndex, i].PutValue(course.Name); break;

                                    default:
                                        break;
                                    }
                                }
                                for (int j = 0; j < exportFieldList.Count; j++)
                                {
                                    report.Worksheets[0].Cells[RowIndex, i + j].PutValue(row.ContainsKey(exportFieldList[j]) ? row[exportFieldList[j]] : "");
                                }
                            }
                            RowIndex++;
                        }
                        miniTotle += miniProgress;
                        ((BackgroundWorker)sender).ReportProgress((int)(totleProgress + miniTotle), _Title + " 處理中...");
                    }
                }
                totleProgress += packageProgress;
                ((BackgroundWorker)sender).ReportProgress((int)(totleProgress), _Title + " 處理中...");
            }
            for (int k = 0; k < courseFieldList.Count + exportFieldList.Count; k++)
            {
                report.Worksheets[0].AutoFitColumn(k, 0, 150);
            }
            report.Worksheets[0].FreezePanes(1, 0, 1, courseFieldList.Count + exportFieldList.Count);
            e.Result = new object[] { report, fileName, RowIndex > 65535 };
        }
        public override void InitializeExport(SmartSchool.API.PlugIn.Export.ExportWizard wizard)
        {
            wizard.ExportableFields.AddRange("學年度", "學期", "課程名稱", "評量名稱", "定期分數", "平時分數", "文字描述");
            wizard.ExportPackage += delegate(object sender, SmartSchool.API.PlugIn.Export.ExportPackageEventArgs e)
            {
                //學生資訊
                List <JHStudentRecord> students = JHStudent.SelectByIDs(e.List);
                //學生修課資訊
                Dictionary <string, List <JHSCAttendRecord> > scattends = new Dictionary <string, List <JHSchool.Data.JHSCAttendRecord> >();
                //學生修習的課程
                Dictionary <string, JHCourseRecord> courses = new Dictionary <string, JHSchool.Data.JHCourseRecord>();
                //評量成績 key: SCAttendID
                Dictionary <string, List <HC.JHSCETakeRecord> > sces = new Dictionary <string, List <HC.JHSCETakeRecord> >();
                //試別資訊
                Dictionary <string, JHExamRecord> exams = new Dictionary <string, JHSchool.Data.JHExamRecord>();

                #region 取得修課記錄
                foreach (JHSCAttendRecord record in JHSCAttend.SelectByStudentIDAndCourseID(e.List, new string[] { }))
                {
                    if (!scattends.ContainsKey(record.RefStudentID))
                    {
                        scattends.Add(record.RefStudentID, new List <JHSchool.Data.JHSCAttendRecord>());
                    }
                    scattends[record.RefStudentID].Add(record);

                    if (!courses.ContainsKey(record.RefCourseID))
                    {
                        courses.Add(record.RefCourseID, null);
                    }
                }
                #endregion

                #region 取得課程資訊
                foreach (JHCourseRecord record in JHCourse.SelectByIDs(new List <string>(courses.Keys)))
                {
                    if (courses.ContainsKey(record.ID))
                    {
                        courses[record.ID] = record;
                    }
                }
                #endregion

                #region 取得試別資訊
                foreach (JHExamRecord exam in JHExam.SelectAll())
                {
                    if (!exams.ContainsKey(exam.ID))
                    {
                        exams.Add(exam.ID, exam);
                    }
                }
                #endregion

                #region 取得評量成績
                foreach (HC.JHSCETakeRecord record in JHSCETake.SelectByStudentAndCourse(new List <string>(scattends.Keys), new List <string>(courses.Keys)).AsHCJHSCETakeRecords())
                {
                    if (!sces.ContainsKey(record.RefSCAttendID))
                    {
                        sces.Add(record.RefSCAttendID, new List <HC.JHSCETakeRecord>());
                    }
                    sces[record.RefSCAttendID].Add(record);
                }
                #endregion

                #region 產生 Row Data
                foreach (JHStudentRecord stu in students)
                {
                    if (!scattends.ContainsKey(stu.ID))
                    {
                        continue;
                    }

                    foreach (JHSCAttendRecord record in scattends[stu.ID])
                    {
                        if (!sces.ContainsKey(record.ID))
                        {
                            continue;
                        }

                        sces[record.ID].Sort(delegate(HC.JHSCETakeRecord x, HC.JHSCETakeRecord y)
                        {
                            return(x.RefExamID.CompareTo(y.RefExamID));
                        });

                        foreach (HC.JHSCETakeRecord sce in sces[record.ID])
                        {
                            string examName = sce.RefExamID;
                            if (exams.ContainsKey(sce.RefExamID))
                            {
                                examName = exams[sce.RefExamID].Name;
                            }

                            RowData row = new RowData();
                            row.ID = stu.ID;
                            foreach (string field in e.ExportFields)
                            {
                                if (wizard.ExportableFields.Contains(field))
                                {
                                    switch (field)
                                    {
                                    case "學年度": row.Add(field, "" + courses[record.RefCourseID].SchoolYear); break;

                                    case "學期": row.Add(field, "" + courses[record.RefCourseID].Semester); break;

                                    case "課程名稱": row.Add(field, courses[record.RefCourseID].Name); break;

                                    case "評量名稱": row.Add(field, examName); break;

                                    case "定期分數": row.Add(field, "" + sce.Score); break;

                                    case "平時分數": row.Add(field, "" + sce.AssignmentScore); break;

                                    case "文字描述": row.Add(field, sce.Text); break;
                                    }
                                }
                            }
                            e.Items.Add(row);
                        }
                    }
                }
                #endregion

                FISCA.LogAgent.ApplicationLog.Log("成績系統.匯入匯出", "匯出評量成績", "總共匯出" + e.Items.Count + "筆評量成績。");
            };
        }
Beispiel #28
0
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            double total = Students.Count;
            double count = 0;

            _worker.ReportProgress(0);

            List <string> studentIDs = Students.Select(x => x.ID).ToList();

            #region 快取資料

            //獎勵
            // 1.依學生編號、開始日期、結束日期,取得學生獎勵紀錄
            // 2.依學生編號進行分群
            Dictionary <string, List <JHMeritRecord> > meritCache = new Dictionary <string, List <JHMeritRecord> >();
            foreach (JHMeritRecord record in JHMerit.Select(studentIDs, _config.StartDate, _config.EndDate, null, null, null, null))
            {
                if (!meritCache.ContainsKey(record.RefStudentID))
                {
                    meritCache.Add(record.RefStudentID, new List <JHMeritRecord>());
                }
                meritCache[record.RefStudentID].Add(record);
            }

            //懲戒
            // 1.依學生編號、開始日期、結束日期,取得學生懲戒紀錄
            // 2.依學生編號進行分群
            Dictionary <string, List <JHDemeritRecord> > demeritCache = new Dictionary <string, List <JHDemeritRecord> >();
            foreach (JHDemeritRecord record in JHDemerit.Select(studentIDs, _config.StartDate, _config.EndDate, null, null, null, null))
            {
                if (!demeritCache.ContainsKey(record.RefStudentID))
                {
                    demeritCache.Add(record.RefStudentID, new List <JHDemeritRecord>());
                }
                demeritCache[record.RefStudentID].Add(record);
            }

            //缺曠
            // 1.依學生編號、開始日期、結束日期,取得學生缺曠紀錄
            // 2.依學生編號進行分群
            Dictionary <string, List <JHAttendanceRecord> > attendanceCache = new Dictionary <string, List <JHAttendanceRecord> >();
            foreach (JHAttendanceRecord record in JHAttendance.Select(studentIDs, _config.StartDate, _config.EndDate, null, null, null))
            {
                if (!attendanceCache.ContainsKey(record.RefStudentID))
                {
                    attendanceCache.Add(record.RefStudentID, new List <JHAttendanceRecord>());
                }
                attendanceCache[record.RefStudentID].Add(record);
            }

            // 建立平時評量與修課成績Idx Key studentID
            Dictionary <string, List <JHSCAttendRecord> > _studAttendRecDict = new Dictionary <string, List <JHSCAttendRecord> >();


            //修課紀錄
            // 1.依學生編號、學年度、學期,取得修課紀錄
            // 2.
            List <string> courseIDs = new List <string>();
            List <string> attendIDs = new List <string>();
            Dictionary <string, List <string> > scCache = new Dictionary <string, List <string> >();
            foreach (var attend in JHSCAttend.Select(studentIDs, null, null, "" + _config.SchoolYear, "" + _config.Semester))
            {
                attendIDs.Add(attend.ID);
                if (!scCache.ContainsKey(attend.RefStudentID))
                {
                    scCache.Add(attend.RefStudentID, new List <string>());
                }
                scCache[attend.RefStudentID].Add(attend.RefCourseID);
                if (!courseIDs.Contains(attend.RefCourseID))
                {
                    courseIDs.Add(attend.RefCourseID);
                }

                // 建立評量與修課成績
                if (_studAttendRecDict.ContainsKey(attend.RefStudentID))
                {
                    _studAttendRecDict[attend.RefStudentID].Add(attend);
                }
                else
                {
                    List <JHSCAttendRecord> atten = new List <JHSCAttendRecord>();
                    atten.Add(attend);
                    _studAttendRecDict.Add(attend.RefStudentID, atten);
                }
            }

            //課程
            // 1.依課程編號取得課程紀錄
            // 2.略過不列入成績計算的課程
            JHCourse.RemoveByIDs(courseIDs);
            Dictionary <string, JHCourseRecord> courseCache = JHCourse.SelectByIDs(courseIDs).Where(x => x.CalculationFlag != "2").ToDictionary(x => x.ID);

            //試別資訊: 取得所有試別
            Dictionary <string, JHExamRecord> examCache = JHExam.SelectAll().ToDictionary(x => x.ID);

            // 取得社團ExamID
            List <string> NExamIDList = new List <string> ();
            foreach (JHExamRecord rec in JHExam.SelectAll())
            {
                if (rec.Name.IndexOf("社團") > -1)
                {
                    NExamIDList.Add(rec.ID);
                }
            }

            //評量成績
            // 1.依修課記錄及所有試別取得評量成績
            // 2.依第1點的評量成績取得試別編號 (實際學生評量成績中的試別編號)
            // 3.依學生編號進行分群
            Dictionary <string, List <KH.JHSCETakeRecord> > sceScoreCache = new Dictionary <string, List <KH.JHSCETakeRecord> >();
            List <string> validExamIDs = new List <string>();

            // 檢查有修課才讀取成績
            if (attendIDs.Count > 0 && examCache.Count > 0)
            {
                foreach (JHSCETakeRecord record in JHSCETake.Select(null, null, examCache.Keys, null, attendIDs))
                {
                    if (!NExamIDList.Contains(record.RefExamID))
                    {
                        if (!validExamIDs.Contains(record.RefExamID))
                        {
                            validExamIDs.Add(record.RefExamID);
                        }
                    }

                    if (!sceScoreCache.ContainsKey(record.RefStudentID))
                    {
                        sceScoreCache.Add(record.RefStudentID, new List <KH.JHSCETakeRecord>());
                    }
                    sceScoreCache[record.RefStudentID].Add(new KH.JHSCETakeRecord(record));
                }
            }

            //將『所有試別編號』與『實際學生評量成績中的試別編號』做交集,以取得使用管理的試別次序
            //假設『所有試別編號』為1,4,3,5
            //假設『實際學生評量成績中的試別編號』為3,4,1
            //交集後的結果為1,4,3
            validExamIDs = examCache.Keys.Intersect(validExamIDs).ToList();

            validExamIDs.Add("平時評量");
            //validExamIDs.Add("課程總成績");

            // 取得學生成績計算規則
            // 如果學生沒有計算規則一律用預設,預設進位方式取到小數點第2位
            ScoreCalculator defaultScoreCalculator = new ScoreCalculator(null);
            //key: ScoreCalcRuleID
            Dictionary <string, ScoreCalculator> calcCache = new Dictionary <string, ScoreCalculator>();
            //key: StudentID, val: ScoreCalcRuleID
            Dictionary <string, string> calcIDCache = new Dictionary <string, string>();

            List <string> scoreCalcRuleIDList = new List <string>();

            // 取得學生計算規則的ID,建立對照表
            // 如果學生身上有指定成績計算規則,就以學生身上成績計算規則為主
            // 如果學生身上沒有指定成績計算規則,就以學生所屬班級成績計算規則為主
            foreach (JHStudentRecord student in _config.Students)
            {
                string calcID = string.Empty;
                if (!string.IsNullOrEmpty(student.OverrideScoreCalcRuleID))
                {
                    calcID = student.OverrideScoreCalcRuleID;
                }
                else if (student.Class != null && !string.IsNullOrEmpty(student.Class.RefScoreCalcRuleID))
                {
                    calcID = student.Class.RefScoreCalcRuleID;
                }

                if (!string.IsNullOrEmpty(calcID))
                {
                    calcIDCache.Add(student.ID, calcID);
                }
            }
            // 取得計算規則建立成績進位器
            foreach (JHScoreCalcRuleRecord record in JHScoreCalcRule.SelectByIDs(calcIDCache.Values))
            {
                if (!calcCache.ContainsKey(record.ID))
                {
                    calcCache.Add(record.ID, new ScoreCalculator(record));
                }
            }

            #endregion


            #region 判斷領域是否需要展開
            //判斷領域是否展開對照表
            //Key:領域名稱
            //Value:false=展開,true=不展開
            //展開: 詳列該領域下所有科目成績
            //不展開: 只列該領域成績
            Dictionary <string, bool> domains = new Dictionary <string, bool>();

            DomainSubjectSetup domainSubjectSetup = _config.DomainSubjectSetup;
            //使用者設定"只列印領域"
            if (domainSubjectSetup == DomainSubjectSetup.Domain)
            {
                //預設從領域資料管理來的領域名稱皆不展開
                foreach (var domain in JHSchool.Evaluation.Subject.Domains)
                {
                    domains.Add(domain, DomainSubjectExpand.展開);
                }
                //彈性課程一定展開
                if (!domains.ContainsKey(""))
                {
                    domains.Add("", DomainSubjectExpand.展開);
                }
            }
            //使用者設定"只列印科目"
            else if (domainSubjectSetup == DomainSubjectSetup.Subject)
            {
                //預設從領域資料管理來的領域名稱皆展開
                foreach (var domain in JHSchool.Evaluation.Subject.Domains)
                {
                    domains.Add(domain, DomainSubjectExpand.展開);
                }
                //彈性課程一定展開
                if (!domains.ContainsKey(""))
                {
                    domains.Add("", DomainSubjectExpand.展開);
                }
            }
            else
            {
                throw new Exception("請重新儲存一次列印設定");
            }

            _config.PrintDomains = domains;
            #endregion

            #region 建立節次對照
            Dictionary <string, string> periodMapping = JHPeriodMapping.SelectAll().ToDictionary(x => x.Name, y => y.Type);
            #endregion

            #region 假別列表
            List <string> absenceList = JHAbsenceMapping.SelectAll().Select(x => x.Name).ToList();
            #endregion

            #region 依評量試別重新劃分範本
            //如有不懂自求多福
            int             rowCount        = 0;
            DocumentBuilder templateBuilder = new DocumentBuilder(_template);
            templateBuilder.MoveToMergeField("各次評量");
            Font   font       = templateBuilder.Font;
            Cell   examsCell  = templateBuilder.CurrentParagraph.ParentNode as Cell;
            Table  table      = examsCell.ParentRow.ParentTable;
            double width      = examsCell.CellFormat.Width;
            double examWidth  = width / (double)validExamIDs.Count;
            double scoreWidth = width / (double)validExamIDs.Count / 2.0;

            //計算有幾個 Score Row
            foreach (Row row in table.Rows)
            {
                if (row.Cells.Count > 3)
                {
                    rowCount++;
                }
            }

            #region Header Cell
            //建立評量欄位對照表
            Dictionary <string, int> columnMapping = new Dictionary <string, int>();
            int columnShift = 3;
            int columnIndex = 0;

            table.Rows[0].LastCell.Remove();
            table.Rows[1].LastCell.Remove();

            foreach (string examID in validExamIDs)
            {
                columnMapping.Add(examID, columnIndex + columnShift);

                Cell topHeaderCell = new Cell(_template);
                if (examID == "平時評量" || examID == "課程總成績")
                {
                    WordHelper.Write(topHeaderCell, font, examID);
                }
                else
                {
                    WordHelper.Write(topHeaderCell, font, examCache[examID].Name);
                }
                table.Rows[0].Cells.Add(topHeaderCell);

                Cell subHeaderCell1 = new Cell(_template);
                WordHelper.Write(subHeaderCell1, font, "分數", "評量");
                table.Rows[1].Cells.Add(subHeaderCell1);
                columnIndex++;

                Cell subHeaderCell2 = new Cell(_template);
                WordHelper.Write(subHeaderCell2, font, "努力", "程度");
                table.Rows[1].Cells.Add(subHeaderCell2);
                columnIndex++;

                topHeaderCell.CellFormat.Width  = examWidth;
                subHeaderCell1.CellFormat.Width = subHeaderCell2.CellFormat.Width = scoreWidth;

                topHeaderCell.CellFormat.VerticalAlignment  = CellVerticalAlignment.Center;
                subHeaderCell1.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
                subHeaderCell2.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
            }

            WordHelper.MergeVerticalCell(table.Rows[0].Cells[1], 2);
            #endregion

            #region Content Cell
            int shift = 2; //Header has 2 rows
            for (int i = 0; i < rowCount; i++)
            {
                table.Rows[i + shift].LastCell.Remove();

                for (int j = 0; j < validExamIDs.Count * 2; j++)
                {
                    Cell contentCell = new Cell(_template);
                    contentCell.CellFormat.Width             = scoreWidth;
                    contentCell.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;

                    table.Rows[i + shift].Cells.Add(contentCell);
                }
            }
            #endregion

            #endregion

            #region 依節權數設定,在畫面上顯示
            string pcDisplay = string.Empty;
            if (_config.PrintPeriod && _config.PrintCredit)
            {
                pcDisplay = "節/權數";
            }
            else if (_config.PrintPeriod)
            {
                pcDisplay = "節數";
            }
            else if (_config.PrintCredit)
            {
                pcDisplay = "權數";
            }

            templateBuilder.MoveToMergeField("節權數");
            templateBuilder.Write(pcDisplay);
            #endregion

            // 取得學期歷程
            Config._StudSemesterHistoryItemDict.Clear();

            List <JHSemesterHistoryRecord> semHisRec = JHSemesterHistory.SelectByStudents(Students);
            // 當畫面學期歷程內的學年度學期與畫面上設定相同,加入
            foreach (JHSemesterHistoryRecord rec in semHisRec)
            {
                foreach (K12.Data.SemesterHistoryItem shi in rec.SemesterHistoryItems)
                {
                    if (shi.SchoolYear == _config.SchoolYear && shi.Semester == _config.Semester)
                    {
                        if (!Config._StudSemesterHistoryItemDict.ContainsKey(shi.RefStudentID))
                        {
                            Config._StudSemesterHistoryItemDict.Add(shi.RefStudentID, shi);
                        }
                    }
                }
            }

            // 取得學生服務學習時數
            Config._SRDict.Clear();
            List <string> sidList = (from data in Students select data.ID).ToList();
            Config._SRDict = Utility.GetServiceLearningDetail(sidList, _config.SchoolYear, _config.Semester);


            #region 產生
            foreach (JHStudentRecord student in Students)
            {
                count++;

                Document        each    = (Document)_template.Clone(true);
                DocumentBuilder builder = new DocumentBuilder(each);

                #region 學生基本資料
                StudentBasicInfo basicInfo = new StudentBasicInfo(builder);
                basicInfo.SetStudent(student);
                #endregion


                #region 各評量成績
                List <KH.JHSCETakeRecord> sceScoreList = null;
                if (sceScoreCache.ContainsKey(student.ID))
                {
                    sceScoreList = sceScoreCache[student.ID];
                }
                else
                {
                    sceScoreList = new List <KH.JHSCETakeRecord>();
                }

                ScoreCalculator studentCalculator = defaultScoreCalculator;
                if (calcIDCache.ContainsKey(student.ID) && calcCache.ContainsKey(calcIDCache[student.ID]))
                {
                    studentCalculator = calcCache[calcIDCache[student.ID]];
                }

                // 課程成績
                Dictionary <string, JHSCAttendRecord> attendRecDict = new Dictionary <string, JHSCAttendRecord>();
                // 領域成績(平時)
                Dictionary <string, decimal?> domainScDict = new Dictionary <string, decimal?>();
                //// 領域成績(總)
                //Dictionary<string, decimal> domainScDictTT = new Dictionary<string, decimal>();

                if (_studAttendRecDict.ContainsKey(student.ID))
                {
                    foreach (JHSCAttendRecord rec in _studAttendRecDict[student.ID])
                    {
                        if (!attendRecDict.ContainsKey(rec.Course.Subject))
                        {
                            attendRecDict.Add(rec.Course.Subject, rec);
                        }
                    }


                    List <string> tName = (from xx in _studAttendRecDict[student.ID] select xx.Course.Domain).Distinct().ToList();

                    foreach (string Name in tName)
                    {
                        decimal?sc = 0, co = 0;
                        foreach (JHSCAttendRecord rec in _studAttendRecDict[student.ID])
                        {
                            if (rec.Course.Domain == Name)
                            {
                                if (rec.OrdinarilyScore.HasValue && rec.Course.Credit.HasValue)
                                {
                                    sc += (rec.OrdinarilyScore.Value * rec.Course.Credit.Value);
                                    // 有成績才算入
                                    co += rec.Course.Credit.Value;
                                }
                            }
                        }

                        if (co.HasValue && sc.HasValue)
                        {
                            if (co.Value > 0)
                            {
                                if (!domainScDict.ContainsKey(Name))
                                {
                                    domainScDict.Add(Name, (sc.Value / co.Value));
                                }
                            }
                        }
                    }
                }

                //StudentExamScore examScore = new StudentExamScore(builder, _config, courseCache, attendRecDict,domainScDict,domainScDictTT);
                StudentExamScore examScore = new StudentExamScore(builder, _config, courseCache, attendRecDict, domainScDict);
                if (scCache.ContainsKey(student.ID))
                {
                    examScore.SetSubjects(scCache[student.ID]);
                }
                examScore.SetColumnMap(columnMapping);
                examScore.SetEffortMapper(_effortMapper);
                examScore.SetCalculator(studentCalculator);
                examScore.SetData(sceScoreList);
                #endregion

                #region 缺曠獎懲
                List <JHMeritRecord>      meritList      = null;
                List <JHDemeritRecord>    demeritList    = null;
                List <JHAttendanceRecord> attendanceList = null;

                meritList      = (meritCache.ContainsKey(student.ID)) ? meritCache[student.ID] : new List <JHMeritRecord>();
                demeritList    = (demeritCache.ContainsKey(student.ID)) ? demeritCache[student.ID] : new List <JHDemeritRecord>();
                attendanceList = (attendanceCache.ContainsKey(student.ID)) ? attendanceCache[student.ID] : new List <JHAttendanceRecord>();

                StudentMoralScore moral = new StudentMoralScore(builder, _config, periodMapping, absenceList);
                moral.SetData(meritList, demeritList, attendanceList);
                #endregion

                foreach (Section sec in each.Sections)
                {
                    _doc.Sections.Add(_doc.ImportNode(sec, true));
                }

                //回報進度
                _worker.ReportProgress((int)(count * 100.0 / total));
            }

            #region 全域 MergeField
            List <string> globalFieldName  = new List <string>();
            List <object> globalFieldValue = new List <object>();

            globalFieldName.Add("學校名稱");
            globalFieldValue.Add(K12.Data.School.ChineseName);

            globalFieldName.Add("學年度");
            globalFieldValue.Add(_config.SchoolYear.ToString());
            //globalFieldValue.Add(K12.Data.School.DefaultSchoolYear);

            globalFieldName.Add("學期");
            globalFieldValue.Add(_config.Semester.ToString());
            //globalFieldValue.Add(K12.Data.School.DefaultSemester);

            globalFieldName.Add("統計期間");
            globalFieldValue.Add(_config.StartDate.ToShortDateString() + " ~ " + _config.EndDate.ToShortDateString());

            globalFieldName.Add("列印日期");
            globalFieldValue.Add(DateConvert.CDate(DateTime.Now.ToString("yyyy/MM/dd")) + " " + DateTime.Now.ToString("HH:mm:ss"));

            string chancellor, eduDirector, stuDirector;
            chancellor = eduDirector = stuDirector = string.Empty;

            XmlElement schoolInfo         = K12.Data.School.Configuration["學校資訊"].PreviousData;
            XmlElement chancellorElement  = (XmlElement)schoolInfo.SelectSingleNode("ChancellorChineseName");
            XmlElement eduDirectorElement = (XmlElement)schoolInfo.SelectSingleNode("EduDirectorName");
            XmlElement stuDirectorElement = (XmlElement)schoolInfo.SelectSingleNode("StuDirectorName");

            if (chancellorElement != null)
            {
                chancellor = chancellorElement.InnerText;
            }
            if (eduDirectorElement != null)
            {
                eduDirector = eduDirectorElement.InnerText;
            }
            if (stuDirectorElement != null)
            {
                stuDirector = stuDirectorElement.InnerText;
            }

            globalFieldName.Add("校長");
            globalFieldValue.Add(chancellor);

            globalFieldName.Add("教務主任");
            globalFieldValue.Add(eduDirector);

            globalFieldName.Add("學務主任");
            globalFieldValue.Add(stuDirector);

            _doc.MailMerge.Execute(globalFieldName.ToArray(), globalFieldValue.ToArray());
            #endregion

            #endregion
        }
        /// <summary>
        /// 根據多筆課程系統編號取得課程
        /// </summary>
        /// <param name="CourseIDs"></param>
        /// <returns></returns>
        public static List <AssignmentExamCourseRecord> SelectByIDs(IEnumerable <string> CourseIDs)
        {
            JHCourse.RemoveByIDs(CourseIDs);

            return(SelectByIDs <AssignmentExamCourseRecord>(CourseIDs));
        }
Beispiel #30
0
        public ImportStartupForm()
        {
            // 每次開啟,就重新載入 代碼對照
            KaoHsiung.ReaderScoreImport_DomainMakeUp.Mapper.ClassCodeMapper.Instance.Reload();
            KaoHsiung.ReaderScoreImport_DomainMakeUp.Mapper.ExamCodeMapper.Instance.Reload();
            KaoHsiung.ReaderScoreImport_DomainMakeUp.Mapper.DomainCodeMapper.Instance.Reload();

            InitializeComponent();
            InitializeSemesters();

            _effortMapper = new EffortMapper();

            // 載入預設儲存值
            LoadConfigData();

            _worker = new BackgroundWorker();
            _worker.WorkerReportsProgress = true;
            _worker.ProgressChanged      += delegate(object sender, ProgressChangedEventArgs e)
            {
                lblMessage.Text = "" + e.UserState;
            };
            _worker.DoWork += delegate(object sender, DoWorkEventArgs e)
            {
                //將錯誤訊息刪光,以便重新統計
                msgList.Clear();


                #region Worker DoWork
                _worker.ReportProgress(0, "檢查讀卡文字格式…");

                #region 檢查文字檔
                ValidateTextFiles  vtf      = new ValidateTextFiles(intStudentNumberLenght.Value);
                ValidateTextResult vtResult = vtf.CheckFormat(_files);
                if (vtResult.Error)
                {
                    e.Result = vtResult;
                    return;
                }
                #endregion

                //文字檔轉 RawData
                RawDataCollection rdCollection = new RawDataCollection();
                rdCollection.ConvertFromFiles(_files);

                //RawData 轉 DataRecord
                DataRecordCollection drCollection = new DataRecordCollection();
                drCollection.ConvertFromRawData(rdCollection);

                _rawDataValidator    = new DataValidator <RawData>();
                _dataRecordValidator = new DataValidator <DataRecord>();

                #region 取得驗證需要的資料
                JHCourse.RemoveAll();
                _worker.ReportProgress(0, "取得學生資料…");
                List <JHStudentRecord> studentList = GetInSchoolStudents();

                List <string> s_ids = new List <string>();
                Dictionary <string, string> studentNumberToStudentIDs = new Dictionary <string, string>();
                foreach (JHStudentRecord student in studentList)
                {
                    string sn = SCValidatorCreator.GetStudentNumberFormat(student.StudentNumber);
                    if (!studentNumberToStudentIDs.ContainsKey(sn))
                    {
                        studentNumberToStudentIDs.Add(sn, student.ID);
                    }
                }

                //紀錄現在所有txt 上 的學號,以處理重覆學號學號問題
                List <string> s_numbers = new List <string>();


                foreach (var dr in drCollection)
                {
                    if (studentNumberToStudentIDs.ContainsKey(dr.StudentNumber))
                    {
                        s_ids.Add(studentNumberToStudentIDs[dr.StudentNumber]);
                    }
                    else
                    {
                        //學號不存在系統中,下面的Validator 會進行處理
                    }

                    //2017/1/8 穎驊註解, 原本的程式碼並沒有驗證學號重覆的問題,且無法在他Validator 的處理邏輯加入,故在此驗證
                    if (!s_numbers.Contains(dr.StudentNumber))
                    {
                        s_numbers.Add(dr.StudentNumber);
                    }
                    else
                    {
                        msgList.Add("學號:" + dr.StudentNumber + ",資料重覆,請檢察資料來源txt是否有重覆填寫的學號資料。");
                    }
                }

                studentList.Clear();

                _worker.ReportProgress(0, "取得學期領域成績…");
                List <JHSemesterScoreRecord> jhssr_list = JHSemesterScore.SelectBySchoolYearAndSemester(s_ids, SchoolYear, Semester);

                #endregion

                #region 註冊驗證
                _worker.ReportProgress(0, "載入驗證規則…");
                _rawDataValidator.Register(new DomainCodeValidator());
                _rawDataValidator.Register(new ClassCodeValidator());
                _rawDataValidator.Register(new ExamCodeValidator());

                SCValidatorCreator scCreator = new SCValidatorCreator(JHStudent.SelectByIDs(s_ids));
                _dataRecordValidator.Register(scCreator.CreateStudentValidator());
                //_dataRecordValidator.Register(new ExamValidator(examList));
                //_dataRecordValidator.Register(scCreator.CreateSCAttendValidator());
                //_dataRecordValidator.Register(new CourseExamValidator(scCreator.StudentCourseInfo, aeList, examList));
                #endregion

                #region 進行驗證
                _worker.ReportProgress(0, "進行驗證中…");


                foreach (RawData rawData in rdCollection)
                {
                    List <string> msgs = _rawDataValidator.Validate(rawData);
                    msgList.AddRange(msgs);
                }
                if (msgList.Count > 0)
                {
                    e.Result = msgList;
                    return;
                }

                foreach (DataRecord dataRecord in drCollection)
                {
                    List <string> msgs = _dataRecordValidator.Validate(dataRecord);
                    msgList.AddRange(msgs);
                }
                if (msgList.Count > 0)
                {
                    e.Result = msgList;
                    return;
                }
                #endregion

                #region 取得學生的評量成績
                _duplicateMakeUpScoreList.Clear();
                _updateMakeUpScoreList.Clear();

                //Dictionary<string, JHSCETakeRecord> sceList = new Dictionary<string, JHSCETakeRecord>();
                //FunctionSpliter<string, JHSCETakeRecord> spliterSCE = new FunctionSpliter<string, JHSCETakeRecord>(300, 3);
                //spliterSCE.Function = delegate(List<string> part)
                //{
                //    return JHSCETake.Select(null, null, null, null, part);
                //};
                //foreach (JHSCETakeRecord sce in spliterSCE.Execute(scaIDs.ToList()))
                //{
                //    string key = GetCombineKey(sce.RefStudentID, sce.RefCourseID, sce.RefExamID);
                //    if (!sceList.ContainsKey(key))
                //        sceList.Add(key, sce);
                //}

                //Dictionary<string, JHExamRecord> examTable = new Dictionary<string, JHExamRecord>();
                //Dictionary<string, JHSCAttendRecord> scaTable = new Dictionary<string, JHSCAttendRecord>();

                //foreach (JHExamRecord exam in examList)
                //    if (!examTable.ContainsKey(exam.Name))
                //        examTable.Add(exam.Name, exam);

                //foreach (JHSCAttendRecord sca in scaList)
                //{
                //    string key = GetCombineKey(sca.RefStudentID, sca.RefCourseID);
                //    if (!scaTable.ContainsKey(key))
                //        scaTable.Add(key, sca);
                //}

                //2018/1/8 穎驊新增
                //填寫補考成績
                foreach (DataRecord dr in drCollection)
                {
                    // 利用學號 將學生的isd 對應出來
                    string s_id = studentNumberToStudentIDs[dr.StudentNumber];

                    // 紀錄學生是否有學期成績,如果連學期成績都沒有,本補考成績將會無法匯入(因為不合理)
                    bool haveSemesterRecord = false;

                    foreach (JHSemesterScoreRecord jhssr in jhssr_list)
                    {
                        if (jhssr.RefStudentID == s_id)
                        {
                            haveSemesterRecord = true;

                            if (jhssr.Domains.ContainsKey(dr.Domain))
                            {
                                // 假如原本已經有補考成績,必須將之加入waring_list,讓使用者決定是否真的要覆蓋
                                if (jhssr.Domains[dr.Domain].ScoreMakeup != null)
                                {
                                    string warning = "學號:" + dr.StudentNumber + "學生,在學年度: " + SchoolYear + ",學期: " + Semester + ",領域: " + dr.Domain + "已有補考成績: " + jhssr.Domains[dr.Domain].ScoreMakeup + ",本次匯入將會將其覆蓋取代。";

                                    _duplicateMakeUpScoreList.Add(jhssr);

                                    if (!msg_DuplicatedDict.ContainsKey(s_id))
                                    {
                                        msg_DuplicatedDict.Add(s_id, warning);
                                    }
                                    else
                                    {
                                    }

                                    jhssr.Domains[dr.Domain].ScoreMakeup = dr.Score;

                                    _updateMakeUpScoreList.Add(jhssr);
                                }
                                else
                                {
                                    jhssr.Domains[dr.Domain].ScoreMakeup = dr.Score;

                                    _updateMakeUpScoreList.Add(jhssr);
                                }
                            }
                            else
                            {
                                // 2018/1/8 穎驊註解,針對假如該學生在當學期成績卻沒有其領域成績時,跳出提醒,因為正常情境是領域成績計算出來不及格,才需要補考。
                                msgList.Add("學號:" + dr.StudentNumber + "學生,在學年度:" + SchoolYear + ",學期:" + Semester + ",並無領域:" + dr.Domain + "成績,請先至學生上確認是否已有結算資料。");
                            }
                        }
                    }

                    if (!haveSemesterRecord)
                    {
                        msgList.Add("學號:" + dr.StudentNumber + "學生,在學年度:" + SchoolYear + ",學期:" + Semester + ",並無學期成績,請先至學生上確認是否已有結算資料。");
                    }
                }

                if (msgList.Count > 0)
                {
                    e.Result = msgList;
                    return;
                }

                #endregion

                e.Result = null;
                #endregion
            };
            _worker.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
            {
                #region Worker Completed
                if (e.Error == null && e.Result == null)
                {
                    if (!_upload.IsBusy)
                    {
                        //如果學生身上已有補考成績,則提醒使用者
                        if (_duplicateMakeUpScoreList.Count > 0)
                        {
                            _warn.RunWorkerAsync();
                        }
                        else
                        {
                            lblMessage.Text = "成績上傳中…";
                            FISCA.Presentation.MotherForm.SetStatusBarMessage("成績上傳中…", 0);
                            counter = 0;
                            _upload.RunWorkerAsync();
                        }
                    }
                }
                else
                {
                    ControlEnable = true;

                    if (e.Error != null)
                    {
                        MsgBox.Show("匯入失敗。" + e.Error.Message);
                        SmartSchool.ErrorReporting.ReportingService.ReportException(e.Error);
                    }
                    else if (e.Result != null && e.Result is ValidateTextResult)
                    {
                        ValidateTextResult    result = e.Result as ValidateTextResult;
                        ValidationErrorViewer viewer = new ValidationErrorViewer();
                        viewer.SetTextFileError(result.LineIndexes, result.ErrorFormatLineIndexes, result.DuplicateLineIndexes);
                        viewer.ShowDialog();
                    }
                    else if (e.Result != null && e.Result is List <string> )
                    {
                        ValidationErrorViewer viewer = new ValidationErrorViewer();
                        viewer.SetErrorLines(e.Result as List <string>);
                        viewer.ShowDialog();
                    }
                }
                #endregion
            };

            _upload = new BackgroundWorker();
            _upload.WorkerReportsProgress = true;
            _upload.ProgressChanged      += new ProgressChangedEventHandler(_upload_ProgressChanged);
            //_upload.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e)
            //{
            //    counter += double.Parse("" + e.ProgressPercentage);
            //    FISCA.Presentation.MotherForm.SetStatusBarMessage("成績上傳中…", (int)(counter * 100f / (double)_addScoreList.Count));
            //};
            _upload.DoWork += new DoWorkEventHandler(_upload_DoWork);


            _upload.RunWorkerCompleted += new RunWorkerCompletedEventHandler(_upload_RunWorkerCompleted);

            _warn = new BackgroundWorker();
            _warn.WorkerReportsProgress = true;
            _warn.DoWork += delegate(object sender, DoWorkEventArgs e)
            {
                _warn.ReportProgress(0, "產生警告訊息...");

                Dictionary <string, string> examDict = new Dictionary <string, string>();
                foreach (JHExamRecord exam in JHExam.SelectAll())
                {
                    if (!examDict.ContainsKey(exam.ID))
                    {
                        examDict.Add(exam.ID, exam.Name);
                    }
                }

                WarningForm form  = new WarningForm();
                int         count = 0;
                foreach (JHSemesterScoreRecord sce in _duplicateMakeUpScoreList)
                {
                    form.Add(sce.RefStudentID, sce.Student.Name, msg_DuplicatedDict[sce.RefStudentID]);
                    _warn.ReportProgress((int)(count * 100 / _duplicateMakeUpScoreList.Count), "產生警告訊息...");
                }

                e.Result = form;
            };
            _warn.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
            {
                WarningForm form = e.Result as WarningForm;

                if (form.ShowDialog() == DialogResult.OK)
                {
                    lblMessage.Text = "成績上傳中…";
                    FISCA.Presentation.MotherForm.SetStatusBarMessage("成績上傳中…", 0);
                    counter = 0;
                    _upload.RunWorkerAsync();
                }
                else
                {
                    this.DialogResult = DialogResult.Cancel;
                }
            };
            _warn.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e)
            {
                FISCA.Presentation.MotherForm.SetStatusBarMessage("" + e.UserState, e.ProgressPercentage);
            };

            _files = new List <FileInfo>();
        }