//void gridView_SelectionChanged(object sender, EventArgs e)
        //{
        //    if (SecuritySystem.CurrentUser is Student)
        //    {
        //        Student student = SecuritySystem.CurrentUser as Student;
        //        string currentClass = student.StudentClass.ClassCode;
        //        ASPxGridView gc = sender as ASPxGridView;
        //        List<Vacancy> tempList = new List<Vacancy>(listVacancies);
        //        List<object> listobj = gc.GetSelectedFieldValues(new string[] { "LessonCode" });
        //        ObjectSpace objectSpace = Application.CreateObjectSpace();
        //        Vacancy vc;
        //        string strFilter = "", strInclude = "";
        //        foreach (int strLessonCode in listobj)
        //        {
        //            Lesson lesson = objectSpace.FindObject<Lesson>(new BinaryOperator("LessonCode", strLessonCode));
        //            strInclude += String.Format("OR ([LessonCode]={0})", lesson.LessonCode);
        //            foreach (TkbSemester tkbsem in lesson.TKBSemesters)
        //            {
        //                vc = new Vacancy(tkbsem.Day, tkbsem.Period, tkbsem.Weeks, (tkbsem.Classroom == null ? "" : tkbsem.Classroom.ClassroomCode));
        //                tempList.Add(vc);
        //            }
        //        }
        //        if (strInclude != "")
        //            strInclude = String.Format("({0})", strInclude.Substring(3));
        //        if (listobj.Count > 0)
        //        {
        //            using (XPCollection xpLesson = new XPCollection(objectSpace.Session, typeof(Lesson)))
        //            {
        //                foreach (Lesson lesson in xpLesson)
        //                {
        //                    foreach (TkbSemester tkbsem in lesson.TKBSemesters)
        //                    {
        //                        vc = new Vacancy(tkbsem.Day, tkbsem.Period, tkbsem.Weeks, (tkbsem.Classroom == null ? "" : tkbsem.Classroom.ClassroomCode));
        //                        if (Utils.IsConfictTKB(tempList, vc))
        //                        {
        //                            strFilter += String.Format("AND ([LessonCode]<>{0})", lesson.LessonCode);
        //                            break;
        //                        }
        //                    }
        //                }
        //                if (strFilter != "")
        //                    strFilter = String.Format("({0})", strFilter.Substring(4));
        //            }
        //        }
        //        if (strInclude != "" && strFilter != "")
        //        {
        //            strFilter = String.Format("({0} OR {1})", strFilter, strInclude);
        //        }
        //        else if (strInclude != "")
        //        {
        //            strFilter = strInclude;
        //        }
        //        if (strFilter != "")
        //        {
        //            if (gc.FilterExpression.Contains("TkbLesson.ClassIDs"))
        //            {
        //                gc.FilterExpression = string.Format("([TkbLesson.ClassIDs] Like '%{0}%') AND {1}", currentClass, strFilter);
        //            }
        //            else
        //            {
        //                gc.FilterExpression = strFilter;
        //            }
        //        }
        //    }
        //}
        //void gridView_DataBound(object sender, EventArgs e)
        //{
        //    if (SecuritySystem.CurrentUser is Student)
        //    {
        //        Student student = SecuritySystem.CurrentUser as Student;
        //        string currentClass = student.StudentClass.ClassCode;
        //        ASPxGridView gc = sender as ASPxGridView;
        //        if (gc.FilterExpression == "")
        //            gc.FilterExpression = string.Format("[TkbLesson.ClassIDs] Like '%{0}%'", currentClass);
        //    }
        //}
        void selectAcception_AcceptingStudent(object sender, DialogControllerAcceptingEventArgs e)
        {
            if (SecuritySystem.CurrentUser is Student)
            {
                ObjectSpace objectSpace = Application.CreateObjectSpace();
                DevExpress.ExpressApp.ListView lv = ((DevExpress.ExpressApp.ListView)((WindowController)sender).Window.View);
                if (SecuritySystem.CurrentUser is Student)
                {
                    objectSpace.Session.BeginTransaction();
                    Student student = SecuritySystem.CurrentUser as Student;
                    Student currentStudent = objectSpace.FindObject<Student>(
                        new BinaryOperator("StudentCode", student.StudentCode));
                    Lesson curLesson;
                    foreach (Lesson lesson in lv.SelectedObjects)
                    {
                        curLesson = objectSpace.FindObject<Lesson>(
                        new BinaryOperator("Oid", lesson.Oid));
                        RegisterDetail regdetail = new RegisterDetail(objectSpace.Session)
                        {
                            Student = currentStudent,
                            Lesson = curLesson,
                            RegisterState =  objectSpace.FindObject<RegisterState>(
                                new BinaryOperator ("Code","SELECTED")),
                            CheckState = objectSpace.FindObject<RegisterState>(
                                new BinaryOperator("Code", "NOTCHECKED"))
                        };

                    }
                    objectSpace.Session.CommitTransaction();
                    //               View.ObjectSpace.CommitChanges();
                    View.ObjectSpace.Refresh();
                }
            }
        }
        void selectAcception_AcceptingAdmin(object sender, DialogControllerAcceptingEventArgs e)
        {
            ObjectSpace objectSpace = Application.CreateObjectSpace();
            DevExpress.ExpressApp.ListView lv = ((DevExpress.ExpressApp.ListView)((WindowController)sender).Window.View);
            User u = (User)SecuritySystem.CurrentUser;
            XPCollection<Role> xpc = new XPCollection<Role>(u.Roles,
                new BinaryOperator("Name", "Administrators"));
            XPCollection<Role> xpc2 = new XPCollection<Role>(u.Roles,
              new BinaryOperator("Name", "DataAdmins"));
            if (xpc.Count + xpc2.Count > 0)
            {

                objectSpace.Session.BeginTransaction();

                Student currentStudent;
                Lesson curLesson;
                foreach (string studentCode in listStudentCode)
                {
                    currentStudent = objectSpace.FindObject<Student>(
                    new BinaryOperator("StudentCode", studentCode));
                    foreach (Lesson lesson in lv.SelectedObjects)
                    {
                        curLesson = objectSpace.FindObject<Lesson>(
                        new BinaryOperator("Oid", lesson.Oid));
                        RegisterDetail regdetail = new RegisterDetail(objectSpace.Session)
                        {
                            Student = currentStudent,
                            Lesson = curLesson,
                            RegisterState = objectSpace.FindObject<RegisterState>(
                                new BinaryOperator("Code", "SELECTED")),
                            CheckState =objectSpace.FindObject<RegisterState>(
                                new BinaryOperator("Code", "NOTCHECKED"))
                        };
                        RuleSet ruleSet = new RuleSet();

                        RuleSetValidationResult result = ruleSet.ValidateTarget(regdetail, DefaultContexts.Save);
                        if (ValidationState.Invalid ==
                            result.GetResultItem("RegisterDetail.StudentRegLessonSemester").State)
                        {
                            regdetail.Delete();
                        }
                        else
                        {
                            regdetail.Save();
                        }

                    }
                }
                objectSpace.Session.CommitTransaction();

                PopUpMessage ms = objectSpace.CreateObject<PopUpMessage>();
                ms.Title = "Lỗi đăng ký";
                ms.Message = string.Format("Error");
                ShowViewParameters svp = new ShowViewParameters();
                svp.CreatedView = Application.CreateDetailView(
                     objectSpace, ms);
                svp.TargetWindow = TargetWindow.NewModalWindow;
                svp.CreatedView.Caption = "Thông báo";
                DialogController  dc = Application.CreateController<DialogController>();
                svp.Controllers.Add(dc);

                dc.SaveOnAccept = false;
                Application.ShowViewStrategy.ShowView(svp,new ShowViewSource(null,null));
                ////               View.ObjectSpace.CommitChanges();
                //View.ObjectSpace.Refresh();
                //ListView view = null;
                //Frame currentFrame = ((ActionBase)sender).Controller.Frame;
                //switch (currentFrame.View.ObjectTypeInfo.Name)
                //{
                //    case "Student":
                //        view = Application.CreateListView(objectSpace,typeof(RegisterDetail),true);
                //        break;
                //}
                //currentFrame.SetView(view);
                //e.Cancel = true;
            }
        }
        void selectAcception_AcceptingStudent(object sender, DialogControllerAcceptingEventArgs e)
        {
            RuleSet ruleSet = new RuleSet();
            RuleSetValidationResult result;

            if (SecuritySystem.CurrentUser is Student)
            {
                ObjectSpace objectSpace = Application.CreateObjectSpace();
                ListView lv = ((ListView)((WindowController)sender).Window.View);
                if (SecuritySystem.CurrentUser is Student)
                {
                    objectSpace.Session.BeginTransaction();
                     PopUpMessage ms = objectSpace.CreateObject<PopUpMessage>();
                    ms.Title = "Chọn nhóm MH thành công";
                    ms.Message = "";
                    Student student = SecuritySystem.CurrentUser as Student;
                    Student currentStudent = objectSpace.FindObject<Student>(
                        new BinaryOperator("StudentCode", student.StudentCode));
                    Lesson curLesson;
                    int checkresult, selectsubject=0;
                    double selectcredits = 0;
                    string subjectcoderesult, msgresult;
                    foreach (Lesson lesson in lv.SelectedObjects)
                    {
                        if (Utils.IsConfictPrerequisite(objectSpace, student.StudentCode, lesson.Subject.SubjectCode, out checkresult, out subjectcoderesult))
                        {
                            switch (checkresult)
                            {
                                case 1: msgresult = "học trước"; break;
                                case 2: msgresult = "tiên quyết"; break;
                                default: msgresult = "-"; break;
                            };
                            Subject subj = objectSpace.FindObject<Subject>(CriteriaOperator.Parse("SubjectCode =?", subjectcoderesult));
                            ms.Message += string.Format("Không chọn được môn [{0}]{1} do vi phạm môn {2} là [{3}]{4}\r\n",
                                lesson.Subject.SubjectCode, lesson.Subject.SubjectName, msgresult, subj.SubjectCode, subj.SubjectName);
                            continue;
                        }
                        curLesson = objectSpace.FindObject<Lesson>(
                        new BinaryOperator("Oid", lesson.Oid));

                        RegisterDetail regdetail = new RegisterDetail(objectSpace.Session)
                        {
                            Student = currentStudent,
                            Lesson = curLesson,
                            RegisterState = objectSpace.FindObject<RegisterState>(
                                new BinaryOperator("Code", "SELECTED")),
                            CheckState = objectSpace.FindObject<RegisterState>(
                                new BinaryOperator("Code", "NOTCHECKED"))
                        };
                        selectcredits += curLesson.Subject.Credit;
                        selectsubject++;
                        result = ruleSet.ValidateTarget(regdetail, DefaultContexts.Save);
                        if (ValidationState.Invalid ==
                            result.GetResultItem("RegisterDetail.StudentRegLessonSemester").State)
                        {
                            regdetail.Delete();
                            selectcredits -= curLesson.Subject.Credit;
                            selectsubject--;
                        }

                    }
                    objectSpace.Session.CommitTransaction();

                    View.ObjectSpace.Refresh();

                    ms.Message += string.Format("Tổng số chọn được {0} nhóm lớp môn học với {1} tín chỉ.", selectsubject, selectcredits);
                    ShowViewParameters svp = new ShowViewParameters();
                    svp.CreatedView = Application.CreateDetailView(
                         objectSpace, ms);
                    svp.TargetWindow = TargetWindow.NewModalWindow;
                    svp.CreatedView.Caption = "Thông báo";
                    DialogController dc = Application.CreateController<DialogController>();
                    svp.Controllers.Add(dc);
                    dc.AcceptAction.Active.SetItemValue("object", false);
                    dc.CancelAction.Caption = "Đóng";
                    dc.SaveOnAccept = false;
                    Application.ShowViewStrategy.ShowView(svp, new ShowViewSource(null, null));
                }
            }
        }
        void selectAcception_AcceptingAdmin(object sender, DialogControllerAcceptingEventArgs e)
        {
            Dictionary<string, int> dicLessonCurrentRegNum = new Dictionary<string, int>();
            ObjectSpace objectSpace = Application.CreateObjectSpace();
            ListView lv = ((ListView)((WindowController)sender).Window.View);
            User u = (User)SecuritySystem.CurrentUser;
            XPCollection<Role> xpc = new XPCollection<Role>(u.Roles,
                new BinaryOperator("Name", "Administrators"));
            XPCollection<Role> xpc2 = new XPCollection<Role>(u.Roles,
              new BinaryOperator("Name", "DataAdmins"));
            if (xpc.Count + xpc2.Count > 0)
            {

                objectSpace.Session.BeginTransaction();

                Student currentStudent;
                Lesson curLesson;
                Dictionary<string, List<string>> errorstudent = new Dictionary<string, List<string>>();
                int numregok = 0;
                foreach (string studentCode in dicStudentRegDetail.Keys)
                {
                    currentStudent = objectSpace.FindObject<Student>(
                    new BinaryOperator("StudentCode", studentCode));
                    foreach (Lesson lesson in lv.SelectedObjects)
                    {
                        if (!dicLessonCurrentRegNum.ContainsKey(lesson.LessonName))
                        {
                            dicLessonCurrentRegNum[lesson.LessonName] = 0;
                        }
                        //si so chon chua vuot qua
                        if (lesson.NumExpectation > dicLessonCurrentRegNum[lesson.LessonName] + lesson.NumRegistration)
                        {
                            curLesson = objectSpace.FindObject<Lesson>(
                            new BinaryOperator("Oid", lesson.Oid));
                            RegisterDetail regdetail = new RegisterDetail(objectSpace.Session)
                            {
                                Student = currentStudent,
                                Lesson = curLesson,
                                RegisterState = objectSpace.FindObject<RegisterState>(
                                new BinaryOperator("Code", "SELECTED")),
                                CheckState = objectSpace.FindObject<RegisterState>(
                                    new BinaryOperator("Code", "NOTCHECKED"))
                            };
                            RuleSet ruleSet = new RuleSet();

                            RuleSetValidationResult result = ruleSet.ValidateTarget(regdetail, DefaultContexts.Save);
                            if (ValidationState.Invalid ==
                                result.GetResultItem("RegisterDetail.StudentRegLessonSemester").State)
                            {
                                if (!errorstudent.ContainsKey(currentStudent.StudentCode))
                                    errorstudent.Add(currentStudent.StudentCode, new List<string>());
                                if (!errorstudent[currentStudent.StudentCode].Contains(curLesson.Subject.SubjectCode))
                                    errorstudent[currentStudent.StudentCode].Add(curLesson.Subject.SubjectCode);
                                regdetail.Delete();
                            }
                            else
                            {
                                numregok++;
                                dicLessonCurrentRegNum[lesson.LessonName]++;
                                regdetail.Save();
                            }
                        }
                        else
                        {
                            if (!errorstudent.ContainsKey(currentStudent.StudentCode))
                                errorstudent.Add(currentStudent.StudentCode, new List<string>());
                            if (!errorstudent[currentStudent.StudentCode].Contains(lesson.Subject.SubjectCode))
                                errorstudent[currentStudent.StudentCode].Add(lesson.Subject.SubjectCode);
                        }

                    }
                }
                objectSpace.Session.CommitTransaction();
                PopUpMessage ms = objectSpace.CreateObject<PopUpMessage>();
                if (errorstudent.Count > 0)
                {
                    ms.Title = "Có lỗi khi chọn nhóm MH đăng ký!";
                    ms.Message = string.Format("Đã chọn được cho {0} sinh viên với {1} lượt nhóm MH\r\n", dicStudentRegDetail.Count, numregok);
                    string strmessage = "Không chọn được nhóm môn học do trùng môn đã đăng ký hoặc hết chỗ: ";
                    foreach (KeyValuePair<string, List<string>> keypair in errorstudent)
                    {
                        strmessage += string.Format("Sinh viên:[{0}] - Môn:[",keypair.Key);
                        foreach (string str in keypair.Value)
                        {
                            strmessage+= str +",";
                        }
                        strmessage= strmessage.TrimEnd(',');
                        strmessage += "]\r\n";
                    }
                    ms.Message += strmessage;
                }
                else
                {
                    ms.Title = "Chọn nhóm MH thành công";
                    ms.Message = string.Format("Chọn nhóm MH thành công cho {0} sinh viên với {1} lượt nhóm MH\r\n", dicStudentRegDetail.Count, numregok);
                }
                ShowViewParameters svp = new ShowViewParameters();
                svp.CreatedView = Application.CreateDetailView(
                     objectSpace, ms);
                svp.TargetWindow = TargetWindow.NewModalWindow;
                svp.CreatedView.Caption = "Thông báo";
                DialogController dc = Application.CreateController<DialogController>();
                svp.Controllers.Add(dc);

                dc.SaveOnAccept = false;
                Application.ShowViewStrategy.ShowView(svp, new ShowViewSource(null, null));
            }
        }
        private void DefaultRegister_Execute(object sender, SimpleActionExecuteEventArgs e)
        {
            ObjectSpace objectSpace = Application.CreateObjectSpace();

            dicStudentRegDetail = new Dictionary<string, List<string>>();
            Student currentStudent;
            Lesson curLesson;
            Dictionary<string, List<string>> errorstudent = new Dictionary<string, List<string>>();
            Dictionary<string, int> dicLessonCurrentRegNum = new Dictionary<string, int>();
            int numregok = 0;
            Vacancy vc;
            bool isConflictTKB = false;
            using (XPCollection<Lesson> newCollectionSource = new XPCollection<Lesson>(objectSpace.Session))
            {
                objectSpace.Session.BeginTransaction();
                foreach (StudentClass studentClass in View.SelectedObjects)
                {
                    newCollectionSource.Criteria = CriteriaOperator.Parse(
                        "ClassIDs like ?", string.Format("%{0}%", studentClass.ClassCode));

                    foreach (Student student in studentClass.Students)
                    {
                        listVacancies = new List<Vacancy>();
                        currentStudent = objectSpace.FindObject<Student>(
                        new BinaryOperator("StudentCode", student.StudentCode));

                        foreach (Lesson lesson in newCollectionSource)
                        {
                            isConflictTKB = false;
                            if (!dicLessonCurrentRegNum.ContainsKey(lesson.LessonName))
                            {
                                dicLessonCurrentRegNum[lesson.LessonName] = 0;
                            }
                            foreach (TkbSemester tkbsem in lesson.TKBSemesters)
                            {
                                vc = new Vacancy(tkbsem.Day, tkbsem.Period, tkbsem.Weeks, (tkbsem.Classroom == null ? "" : tkbsem.Classroom.ClassroomCode));
                                if (Utils.IsConfictTKB(listVacancies, vc))
                                {
                                    isConflictTKB = true;
                                    break;
                                }
                            }

                            if (isConflictTKB)
                            {
                                if (!errorstudent.ContainsKey(currentStudent.StudentCode))
                                    errorstudent.Add(currentStudent.StudentCode, new List<string>());
                                if (!errorstudent[currentStudent.StudentCode].Contains(lesson.Subject.SubjectCode))
                                    errorstudent[currentStudent.StudentCode].Add(lesson.Subject.SubjectCode + "{T}");
                            }
                            else
                            {
                                //si so chon chua vuot qua
                                if (lesson.NumExpectation > dicLessonCurrentRegNum[lesson.LessonName] + lesson.NumRegistration)
                                {
                                    curLesson = objectSpace.FindObject<Lesson>(
                                    new BinaryOperator("Oid", lesson.Oid));
                                    RegisterDetail regdetail = new RegisterDetail(objectSpace.Session)
                                    {
                                        Student = currentStudent,
                                        Lesson = curLesson,
                                        RegisterState = objectSpace.FindObject<RegisterState>(
                                            new BinaryOperator("Code", "SELECTED")),
                                        CheckState = objectSpace.FindObject<RegisterState>(
                                        new BinaryOperator("Code", "NOTCHECKED"))
                                    };
                                    RuleSet ruleSet = new RuleSet();

                                    RuleSetValidationResult result = ruleSet.ValidateTarget(regdetail, DefaultContexts.Save);
                                    if (ValidationState.Invalid ==
                                        result.GetResultItem("RegisterDetail.StudentRegLessonSemester").State)
                                    {
                                        if (!errorstudent.ContainsKey(currentStudent.StudentCode))
                                            errorstudent.Add(currentStudent.StudentCode, new List<string>());
                                        if (!errorstudent[currentStudent.StudentCode].Contains(curLesson.Subject.SubjectCode))
                                            errorstudent[currentStudent.StudentCode].Add(curLesson.Subject.SubjectCode + "{D}");
                                        regdetail.Delete();
                                        //regdetail.Reload();

                                    }
                                    else
                                    {
                                        numregok++;
                                        if (!dicStudentRegDetail.ContainsKey(student.StudentCode))
                                            dicStudentRegDetail.Add(student.StudentCode,new List<string>());
                                        dicStudentRegDetail[student.StudentCode].Add(curLesson.LessonName);

                                        dicLessonCurrentRegNum[lesson.LessonName]++;
                                        foreach (TkbSemester tkbsem in curLesson.TKBSemesters)
                                        {
                                            vc = new Vacancy(tkbsem.Day, tkbsem.Period, tkbsem.Weeks, (tkbsem.Classroom == null ? "" : tkbsem.Classroom.ClassroomCode));
                                            listVacancies.Add(vc);
                                        }
                                        regdetail.Save();
                                    }
                                }
                                else
                                {
                                    if (!errorstudent.ContainsKey(currentStudent.StudentCode))
                                        errorstudent.Add(currentStudent.StudentCode, new List<string>());
                                    if (!errorstudent[currentStudent.StudentCode].Contains(lesson.Subject.SubjectCode))
                                        errorstudent[currentStudent.StudentCode].Add(lesson.Subject.SubjectCode + "{H}");
                                }
                            }
                        }
                    }
                }
                objectSpace.Session.CommitTransaction();
                PopUpMessage ms = objectSpace.CreateObject<PopUpMessage>();
                if (errorstudent.Count > 0)
                {
                    ms.Title = "Có lỗi khi chọn nhóm MH đăng ký!";
                    ms.Message = string.Format("Đã chọn được cho {0} sinh viên với {1} lượt nhóm MH\r\n", dicStudentRegDetail.Count, numregok);
                    string strmessage = "Không chọn được nhóm môn học do trùng môn đã đăng ký, trùng lịch hoặc hết chỗ: ";
                    foreach (KeyValuePair<string, List<string>> keypair in errorstudent)
                    {
                        strmessage += string.Format("Sinh viên:[{0}] - Môn:[", keypair.Key);
                        foreach (string str in keypair.Value)
                        {
                            strmessage += str + ",";
                        }
                        strmessage = strmessage.TrimEnd(',');
                        strmessage += "]\r\n";
                    }
                    ms.Message += strmessage;
                }
                else
                {
                    ms.Title = "Chọn nhóm MH thành công";
                    ms.Message = string.Format("Chọn nhóm MH thành công cho {0} sinh viên với {1} lượt nhóm MH\r\n", dicStudentRegDetail.Count, numregok);
                }
                ShowViewParameters svp = new ShowViewParameters();
                svp.CreatedView = Application.CreateDetailView(
                     objectSpace, ms);
                svp.TargetWindow = TargetWindow.NewModalWindow;
                svp.CreatedView.Caption = "Thông báo";
                DialogController dc = Application.CreateController<DialogController>();
                svp.Controllers.Add(dc);

                dc.SaveOnAccept = false;
                Application.ShowViewStrategy.ShowView(svp, new ShowViewSource(null, null));
            }
        }