Пример #1
0
        protected override void ExecuteEdit(DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs args)
        {
            if (View.CurrentObject.GetType() == typeof(WorkCalendarEvent))
            {
                WorkCalendarEvent workCalendarEvent = this.View.CurrentObject as WorkCalendarEvent;

                if (workCalendarEvent.JobCard != null)
                {
                    this.LoadDetailView(args, workCalendarEvent.JobCard);
                }
                else if (workCalendarEvent.Project != null)
                {
                    this.LoadDetailView(args, workCalendarEvent.Project);
                }
                else if (workCalendarEvent.WorkFlowTask != null)
                {
                    this.LoadDetailView(args, workCalendarEvent.WorkFlowTask);
                }
                else if (workCalendarEvent.Task != null)
                {
                    this.LoadDetailView(args, workCalendarEvent.Task);
                }
                else if (workCalendarEvent.Booking != null)
                {
                    this.LoadDetailView(args, workCalendarEvent.Booking);
                }

                return;
            }

            base.ExecuteEdit(args);
        }
Пример #2
0
        void myAction_Execute(object sender, DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs e)
        {
            var args = new SingleChoiceActionExecuteEventArgs(e.Action, e.Action.SelectionContext, new ChoiceActionItem("NewObject", typeof(LocationData)));

            New(args);
            e.ShowViewParameters.Assign(args.ShowViewParameters);
        }
Пример #3
0
 void SetEnableSelectAction_Execute(object sender, DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs e)
 {
     foreach (Lesson l in View.SelectedObjects)
     {
         View.ObjectSpace.SetModified(l);
         l.CanRegister = true;
     }
     View.ObjectSpace.CommitChanges();
 }
        protected void AcceptAction_Execute(object sender, DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs e)
        {
            var paramObj = (ImportDelimitedFileDataParam)View.CurrentObject;

            switch (paramObj.ImportLibrary)
            {
            case ImportLibrary.FastCsvReader:
                FastCsvImport();
                break;
            }
        }
Пример #5
0
        void myAction_Execute(object sender, DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs e)
        {
            var f = new NKD.Module.Win.Controllers.UpdateConfig();

            if (f.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                //System.Windows.Forms.Application.Restart();
                System.Diagnostics.Process.Start(System.Windows.Forms.Application.ExecutablePath);
                Process.GetCurrentProcess().Kill();
            }
        }
Пример #6
0
 private void SimpleAction_GenerateMessages_Execute(object sender, DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs e)
 {
     using (var uow = new UnitOfWork(XpoDefault.DataLayer))
     {
         var currentObject = uow.GetObjectByKey <DoSoScheduleBase>(ViewCurrentObject.ID);
         //currentObject.CreateDataSourceFromXml();
         var list = currentObject.GenerateMessages(uow, false);
         currentObject.GetNextExecutionDate();
         uow.CommitChanges();
     }
 }
Пример #7
0
        private void LoadDetailView(DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs args, Type Type)
        {
            IObjectSpace objectSpace   = Application.CreateObjectSpace();
            object       currentObject = objectSpace.CreateObject(Type);

            DetailView view = Application.CreateDetailView(objectSpace, currentObject, true);

            view.ViewEditMode = DevExpress.ExpressApp.Editors.ViewEditMode.Edit;
            view.Closed      += View_Closed;

            args.ShowViewParameters.CreatedView     = view;
            args.ShowViewParameters.CreatedView.Tag = objectSpace.GetKeyValue(currentObject);
            args.ShowViewParameters.TargetWindow    = TargetWindow.NewModalWindow;
            args.ShowViewParameters.Context         = TemplateContext.PopupWindow;
        }
Пример #8
0
        void ViewClassTrackingAction_Execute(object sender, DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs e)
        {
            ObjectSpace objectSpace = Application.CreateObjectSpace();
            Semester    semester    = View.SelectedObjects[0] as Semester;

            Data.CreateStudentClassTrackingData(objectSpace, semester.SemesterName);

            ReportData reportData = objectSpace.FindObject <ReportData>(
                new BinaryOperator("Name", "Tỉ lệ nợ lớp biên chế NHHK"));
            string strParse = string.Format("Semester.SemesterName= '{0}'", semester.SemesterName);

            ReportServiceController rsc = Frame.GetController <ReportServiceController>();

            rsc.ShowPreview((IReportData)reportData, CriteriaOperator.Parse(strParse));
        }
Пример #9
0
        private void LoadDetailView(DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs args, object Workflow)
        {
            IObjectSpace objectSpace   = Application.CreateObjectSpace();
            Session      session       = ((XPObjectSpace)objectSpace).Session;
            object       currentObject = session.FindObject(Workflow.GetType(), CriteriaOperator.Parse("Oid == ?", (Workflow as BaseObject).Oid));

            DetailView view = Application.CreateDetailView(objectSpace, currentObject, true);

            view.ViewEditMode = DevExpress.ExpressApp.Editors.ViewEditMode.Edit;
            view.Closed      += View_Closed;

            args.ShowViewParameters.CreatedView     = view;
            args.ShowViewParameters.CreatedView.Tag = objectSpace.GetKeyValue(currentObject);
            args.ShowViewParameters.TargetWindow    = TargetWindow.NewModalWindow;
            args.ShowViewParameters.Context         = TemplateContext.PopupWindow;
        }
        void ViewClassTransactionTrackingAction_Execute(object sender, DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs e)
        {
            ObjectSpace objectSpace = Application.CreateObjectSpace();


            if (View.SelectedObjects.Count > 0)
            {
                DialogController selectSemesterAcception;
                ListView         lvSemester = Application.CreateListView(objectSpace, typeof(Semester), true);
                lvSemester.Editor.AllowEdit = false;

                e.ShowViewParameters.CreatedView          = lvSemester;
                e.ShowViewParameters.TargetWindow         = TargetWindow.NewModalWindow;
                e.ShowViewParameters.CreateAllControllers = true;

                selectSemesterAcception = new DialogController();
                e.ShowViewParameters.Controllers.Add(selectSemesterAcception);
                selectSemesterAcception.Accepting += new EventHandler <DialogControllerAcceptingEventArgs>(selectSemesterForClassTransactionTrackingAcception_Accepting);
                selectSemesterAcception.AcceptAction.TargetObjectsCriteriaMode = TargetObjectsCriteriaMode.TrueForAll;
                selectSemesterAcception.AcceptAction.TargetObjectType          = typeof(Semester);
                selectSemesterAcception.AcceptAction.SelectionDependencyType   = SelectionDependencyType.RequireSingleObject;
                selectSemesterAcception.AcceptAction.TargetViewType            = ViewType.ListView;
                selectSemesterAcception.AcceptAction.Caption = "Chọn";
                selectSemesterAcception.CancelAction.Caption = "Bỏ qua";
            }
            else
            {
                PopUpMessage     ms;
                DialogController dc;
                ms         = objectSpace.CreateObject <PopUpMessage>();
                ms.Title   = "Thông báo";
                ms.Message = string.Format("Vui lòng chọn ít nhất một lớp biên chế để xem kết quả tổng hợp học phí");
                e.ShowViewParameters.CreatedView = Application.CreateDetailView(
                    objectSpace, ms);
                e.ShowViewParameters.TargetWindow        = TargetWindow.NewModalWindow;
                e.ShowViewParameters.CreatedView.Caption = "Thông báo";
                dc = Application.CreateController <DialogController>();
                dc.AcceptAction.Active.SetItemValue("object", false);
                dc.CancelAction.Caption = "Đóng";
                dc.SaveOnAccept         = false;
                e.ShowViewParameters.Controllers.Add(dc);
            }
        }
Пример #11
0
        void ViewTeacherTimetableAction_Execute(object sender, DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs e)
        {
            ObjectSpace      objectSpace = Application.CreateObjectSpace();
            DialogController selectSemesterAcception;

            ListView lvSemester = Application.CreateListView(objectSpace, typeof(Semester), true);

            lvSemester.Editor.AllowEdit = false;

            e.ShowViewParameters.CreatedView          = lvSemester;
            e.ShowViewParameters.TargetWindow         = TargetWindow.NewModalWindow;
            e.ShowViewParameters.CreateAllControllers = true;

            selectSemesterAcception = new DialogController();
            e.ShowViewParameters.Controllers.Add(selectSemesterAcception);
            selectSemesterAcception.Accepting += new EventHandler <DialogControllerAcceptingEventArgs>(selectSemesterAcception_Accepting);
            selectSemesterAcception.AcceptAction.TargetObjectsCriteriaMode = TargetObjectsCriteriaMode.TrueForAll;
            selectSemesterAcception.AcceptAction.TargetObjectType          = typeof(Semester);
            selectSemesterAcception.AcceptAction.SelectionDependencyType   = SelectionDependencyType.RequireSingleObject;
            selectSemesterAcception.AcceptAction.TargetViewType            = ViewType.ListView;
            selectSemesterAcception.AcceptAction.Caption = "Chọn";
            selectSemesterAcception.CancelAction.Caption = "Bỏ qua";
        }
Пример #12
0
        private void SimpleAction_PrevewMessages_Execute(object sender, DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs e)
        {
            var os   = Application.CreateObjectSpace() as XPObjectSpace;
            var list = ViewCurrentObject.GenerateMessages(os.Session, true);

            if (!list.Any())
            {
                return;
            }

            var type = list.FirstOrDefault().GetType();

            var collection = new CollectionSource(os, type);
            var listView   = Application.CreateListView(Application.FindListViewId(type), collection, false);

            listView.CreateControls();

            var itemInOs = os.GetCollectionSorting(list);// .GetObjects(typeof(DoSoMessageBase), CriteriaOperator.Parse("ID = 0"), true);

            foreach (var item in list)
            {
                listView.CollectionSource.List.Add(item);
            }
            //e.Context = TemplateContext.LookupControl;

            var svp = new ShowViewParameters
            {
                CreatedView     = listView,
                NewWindowTarget = NewWindowTarget.Default,
                TargetWindow    = TargetWindow.NewModalWindow,
                Context         = TemplateContext.View
            };

            svp.Controllers.Add(new ToolbarVisibilityController());
            Application.ShowViewStrategy.ShowView(svp, new ShowViewSource(null, null));
        }
Пример #13
0
        void ImportSubjectAction_Execute(object sender, DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs e)
        {
            ObjectSpace      objectSpace      = Application.CreateObjectSpace();
            CollectionSource collectionSource = new CollectionSource(objectSpace, typeof(MyImportResult));
            int count = 0;
            int iLine = 0;

            if ((collectionSource.Collection as XPBaseCollection) != null)
            {
                ((XPBaseCollection)collectionSource.Collection).LoadingEnabled = false;
            }

            foreach (SubjectFile actFile in View.SelectedObjects)
            {
                if (actFile.Note == "")
                {
                    throw new UserFriendlyException("Vui lòng thêm thông tin Ghi chú trước khi import!!!");
                }

                string tempStudentFile;
                string tempStudentFolderPath;
                string tempStudentLogFile;
                string templogname = "";
                if (HttpContext.Current != null)
                {
                    tempStudentFolderPath = HttpContext.Current.Request.MapPath("~/tempFolder");
                    tempStudentFile       = HttpContext.Current.Request.MapPath("~/tempFolder/" + actFile.CsvFile.FileName);
                    templogname           = actFile.CsvFile.FileName + DateTime.Now.ToString("dd-MM-yyyy-HHmmss") + "-log.html";
                    tempStudentLogFile    = HttpContext.Current.Request.MapPath("~/tempFolder/" + templogname);
                }
                else
                {
                    tempStudentFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder");
                    tempStudentFile       = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder/", actFile.CsvFile.FileName);
                    templogname           = actFile.CsvFile.FileName + DateTime.Now.ToString("dd-MM-yyyy-HHmmss") + "-log.html";
                    tempStudentLogFile    = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder/", templogname);
                }

                if (!Directory.Exists(tempStudentFolderPath))
                {
                    Directory.CreateDirectory(tempStudentFolderPath);
                }

                using (System.IO.FileStream fileStream = new FileStream(tempStudentFile, FileMode.OpenOrCreate))
                {
                    Dictionary <string, int>    columnIndexs = new Dictionary <string, int>();
                    Dictionary <string, object> valueIndexs  = new Dictionary <string, object>();
                    valueIndexs.Add("MAMH", "");
                    valueIndexs.Add("TENMH", "");
                    valueIndexs.Add("SOTC", "");
                    valueIndexs.Add("MANGANH", "");
                    valueIndexs.Add("TENNGANH", "");

                    columnIndexs.Add("MAMH", -1);
                    columnIndexs.Add("TENMH", -1);
                    columnIndexs.Add("SOTC", -1);
                    columnIndexs.Add("MANGANH", -1);
                    columnIndexs.Add("TENNGANH", -1);


                    // open xls file
                    actFile.CsvFile.SaveToStream(fileStream);
                    fileStream.Close();
                    Workbook  book  = Workbook.Open(tempStudentFile);
                    Worksheet sheet = book.Worksheets[0];


                    bool foundHeader = false;

                    Row row;
                    //Tìm dòng chứa TEN cột
                    for (iLine = sheet.Cells.FirstRowIndex;
                         iLine <= sheet.Cells.LastRowIndex && !foundHeader; iLine++)
                    {
                        row = sheet.Cells.GetRow(iLine);
                        for (int colIndex = row.FirstColIndex;
                             colIndex <= row.LastColIndex; colIndex++)
                        {
                            Cell cell = row.GetCell(colIndex);
                            if (columnIndexs.ContainsKey(cell.Value.ToString().ToUpper().Trim()))
                            {
                                columnIndexs[cell.Value.ToString().ToUpper().Trim()] = colIndex; //Đã tìm thấy dòng chứa TEN cột. Xác định vị trí của cột
                            }
                        }
                        if (!columnIndexs.Values.Contains(-1))
                        {
                            foundHeader = true;
                        }
                        else
                        {
                            for (int colIndex = row.FirstColIndex; colIndex <= row.LastColIndex; colIndex++)
                            {
                                Cell cell = row.GetCell(colIndex);
                                if (columnIndexs.ContainsKey(cell.Value.ToString().ToUpper().Trim()))
                                {
                                    columnIndexs[cell.Value.ToString().ToUpper().Trim()] = -1; //không tìm thấy dòng chứa TEN cột. Xác định vị trí của cột
                                }
                            }
                        }
                    }
                    if (!foundHeader)
                    {
                        throw new UserFriendlyException("Lỗi cấu trúc file");
                    }

                    using (System.IO.StreamWriter fileStreamlog = new System.IO.StreamWriter(tempStudentLogFile, true))
                    {
                        fileStreamlog.WriteLine("<html><header><title>" + actFile.CsvFile.FileName + DateTime.Now.ToString("dd-MM-yyyy-HHmmss") + "-log </title>	"+
                                                "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />" +
                                                "</head><body>\r\n<table border=\"1px\"> <tr><Th>DÒNG</Th><th>TÌNH TRẠNG</th><th>THÔNG ĐIỆP</th></Tr>");
                        //Các dòng sau đó đều là dòng dữ liệu

                        List <Branch> listBranches = new List <Branch>();


                        for (; iLine <= sheet.Cells.LastRowIndex; iLine++)
                        {
                            row = sheet.Cells.GetRow(iLine);
                            try
                            {
                                foreach (var column in columnIndexs)
                                {
                                    Cell cell = row.GetCell(column.Value);
                                    valueIndexs[column.Key] = cell.Value;
                                }

                                if (valueIndexs["MAMH"] == null || valueIndexs["TENMH"] == null || valueIndexs["SOTC"] == null)
                                {
                                    fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "ERROR",
                                                            string.Format("Can not import line with  [MAMH or TENMH or SOTINCHI] is NULL on {0:dd-mm-yy HH:MM:ss}", DateTime.Now));
                                    continue;
                                }
                                //tạo NGÀNH
                                Branch branch;
                                if (valueIndexs["MANGANH"] == null)
                                {
                                    branch = null;
                                }
                                else
                                {
                                    branch = listBranches.Find(l => l.BranchCode == valueIndexs["MANGANH"].ToString());
                                    if (branch == null)
                                    {
                                        objectSpace.FindObject <Branch>(new BinaryOperator("BranchCode", valueIndexs["MANGANH"].ToString()));
                                    }
                                    if (branch != null)
                                    {
                                        if (valueIndexs["TENNGANH"] == null || branch.BranchName != valueIndexs["TENNGANH"].ToString())
                                        {
                                            fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "WARNING",
                                                                    string.Format("Branch: \"{0}\" has name \"{1}\" different to \"{2}\" on {3:dd-mm-yy HH:MM:ss}",
                                                                                  branch.BranchCode, branch.BranchName, valueIndexs["TENNGANH"], DateTime.Now));
                                        }
                                        if (!listBranches.Contains(branch))
                                        {
                                            listBranches.Add(branch);
                                        }
                                    }
                                    else
                                    {
                                        branch = objectSpace.CreateObject <Branch>();

                                        branch.BranchCode = valueIndexs["MANGANH"].ToString();
                                        branch.BranchName = valueIndexs["TENNGANH"] == null ? null : valueIndexs["TENNGANH"].ToString();
                                        branch.Save();
                                        listBranches.Add(branch);
                                        fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "CREATE NEW",
                                                                string.Format("Create new branch: \"{0}\"-\"{1}\" on {2:dd-mm-yy HH:MM:ss}",
                                                                              branch.BranchCode, branch.BranchName, DateTime.Now));
                                    }
                                }

                                //tạo MÔN HỌC
                                Subject subject = objectSpace.FindObject <Subject>(new BinaryOperator("SubjectCode", valueIndexs["MAMH"].ToString()));
                                if (subject != null)
                                {
                                    //subject.SubjectCode = valueIndexs["MAMH"].ToString();
                                    subject.SubjectName = valueIndexs["TENMH"].ToString();
                                    subject.Credit      = (double)valueIndexs["SOTC"];
                                    subject.Branch      = branch;
                                    subject.Note        = actFile.Note;
                                    subject.Save();
                                    fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "UPDATE",
                                                            string.Format("Update subject: [{0}]-[{1}({2:#.#})] on {3:dd-mm-yy HH:MM:ss}",
                                                                          subject.SubjectCode, subject.SubjectName, subject.Credit, DateTime.Now));
                                }
                                else
                                {
                                    subject             = objectSpace.CreateObject <Subject>();
                                    subject.SubjectCode = valueIndexs["MAMH"].ToString();
                                    subject.SubjectName = valueIndexs["TENMH"].ToString();
                                    subject.Credit      = (double)valueIndexs["SOTC"];
                                    subject.Branch      = branch;
                                    subject.Note        = actFile.Note;
                                    subject.Save();
                                    fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "CREATE NEW",
                                                            string.Format("Create subject: [{0}]-[{1}({2:#.#})] on {3:dd-mm-yy HH:MM:ss}",
                                                                          subject.SubjectCode, subject.SubjectName, subject.Credit, DateTime.Now));
                                }
                                objectSpace.CommitChanges();
                                count++;
                            }
                            catch (Exception ex)
                            {
                                fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "ERROR",
                                                        ex.Message + ex.StackTrace);
                            }
                        }
                        fileStreamlog.WriteLine("</table></body></html>");
                        fileStreamlog.Close();
                    }

                    View.ObjectSpace.SetModified(actFile);
                    actFile.IsImported = true;
                    actFile.ResultLink = "/tempFolder/" + templogname;

                    View.ObjectSpace.CommitChanges();
                }
            }
            PopUpMessage     ms;
            DialogController dc;

            ms         = objectSpace.CreateObject <PopUpMessage>();
            ms.Title   = "Kết quả import";
            ms.Message = string.Format("Đã thực hiện import {0} kết quả cho {1} dòng trong file\r\n Vui lòng xem link kết quả", count, iLine);
            e.ShowViewParameters.CreatedView = Application.CreateDetailView(
                objectSpace, ms);
            e.ShowViewParameters.TargetWindow        = TargetWindow.NewModalWindow;
            e.ShowViewParameters.CreatedView.Caption = "Thông báo";
            dc = Application.CreateController <DialogController>();
            dc.AcceptAction.Active.SetItemValue("object", false);
            dc.CancelAction.Caption = "Đóng";
            dc.SaveOnAccept         = false;
            e.ShowViewParameters.Controllers.Add(dc);
        }
Пример #14
0
        void ImportTransactionDataAction_Execute(object sender, DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs e)
        {
            ObjectSpace objectSpace = Application.CreateObjectSpace();
            //ObjectSpace objectSpace =  ObjectSpaceInMemory.CreateNew();
            CollectionSource collectionSource = new CollectionSource(objectSpace, typeof(MyImportResult));

            if ((collectionSource.Collection as XPBaseCollection) != null)
            {
                ((XPBaseCollection)collectionSource.Collection).LoadingEnabled = false;
            }
            actFilesSelect.Clear();
            foreach (AccountTransactionFile actFile in View.SelectedObjects)
            {
                if (actFile.Note == "")
                {
                    throw new UserFriendlyException("Vui lòng thêm thông tin Ghi chú trước khi import!!!");
                }
                if (actFile.Semester == null)
                {
                    throw new UserFriendlyException("Vui lòng thêm thông tin NHHK trước khi import!!!");
                }

                actFilesSelect.Add(actFile.Oid);
                string tempStudentFolderPath;
                string tempStudentFile;
                string tempStudentLogFile;
                if (HttpContext.Current != null)
                {
                    tempStudentFolderPath = HttpContext.Current.Request.MapPath("~/tempFolder");
                    tempStudentFile       = HttpContext.Current.Request.MapPath("~/tempFolder/" + actFile.CsvFile.FileName);
                    tempStudentLogFile    = HttpContext.Current.Request.MapPath("~/tempFolder/" + actFile.CsvFile.FileName + DateTime.Now.ToString("dd-MM-yyyy-HHmmss") + "-log.txt");
                }
                else
                {
                    tempStudentFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder");
                    tempStudentFile       = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder/", actFile.CsvFile.FileName);
                    tempStudentLogFile    = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder/", actFile.CsvFile.FileName + "-log.html");
                }

                if (!Directory.Exists(tempStudentFolderPath))
                {
                    Directory.CreateDirectory(tempStudentFolderPath);
                }
                using (System.IO.FileStream fileStream = new FileStream(tempStudentFile, FileMode.OpenOrCreate))
                {
                    Dictionary <string, int>    columnIndexs = new Dictionary <string, int>();
                    Dictionary <string, object> valueIndexs  = new Dictionary <string, object>();
                    valueIndexs.Add("MSSV", "");
                    valueIndexs.Add("HOLOT", "");
                    valueIndexs.Add("TEN", "");
                    valueIndexs.Add("SOTIEN", "");
                    valueIndexs.Add("NGAYNOP", "");
                    valueIndexs.Add("DIENGIAI", "");

                    columnIndexs.Add("MSSV", -1);
                    columnIndexs.Add("HOLOT", -1);
                    columnIndexs.Add("TEN", -1);
                    columnIndexs.Add("SOTIEN", -1);
                    columnIndexs.Add("NGAYNOP", -1);
                    columnIndexs.Add("DIENGIAI", -1);

                    // open xls file
                    actFile.CsvFile.SaveToStream(fileStream);
                    fileStream.Close();
                    Workbook  book  = Workbook.Open(tempStudentFile);
                    Worksheet sheet = book.Worksheets[0];


                    bool foundHeader = false;
                    int  iLine;
                    Row  row;
                    //Tìm dòng chứa TEN cột
                    for (iLine = sheet.Cells.FirstRowIndex;
                         iLine <= sheet.Cells.LastRowIndex && !foundHeader; iLine++)
                    {
                        row = sheet.Cells.GetRow(iLine);
                        for (int colIndex = row.FirstColIndex;
                             colIndex <= row.LastColIndex; colIndex++)
                        {
                            Cell cell = row.GetCell(colIndex);
                            if (columnIndexs.ContainsKey(cell.Value.ToString().ToUpper().Trim()))
                            {
                                columnIndexs[cell.Value.ToString().ToUpper().Trim()] = colIndex; //Đã tìm thấy dòng chứa TEN cột. Xác định vị trí của cột
                            }
                        }
                        if (!columnIndexs.Values.Contains(-1))
                        {
                            foundHeader = true;
                        }
                        else
                        {
                            for (int colIndex = row.FirstColIndex; colIndex <= row.LastColIndex; colIndex++)
                            {
                                Cell cell = row.GetCell(colIndex);
                                if (columnIndexs.ContainsKey(cell.Value.ToString().ToUpper().Trim()))
                                {
                                    columnIndexs[cell.Value.ToString().ToUpper().Trim()] = -1; //không tìm thấy dòng chứa TEN cột. Xác định vị trí của cột
                                }
                            }
                        }
                    }
                    if (!foundHeader)
                    {
                        throw new UserFriendlyException("Lỗi cấu trúc file");
                    }


                    //actFile.IsImported  = true;
                    //header row
                    MyImportResult myImportResult = objectSpace.CreateObject <MyImportResult>();

                    row = sheet.Cells.GetRow(iLine - 1);
                    myImportResult.vwKey = iLine - 1;
                    myImportResult.Line  = iLine - 1;
                    myImportResult.Data  = "";
                    foreach (var column in columnIndexs)
                    {
                        Cell cell = row.GetCell(column.Value);
                        valueIndexs[column.Key] = cell.Value;
                        myImportResult.Data    += (myImportResult.Data == "" ? "" : "|") + cell.Value.ToString();
                    }
                    myImportResult.CanImport = false;
                    myImportResult.Message   = "HEADER LINE";
                    collectionSource.List.Add(myImportResult);


                    //Các dòng sau đó đều là dòng dữ liệu
                    for (; iLine <= sheet.Cells.LastRowIndex; iLine++)
                    {
                        myImportResult           = objectSpace.CreateObject <MyImportResult>();
                        row                      = sheet.Cells.GetRow(iLine);
                        myImportResult.vwKey     = iLine;
                        myImportResult.Line      = iLine;
                        myImportResult.Data      = "";
                        myImportResult.Message   = "";
                        myImportResult.Status    = "OK";
                        myImportResult.CanImport = true;

                        foreach (var column in columnIndexs)
                        {
                            Cell cell = row.GetCell(column.Value);
                            valueIndexs[column.Key] = cell.Value;
                            myImportResult.Data    += (myImportResult.Data == "" ? "" : "|") + (valueIndexs[column.Key] == null ? "" : valueIndexs[column.Key].ToString());
                        }
                        // tìm sinh viên
                        if (valueIndexs["MSSV"] == null)
                        {
                            myImportResult.CanImport = false;
                            myImportResult.Status    = "LỖI";
                            myImportResult.Message   = (myImportResult.Message == "" ? "" : ",") +
                                                       string.Format("Cannot find student: \"{0}\"", valueIndexs["MSSV"]);
                        }

                        Student student = objectSpace.FindObject <Student>(new BinaryOperator("StudentCode", valueIndexs["MSSV"]));
                        if (student == null)
                        {
                            myImportResult.CanImport = false;
                            myImportResult.Status    = "LỖI";
                            myImportResult.Message   = (myImportResult.Message == "" ? "" : ",") +
                                                       string.Format("Cannot find student: \"{0}\"", valueIndexs["MSSV"]);
                        }
                        else
                        {
                            if (valueIndexs["HOLOT"] == null || valueIndexs["TEN"] == null ||
                                student.FirstName.Trim() != valueIndexs["HOLOT"].ToString().Trim() ||
                                student.LastName.Trim() != valueIndexs["TEN"].ToString().Trim())
                            {
                                myImportResult.Status   = (myImportResult.Status == "OK" ? "CẢNH BÁO" : myImportResult.Status);
                                myImportResult.Message += (myImportResult.Message == "" ? "" : ",") +
                                                          string.Format("Found StudentCode: \"{0}\" but Full Name \"{1} \" is not like \"{2} {3}\"",
                                                                        student.StudentCode, student.FullName, valueIndexs["HOLOT"], valueIndexs["TEN"]);
                            }
                        }
                        try
                        {
                            DateTime d = new DateTime(1900, 1, 1).AddDays(
                                Double.Parse(valueIndexs["NGAYNOP"].ToString()) - 2);
                        }
                        catch
                        {
                            myImportResult.Status   = (myImportResult.Status == "OK" ? "CẢNH BÁO" : myImportResult.Status);
                            myImportResult.Message += (myImportResult.Message == "" ? "" : ",") +
                                                      string.Format("Can not convert to DateTime value: {0}", valueIndexs["NGAYNOP"]);
                        }

                        try
                        {
                            decimal money = Decimal.Parse(valueIndexs["SOTIEN"].ToString());
                        }
                        catch
                        {
                            myImportResult.CanImport = false;
                            myImportResult.Status    = "LỖI";
                            myImportResult.Message  += (myImportResult.Message == "" ? "" : ",") +
                                                       string.Format("Cannot convert to Decimal value:{0}", valueIndexs["SOTIEN"]);
                        }
                        collectionSource.List.Add(myImportResult);
                    }
                }
            }
            ListView view = Application.CreateListView(Application.GetListViewId(typeof(MyImportResult)),
                                                       collectionSource, false);

            view.Editor.AllowEdit                     = false;
            e.ShowViewParameters.CreatedView          = view;
            e.ShowViewParameters.TargetWindow         = TargetWindow.NewModalWindow;
            e.ShowViewParameters.CreateAllControllers = true;
            //args.ShowViewParameters.Context = TemplateContext.View;
            DialogController selectAcception = new DialogController();

            e.ShowViewParameters.Controllers.Add(selectAcception);

            selectAcception.Accepting += new EventHandler <DialogControllerAcceptingEventArgs>(selectAcception_Accepting);

            selectAcception.AcceptAction.Caption = "Import";
            selectAcception.CancelAction.Caption = "Bỏ qua";
        }
Пример #15
0
        void myAction_Execute(object sender, DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs e)
        {
            var f = new NKD.Module.Win.Controllers.SendConfig(Application);

            f.ShowDialog();
        }
Пример #16
0
        void ImportTeacherAction_Execute(object sender, DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs e)
        {
            ObjectSpace      objectSpace      = Application.CreateObjectSpace();
            CollectionSource collectionSource = new CollectionSource(objectSpace, typeof(MyImportResult));
            int count = 0;
            int iLine = 0;

            if ((collectionSource.Collection as XPBaseCollection) != null)
            {
                ((XPBaseCollection)collectionSource.Collection).LoadingEnabled = false;
            }

            foreach (TeacherFile actFile in View.SelectedObjects)
            {
                if (actFile.Note == "")
                {
                    throw new UserFriendlyException("Vui lòng thêm thông tin Ghi chú trước khi import!!!");
                }

                string tempStudentFile;
                string tempStudentFolderPath;
                string tempStudentLogFile;
                string templogname = "";
                if (HttpContext.Current != null)
                {
                    tempStudentFolderPath = HttpContext.Current.Request.MapPath("~/tempFolder");
                    tempStudentFile       = HttpContext.Current.Request.MapPath("~/tempFolder/" + actFile.CsvFile.FileName);
                    templogname           = actFile.CsvFile.FileName + DateTime.Now.ToString("dd-MM-yyyy-HHmmss") + "-log.html";
                    tempStudentLogFile    = HttpContext.Current.Request.MapPath("~/tempFolder/" + templogname);
                }
                else
                {
                    tempStudentFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder");
                    tempStudentFile       = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder/", actFile.CsvFile.FileName);
                    templogname           = actFile.CsvFile.FileName + DateTime.Now.ToString("dd-MM-yyyy-HHmmss") + "-log.html";
                    tempStudentLogFile    = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder/", templogname);
                }

                if (!Directory.Exists(tempStudentFolderPath))
                {
                    Directory.CreateDirectory(tempStudentFolderPath);
                }

                using (System.IO.FileStream fileStream = new FileStream(tempStudentFile, FileMode.OpenOrCreate))
                {
                    Dictionary <string, int>    columnIndexs = new Dictionary <string, int>();
                    Dictionary <string, object> valueIndexs  = new Dictionary <string, object>();
                    valueIndexs.Add("MSGV", "");
                    valueIndexs.Add("HO", "");
                    valueIndexs.Add("TEN", "");
                    valueIndexs.Add("TENVIETTAT", "");
                    valueIndexs.Add("NGAYSINH", "");
                    valueIndexs.Add("PHAI", "");
                    valueIndexs.Add("EMAIL", "");
                    valueIndexs.Add("DIENTHOAI", "");
                    valueIndexs.Add("DIDONG", "");
                    valueIndexs.Add("LATHINHGIANG", "");
                    valueIndexs.Add("MAKHOA", "");
                    valueIndexs.Add("TENKHOA", "");

                    columnIndexs.Add("MSGV", -1);
                    columnIndexs.Add("HO", -1);
                    columnIndexs.Add("TEN", -1);
                    columnIndexs.Add("TENVIETTAT", -1);
                    columnIndexs.Add("NGAYSINH", -1);
                    columnIndexs.Add("PHAI", -1);
                    columnIndexs.Add("EMAIL", -1);
                    columnIndexs.Add("DIENTHOAI", -1);
                    columnIndexs.Add("DIDONG", -1);
                    columnIndexs.Add("LATHINHGIANG", -1);
                    columnIndexs.Add("MAKHOA", -1);
                    columnIndexs.Add("TENKHOA", -1);


                    // open xls file
                    actFile.CsvFile.SaveToStream(fileStream);
                    fileStream.Close();
                    Workbook  book  = Workbook.Open(tempStudentFile);
                    Worksheet sheet = book.Worksheets[0];


                    bool foundHeader = false;

                    Row row;
                    //Tìm dòng chứa TEN cột
                    for (iLine = sheet.Cells.FirstRowIndex;
                         iLine <= sheet.Cells.LastRowIndex && !foundHeader; iLine++)
                    {
                        row = sheet.Cells.GetRow(iLine);
                        for (int colIndex = row.FirstColIndex;
                             colIndex <= row.LastColIndex; colIndex++)
                        {
                            Cell cell = row.GetCell(colIndex);
                            if (columnIndexs.ContainsKey(cell.Value.ToString().ToUpper().Trim()))
                            {
                                columnIndexs[cell.Value.ToString().ToUpper().Trim()] = colIndex; //Đã tìm thấy dòng chứa TEN cột. Xác định vị trí của cột
                            }
                        }
                        if (!columnIndexs.Values.Contains(-1))
                        {
                            foundHeader = true;
                        }
                        else
                        {
                            for (int colIndex = row.FirstColIndex; colIndex <= row.LastColIndex; colIndex++)
                            {
                                Cell cell = row.GetCell(colIndex);
                                if (columnIndexs.ContainsKey(cell.Value.ToString().ToUpper().Trim()))
                                {
                                    columnIndexs[cell.Value.ToString().ToUpper().Trim()] = -1; //không tìm thấy dòng chứa TEN cột. Xác định vị trí của cột
                                }
                            }
                        }
                    }
                    if (!foundHeader)
                    {
                        throw new UserFriendlyException("Lỗi cấu trúc file");
                    }

                    using (System.IO.StreamWriter fileStreamlog = new System.IO.StreamWriter(tempStudentLogFile, true))
                    {
                        fileStreamlog.WriteLine("<html><header><title>" + actFile.CsvFile.FileName + DateTime.Now.ToString("dd-MM-yyyy-HHmmss") + "-log </title>	"+
                                                "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />" +
                                                "</head><body>\r\n<table border=\"1px\"> <tr><Th>DÒNG</Th><th>TÌNH TRẠNG</th><th>THÔNG ĐIỆP</th></Tr>");
                        //Các dòng sau đó đều là dòng dữ liệu

                        List <Department> listDepartments = new List <Department>();


                        for (; iLine <= sheet.Cells.LastRowIndex; iLine++)
                        {
                            row = sheet.Cells.GetRow(iLine);
                            try
                            {
                                foreach (var column in columnIndexs)
                                {
                                    Cell cell = row.GetCell(column.Value);
                                    valueIndexs[column.Key] = cell.Value;
                                }

                                if (valueIndexs["MSGV"] == null || valueIndexs["TEN"] == null || valueIndexs["TENVIETTAT"] == null)
                                {
                                    fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "ERROR",
                                                            string.Format("Can not import line with  [MSGV or TEN or TENVIETTAT] is NULL on {0:dd-mm-yy HH:MM:ss}", DateTime.Now));
                                    continue;
                                }
                                //tạo khoa
                                Department dept;
                                if (valueIndexs["MAKHOA"] == null)
                                {
                                    dept = null;
                                }
                                else
                                {
                                    dept = listDepartments.Find(l => l.DepartmentCode == valueIndexs["MAKHOA"].ToString());
                                    if (dept == null)
                                    {
                                        dept = objectSpace.FindObject <Department>(new BinaryOperator("DepartmentCode", valueIndexs["MAKHOA"].ToString()));
                                    }
                                    if (dept != null)
                                    {
                                        if (valueIndexs["TENKHOA"] == null || dept.DepartmentName != valueIndexs["TENKHOA"].ToString())
                                        {
                                            fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "WARNING",
                                                                    string.Format("Department: \"{0}\" has name \"{1}\" different to \"{2}\" on {3:dd-mm-yy HH:MM:ss}",
                                                                                  dept.DepartmentCode, dept.DepartmentName, valueIndexs["TENKHOA"], DateTime.Now));
                                        }
                                        if (!listDepartments.Contains(dept))
                                        {
                                            listDepartments.Add(dept);
                                        }
                                    }
                                    else
                                    {
                                        dept = objectSpace.CreateObject <Department>();
                                        dept.DepartmentCode = valueIndexs["MAKHOA"].ToString();
                                        dept.DepartmentName = valueIndexs["TENKHOA"] == null ? null : valueIndexs["TENKHOA"].ToString();
                                        dept.Save();
                                        fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "CREATE NEW",
                                                                string.Format("Create new department: \"{0}\"-\"{1}\" on {2:dd-mm-yy HH:MM:ss}",
                                                                              dept.DepartmentCode, dept.DepartmentName, DateTime.Now));
                                        listDepartments.Add(dept);
                                    }
                                }

                                //tạo giảng viên
                                Teacher teacher = objectSpace.FindObject <Teacher>(new BinaryOperator("TeacherCode", valueIndexs["MSGV"].ToString()));
                                if (teacher != null)
                                {
                                    teacher.FirstName = valueIndexs["HO"] == null ? null : valueIndexs["HO"].ToString();
                                    teacher.LastName  = valueIndexs["TEN"].ToString();
                                    teacher.ShortName = valueIndexs["TENVIETTAT"].ToString();
                                    //try
                                    //{
                                    //    DateTime d = new DateTime(1900, 1, 1).AddDays(
                                    //        Double.Parse(valueIndexs["NGAYSINH"].ToString()) - 2);
                                    //    teacher.Birthday = d.ToString("dd/MM/yyyy");
                                    //}
                                    //catch
                                    //{
                                    teacher.Birthday = valueIndexs["NGAYSINH"] == null ? null : valueIndexs["NGAYSINH"].ToString();
                                    //}
                                    if (valueIndexs["PHAI"] == null || valueIndexs["PHAI"].ToString() == "0")
                                    {
                                        teacher.Sex = false;
                                    }
                                    else if (valueIndexs["PHAI"].ToString() == "1")
                                    {
                                        teacher.Sex = true;
                                    }
                                    teacher.Email  = valueIndexs["EMAIL"] == null ? null : valueIndexs["EMAIL"].ToString();
                                    teacher.Phone  = valueIndexs["DIENTHOAI"] == null ? null : valueIndexs["DIENTHOAI"].ToString();
                                    teacher.Mobile = valueIndexs["DIDONG"] == null ? null : valueIndexs["DIDONG"].ToString();
                                    if (valueIndexs["LATHINHGIANG"] == null || valueIndexs["LATHINHGIANG"].ToString() == "0")
                                    {
                                        teacher.isNotEmployee = false;
                                    }
                                    else if (valueIndexs["LATHINHGIANG"].ToString() == "1")
                                    {
                                        teacher.isNotEmployee = true;
                                    }
                                    teacher.Department = dept;
                                    teacher.Save();
                                    fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "UPDATE",
                                                            string.Format("Update teacher: \"{0}\"-\"{1}\" on {2:dd-mm-yy HH:MM:ss}", teacher.TeacherCode, teacher.FullName, DateTime.Now));
                                }
                                else
                                {
                                    teacher             = objectSpace.CreateObject <Teacher>();
                                    teacher.TeacherCode = valueIndexs["MSGV"].ToString();
                                    teacher.FirstName   = valueIndexs["HO"] == null ? null : valueIndexs["HO"].ToString();
                                    teacher.LastName    = valueIndexs["TEN"].ToString();
                                    teacher.ShortName   = valueIndexs["TENVIETTAT"].ToString();
                                    //try
                                    //{
                                    //    DateTime d = new DateTime(1900, 1, 1).AddDays(
                                    //        Double.Parse(valueIndexs["NGAYSINH"].ToString()) - 2);
                                    //    teacher.Birthday = d.ToString("dd/MM/yyyy");
                                    //}
                                    //catch
                                    //{
                                    teacher.Birthday = valueIndexs["NGAYSINH"] == null ? null : valueIndexs["NGAYSINH"].ToString();
                                    //}
                                    if (valueIndexs["PHAI"] == null || valueIndexs["PHAI"].ToString() == "0")
                                    {
                                        teacher.Sex = false;
                                    }
                                    else if (valueIndexs["PHAI"].ToString() == "1")
                                    {
                                        teacher.Sex = true;
                                    }
                                    teacher.Email  = valueIndexs["EMAIL"] == null ? null : valueIndexs["EMAIL"].ToString();
                                    teacher.Phone  = valueIndexs["DIENTHOAI"] == null ? null : valueIndexs["DIENTHOAI"].ToString();
                                    teacher.Mobile = valueIndexs["DIDONG"] == null ? null : valueIndexs["DIDONG"].ToString();
                                    if (valueIndexs["LATHINHGIANG"] == null || valueIndexs["LATHINHGIANG"].ToString() == "0")
                                    {
                                        teacher.isNotEmployee = false;
                                    }
                                    else if (valueIndexs["LATHINHGIANG"].ToString() == "1")
                                    {
                                        teacher.isNotEmployee = true;
                                    }
                                    teacher.Department = dept;
                                    //RuleSet ruleSet = new RuleSet();
                                    //RuleSetValidationResult result = ruleSet.ValidateTarget(teacher, DefaultContexts.Save);
                                    //if (ValidationState.Invalid ==
                                    //    result.GetResultItem("RuleRequiredField for Teacher.TeacherCode").State)
                                    //{
                                    //    fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "ERROR",
                                    //        string.Format("Cannot create teacher: \"{0}\" with null MSSV on {1:dd-mm-yy HH:MM:ss}",
                                    //    teacher.FullName, DateTime.Now));
                                    //    teacher.Delete();
                                    //}
                                    //else
                                    //{
                                    teacher.Save();
                                    fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "CREATE NEW",
                                                            string.Format("Create teacher: \"{0}\"-\"{1}\" on {2:dd-mm-yy HH:MM:ss}",
                                                                          teacher.TeacherCode, teacher.FullName, DateTime.Now));
                                    //}
                                }
                                objectSpace.CommitChanges();
                                count++;
                            }
                            catch (Exception ex)
                            {
                                fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "ERROR",
                                                        ex.Message + ex.StackTrace);
                            }
                        }
                        fileStreamlog.WriteLine("</table></body></html>");
                        fileStreamlog.Close();
                    }

                    View.ObjectSpace.SetModified(actFile);
                    actFile.IsImported = true;
                    actFile.ResultLink = "/tempFolder/" + templogname;

                    View.ObjectSpace.CommitChanges();
                }
            }
            PopUpMessage     ms;
            DialogController dc;

            ms         = objectSpace.CreateObject <PopUpMessage>();
            ms.Title   = "Kết quả import";
            ms.Message = string.Format("Đã thực hiện import {0} kết quả cho {1} dòng trong file\r\n Vui lòng xem link kết quả", count, iLine);
            e.ShowViewParameters.CreatedView = Application.CreateDetailView(
                objectSpace, ms);
            e.ShowViewParameters.TargetWindow        = TargetWindow.NewModalWindow;
            e.ShowViewParameters.CreatedView.Caption = "Thông báo";
            dc = Application.CreateController <DialogController>();
            dc.AcceptAction.Active.SetItemValue("object", false);
            dc.CancelAction.Caption = "Đóng";
            dc.SaveOnAccept         = false;
            e.ShowViewParameters.Controllers.Add(dc);
        }
        void ImportStudentResultAction_Execute(object sender, DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs e)
        {
            ObjectSpace objectSpace = Application.CreateObjectSpace();
            //ObjectSpace objectSpace =  ObjectSpaceInMemory.CreateNew();
            CollectionSource collectionSource = new CollectionSource(objectSpace, typeof(MyImportResult));
            int count = 0;
            int iLine = 0;

            if ((collectionSource.Collection as XPBaseCollection) != null)
            {
                ((XPBaseCollection)collectionSource.Collection).LoadingEnabled = false;
            }

            foreach (StudentResultFile actFile in View.SelectedObjects)
            {
                if (actFile.Note == null || actFile.Note == "")
                {
                    throw new UserFriendlyException("Vui lòng thêm thông tin Ghi chú trước khi import!!!");
                }

                string tempStudentFile;
                string tempStudentFolderPath;
                string tempStudentLogFile;
                string templogname = "";
                if (HttpContext.Current != null)
                {
                    tempStudentFolderPath = HttpContext.Current.Request.MapPath("~/tempFolder");
                    tempStudentFile       = HttpContext.Current.Request.MapPath("~/tempFolder/" + actFile.CsvFile.FileName);
                    templogname           = actFile.CsvFile.FileName + DateTime.Now.ToString("dd-MM-yyyy-HHmmss") + "-log.html";
                    tempStudentLogFile    = HttpContext.Current.Request.MapPath("~/tempFolder/" + templogname);
                }
                else
                {
                    tempStudentFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder");
                    tempStudentFile       = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder/", actFile.CsvFile.FileName);
                    templogname           = actFile.CsvFile.FileName + DateTime.Now.ToString("dd-MM-yyyy-HHmmss") + "-log.html";
                    tempStudentLogFile    = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder/", templogname);
                }

                if (!Directory.Exists(tempStudentFolderPath))
                {
                    Directory.CreateDirectory(tempStudentFolderPath);
                }

                using (System.IO.FileStream fileStream = new FileStream(tempStudentFile, FileMode.OpenOrCreate))
                {
                    Dictionary <string, int>    columnIndexs = new Dictionary <string, int>();
                    Dictionary <string, object> valueIndexs  = new Dictionary <string, object>();
                    valueIndexs.Add("NHHK", "");
                    valueIndexs.Add("MSSV", "");
                    valueIndexs.Add("HO", "");
                    valueIndexs.Add("TEN", "");
                    valueIndexs.Add("NHOMLOPMH", "");
                    valueIndexs.Add("MAMH", "");
                    valueIndexs.Add("TENMH", "");
                    valueIndexs.Add("SOTC", "");
                    valueIndexs.Add("DTB10", "");
                    valueIndexs.Add("DTB4", "");
                    valueIndexs.Add("DIEMCHU", "");


                    columnIndexs.Add("NHHK", -1);
                    columnIndexs.Add("MSSV", -1);
                    columnIndexs.Add("HO", -1);
                    columnIndexs.Add("TEN", -1);
                    columnIndexs.Add("NHOMLOPMH", -1);
                    columnIndexs.Add("MAMH", -1);
                    columnIndexs.Add("TENMH", -1);
                    columnIndexs.Add("SOTC", -1);
                    columnIndexs.Add("DTB10", -1);
                    columnIndexs.Add("DTB4", -1);
                    columnIndexs.Add("DIEMCHU", -1);

                    // open xls file
                    actFile.CsvFile.SaveToStream(fileStream);
                    fileStream.Close();
                    Workbook  book  = Workbook.Open(tempStudentFile);
                    Worksheet sheet = book.Worksheets[0];


                    bool foundHeader = false;

                    Row row;
                    //Tìm dòng chứa TEN cột
                    for (iLine = sheet.Cells.FirstRowIndex;
                         iLine <= sheet.Cells.LastRowIndex && !foundHeader; iLine++)
                    {
                        row = sheet.Cells.GetRow(iLine);
                        for (int colIndex = row.FirstColIndex;
                             colIndex <= row.LastColIndex; colIndex++)
                        {
                            Cell cell = row.GetCell(colIndex);
                            if (columnIndexs.ContainsKey(cell.Value.ToString().ToUpper().Trim()))
                            {
                                columnIndexs[cell.Value.ToString().ToUpper().Trim()] = colIndex; //Đã tìm thấy dòng chứa TEN cột. Xác định vị trí của cột
                            }
                        }
                        if (!columnIndexs.Values.Contains(-1))
                        {
                            foundHeader = true;
                        }
                        else
                        {
                            for (int colIndex = row.FirstColIndex; colIndex <= row.LastColIndex; colIndex++)
                            {
                                Cell cell = row.GetCell(colIndex);
                                if (columnIndexs.ContainsKey(cell.Value.ToString().ToUpper().Trim()))
                                {
                                    columnIndexs[cell.Value.ToString().ToUpper().Trim()] = -1; //không tìm thấy dòng chứa TEN cột. Xác định vị trí của cột
                                }
                            }
                        }
                    }
                    if (!foundHeader)
                    {
                        throw new UserFriendlyException("Lỗi cấu trúc file");
                    }

                    using (System.IO.StreamWriter fileStreamlog = new System.IO.StreamWriter(tempStudentLogFile, true))
                    {
                        fileStreamlog.WriteLine("<html><header><title>" + actFile.CsvFile.FileName + DateTime.Now.ToString("dd-MM-yyyy-HHmmss") + "-log </title>	"+
                                                "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />" +
                                                "</head><body>\r\n<table border=\"1px\"> <tr><Th>DÒNG</Th><th>TÌNH TRẠNG</th><th>THÔNG ĐIỆP</th></Tr>");
                        //Các dòng sau đó đều là dòng dữ liệu

                        List <Student>  listStudent  = new List <Student>();
                        List <Lesson>   listLessons  = new List <Lesson>();
                        List <Subject>  listSubject  = new List <Subject>();
                        List <Semester> listSemester = new List <Semester>();

                        for (; iLine <= sheet.Cells.LastRowIndex; iLine++)
                        {
                            row = sheet.Cells.GetRow(iLine);
                            try
                            {
                                foreach (var column in columnIndexs)
                                {
                                    Cell cell = row.GetCell(column.Value);
                                    valueIndexs[column.Key] = cell.Value;
                                }

                                //tìm sinh viên
                                Student student = listStudent.Find(s => s.StudentCode == valueIndexs["MSSV"].ToString().Trim());
                                if (student == null)
                                {
                                    student = objectSpace.FindObject <Student>(CriteriaOperator.Parse("StudentCode = ?", valueIndexs["MSSV"].ToString().Trim()));
                                }
                                if (student == null)
                                {
                                    fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "ERROR",
                                                            string.Format("Cannot find student: \"{0} - {1} {2} \" on {3:dd-mm-yy HH:MM:ss} - CANNOT IMPORT THIS LINE",
                                                                          valueIndexs["MSSV"], valueIndexs["HO"], valueIndexs["TEN"], DateTime.Now));
                                    continue;
                                }
                                else
                                {
                                    if (!(student.FirstName.Contains(valueIndexs["HO"].ToString()) && student.LastName.Contains(valueIndexs["TEN"].ToString())))
                                    {
                                        fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "WARNING",
                                                                string.Format("Found student: \"{0}\" but Name:\"{1} {2}\" is not Like \"{3} {4}\" on {5:dd-mm-yy HH:MM:ss}",
                                                                              valueIndexs["MSSV"], student.FirstName, student.LastName, valueIndexs["HO"], valueIndexs["TEN"], DateTime.Now));
                                    }
                                    listStudent.Add(student);
                                }
                                //found student
                                //tìm nhóm lớp
                                int nhomlop;
                                if (!int.TryParse(valueIndexs["NHOMLOPMH"].ToString().Trim(), out nhomlop))
                                {
                                    fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "ERROR",
                                                            string.Format("CANNNOT CONVERT TO NUMBER for LessonCode: \"{0}\" on {3:dd-mm-yy HH:MM:ss}- CANNOT IMPORT THIS LINE",
                                                                          valueIndexs["NHOMLOPMH"], DateTime.Now));
                                    continue;
                                }
                                Lesson lesson = listLessons.Find(l => l.LessonCode == nhomlop);
                                if (lesson == null)
                                {
                                    lesson = objectSpace.FindObject <Lesson>(CriteriaOperator.Parse("LessonCode = ?", nhomlop));
                                }
                                if (lesson != null)
                                {
                                    if (lesson.Semester.SemesterName.Trim() != valueIndexs["NHHK"].ToString().Trim())
                                    {
                                        fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "ERROR",
                                                                string.Format("Found Lesson \"{0}\" but Semester {1} not same {2} on  {3:dd-mm-yy HH:MM:ss} - CANNOT IMPORT THIS LINE",
                                                                              valueIndexs["NHOMLOPMH"], lesson.Semester.SemesterName, valueIndexs["NHHK"], DateTime.Now));
                                        continue;
                                    }
                                    if (lesson.Subject.SubjectCode != valueIndexs["MAMH"].ToString().Trim())
                                    {
                                        fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "ERROR",
                                                                string.Format("Found Lesson \"{0}\" but Subject Code {1} not same {2} on {3:dd-mm-yy HH:MM:ss} - CANNOT IMPORT THIS LINE",
                                                                              valueIndexs["NHOMLOPMH"], lesson.Subject.SubjectCode, valueIndexs["MAMH"], DateTime.Now));
                                        continue;
                                    }
                                    if (!lesson.ClassIDs.Contains(student.StudentClass.ClassCode))
                                    {
                                        lesson.ClassIDs += "," + student.StudentClass.ClassCode;
                                    }
                                    if (!listLessons.Contains(lesson))
                                    {
                                        listLessons.Add(lesson);
                                    }
                                }
                                else //create new lesson
                                {
                                    Semester semester = listSemester.Find(s => s.SemesterName == valueIndexs["NHHK"].ToString());
                                    if (semester == null)
                                    {
                                        semester = objectSpace.FindObject <Semester>(CriteriaOperator.Parse("SemesterName = ?", valueIndexs["NHHK"]));
                                    }
                                    if (semester == null) //create new semester
                                    {
                                        semester = objectSpace.CreateObject <Semester>();

                                        semester.SemesterName = valueIndexs["NHHK"].ToString();

                                        semester.Save();
                                        fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "CREATE NEW",
                                                                string.Format("Create Semester:{0} -  on {1:dd-mm-yy HH:MM:ss} ",
                                                                              valueIndexs["NHHK"], DateTime.Now));
                                        listSemester.Add(semester);
                                    }
                                    else if (!listSemester.Contains(semester))
                                    {
                                        listSemester.Add(semester);
                                    }

                                    Subject subject = listSubject.Find(s => s.SubjectCode == valueIndexs["MAMH"].ToString());
                                    if (subject == null)
                                    {
                                        subject = objectSpace.FindObject <Subject>(CriteriaOperator.Parse("SubjectCode = ?", valueIndexs["MAMH"]));
                                    }

                                    if (subject != null)
                                    {
                                        if (subject.SubjectName != valueIndexs["TENMH"].ToString())
                                        {
                                            fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "WARNING",
                                                                    string.Format("Found Subject \"{0}\" for lesson {1} but Name {2} not same {3} on  {4:dd-mm-yy HH:MM:ss}",
                                                                                  valueIndexs["MAMH"], valueIndexs["NHOMLOPMH"], subject.SubjectName, valueIndexs["TENMH"], DateTime.Now));
                                        }
                                        if (!listSubject.Contains(subject))
                                        {
                                            listSubject.Add(subject);
                                        }
                                    }
                                    else//create new subject
                                    {
                                        subject = objectSpace.CreateObject <Subject>();

                                        subject.SubjectCode = valueIndexs["MAMH"].ToString();
                                        subject.SubjectName = valueIndexs["TENMH"].ToString();
                                        subject.Credit      = Convert.ToDouble(valueIndexs["SOTC"]);

                                        subject.Save();
                                        fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "CREATE NEW",
                                                                string.Format("Create Subject:{0} - {1} ({2}TC)  on {3:dd-mm-yy HH:MM:ss} ",
                                                                              valueIndexs["MAMH"], valueIndexs["TENMH"], valueIndexs["SOTC"], DateTime.Now));
                                        listSubject.Add(subject);
                                    }


                                    lesson = objectSpace.CreateObject <Lesson>();

                                    lesson.Semester    = semester;
                                    lesson.Subject     = subject;
                                    lesson.LessonCode  = nhomlop;
                                    lesson.CanRegister = false;
                                    lesson.LessonNote  = "Tạo mới cho phân hệ điểm";
                                    lesson.ClassIDs    = student.StudentClass.ClassCode;

                                    lesson.Save();
                                    fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "CREATE NEW",
                                                            string.Format("Create Lesson :{0} - {1} ({2}TC)  on {3:dd-mm-yy HH:MM:ss}",
                                                                          nhomlop, valueIndexs["MAMH"], valueIndexs["NHHK"], DateTime.Now));
                                    listLessons.Add(lesson);
                                }

                                try
                                {
                                    StudentResult studResult = objectSpace.FindObject <StudentResult>(CriteriaOperator.Parse("Student = ? and Lesson=?", student, lesson));
                                    if (studResult == null)
                                    {
                                        studResult = objectSpace.CreateObject <StudentResult>();

                                        studResult.Student   = student;
                                        studResult.Lesson    = lesson;
                                        studResult.AvgMark10 = Convert.ToDouble(valueIndexs["DTB10"]);
                                        studResult.AvgMark4  = Convert.ToDouble(valueIndexs["DTB4"]);
                                        studResult.AvgChar   = valueIndexs["DIEMCHU"].ToString();
                                        studResult.Save();
                                        fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "CREATE NEW",
                                                                string.Format("Create StudentResult Lesson {0} with Subject Code {1} for student: \"{2}\"-\"{3}\" on {4:dd-mm-yy HH:MM:ss}",
                                                                              lesson.LessonCode, lesson.Subject.SubjectCode, student.StudentCode, student.FullName, DateTime.Now));
                                    }
                                    else
                                    {
                                        studResult.AvgMark10 = Convert.ToDouble(valueIndexs["DTB10"]);
                                        studResult.AvgMark4  = Convert.ToDouble(valueIndexs["DTB4"]);
                                        studResult.AvgChar   = valueIndexs["DIEMCHU"].ToString();
                                        studResult.Save();
                                        fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "WARNING",
                                                                string.Format("Update StudentResult Lesson {0} with Subject Code {1} for student: \"{2}\"-\"{3}\" on {4:dd-mm-yy HH:MM:ss}",
                                                                              lesson.LessonCode, lesson.Subject.SubjectCode, student.StudentCode, student.FullName, DateTime.Now));
                                    }
                                    count++;
                                }
                                catch (Exception ex)
                                {
                                    fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "ERROR",
                                                            string.Format("Cannot create StudentResult for student \"{0}\"-{1} on {2:dd-mm-yy HH:MM:ss} <BR/> {3} <BR/>{4}",
                                                                          student.StudentCode, student.FullName, DateTime.Now, ex.Message, ex.StackTrace));
                                }
                                objectSpace.CommitChanges();
                            }
                            catch (Exception ex)
                            {
                                fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "ERROR",
                                                        ex.Message + ex.StackTrace);
                            }
                        }
                        fileStreamlog.WriteLine("</table></body></html>");
                        fileStreamlog.Close();
                    }

                    View.ObjectSpace.SetModified(actFile);
                    actFile.IsImported = true;
                    actFile.ResultLink = "/tempFolder/" + templogname;

                    View.ObjectSpace.CommitChanges();
                }
            }
            PopUpMessage     ms;
            DialogController dc;

            ms         = objectSpace.CreateObject <PopUpMessage>();
            ms.Title   = "Kết quả import";
            ms.Message = string.Format("Đã thực hiện import {0} kết quả cho {1} dòng trong file\r\n Vui lòng xem link kết quả", count, iLine);
            e.ShowViewParameters.CreatedView = Application.CreateDetailView(
                objectSpace, ms);
            e.ShowViewParameters.TargetWindow        = TargetWindow.NewModalWindow;
            e.ShowViewParameters.CreatedView.Caption = "Thông báo";
            dc = Application.CreateController <DialogController>();
            dc.AcceptAction.Active.SetItemValue("object", false);
            dc.CancelAction.Caption = "Đóng";
            dc.SaveOnAccept         = false;
            e.ShowViewParameters.Controllers.Add(dc);
        }
Пример #18
0
        void ImportStudentAction_Execute(object sender, DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs e)
        {
            ObjectSpace      objectSpace      = Application.CreateObjectSpace();
            CollectionSource collectionSource = new CollectionSource(objectSpace, typeof(MyImportResult));
            int count = 0;
            int iLine = 0;

            if ((collectionSource.Collection as XPBaseCollection) != null)
            {
                ((XPBaseCollection)collectionSource.Collection).LoadingEnabled = false;
            }

            foreach (StudentFile actFile in View.SelectedObjects)
            {
                if (actFile.Note == "")
                {
                    throw new UserFriendlyException("Vui lòng thêm thông tin Ghi chú trước khi import!!!");
                }

                string tempStudentFile;
                string tempStudentFolderPath;
                string tempStudentLogFile;
                string templogname = "";
                if (HttpContext.Current != null)
                {
                    tempStudentFolderPath = HttpContext.Current.Request.MapPath("~/tempFolder");
                    tempStudentFile       = HttpContext.Current.Request.MapPath("~/tempFolder/" + actFile.CsvFile.FileName);
                    templogname           = actFile.CsvFile.FileName + DateTime.Now.ToString("dd-MM-yyyy-HHmmss") + "-log.html";
                    tempStudentLogFile    = HttpContext.Current.Request.MapPath("~/tempFolder/" + templogname);
                }
                else
                {
                    tempStudentFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder");
                    tempStudentFile       = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder/", actFile.CsvFile.FileName);
                    templogname           = actFile.CsvFile.FileName + DateTime.Now.ToString("dd-MM-yyyy-HHmmss") + "-log.html";
                    tempStudentLogFile    = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder/", templogname);
                }

                if (!Directory.Exists(tempStudentFolderPath))
                {
                    Directory.CreateDirectory(tempStudentFolderPath);
                }

                using (System.IO.FileStream fileStream = new FileStream(tempStudentFile, FileMode.OpenOrCreate))
                {
                    Dictionary <string, int>    columnIndexs = new Dictionary <string, int>();
                    Dictionary <string, object> valueIndexs  = new Dictionary <string, object>();
                    valueIndexs.Add("MSSV", "");
                    valueIndexs.Add("HO", "");
                    valueIndexs.Add("TEN", "");
                    valueIndexs.Add("NGAYSINH", "");
                    valueIndexs.Add("LOP", "");
                    valueIndexs.Add("PHAI", "");
                    valueIndexs.Add("DANTOC", "");
                    valueIndexs.Add("NOISINH", "");
                    valueIndexs.Add("MATKHAU", "");
                    valueIndexs.Add("KHOA", "");
                    valueIndexs.Add("MANGANH", "");
                    valueIndexs.Add("TENNGANH", "");
                    valueIndexs.Add("MAKHOA", "");
                    valueIndexs.Add("TENKHOA", "");
                    valueIndexs.Add("NHHKNHAPHOC", "");
                    valueIndexs.Add("NHHKTOTNGHIEP", "");

                    columnIndexs.Add("MSSV", -1);
                    columnIndexs.Add("HO", -1);
                    columnIndexs.Add("TEN", -1);
                    columnIndexs.Add("NGAYSINH", -1);
                    columnIndexs.Add("LOP", -1);
                    columnIndexs.Add("PHAI", -1);
                    columnIndexs.Add("DANTOC", -1);
                    columnIndexs.Add("NOISINH", -1);
                    columnIndexs.Add("MATKHAU", -1);
                    columnIndexs.Add("KHOA", -1);
                    columnIndexs.Add("MANGANH", -1);
                    columnIndexs.Add("TENNGANH", -1);
                    columnIndexs.Add("MAKHOA", -1);
                    columnIndexs.Add("TENKHOA", -1);
                    columnIndexs.Add("NHHKNHAPHOC", -1);
                    columnIndexs.Add("NHHKTOTNGHIEP", -1);

                    // open xls file
                    actFile.CsvFile.SaveToStream(fileStream);
                    fileStream.Close();
                    Workbook  book  = Workbook.Open(tempStudentFile);
                    Worksheet sheet = book.Worksheets[0];


                    bool foundHeader = false;

                    Row row;
                    //Tìm dòng chứa TEN cột
                    for (iLine = sheet.Cells.FirstRowIndex;
                         iLine <= sheet.Cells.LastRowIndex && !foundHeader; iLine++)
                    {
                        row = sheet.Cells.GetRow(iLine);
                        for (int colIndex = row.FirstColIndex;
                             colIndex <= row.LastColIndex; colIndex++)
                        {
                            Cell cell = row.GetCell(colIndex);
                            if (columnIndexs.ContainsKey(cell.Value.ToString().ToUpper().Trim()))
                            {
                                columnIndexs[cell.Value.ToString().ToUpper().Trim()] = colIndex; //Đã tìm thấy dòng chứa TEN cột. Xác định vị trí của cột
                            }
                        }
                        if (!columnIndexs.Values.Contains(-1))
                        {
                            foundHeader = true;
                        }
                        else
                        {
                            for (int colIndex = row.FirstColIndex; colIndex <= row.LastColIndex; colIndex++)
                            {
                                Cell cell = row.GetCell(colIndex);
                                if (columnIndexs.ContainsKey(cell.Value.ToString().ToUpper().Trim()))
                                {
                                    columnIndexs[cell.Value.ToString().ToUpper().Trim()] = -1; //không tìm thấy dòng chứa TEN cột. Xác định vị trí của cột
                                }
                            }
                        }
                    }
                    if (!foundHeader)
                    {
                        throw new UserFriendlyException("Lỗi cấu trúc file");
                    }

                    using (System.IO.StreamWriter fileStreamlog = new System.IO.StreamWriter(tempStudentLogFile, true))
                    {
                        fileStreamlog.WriteLine("<html><header><title>" + actFile.CsvFile.FileName + DateTime.Now.ToString("dd-MM-yyyy-HHmmss") + "-log </title>	"+
                                                "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />" +
                                                "</head><body>\r\n<table border=\"1px\"> <tr><Th>DÒNG</Th><th>TÌNH TRẠNG</th><th>THÔNG ĐIỆP</th></Tr>");
                        //Các dòng sau đó đều là dòng dữ liệu

                        List <Student>      listStudent        = new List <Student>();
                        List <Department>   listDepartments    = new List <Department>();
                        List <Branch>       listBranchs        = new List <Branch>();
                        List <Semester>     listSemesters      = new List <Semester>();
                        List <StudentClass> listStudentClasses = new List <StudentClass>();

                        for (; iLine <= sheet.Cells.LastRowIndex; iLine++)
                        {
                            row = sheet.Cells.GetRow(iLine);
                            try
                            {
                                foreach (var column in columnIndexs)
                                {
                                    Cell cell = row.GetCell(column.Value);
                                    valueIndexs[column.Key] = cell.Value;
                                }

                                if (valueIndexs["MSSV"] == null || valueIndexs["TEN"] == null || valueIndexs["LOP"] == null || valueIndexs["MATKHAU"] == null)
                                {
                                    fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "ERROR",
                                                            string.Format("Can not import line with  [MSSV or TEN or LOP or MATKHAU] is NULL on {0:dd-mm-yy HH:MM:ss}", DateTime.Now));
                                    continue;
                                }
                                //tạo khoa
                                Department dept;
                                if (valueIndexs["MAKHOA"] == null)
                                {
                                    dept = null;
                                }
                                else
                                {
                                    dept = listDepartments.Find(l => l.DepartmentCode == valueIndexs["MAKHOA"].ToString());
                                    if (dept == null)
                                    {
                                        dept = objectSpace.FindObject <Department>(new BinaryOperator("DepartmentCode", valueIndexs["MAKHOA"].ToString()));
                                    }
                                    if (dept != null)
                                    {
                                        if (valueIndexs["TENKHOA"] == null || dept.DepartmentName != valueIndexs["TENKHOA"].ToString())
                                        {
                                            fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "WARNING",
                                                                    string.Format("Department: \"{0}\" has name \"{1}\" different to \"{2}\" on {3:dd-mm-yy HH:MM:ss}",
                                                                                  dept.DepartmentCode, dept.DepartmentName, valueIndexs["TENKHOA"], DateTime.Now));
                                        }
                                        if (!listDepartments.Contains(dept))
                                        {
                                            listDepartments.Add(dept);
                                        }
                                    }
                                    else
                                    {
                                        dept = objectSpace.CreateObject <Department>();
                                        dept.DepartmentCode = valueIndexs["MAKHOA"].ToString();
                                        dept.DepartmentName = valueIndexs["TENKHOA"] == null ? null : valueIndexs["TENKHOA"].ToString();
                                        dept.Save();
                                        fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "CREATE NEW",
                                                                string.Format("Create new department: \"{0}\"-\"{1}\" on {2:dd-mm-yy HH:MM:ss}",
                                                                              dept.DepartmentCode, dept.DepartmentName, DateTime.Now));
                                        listDepartments.Add(dept);
                                    }
                                }
                                Branch branch;
                                if (valueIndexs["MANGANH"] == null)
                                {
                                    branch = null;
                                }
                                else
                                {
                                    branch = listBranchs.Find(l => l.BranchCode == valueIndexs["MANGANH"].ToString().Trim());
                                    if (branch == null)
                                    {
                                        branch = objectSpace.FindObject <Branch>(new BinaryOperator("BranchCode", valueIndexs["MANGANH"].ToString().Trim()));
                                    }
                                    if (branch != null)
                                    {
                                        if (valueIndexs["TENNGANH"] == null || branch.BranchName != valueIndexs["TENNGANH"].ToString())
                                        {
                                            fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "WARNING",
                                                                    string.Format("Branch: \"{0}\" has name \"{1}\" different to \"{2}\" on {3:dd-mm-yy HH:MM:ss}",
                                                                                  branch.BranchCode, branch.BranchName, valueIndexs["TENNGANH"], DateTime.Now));
                                        }
                                        if (!listBranchs.Contains(branch))
                                        {
                                            listBranchs.Add(branch);
                                        }
                                    }
                                    else
                                    {
                                        branch = objectSpace.CreateObject <Branch>();

                                        branch.BranchCode = valueIndexs["MANGANH"].ToString().Trim();
                                        branch.BranchName = valueIndexs["TENNGANH"] == null?null:valueIndexs["TENNGANH"].ToString().Trim();
                                        branch.Department = dept;
                                        branch.Save();
                                        listBranchs.Add(branch);
                                        fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "CREATE NEW",
                                                                string.Format("Create new branch: \"{0}\"-\"{1}\" on {2:dd-mm-yy HH:MM:ss}",
                                                                              branch.BranchCode, branch.BranchName, DateTime.Now));
                                    }
                                }
                                Semester semester;
                                if (valueIndexs["NHHKNHAPHOC"] == null)
                                {
                                    semester = null;
                                }
                                else
                                {
                                    semester = listSemesters.Find(l => l.SemesterName == valueIndexs["NHHKNHAPHOC"].ToString());
                                    if (semester == null)
                                    {
                                        semester = objectSpace.FindObject <Semester>(new BinaryOperator("SemesterName", valueIndexs["NHHKNHAPHOC"].ToString()));
                                    }
                                    if (semester != null)
                                    {
                                        if (!listSemesters.Contains(semester))
                                        {
                                            listSemesters.Add(semester);
                                        }
                                    }
                                    else
                                    {
                                        semester = objectSpace.CreateObject <Semester>();
                                        semester.SemesterName = valueIndexs["NHHKNHAPHOC"].ToString();
                                        semester.Save();
                                        listSemesters.Add(semester);
                                        fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "CREATE NEW",
                                                                string.Format("Create new semester: \"{0}\" on {1:dd-mm-yy HH:MM:ss}",
                                                                              semester.SemesterName, DateTime.Now));
                                    }
                                }
                                Semester semesterGraduate;
                                if (valueIndexs["NHHKTOTNGHIEP"] == null)
                                {
                                    semesterGraduate = null;
                                }
                                else
                                {
                                    semesterGraduate = listSemesters.Find(l => l.SemesterName == valueIndexs["NHHKTOTNGHIEP"].ToString());

                                    if (semesterGraduate == null)
                                    {
                                        semesterGraduate = objectSpace.FindObject <Semester>(new BinaryOperator("SemesterName", valueIndexs["NHHKTOTNGHIEP"].ToString()));
                                    }
                                    if (semesterGraduate != null)
                                    {
                                        if (!listSemesters.Contains(semesterGraduate))
                                        {
                                            listSemesters.Add(semesterGraduate);
                                        }
                                    }
                                    else
                                    {
                                        semesterGraduate = objectSpace.CreateObject <Semester>();
                                        semesterGraduate.SemesterName = valueIndexs["NHHKTOTNGHIEP"].ToString();
                                        semesterGraduate.Save();
                                        listSemesters.Add(semesterGraduate);
                                        fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "CREATE NEW",
                                                                string.Format("Create new semester: \"{0}\" on {1:dd-mm-yy HH:MM:ss}",
                                                                              semesterGraduate.SemesterName, DateTime.Now));
                                    }
                                }
                                StudentClass studClass = listStudentClasses.Find(
                                    l => l.ClassCode == valueIndexs["LOP"].ToString());
                                if (studClass == null)
                                {
                                    studClass = objectSpace.FindObject <StudentClass>(
                                        new BinaryOperator("ClassCode", valueIndexs["LOP"].ToString()));
                                }
                                if (studClass != null)
                                {
                                    if (studClass.ClassName != valueIndexs["LOP"].ToString() ||
                                        studClass.Branch != branch ||
                                        studClass.EnrollSemester != semester ||
                                        studClass.GraduateSemester != semesterGraduate)
                                    {
                                        fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "WARNING",
                                                                string.Format("StudentClass: \"{0}\" has name [{1}] branch[{2}] enrollsemester [{3}] graduate semester [{4}] different to" +
                                                                              "[{5}]-[{6}]-[{7}]-[{8}] on {9:dd-mm-yy HH:MM:ss}",
                                                                              studClass.ClassCode, studClass.ClassName, studClass.Branch, studClass.EnrollSemester, studClass.GraduateSemester,
                                                                              valueIndexs["LOP"].ToString(), branch, semester, semesterGraduate,
                                                                              DateTime.Now));
                                    }
                                    if (!listStudentClasses.Contains(studClass))
                                    {
                                        listStudentClasses.Add(studClass);
                                    }
                                }
                                else
                                {
                                    studClass = objectSpace.CreateObject <StudentClass>();

                                    studClass.ClassCode        = valueIndexs["LOP"].ToString();
                                    studClass.ClassName        = valueIndexs["LOP"].ToString();
                                    studClass.Branch           = branch;
                                    studClass.EnrollSemester   = semester;
                                    studClass.GraduateSemester = semesterGraduate;
                                    studClass.Save();
                                    fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "CREATE NEW",
                                                            string.Format("Create new class: \"{0}\" on {1:dd-mm-yy HH:MM:ss}", valueIndexs["LOP"],
                                                                          DateTime.Now));
                                }

                                //tạo sinh viên
                                Student student = objectSpace.FindObject <Student>(new BinaryOperator("StudentCode", valueIndexs["MSSV"].ToString()));
                                if (student != null)
                                {
                                    student.ChangePasswordOnFirstLogon = true;
                                    student.UserName     = valueIndexs["MSSV"].ToString();
                                    student.StudentClass = studClass;
                                    student.FirstName    = valueIndexs["HO"] == null?null:valueIndexs["HO"].ToString();
                                    student.LastName     = valueIndexs["TEN"].ToString();
                                    try
                                    {
                                        DateTime d = new DateTime(1900, 1, 1).AddDays(
                                            Double.Parse(valueIndexs["NGAYSINH"].ToString()) - 2);
                                        student.BirthdayText = d.ToString("dd/MM/yyyy");
                                    }
                                    catch
                                    {
                                        student.BirthdayText = valueIndexs["NGAYSINH"] == null ? null : valueIndexs["NGAYSINH"].ToString();
                                    }
                                    student.BirthPlace = valueIndexs["NOISINH"] == null ? null : valueIndexs["NOISINH"].ToString();
                                    student.Ethnic     = valueIndexs["DANTOC"] == null ? null : valueIndexs["DANTOC"].ToString();
                                    if (valueIndexs["PHAI"] == null || valueIndexs["PHAI"].ToString().Trim() == "0" || valueIndexs["PHAI"].ToString().Trim() == "Nam")
                                    {
                                        student.IsFemale = false;
                                    }
                                    else if (valueIndexs["PHAI"].ToString().Trim() == "1" || valueIndexs["PHAI"].ToString().Trim() == "Nữ")
                                    {
                                        student.IsFemale = true;
                                    }
                                    else
                                    {
                                        fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "WARNING",
                                                                string.Format("PHAI value must be \"Nam\" or \"0\" or \"1\" or \"Nữ\", read value was \"{0}\" on {1:dd-mm-yy HH:MM:ss}",
                                                                              valueIndexs["PHAI"].ToString().Trim(), DateTime.Now));
                                    }
                                    student.Course = valueIndexs["KHOA"] == null ? null : valueIndexs["KHOA"].ToString();
                                    student.SetPassword(valueIndexs["MATKHAU"].ToString());

                                    Role studRole = objectSpace.FindObject <Role>(new BinaryOperator("Name", "Students"));
                                    student.Roles.Add(studRole);
                                    studRole = objectSpace.FindObject <Role>(new BinaryOperator("Name", "Users"));
                                    student.Roles.Add(studRole);
                                    student.Save();
                                    fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "UPDATE",
                                                            string.Format("Update student: \"{0}\"-\"{1}\" on {2:dd-mm-yy HH:MM:ss}", student.StudentCode, student.FullName, DateTime.Now));
                                }
                                else
                                {
                                    student = objectSpace.CreateObject <Student>();

                                    student.ChangePasswordOnFirstLogon = true;
                                    student.UserName     = valueIndexs["MSSV"].ToString();
                                    student.StudentClass = studClass;
                                    student.FirstName    = valueIndexs["HO"] == null ? null : valueIndexs["HO"].ToString();
                                    student.LastName     = valueIndexs["TEN"].ToString();
                                    student.BirthdayText = valueIndexs["NGAYSINH"] == null ? null : valueIndexs["NGAYSINH"].ToString();
                                    student.BirthPlace   = valueIndexs["NOISINH"] == null ? null : valueIndexs["NOISINH"].ToString();
                                    student.Ethnic       = valueIndexs["DANTOC"] == null ? null : valueIndexs["DANTOC"].ToString();
                                    if (valueIndexs["PHAI"] == null || valueIndexs["PHAI"].ToString() == "0")
                                    {
                                        student.IsFemale = false;
                                    }
                                    else if (valueIndexs["PHAI"].ToString() == "1")
                                    {
                                        student.IsFemale = true;
                                    }
                                    student.Course = valueIndexs["KHOA"] == null ? null : valueIndexs["KHOA"].ToString();
                                    student.SetPassword(valueIndexs["MATKHAU"].ToString());

                                    Role studRole = objectSpace.FindObject <Role>(new BinaryOperator("Name", "Students"));
                                    student.Roles.Add(studRole);
                                    studRole = objectSpace.FindObject <Role>(new BinaryOperator("Name", "Users"));
                                    student.Roles.Add(studRole);

                                    student.Save();
                                    fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "CREATE NEW",
                                                            string.Format("Create student: \"{0}\"-\"{1}\" on {2:dd-mm-yy HH:MM:ss}",
                                                                          student.StudentCode, student.FullName, DateTime.Now));
                                }
                                objectSpace.CommitChanges();
                                count++;
                            }
                            catch (Exception ex)
                            {
                                fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "ERROR",
                                                        ex.Message + ex.StackTrace);
                            }
                        }
                        fileStreamlog.WriteLine("</table></body></html>");
                        fileStreamlog.Close();
                    }

                    View.ObjectSpace.SetModified(actFile);
                    actFile.IsImported = true;
                    actFile.ResultLink = "/tempFolder/" + templogname;

                    View.ObjectSpace.CommitChanges();
                }
            }
            PopUpMessage     ms;
            DialogController dc;

            ms         = objectSpace.CreateObject <PopUpMessage>();
            ms.Title   = "Kết quả import";
            ms.Message = string.Format("Đã thực hiện import {0} kết quả cho {1} dòng trong file\r\n Vui lòng xem link kết quả", count, iLine);
            e.ShowViewParameters.CreatedView = Application.CreateDetailView(
                objectSpace, ms);
            e.ShowViewParameters.TargetWindow        = TargetWindow.NewModalWindow;
            e.ShowViewParameters.CreatedView.Caption = "Thông báo";
            dc = Application.CreateController <DialogController>();
            dc.AcceptAction.Active.SetItemValue("object", false);
            dc.CancelAction.Caption = "Đóng";
            dc.SaveOnAccept         = false;
            e.ShowViewParameters.Controllers.Add(dc);
        }
Пример #19
0
        private void SimpleAction_OpenWorkBook_Execute(object sender, DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs e)
        {
            var form = new DoSoSheetFrom(false);

            form.Show();
        }