예제 #1
0
 private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
 {
     FISCA.UDT.AccessHelper ah = new FISCA.UDT.AccessHelper();
     string query = string.Format("ref_student_id={0} and ref_template_id ='{1}'", this.PrimaryKey, this.currentTemplate.UID);
     List<DAO.UDT_ABCardDataDef> records = ah.Select<DAO.UDT_ABCardDataDef>(query);
     if (records.Count > 0)
     {
         this.card_data = records[0];
     }
     else
     {
         this.card_data = null;
     }
 }
        public StudentMoralProcessor(DocumentBuilder builder, SemesterMap map)
        {
            _builder = builder;

            _map = map;
            _types = new Dictionary<string, List<string>>();

            _run = WordHelper.CreateRun(_builder);

            #region 取得假別設定
            ConfigData cd = K12.Data.School.Configuration["學籍表"];
            if (cd.Contains("假別設定"))
            {
                XmlElement config = Framework.XmlHelper.LoadXml(cd["假別設定"]);

                foreach (XmlElement type in config.SelectNodes("Type"))
                {
                    string typeName = type.GetAttribute("Text");
                    if (!_types.ContainsKey(typeName))
                        _types.Add(typeName, new List<string>());

                    foreach (XmlElement absence in type.SelectNodes("Absence"))
                    {
                        string absenceName = absence.GetAttribute("Text");
                        if (!_types[typeName].Contains(absenceName))
                            _types[typeName].Add(absenceName);
                    }
                }
            }
            #endregion

            #region 取得社團成績
            _assnScoreCache = new Dictionary<string, List<AssnScore>>();

            FISCA.UDT.AccessHelper ah = new FISCA.UDT.AccessHelper();
//            string condition = string.Format("SchoolYear='{0}' and Semester='{1}'", options.SchoolYear, options.Semester);
//            List<AssnCode> list = ah.Select<AssnCode>(condition);

            if (AssociationUDTCache == null)
                AssociationUDTCache = ah.Select<AssnCode>();

            List<AssnCode> list = AssociationUDTCache;
            foreach (AssnCode record in list)
            {
                //if (!_assnScoreCache.ContainsKey(record.StudentID))
                //{
                    XmlElement scores = K12.Data.XmlHelper.LoadXml(record.Scores);
                    XmlElement itemElement = (XmlElement)scores.SelectSingleNode("Item");
                    if (itemElement != null)
                    {
                        AssnScore assnScore = new AssnScore()
                        {
                            Score = itemElement.GetAttribute("Score"),
                            Effort = itemElement.GetAttribute("Effort"),
                            Text = itemElement.GetAttribute("Text"),
                            SchoolYear = record.SchoolYear,
                            Semester = record.Semester
                        };
                        if (_assnScoreCache.ContainsKey(record.StudentID))
                            _assnScoreCache[record.StudentID].Add(assnScore);
                        else
                        {
                            List<AssnScore> lis = new List<AssnScore>();
                            lis.Add(assnScore);
                            _assnScoreCache.Add(record.StudentID, lis);
                        }
                    }
                //}
            }

            //<Content>
            //<Item AssociationName="籃球社" Score="" Effort="" Text=""></Item>
            //</Content>
            #endregion
        }
예제 #3
0
        public ConfigForm()
        {
            InitializeComponent();
            List <ExamRecord> exams = new List <ExamRecord>();
            BackgroundWorker  bkw   = new BackgroundWorker();

            bkw.DoWork += delegate
            {
                bkw.ReportProgress(1);
                //預設學年度學期
                _DefalutSchoolYear = "" + K12.Data.School.DefaultSchoolYear;
                _DefaultSemester   = "" + K12.Data.School.DefaultSemester;
                bkw.ReportProgress(10);
                //試別清單
                exams = K12.Data.Exam.SelectAll();
                bkw.ReportProgress(20);
                //學生類別清單
                _TagConfigRecords = K12.Data.TagConfig.SelectByCategory(TagCategory.Student);
                #region 整理所有試別對應科目
                var AEIncludeRecords = K12.Data.AEInclude.SelectAll();
                bkw.ReportProgress(30);
                var AssessmentSetupRecords = K12.Data.AssessmentSetup.SelectAll();
                bkw.ReportProgress(40);
                List <string> courseIDs = new List <string>();
                foreach (var scattentRecord in K12.Data.SCAttend.SelectByStudentIDs(K12.Presentation.NLDPanels.Student.SelectedSource))
                {
                    if (!courseIDs.Contains(scattentRecord.RefCourseID))
                    {
                        courseIDs.Add(scattentRecord.RefCourseID);
                    }
                }
                bkw.ReportProgress(60);
                foreach (var courseRecord in K12.Data.Course.SelectAll())
                {
                    foreach (var aeIncludeRecord in AEIncludeRecords)
                    {
                        if (aeIncludeRecord.RefAssessmentSetupID == courseRecord.RefAssessmentSetupID)
                        {
                            string key = courseRecord.SchoolYear + "^^" + courseRecord.Semester + "^^" + aeIncludeRecord.RefExamID;
                            if (!_ExamSubjectFull.ContainsKey(key))
                            {
                                _ExamSubjectFull.Add(key, new List <string>());
                            }
                            if (!_ExamSubjectFull[key].Contains(courseRecord.Subject))
                            {
                                _ExamSubjectFull[key].Add(courseRecord.Subject);
                            }
                            if (courseIDs.Contains(courseRecord.ID))
                            {
                                if (!_ExamSubjects.ContainsKey(key))
                                {
                                    _ExamSubjects.Add(key, new List <string>());
                                }
                                if (!_ExamSubjects[key].Contains(courseRecord.Subject))
                                {
                                    _ExamSubjects[key].Add(courseRecord.Subject);
                                }
                            }
                        }
                    }
                }
                bkw.ReportProgress(70);
                foreach (var list in _ExamSubjectFull.Values)
                {
                    #region 排序
                    list.Sort(new StringComparer("國文"
                                                 , "英文"
                                                 , "數學"
                                                 , "理化"
                                                 , "生物"
                                                 , "社會"
                                                 , "物理"
                                                 , "化學"
                                                 , "歷史"
                                                 , "地理"
                                                 , "公民"));
                    #endregion
                }
                #endregion
                bkw.ReportProgress(80);
                _Configures = _AccessHelper.Select <Configure>();
                bkw.ReportProgress(100);
            };
            bkw.WorkerReportsProgress = true;
            bkw.ProgressChanged      += delegate(object sender, ProgressChangedEventArgs e)
            {
                circularProgress1.Value = e.ProgressPercentage;
            };
            bkw.RunWorkerCompleted += delegate
            {
                cboConfigure.Items.Clear();
                foreach (var item in _Configures)
                {
                    cboConfigure.Items.Add(item);
                }
                cboConfigure.Items.Add(new Configure()
                {
                    Name = "新增"
                });
                int i;
                if (int.TryParse(_DefalutSchoolYear, out i))
                {
                    for (int j = 0; j < 5; j++)
                    {
                        cboSchoolYear.Items.Add("" + (i - j));
                    }
                }
                cboSemester.Items.Add("1");
                cboSemester.Items.Add("2");
                cboExam.Items.Clear();
                cboRefExam.Items.Clear();
                cboExam.Items.AddRange(exams.ToArray());
                cboRefExam.Items.Add(new ExamRecord("", "", 0));
                cboRefExam.Items.AddRange(exams.ToArray());
                List <string> prefix = new List <string>();
                List <string> tag    = new List <string>();
                foreach (var item in _TagConfigRecords)
                {
                    if (item.Prefix != "")
                    {
                        if (!prefix.Contains(item.Prefix))
                        {
                            prefix.Add(item.Prefix);
                        }
                    }
                    else
                    {
                        tag.Add(item.Name);
                    }
                }
                cboRankRilter.Items.Clear();
                cboTagRank1.Items.Clear();
                cboTagRank2.Items.Clear();
                cboRankRilter.Items.Add("");
                cboTagRank1.Items.Add("");
                cboTagRank2.Items.Add("");
                foreach (var s in prefix)
                {
                    cboRankRilter.Items.Add("[" + s + "]");
                    cboTagRank1.Items.Add("[" + s + "]");
                    cboTagRank2.Items.Add("[" + s + "]");
                }
                foreach (var s in tag)
                {
                    cboRankRilter.Items.Add(s);
                    cboTagRank1.Items.Add(s);
                    cboTagRank2.Items.Add(s);
                }
                circularProgress1.Hide();
                if (_Configures.Count > 0)
                {
                    cboConfigure.SelectedIndex = 0;
                }
                else
                {
                    cboConfigure.SelectedIndex = -1;
                }
            };
            bkw.RunWorkerAsync();
        }
예제 #4
0
        private void loadTemplate()
        {
            FISCA.UDT.AccessHelper ah = new FISCA.UDT.AccessHelper();
            this.template = ah.Select<UDT_ABCardTemplateDefinitionDef>();
            this.template.Sort(delegate(UDT_ABCardTemplateDefinitionDef t1, UDT_ABCardTemplateDefinitionDef t2)
            {
                return t1.ToString().CompareTo(t2.ToString());
            }
            );
            //MessageBox.Show(this.template.Count.ToString());
            this.comboBoxEx1.Items.Clear();
            this.comboBoxEx1.Items.AddRange(this.template.ToArray());

            if (this.comboBoxEx1.Items.Count > 0)
                this.comboBoxEx1.SelectedIndex = 0;

            //initUI();
        }
예제 #5
0
        public StudentMoralProcessor(DocumentBuilder builder, SemesterMap map)
        {
            _builder = builder;

            _map   = map;
            _types = new Dictionary <string, List <string> >();

            _run = WordHelper.CreateRun(_builder);

            #region 取得假別設定
            ConfigData cd = K12.Data.School.Configuration["學籍表"];
            if (cd.Contains("假別設定"))
            {
                XmlElement config = Framework.XmlHelper.LoadXml(cd["假別設定"]);

                foreach (XmlElement type in config.SelectNodes("Type"))
                {
                    string typeName = type.GetAttribute("Text");
                    if (!_types.ContainsKey(typeName))
                    {
                        _types.Add(typeName, new List <string>());
                    }

                    foreach (XmlElement absence in type.SelectNodes("Absence"))
                    {
                        string absenceName = absence.GetAttribute("Text");
                        if (!_types[typeName].Contains(absenceName))
                        {
                            _types[typeName].Add(absenceName);
                        }
                    }
                }
            }
            #endregion

            #region 取得社團成績
            _assnScoreCache = new Dictionary <string, List <AssnScore> >();

            FISCA.UDT.AccessHelper ah = new FISCA.UDT.AccessHelper();
//            string condition = string.Format("SchoolYear='{0}' and Semester='{1}'", options.SchoolYear, options.Semester);
//            List<AssnCode> list = ah.Select<AssnCode>(condition);

            if (AssociationUDTCache == null)
            {
                AssociationUDTCache = ah.Select <AssnCode>();
            }

            List <AssnCode> list = AssociationUDTCache;
            foreach (AssnCode record in list)
            {
                //if (!_assnScoreCache.ContainsKey(record.StudentID))
                //{
                XmlElement scores      = K12.Data.XmlHelper.LoadXml(record.Scores);
                XmlElement itemElement = (XmlElement)scores.SelectSingleNode("Item");
                if (itemElement != null)
                {
                    AssnScore assnScore = new AssnScore()
                    {
                        Score      = itemElement.GetAttribute("Score"),
                        Effort     = itemElement.GetAttribute("Effort"),
                        Text       = itemElement.GetAttribute("Text"),
                        SchoolYear = record.SchoolYear,
                        Semester   = record.Semester
                    };
                    if (_assnScoreCache.ContainsKey(record.StudentID))
                    {
                        _assnScoreCache[record.StudentID].Add(assnScore);
                    }
                    else
                    {
                        List <AssnScore> lis = new List <AssnScore>();
                        lis.Add(assnScore);
                        _assnScoreCache.Add(record.StudentID, lis);
                    }
                }
                //}
            }

            //<Content>
            //<Item AssociationName="籃球社" Score="" Effort="" Text=""></Item>
            //</Content>
            #endregion
        }
        public static void AddMenuButton()
        {
            var ribbonBarItem = K12.Presentation.NLDPanels.Course.RibbonBarItems["課程行事曆"];

            Catalog button_syncCalendar = RoleAclSource.Instance["課程"]["功能按鈕"];
            button_syncCalendar.Add(new RibbonFeature("Reset_Course_Calendar", "重置課程行事曆"));
            bool isEnabled = UserAcl.Current["Reset_Course_Calendar"].Executable;
            var btn = ribbonBarItem["重置課程行事曆"];
            if (isEnabled)
            {
                ribbonBarItem["重置課程行事曆"].Click += delegate
                {
                    if (System.Windows.Forms.MessageBox.Show("將會清空行事例曆中所有資料,\n以及系統內課程同步狀態。\n\nPS.不會影響輸入的上課時間資料。", "重置課程行事曆", System.Windows.Forms.MessageBoxButtons.OKCancel, System.Windows.Forms.MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.OK)
                    {
                        System.ComponentModel.BackgroundWorker bkw = new System.ComponentModel.BackgroundWorker();
                        bkw.WorkerReportsProgress = true;
                        bkw.RunWorkerCompleted += delegate
                        {
                            FISCA.Presentation.MotherForm.SetStatusBarMessage("重置課程行事曆完成。", 100);
                            System.Windows.Forms.MessageBox.Show("課程行事曆已重置,\n請上google calendar檢查,\n如有殘留資料請再執行此功能。");
                        };
                        bkw.ProgressChanged += delegate(object sender, System.ComponentModel.ProgressChangedEventArgs e)
                        {
                            FISCA.Presentation.MotherForm.SetStatusBarMessage("重置課程行事曆...", e.ProgressPercentage);
                        };
                        bkw.DoWork += delegate
                        {
                            bkw.ReportProgress(1);
                            var accessHelper = new FISCA.UDT.AccessHelper();
                            var l1 = accessHelper.Select<Section>();
                            foreach (Section section in l1)
                            {
                                section.IsPublished = false;
                            }
                            l1.SaveAll();
                            bkw.ReportProgress(5);
                            var l2 = accessHelper.Select<Calendar>();
                            foreach (Calendar cal in l2)
                            {
                                cal.Deleted = true;
                            }
                            l2.SaveAll();
                            bkw.ReportProgress(10);
                            #region 清空行事曆
                            CalendarService myService = new CalendarService("ischool.CourseCalendar");
                            myService.setUserCredentials(googleAcc, googlePWD);
                            CalendarQuery cq = new CalendarQuery();
                            cq.Uri = new Uri("http://www.google.com/calendar/feeds/default/owncalendars/full");
                            CalendarFeed resultFeed = myService.Query(cq);
                            foreach (CalendarEntry entry in resultFeed.Entries)
                            {
                                String calendarURI = entry.Id.Uri.ToString();
                                String calendarID = calendarURI.Substring(calendarURI.LastIndexOf("/") + 1);
                                clearAndDeleteCalender(calendarID);
                            }
                            bkw.ReportProgress(55);
                            deleteAllEvent("default");
                            #endregion
                            bkw.ReportProgress(100);
                        };
                        bkw.RunWorkerAsync();
                    }
                };
            }
            else
            {
                btn.Enable = false;
            }
        }
예제 #7
0
        // 列印
        private void btnPrint_Click_1(object s, EventArgs ea)
        {
            if (comboBox_ChooseSchoolYear.SelectedItem == null)
            {
                // 請使用者一定要選擇學年度,否則系統會當機
                MsgBox.Show("請先選擇學年度");
            }
            else
            {
                string schoolYear = comboBox_ChooseSchoolYear.Text;
                string returnDate = textBoxHandInDay.Text;
                string printDate  = DateTime.Today.ToShortDateString();

                BackgroundWorker BGW = new BackgroundWorker();
                BGW.WorkerReportsProgress = true;

                BGW.DoWork += delegate(object sender, DoWorkEventArgs e)
                {
                    #region DoWork
                    FISCA.UDT.AccessHelper accessHelper = new FISCA.UDT.AccessHelper();

                    Aspose.Words.Document Template;
                    Template = new Aspose.Words.Document(new MemoryStream(Properties.Resources.班級體適能確認單範本1));
                    // 取得選取班級
                    List <ClassRecord> ClassList = K12.Data.Class.SelectByIDs(K12.Presentation.NLDPanels.Class.SelectedSource);
                    Dictionary <string, StudentFitnessRecord> dicStudentFitnessRecord = new Dictionary <string, StudentFitnessRecord>();
                    var studentIDList = new List <string>();
                    foreach (ClassRecord classrecord in ClassList)
                    {
                        foreach (var studentRec in classrecord.Students)
                        {
                            studentIDList.Add(studentRec.ID);
                        }
                    }
                    BGW.ReportProgress(10);

                    var studentFitnessRecordList = accessHelper.Select <StudentFitnessRecord>(string.Format("ref_student_id in ('{0}') AND school_year = {1}", string.Join("','", studentIDList), schoolYear));

                    foreach (var fitnessRec in studentFitnessRecordList)
                    {
                        //2021/3/16 -  如果沒有新增,避免爆掉
                        //- By Dylan
                        if (!dicStudentFitnessRecord.ContainsKey(fitnessRec.StudentID))
                        {
                            dicStudentFitnessRecord.Add(fitnessRec.StudentID, fitnessRec);
                        }
                        else
                        {
                            StudentRecord stud = K12.Data.Student.SelectByID(fitnessRec.StudentID);
                            MsgBox.Show(string.Format("學生「{0}」體適能資料重複\n(一學年僅會有一筆體適能紀錄)", stud.Name));
                        }
                    }

                    BGW.ReportProgress(20);

                    //填資料部份
                    DataTable table = new DataTable();
                    table.Columns.Add("製表日期");
                    table.Columns.Add("學年");
                    table.Columns.Add("學期");
                    table.Columns.Add("班級");
                    table.Columns.Add("導師");
                    table.Columns.Add("繳回日期");


                    int classIndex = 0;
                    foreach (ClassRecord classRec in ClassList)
                    {
                        DataRow row = table.NewRow();
                        row["學年"] = schoolYear;

                        row["班級"] = classRec.Name;

                        if (classRec.Teacher != null)
                        {
                            row["導師"] = classRec.Teacher.Name;
                        }
                        //  取得視窗輸入的繳回日期
                        row["繳回日期"] = returnDate;

                        row["製表日期"] = printDate;

                        int studentCounter = 0;

                        foreach (StudentRecord studentRec in classRec.Students)
                        {
                            //2016/11/11 穎驊更正,限制抓取"一般"狀態的學生,要不然會在同一班 抓到畢業、休學、刪除的學生資料
                            if (studentRec.Status == StudentRecord.StudentStatus.一般)
                            {
                                string col = "";

                                col = string.Format("姓名{0}", studentCounter);
                                if (!table.Columns.Contains(col))
                                {
                                    table.Columns.Add(col);
                                }
                                row[col] = studentRec.Name;

                                col = string.Format("座號{0}", studentCounter);
                                if (!table.Columns.Contains(col))
                                {
                                    table.Columns.Add(col);
                                }
                                row[col] = studentRec.SeatNo;

                                if (dicStudentFitnessRecord.ContainsKey(studentRec.ID))
                                {
                                    col = string.Format("測驗日期{0}", studentCounter);
                                    if (!table.Columns.Contains(col))
                                    {
                                        table.Columns.Add(col);
                                    }
                                    row[col] = dicStudentFitnessRecord[studentRec.ID].TestDate.ToShortDateString();

                                    col = string.Format("身高{0}", studentCounter);
                                    if (!table.Columns.Contains(col))
                                    {
                                        table.Columns.Add(col);
                                    }
                                    row[col] = dicStudentFitnessRecord[studentRec.ID].Height;

                                    col = string.Format("體重{0}", studentCounter);
                                    if (!table.Columns.Contains(col))
                                    {
                                        table.Columns.Add(col);
                                    }
                                    row[col] = dicStudentFitnessRecord[studentRec.ID].Weight;

                                    col = string.Format("坐姿體前彎{0}", studentCounter);
                                    if (!table.Columns.Contains(col))
                                    {
                                        table.Columns.Add(col);
                                    }
                                    row[col] = dicStudentFitnessRecord[studentRec.ID].SitAndReach;

                                    col = string.Format("坐姿體前彎常模{0}", studentCounter);
                                    if (!table.Columns.Contains(col))
                                    {
                                        table.Columns.Add(col);
                                    }
                                    row[col] = dicStudentFitnessRecord[studentRec.ID].SitAndReachDegree;

                                    col = string.Format("立定跳遠{0}", studentCounter);
                                    if (!table.Columns.Contains(col))
                                    {
                                        table.Columns.Add(col);
                                    }
                                    row[col] = dicStudentFitnessRecord[studentRec.ID].StandingLongJump;

                                    col = string.Format("立定跳遠常模{0}", studentCounter);
                                    if (!table.Columns.Contains(col))
                                    {
                                        table.Columns.Add(col);
                                    }
                                    row[col] = dicStudentFitnessRecord[studentRec.ID].StandingLongJumpDegree;

                                    col = string.Format("仰臥起坐{0}", studentCounter);
                                    if (!table.Columns.Contains(col))
                                    {
                                        table.Columns.Add(col);
                                    }
                                    row[col] = dicStudentFitnessRecord[studentRec.ID].SitUp;

                                    col = string.Format("仰臥起坐常模{0}", studentCounter);
                                    if (!table.Columns.Contains(col))
                                    {
                                        table.Columns.Add(col);
                                    }
                                    row[col] = dicStudentFitnessRecord[studentRec.ID].SitUpDegree;

                                    col = string.Format("心肺適能{0}", studentCounter);
                                    if (!table.Columns.Contains(col))
                                    {
                                        table.Columns.Add(col);
                                    }
                                    row[col] = dicStudentFitnessRecord[studentRec.ID].Cardiorespiratory;

                                    col = string.Format("心肺適能常模{0}", studentCounter);
                                    if (!table.Columns.Contains(col))
                                    {
                                        table.Columns.Add(col);
                                    }
                                    row[col] = dicStudentFitnessRecord[studentRec.ID].CardiorespiratoryDegree;
                                }

                                studentCounter++;

                                //2016/11/11 光棍節,穎驊新增,由於目前Word樣板只支援38個學生,當班級學生數量將會有印不下的問題,
                                //因此 將第39位後的學生資料,印在第二頁、第三頁...
                                if (studentCounter >= 38)
                                {
                                    studentCounter = 0;
                                    table.Rows.Add(row);

                                    row = table.NewRow();

                                    row["學年"] = schoolYear;

                                    row["班級"] = classRec.Name;

                                    if (classRec.Teacher != null)
                                    {
                                        row["導師"] = classRec.Teacher.Name;
                                    }
                                    //  取得視窗輸入的繳回日期
                                    row["繳回日期"] = returnDate;

                                    row["製表日期"] = printDate;
                                }
                            }
                        }
                        // 一個row 一班
                        if (studentCounter != 0)
                        {
                            table.Rows.Add(row);
                        }

                        classIndex++;
                        BGW.ReportProgress(20 + classIndex * 80 / ClassList.Count);
                    }

                    #region 自動生成功變數代碼(開發用很方便,平常註解掉)

                    // 雖然已經講過了,但穎驊不得不大力推薦,這~真~的~超~級~好~用~的!!! 原本自己手動改,三個小時還不一全部改得完、正確,
                    // 用程式自動產生功能變數mailmerge名稱後,十分鐘內就完成&確認檢查完畢了


                    //Document doc = new Document();
                    //DocumentBuilder bu = new DocumentBuilder(doc);
                    //bu.MoveToDocumentStart();
                    //bu.CellFormat.Borders.LineStyle = LineStyle.Single;
                    //bu.CellFormat.VerticalAlignment = CellVerticalAlignment.Center;
                    //Table table1 = bu.StartTable();

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

                    //fitnessItem.Add("座號");
                    //fitnessItem.Add("姓名");
                    //fitnessItem.Add("測驗日期");
                    //fitnessItem.Add("身高");
                    //fitnessItem.Add("體重");
                    //fitnessItem.Add("坐姿體前彎");
                    //fitnessItem.Add("坐姿體前彎常模");
                    //fitnessItem.Add("立定跳遠");
                    //fitnessItem.Add("立定跳遠常模");
                    //fitnessItem.Add("仰臥起坐");
                    //fitnessItem.Add("仰臥起坐常模");
                    //fitnessItem.Add("心肺適能");
                    //fitnessItem.Add("心肺適能常模");

                    //    foreach (String item in fitnessItem)
                    //    {
                    //        for (int fitnessCounter = 0; fitnessCounter < 40; fitnessCounter++)
                    //        {
                    //        bu.InsertCell();
                    //        bu.CellFormat.Width = 15;
                    //        bu.InsertField("MERGEFIELD " + item + fitnessCounter + @" \* MERGEFORMAT", "«»");
                    //        bu.ParagraphFormat.Alignment = ParagraphAlignment.Center;
                    //        bu.InsertCell();
                    //        bu.CellFormat.Width = 125;
                    //        bu.Write(item + fitnessCounter);
                    //        bu.ParagraphFormat.Alignment = ParagraphAlignment.Left;
                    //        bu.EndRow();

                    //    }

                    //}
                    //    table1.AllowAutoFit = false;
                    //bu.EndTable();
                    //Document PageOne = (Document)Template.Clone(true);
                    //PageOne = doc;

                    # endregion

                    Document PageOne = (Document)Template.Clone(true);
                    PageOne.MailMerge.Execute(table);
                    PageOne.MailMerge.DeleteFields();


                    e.Result = PageOne;
                    #endregion
                };

                BGW.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e)
                {
                    FISCA.Presentation.MotherForm.SetStatusBarMessage("班級體適能通知單產生中...", e.ProgressPercentage);
                };

                BGW.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
                {
                    #region RunWorkerCompleted
                    if (e.Cancelled)
                    {
                        MsgBox.Show("作業已被中止!!");
                    }
                    else
                    {
                        if (e.Error == null)
                        {
                            Document inResult = (Document)e.Result;

                            try
                            {
                                SaveFileDialog SaveFileDialog1 = new SaveFileDialog();

                                SaveFileDialog1.Filter   = "Word (*.docx)|*.docx|所有檔案 (*.*)|*.*";
                                SaveFileDialog1.FileName = "班級體適能通知單";

                                if (SaveFileDialog1.ShowDialog() == DialogResult.OK)
                                {
                                    inResult.Save(SaveFileDialog1.FileName);
                                    Process.Start(SaveFileDialog1.FileName);
                                }
                                else
                                {
                                    FISCA.Presentation.Controls.MsgBox.Show("檔案未儲存");
                                    return;
                                }
                            }
                            catch
                            {
                                FISCA.Presentation.Controls.MsgBox.Show("檔案儲存錯誤,請檢查檔案是否開啟中!!");
                                return;
                            }

                            FISCA.Presentation.MotherForm.SetStatusBarMessage("班級體適能通知單產生完成", 100);
                        }
                        else
                        {
                            MsgBox.Show("列印資料發生錯誤\n" + e.Error.Message);
                        }
                    }
                    #endregion
                };

                FISCA.Presentation.MotherForm.SetStatusBarMessage("班級體適能通知單產生中...", 0);

                BGW.RunWorkerAsync();
                this.Close();
            }
        private void Worker_DoWork(object sender, DoWorkEventArgs e)
        {
            _worker.ReportProgress(0, "開始列印 ESL報表...");

            #region 取得課程成績單 設定樣板
            _eslCouseList = new List <K12.Data.CourseRecord>();

            _eslCouseList = K12.Data.Course.SelectByIDs(_courseIDList);

            _refAssessmentSetupIDList = new List <string>();

            foreach (K12.Data.CourseRecord courseRecord in _eslCouseList)
            {
                if (!_refAssessmentSetupIDList.Contains("'" + courseRecord.RefAssessmentSetupID + "'"))
                {
                    _refAssessmentSetupIDList.Add("'" + courseRecord.RefAssessmentSetupID + "'");
                }

                if (!_courseIDPairDict.ContainsKey(courseRecord.ID))
                {
                    _courseIDPairDict.Add(courseRecord.ID, courseRecord.RefAssessmentSetupID);
                }

                if (!_assessmentSetupIDPairDict.ContainsKey(courseRecord.RefAssessmentSetupID))
                {
                    _assessmentSetupIDPairDict.Add(courseRecord.RefAssessmentSetupID, courseRecord.ID);
                }
            }

            string assessmentSetupIDs = string.Join(",", _refAssessmentSetupIDList);


            FISCA.UDT.AccessHelper _AccessHelper = new FISCA.UDT.AccessHelper();

            _worker.ReportProgress(0, "取得課程成績單設定樣板...");


            string qry = "ref_exam_template_id IN (" + assessmentSetupIDs + ") and schoolyear='" + K12.Data.School.DefaultSchoolYear + "' and semester ='" + K12.Data.School.DefaultSemester + "' and exam ='" + _examType + "'";

            List <UDT_ReportTemplate> configures = _AccessHelper.Select <UDT_ReportTemplate>(qry);

            _documentDict = new Dictionary <string, Document>();

            foreach (UDT_ReportTemplate templateconfig in configures)
            {
                if (!_documentDict.ContainsKey(templateconfig.Ref_exam_Template_ID))
                {
                    Document _doc = new Document();

                    templateconfig.Decode(); // 將 stream 轉成 Word

                    _doc = templateconfig.Template;

                    _documentDict.Add(templateconfig.Ref_exam_Template_ID, _doc);
                }
            }
            #endregion


            #region 取得修課學生、 並做整理
            List <K12.Data.SCAttendRecord> scList = K12.Data.SCAttend.SelectByCourseIDs(_courseIDList);

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


            foreach (K12.Data.SCAttendRecord scr in scList)
            {
                studentIDList.Add(scr.Student.ID);

                // 建立成績整理 Dict ,[studentID_courseID,[scoreKey,scoreID]]
                _scoreDict.Add(scr.Student.ID + "_" + scr.Course.ID, new Dictionary <string, string>());
            }
            #endregion

            // 建立功能變數對照
            CreateFieldTemplate();

            #region 取得、整理ESL成績
            _worker.ReportProgress(20, "取得ESL課程成績");


            int     progress = 80;
            decimal per      = (decimal)(100 - progress) / scList.Count;
            int     count    = 0;

            string course_ids = string.Join("','", _courseIDList);

            string student_ids = string.Join("','", studentIDList);

            string sql = "SELECT * FROM $esl.gradebook_assessment_score WHERE ref_course_id IN ('" + course_ids + "') AND ref_student_id IN ('" + student_ids + "') "; // 2018/6/21 通通都抓了,因為一張成績單上資訊,不只Final的

            QueryHelper qh = new QueryHelper();
            DataTable   dt = qh.Select(sql);


            foreach (DataRow row in dt.Rows)
            {
                string termWord       = "" + row["term"];
                string subjectWord    = "" + row["subject"];
                string assessmentWord = "" + row["assessment"];

                string id = "" + row["ref_student_id"] + "_" + row["ref_course_id"];

                // 有教師自訂的子項目成績就跳掉 不處理
                if ("" + row["custom_assessment"] != "")
                {
                    continue;
                }

                // 要設計一個模式 處理 三種成績

                // 項目都有,為assessment 成績
                if (termWord != "" && "" + subjectWord != "" && "" + assessmentWord != "")
                {
                    if (_scoreDict.ContainsKey(id))
                    {
                        // 指標型成績
                        if (_indicatorList.Contains("" + row["ref_course_id"] + "_" + "_" + termWord + "_" + subjectWord + "_" + assessmentWord))
                        {
                            _scoreDict[id].Add("評量" + "_" + termWord.Trim().Replace(' ', '_').Replace('"', '_') + "/" + subjectWord.Trim().Replace(' ', '_').Replace('"', '_') + "/" + assessmentWord.Trim().Replace(' ', '_').Replace('"', '_') + "_" + "指標", "" + row["value"]);
                        }
                        // 評語型成績
                        else if (_commentList.Contains("" + row["ref_course_id"] + "_" + "_" + termWord + "_" + subjectWord + "_" + assessmentWord))
                        {
                            _scoreDict[id].Add("評量" + "_" + termWord.Trim().Replace(' ', '_').Replace('"', '_') + "/" + subjectWord.Trim().Replace(' ', '_').Replace('"', '_') + "/" + assessmentWord.Trim().Replace(' ', '_').Replace('"', '_') + "_" + "評語", "" + row["value"]);
                        }
                        // 分數型成績
                        else
                        {
                            _scoreDict[id].Add("評量" + "_" + termWord.Trim().Replace(' ', '_').Replace('"', '_') + "/" + subjectWord.Trim().Replace(' ', '_').Replace('"', '_') + "/" + assessmentWord.Trim().Replace(' ', '_').Replace('"', '_') + "_" + "分數", "" + row["value"]);
                        }
                    }
                }

                // 沒有assessment,為subject 成績
                if (termWord != "" && "" + subjectWord != "" && "" + assessmentWord == "")
                {
                    if (_scoreDict.ContainsKey(id))
                    {
                        _scoreDict[id].Add("評量" + "_" + termWord.Trim().Replace(' ', '_').Replace('"', '_') + "/" + subjectWord.Trim().Replace(' ', '_').Replace('"', '_') + "_" + "分數", "" + row["value"]);
                    }
                }
                // 沒有assessment、subject,為term 成績
                if (termWord != "" && "" + subjectWord == "" && "" + assessmentWord == "")
                {
                    if (_scoreDict.ContainsKey(id))
                    {
                        _scoreDict[id].Add("評量" + "_" + termWord.Trim().Replace(' ', '_').Replace('"', '_') + "_" + "分數", "" + row["value"]);
                    }
                }
            }
            #endregion



            //// 配對學生 與 其功能變數關係
            //foreach (K12.Data.SCAttendRecord scar in scList)
            //{
            //    string id = scar.RefStudentID + "_" + scar.RefCourseID;

            //    string assessmentSetID = _courseIDPairDict[scar.RefCourseID];

            //    _scoreDataTableDict.Add(id, _assessmentSetupDataTableDict[assessmentSetID]);
            //}


            foreach (K12.Data.SCAttendRecord scar in scList)
            {
                string id = scar.RefStudentID + "_" + scar.RefCourseID;

                string assessmentSetID = _courseIDPairDict[scar.RefCourseID];

                DataTable data = _assessmentSetupDataTableDict[assessmentSetID];

                DataRow row = data.NewRow();
                row["電子報表辨識編號"] = "系統編號{" + scar.Student.ID + "}"; // 學生系統編號

                row["學號"]     = scar.Student.StudentNumber;
                row["年級"]     = scar.Student.Class != null ? "" + scar.Student.Class.GradeYear : "";
                row["英文課程名稱"] = scar.Course.Name;
                row["原班級名稱"]  = scar.Student.Class != null ? "" + scar.Student.Class.Name : "";
                row["學生英文姓名"] = scar.Student.EnglishName;
                row["學生中文姓名"] = scar.Student.Name;
                row["教師一"]    = scar.Course.Teachers.Count > 0 ? scar.Course.Teachers.Find(x => x.Sequence == 1).TeacherName : ""; // 新寫法 直接找list 內教師條件
                row["教師二"]    = scar.Course.Teachers.Count > 1 ? scar.Course.Teachers.Find(x => x.Sequence == 2).TeacherName : "";
                row["教師三"]    = scar.Course.Teachers.Count > 2 ? scar.Course.Teachers.Find(x => x.Sequence == 3).TeacherName : "";

                if (_itemDict.ContainsKey(scar.RefCourseID))
                {
                    foreach (KeyValuePair <string, string> p in _itemDict[scar.RefCourseID])
                    {
                        row[p.Key] = p.Value;
                    }
                }


                if (_scoreDict.ContainsKey(id))
                {
                    foreach (KeyValuePair <string, string> p in _scoreDict[id])
                    {
                        row[p.Key] = p.Value;
                    }
                }



                data.Rows.Add(row);

                count++;
                progress += (int)(count * per);
                _worker.ReportProgress(progress);
            }

            Document docFinal = new Document();

            foreach (string assessmentSetupID in _assessmentSetupDataTableDict.Keys)
            {
                Document doc = _documentDict[assessmentSetupID];

                DataTable data = _assessmentSetupDataTableDict[assessmentSetupID];

                doc.MailMerge.Execute(data);

                docFinal.AppendDocument(doc, ImportFormatMode.KeepSourceFormatting);
            }


            docFinal.Sections[0].Remove();// 把第一頁刪掉


            e.Result = docFinal;


            _worker.ReportProgress(100, "ESL 報表列印完成。");
        }
예제 #9
0
        public static void Main()
        {
            FISCA.UDT.AccessHelper accessHelper = new FISCA.UDT.AccessHelper();

            // 先將UDT 選起來,如果是第一次開啟沒有話就會新增
            accessHelper.Select <UDT_MakeUpBatch>();
            accessHelper.Select <UDT_MakeUpGroup>();
            accessHelper.Select <UDT_MakeUpData>();
            accessHelper.Select <UDT_ReportTemplate>();


            MotherForm.RibbonBarItems["教務作業", "補考作業"]["補考作業"].Size = RibbonBarButton.MenuButtonSize.Large;

            MotherForm.RibbonBarItems["教務作業", "補考作業"]["補考作業"].Image = Properties.Resources.calc_64;

            {
                Catalog ribbon = RoleAclSource.Instance["教務作業"]["補考作業"];
                ribbon.Add(new RibbonFeature("BE538A8F-71BA-4979-A04A-32A8C239E716", "管理補考梯次"));

                MotherForm.RibbonBarItems["教務作業", "補考作業"]["補考作業"]["管理補考梯次"].Enable = UserAcl.Current["BE538A8F-71BA-4979-A04A-32A8C239E716"].Executable;

                MotherForm.RibbonBarItems["教務作業", "補考作業"]["補考作業"]["管理補考梯次"].Click += delegate
                {
                    Form.MakeUpBatchManagerForm mubmf = new Form.MakeUpBatchManagerForm();

                    mubmf.ShowDialog();
                };
            }

            {
                Catalog ribbon = RoleAclSource.Instance["教務作業"]["補考作業"];
                ribbon.Add(new RibbonFeature("AE783777-B1F1-47F7-814B-887FC0C2460D", "管理補考群組"));

                MotherForm.RibbonBarItems["教務作業", "補考作業"]["補考作業"]["管理補考群組"].Enable = UserAcl.Current["AE783777-B1F1-47F7-814B-887FC0C2460D"].Executable;

                MotherForm.RibbonBarItems["教務作業", "補考作業"]["補考作業"]["管理補考群組"].Click += delegate
                {
                    Form.MakeUpGroupManagerForm mugmf = new Form.MakeUpGroupManagerForm("管理補考群組");

                    mugmf.ShowDialog();
                };
            }

            {
                Catalog ribbon = RoleAclSource.Instance["教務作業"]["補考作業"];
                ribbon.Add(new RibbonFeature("5AA949A7-7535-42DD-A81C-D4E4DB2B677C", "產生補考公告"));

                MotherForm.RibbonBarItems["教務作業", "補考作業"]["補考作業"]["產生補考公告"].Enable = UserAcl.Current["5AA949A7-7535-42DD-A81C-D4E4DB2B677C"].Executable;

                MotherForm.RibbonBarItems["教務作業", "補考作業"]["補考作業"]["產生補考公告"].Click += delegate
                {
                    Form.ExportMakeUpReportForm emurf = new Form.ExportMakeUpReportForm();

                    emurf.ShowDialog();
                };
            }

            {
                Catalog ribbon = RoleAclSource.Instance["教務作業"]["補考作業"];
                ribbon.Add(new RibbonFeature("6AED85C7-F6CF-49A5-8AAC-C97CF7127AEB", "補考成績輸入狀況"));

                MotherForm.RibbonBarItems["教務作業", "補考作業"]["補考作業"]["補考成績輸入狀況"].Enable = UserAcl.Current["6AED85C7-F6CF-49A5-8AAC-C97CF7127AEB"].Executable;

                MotherForm.RibbonBarItems["教務作業", "補考作業"]["補考作業"]["補考成績輸入狀況"].Click += delegate
                {
                    Form.MakeUpScoreStatusForm myssf = new Form.MakeUpScoreStatusForm();

                    myssf.ShowDialog();
                };
            }



            // 2019/06/03 穎驊註解, 後來有了 補考成績輸入狀況 檢查, 就把 管理成績輸入 介面一併 併過了去了, 這個專門輸入成績的流程 先隱藏
            //{
            //    Catalog ribbon = RoleAclSource.Instance["教務作業"]["補考作業"];
            //    ribbon.Add(new RibbonFeature("47A870E8-0C03-4DE0-A85E-C2B4551351C8", "管理補考成績"));

            //    MotherForm.RibbonBarItems["教務作業", "補考作業"]["補考作業"]["管理補考成績"].Enable = UserAcl.Current["47A870E8-0C03-4DE0-A85E-C2B4551351C8"].Executable;

            //    MotherForm.RibbonBarItems["教務作業", "補考作業"]["補考作業"]["管理補考成績"].Click += delegate
            //    {
            //        Form.MakeUpGroupManagerForm mugmf = new Form.MakeUpGroupManagerForm("管理補考成績");

            //        mugmf.ShowDialog();
            //    };
            //}


            {
                Catalog ribbon = RoleAclSource.Instance["教務作業"]["補考作業"];
                ribbon.Add(new RibbonFeature("E3D987DC-E75C-4472-BAB8-C58EEAA844F9", "產生學期科目成績匯入檔"));

                MotherForm.RibbonBarItems["教務作業", "補考作業"]["補考作業"]["產生學期科目成績匯入檔"].Enable = UserAcl.Current["E3D987DC-E75C-4472-BAB8-C58EEAA844F9"].Executable;

                MotherForm.RibbonBarItems["教務作業", "補考作業"]["補考作業"]["產生學期科目成績匯入檔"].Click += delegate
                {
                    Form.ExportMakeUpScoreForm emusf = new Form.ExportMakeUpScoreForm();

                    emusf.ShowDialog();
                };
            }
        }
예제 #10
0
        public ConfigForm()
        {
            InitializeComponent();
            List <ExamRecord> exams = new List <ExamRecord>();
            BackgroundWorker  bkw   = new BackgroundWorker();

            bkw.DoWork += delegate
            {
                bkw.ReportProgress(1);
                //預設學年度學期
                _DefalutSchoolYear = "" + K12.Data.School.DefaultSchoolYear;
                _DefaultSemester   = "" + K12.Data.School.DefaultSemester;
                bkw.ReportProgress(10);

                // 檢查預設樣板是否存在
                _UDTConfigList = DAO.UDTTransfer.GetDefaultConfigNameListByTableName(Global._UDTTableName);
                // 沒有設定檔,建立預設設定檔
                if (_UDTConfigList.Count < 2)
                {
                    bkw.ReportProgress(20);
                    foreach (string name in Global.DefaultConfigNameList())
                    {
                        Configure cn = new Configure();
                        cn.Name       = name;
                        cn.SchoolYear = K12.Data.School.DefaultSchoolYear;
                        cn.Semester   = K12.Data.School.DefaultSemester;
                        DAO.UDT_ScoreConfig conf = new DAO.UDT_ScoreConfig();
                        conf.Name         = name;
                        conf.UDTTableName = Global._UDTTableName;
                        conf.ProjectName  = Global._ProjectName;
                        conf.Type         = Global._DefaultConfTypeName;
                        _UDTConfigList.Add(conf);

                        // 設預設樣板
                        switch (name)
                        {
                        case "班級學期成績單13科":
                            cn.Template = new Document(new MemoryStream(Properties.Resources.高中班級學期成績單樣版));

                            break;

                        case "班級學期成績單24科":
                            cn.Template = new Document(new MemoryStream(Properties.Resources.班級_學期成績單24科50學生));
                            break;
                        }

                        if (cn.Template == null)
                        {
                            cn.Template = new Document(new MemoryStream(Properties.Resources.高中班級學期成績單樣版));
                        }

                        try
                        {
                            List <string> fields = new List <string>(cn.Template.MailMerge.GetFieldNames());
                            cn.SubjectLimit = 0;
                            while (fields.Contains("科目名稱" + (cn.SubjectLimit + 1)))
                            {
                                cn.SubjectLimit++;
                            }
                            cn.StudentLimit = 0;
                            while (fields.Contains("姓名" + (cn.StudentLimit + 1)))
                            {
                                cn.StudentLimit++;
                            }
                        }
                        catch (Exception ex)
                        { }

                        cn.Encode();
                        cn.Save();
                    }
                    if (_UDTConfigList.Count > 0)
                    {
                        DAO.UDTTransfer.InsertConfigData(_UDTConfigList);
                    }
                }
                bkw.ReportProgress(40);
                _Configures = _AccessHelper.Select <Configure>();
                //學生類別清單
                _TagConfigRecords = K12.Data.TagConfig.SelectByCategory(TagCategory.Student);
                #region 整理所有試別對應科目

                bkw.ReportProgress(60);
                // 取得班級學生(一般生)
                List <string> ClassStudentIDList = DAO.QueryData.GetClassStudentIDByClassID(K12.Presentation.NLDPanels.Class.SelectedSource);
                AccessHelper  accessHelper       = new AccessHelper();
                List <SmartSchool.Customization.Data.StudentRecord> StudentRecList = accessHelper.StudentHelper.GetStudents(ClassStudentIDList);
                bkw.ReportProgress(70);
                // 放入學生學期成績
                accessHelper.StudentHelper.FillSemesterSubjectScore(true, StudentRecList);
                bkw.ReportProgress(80);
                // 取得科目名稱
                foreach (SmartSchool.Customization.Data.StudentRecord stud in StudentRecList)
                {
                    foreach (SemesterSubjectScoreInfo ss in stud.SemesterSubjectScoreList)
                    {
                        string key = ss.SchoolYear + "^^" + ss.Semester;
                        if (!_ExamSubjectFull.ContainsKey(key))
                        {
                            _ExamSubjectFull.Add(key, new List <string>());
                        }
                        if (!_ExamSubjectFull[key].Contains(ss.Subject))
                        {
                            _ExamSubjectFull[key].Add(ss.Subject);
                        }
                    }
                }

                bkw.ReportProgress(90);
                foreach (var list in _ExamSubjectFull.Values)
                {
                    #region 排序
                    //list.Sort(new StringComparer("國文","國語文"
                    //                , "英文", "英語文"
                    //                , "數學"
                    //                , "理化"
                    //                , "生物"
                    //                , "社會"
                    //                , "物理"
                    //                , "化學"
                    //                , "歷史"
                    //                , "地理"
                    //                , "公民"));
                    list.Sort(new StringComparer(Utility.GetSubjectOrder().ToArray()));
                    #endregion
                }
                #endregion

                bkw.ReportProgress(100);
            };
            bkw.WorkerReportsProgress = true;
            bkw.ProgressChanged      += delegate(object sender, ProgressChangedEventArgs e)
            {
                circularProgress1.Value = e.ProgressPercentage;
            };
            bkw.RunWorkerCompleted += delegate
            {
                if (Configure == null)
                {
                    Configure = new Configure();
                }

                cboConfigure.Items.Clear();
                foreach (var item in _Configures)
                {
                    cboConfigure.Items.Add(item);
                }
                cboConfigure.Items.Add(new Configure()
                {
                    Name = "新增"
                });
                int i;
                if (int.TryParse(_DefalutSchoolYear, out i))
                {
                    for (int j = 0; j < 5; j++)
                    {
                        cboSchoolYear.Items.Add("" + (i - j));
                    }
                }
                cboSemester.Items.Add("1");
                cboSemester.Items.Add("2");

                List <string> prefix = new List <string>();
                List <string> tag    = new List <string>();
                foreach (var item in _TagConfigRecords)
                {
                    if (item.Prefix != "")
                    {
                        if (!prefix.Contains(item.Prefix))
                        {
                            prefix.Add(item.Prefix);
                        }
                    }
                    else
                    {
                        tag.Add(item.Name);
                    }
                }

                circularProgress1.Hide();
                if (_Configures.Count > 0)
                {
                    string userSelectConfigName = "";
                    // 檢查畫面上是否有使用者選的
                    foreach (DAO.UDT_ScoreConfig conf in _UDTConfigList)
                    {
                        if (conf.Type == Global._UserConfTypeName)
                        {
                            userSelectConfigName = conf.Name;
                            break;
                        }
                    }

                    cboConfigure.Text = userSelectConfigName;
                }
                else
                {
                    cboConfigure.SelectedIndex = -1;
                }
            };
            bkw.RunWorkerAsync();
        }
        public static void AddMenuButton()
        {
            var accessHelper = new FISCA.UDT.AccessHelper();
            var ribbonBarItem = K12.Presentation.NLDPanels.Course.RibbonBarItems["課程行事曆"];
            var syncButton = ribbonBarItem["同步行事曆"];

            Catalog button_syncCalendar = RoleAclSource.Instance["課程"]["功能按鈕"];
            button_syncCalendar.Add(new RibbonFeature("Sync_Course_Calendar", "同步課程行事曆"));
            bool isEnabled = UserAcl.Current["Sync_Course_Calendar"].Executable;

            syncButton.Enable = ((K12.Presentation.NLDPanels.Course.SelectedSource.Count > 0) && isEnabled);
            K12.Presentation.NLDPanels.Course.SelectedSourceChanged += delegate(object sender, EventArgs e)
            {

                syncButton.Enable = ((K12.Presentation.NLDPanels.Course.SelectedSource.Count > 0) && isEnabled);
            };
            syncButton.Click += delegate
            {
                bool hasFaild = false;
                FISCA.Presentation.MotherForm.SetStatusBarMessage("課程行事曆同步中...", 0);
                List<string> selectedSource = new List<string>(K12.Presentation.NLDPanels.Course.SelectedSource);
                BackgroundWorker bkw = new System.ComponentModel.BackgroundWorker() { WorkerReportsProgress = true };
                bkw.ProgressChanged += delegate(object sender, ProgressChangedEventArgs e)
                {
                    FISCA.Presentation.MotherForm.SetStatusBarMessage("課程行事曆同步中...", e.ProgressPercentage);
                };
                bkw.RunWorkerCompleted += delegate(object sender, RunWorkerCompletedEventArgs e)
                {
                    SectionSyncColumn.Reload();
                    FISCA.Presentation.MotherForm.SetStatusBarMessage("課程行事曆同步完成");
                    if (hasFaild)
                    {
                        FISCA.Presentation.Controls.MsgBox.Show("課程行事曆同步完成,其中部分資料同步失敗,請稍後再試。");
                    }
                };
                bkw.DoWork += delegate(object sender, DoWorkEventArgs e)
                {
                    Dictionary<string, Calendar> calendars = new Dictionary<string, Calendar>();
                    Dictionary<string, List<string>> courseAttend = new Dictionary<string, List<string>>();
                    Dictionary<string, List<Section>> publishItems = new Dictionary<string, List<Section>>();
                    Dictionary<string, string> studentLoginAccount = new Dictionary<string, string>();
                    List<string> syncCourses = new List<string>();
                    int count = 0;
                    string condition = "RefCourseID in (";
                    foreach (string key in selectedSource)
                    {
                        if (condition != "RefCourseID in (")
                            condition += ",";
                        condition += "'" + key + "'";
                    }
                    condition += ")";
                    string condition2 = "ref_course_id in (";
                    foreach (string key in selectedSource)
                    {
                        if (condition2 != "ref_course_id in (")
                            condition2 += ",";
                        condition2 += "'" + key + "'";
                    }
                    condition2 += ")";
                    bkw.ReportProgress(3);
                    foreach (Section section in accessHelper.Select<Section>(condition))
                    {
                        if (!section.IsPublished || section.Removed)
                        {
                            if (!publishItems.ContainsKey(section.RefCourseID))
                                publishItems.Add(section.RefCourseID, new List<Section>());
                            publishItems[section.RefCourseID].Add(section);
                            count++;
                        }
                    }
                    foreach (Calendar cal in accessHelper.Select<Calendar>(condition))
                    {
                        if (!calendars.ContainsKey(cal.RefCourseID))
                            calendars.Add(cal.RefCourseID, cal);
                    }
                    syncCourses.AddRange(publishItems.Keys);
                    foreach (var item in accessHelper.Select<SCAttendExt>(condition2))
                    {
                        if (!courseAttend.ContainsKey(item.CourseID.ToString()))
                            courseAttend.Add(item.CourseID.ToString(), new List<string>());
                        courseAttend[item.CourseID.ToString()].Add(item.StudentID.ToString());
                        if (!studentLoginAccount.ContainsKey(item.StudentID.ToString()))
                            studentLoginAccount.Add(item.StudentID.ToString(), "");
                        count++;
                    }
                    foreach (string key in selectedSource)
                    {
                        if (!courseAttend.ContainsKey(key))
                            courseAttend.Add(key, new List<string>());
                    }
                    foreach (var student in K12.Data.Student.SelectByIDs(studentLoginAccount.Keys))
                    {
                        if (student.SALoginName != "")
                        {
                            studentLoginAccount[student.ID] = student.SALoginName.ToLower();
                        }
                    }
                    foreach (string calid in courseAttend.Keys)
                    {
                        if (calendars.ContainsKey(calid))
                        {
                            Calendar cal = calendars[calid];
                            List<string> aclList = new List<string>(cal.ACLList.Split("%".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
                            List<string> attentAccounts = new List<string>();
                            foreach (string sid in courseAttend[calid])
                            {
                                if (studentLoginAccount[sid] != "")
                                    attentAccounts.Add(studentLoginAccount[sid]);
                            }
                            if (aclList.Count != attentAccounts.Count)
                            {
                                if (!syncCourses.Contains(calid))
                                    syncCourses.Add(calid);
                            }
                            else
                            {
                                foreach (string acc in aclList)
                                {
                                    if (!attentAccounts.Contains(acc.ToLower()))
                                    {
                                        if (!syncCourses.Contains(calid))
                                            syncCourses.Add(calid);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    bkw.ReportProgress(5);
                    CalendarService myService = new CalendarService("ischool.CourseCalendar");
                    myService.setUserCredentials(googleAcc, googlePWD);
                    bkw.ReportProgress(20);
                    List<Section> syncedSections = new List<Section>();
                    foreach (K12.Data.CourseRecord course in K12.Data.Course.SelectByIDs(syncCourses))
                    {
                        //CalendarEntry targetCalender = null;
                        Calendar targetCal = null;
                        try
                        {
                            if (!calendars.ContainsKey(course.ID))
                            {
                                #region 建立新Calender
                                string[] colorLists = new string[]{"#A32929","#B1365F","#7A367A","#5229A3","#29527A","#2952A3","#1B887A",
                            "#28754E","#0D7813","#528800","#88880E","#AB8B00","#BE6D00","#B1440E",
                            "#865A5A","#705770","#4E5D6C","#5A6986","#4A716C","#6E6E41","#8D6F47"};
                                CalendarEntry newCal = new CalendarEntry();
                                newCal.Title.Text = course.Name;
                                newCal.Summary.Text = "科目:" + course.Subject
                                    + "\n學年度:" + course.SchoolYear
                                    + "\n學期:" + course.Semester
                                    + "\n學分數:" + course.Credit;
                                newCal.TimeZone = "Asia/Taipei";
                                //targetCalender.Hidden = false;
                                newCal.Color = colorLists[new Random(DateTime.Now.Millisecond).Next(0, colorLists.Length)];
                                Uri postUri = new Uri("http://www.google.com/calendar/feeds/default/owncalendars/full");
                                newCal = (CalendarEntry)myService.Insert(postUri, newCal);
                                #endregion
                                String calendarURI = newCal.Id.Uri.ToString();
                                String calendarID = calendarURI.Substring(calendarURI.LastIndexOf("/") + 1);
                                targetCal = new Calendar() { RefCourseID = course.ID, GoogleCalanderID = calendarID };
                                targetCal.Save();
                            }
                            else
                            {
                                targetCal = calendars[course.ID];
                            }
                        }
                        catch
                        {
                            hasFaild = true;
                        }
                        if (targetCal != null)
                        {
                            try
                            {
                                #region ACL
                                if (courseAttend.ContainsKey(course.ID))
                                {
                                    List<string> aclList = new List<string>(targetCal.ACLList.Split("%".ToCharArray(), StringSplitOptions.RemoveEmptyEntries));
                                    for (int i = 0; i < aclList.Count; i++)
                                    {
                                        aclList[i] = aclList[i].ToLower();
                                    }
                                    List<string> attentAccounts = new List<string>();
                                    foreach (string sid in courseAttend[course.ID])
                                    {
                                        if (studentLoginAccount[sid] != "")
                                            attentAccounts.Add(studentLoginAccount[sid]);
                                    }
                                    foreach (string acc in attentAccounts)
                                    {
                                        if (!aclList.Contains(acc))
                                        {
                                            try
                                            {
                                                #region 新增分享
                                                AclEntry entry = new AclEntry();
                                                entry.Scope = new AclScope();
                                                entry.Scope.Type = AclScope.SCOPE_USER;
                                                entry.Scope.Value = acc;
                                                entry.Role = AclRole.ACL_CALENDAR_READ;
                                                try
                                                {
                                                    AclEntry insertedEntry = myService.Insert(new Uri("https://www.google.com/calendar/feeds/" + targetCal.GoogleCalanderID + "/acl/full"), entry);
                                                }
                                                catch (GDataRequestException gex)
                                                {
                                                    if (!gex.InnerException.Message.Contains("(409)"))
                                                        throw;
                                                }
                                                #endregion
                                                aclList.Add(acc);
                                            }
                                            catch
                                            {
                                                hasFaild = true;
                                            }
                                        }
                                    }
                                    List<string> removeList = new List<string>();
                                    if (aclList.Count != attentAccounts.Count)
                                    {
                                        #region 移除分享
                                        AtomFeed calFeed = myService.Query(new FeedQuery("https://www.google.com/calendar/feeds/" + targetCal.GoogleCalanderID + "/acl/full"));
                                        foreach (string acc in aclList)
                                        {
                                            if (!attentAccounts.Contains(acc))
                                            {
                                                try
                                                {
                                                    foreach (AtomEntry atomEntry in calFeed.Entries)
                                                    {
                                                        if (atomEntry is AtomEntry)
                                                        {
                                                            AclEntry aclEntry = (AclEntry)atomEntry;
                                                            if (aclEntry.Scope.Value.ToLower() == acc)
                                                            {
                                                                aclEntry.Delete();
                                                                break;
                                                            }
                                                        }
                                                    }
                                                    removeList.Add(acc);
                                                }
                                                catch
                                                {
                                                    hasFaild = true;
                                                }
                                            }
                                        }
                                        #endregion
                                    }
                                    foreach (string acc in removeList)
                                    {
                                        if (aclList.Contains(acc)) aclList.Remove(acc);
                                    }
                                    targetCal.ACLList = "";
                                    foreach (string acc in aclList)
                                    {
                                        targetCal.ACLList += (targetCal.ACLList == "" ? "" : "%") + acc;
                                    }
                                }
                                #endregion
                                #region Events
                                if (publishItems.ContainsKey(course.ID))
                                {
                                    EventFeed feed = myService.Query(new EventQuery("https://www.google.com/calendar/feeds/" + targetCal.GoogleCalanderID + "/private/full"));
                                    AtomFeed batchFeed = new AtomFeed(feed);
                                    foreach (Section section in publishItems[course.ID])
                                    {
                                        if (!section.Removed)
                                        {
                                            #region 新增Event
                                            Google.GData.Calendar.EventEntry eventEntry = new Google.GData.Calendar.EventEntry();

                                            eventEntry.Title.Text = course.Name;
                                            //eventEntry
                                            Where eventLocation = new Where();
                                            eventLocation.ValueString = section.Place;
                                            eventEntry.Locations.Add(eventLocation);
                                            eventEntry.Notifications = true;
                                            eventEntry.Times.Add(new When(section.StartTime, section.EndTime));
                                            eventEntry.Participants.Add(new Who()
                                            {
                                                ValueString = googleAcc,
                                                Attendee_Type = new Who.AttendeeType() { Value = Who.AttendeeType.EVENT_REQUIRED },
                                                Attendee_Status = new Who.AttendeeStatus() { Value = Who.AttendeeStatus.EVENT_ACCEPTED },
                                                Rel = Who.RelType.EVENT_ATTENDEE
                                            });
                                            eventEntry.BatchData = new GDataBatchEntryData(section.UID, GDataBatchOperationType.insert);
                                            batchFeed.Entries.Add(eventEntry);
                                            #endregion
                                        }
                                        else
                                        {
                                            #region 刪除Event

                                            EventEntry toDelete = (EventEntry)feed.Entries.FindById(new AtomId(feed.Id.AbsoluteUri + "/" + section.EventID));
                                            if (toDelete != null)
                                            {
                                                toDelete.Id = new AtomId(toDelete.EditUri.ToString());
                                                toDelete.BatchData = new GDataBatchEntryData(section.UID, GDataBatchOperationType.delete);
                                                batchFeed.Entries.Add(toDelete);
                                            }
                                            else
                                            {
                                                section.Deleted = true;
                                                syncedSections.Add(section);
                                            }
                                            #endregion
                                        }
                                        int p = syncedSections.Count * 80 / count + 20;
                                        if (p > 100) p = 100;
                                        if (p < 0) p = 0;
                                        bkw.ReportProgress(p);
                                    }
                                    EventFeed batchResultFeed = (EventFeed)myService.Batch(batchFeed, new Uri(feed.Batch));
                                    foreach (Section section in publishItems[course.ID])
                                    {
                                        if (syncedSections.Contains(section)) continue;
                                        #region 儲存Section狀態
                                        bool match = false;
                                        if (section.Removed)
                                        {
                                            foreach (EventEntry entry in batchResultFeed.Entries)
                                            {
                                                if (entry.BatchData.Status.Code == 200)
                                                {
                                                    if (section.UID == entry.BatchData.Id)
                                                    {
                                                        section.Deleted = true;
                                                        match = true;
                                                        syncedSections.Add(section);
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                        else
                                        {
                                            foreach (EventEntry entry in batchResultFeed.Entries)
                                            {
                                                if (entry.BatchData.Status.Code == 201)
                                                {
                                                    if (section.UID == entry.BatchData.Id)
                                                    {
                                                        section.IsPublished = true;
                                                        match = true;
                                                        section.EventID = entry.EventId;
                                                        syncedSections.Add(section);
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                        if (!match)
                                            hasFaild = true;
                                        #endregion
                                    }
                                }
                                #endregion
                            }
                            catch
                            {
                                hasFaild = true;
                            }
                            targetCal.Save();
                        }
                    }
                    syncedSections.SaveAll();
                };
                bkw.RunWorkerAsync();
            };
        }