Exemplo n.º 1
0
        //[Action(ToolTip = "Import Students Accumulation to Database", TargetObjectsCriteria = "IsImported=false")]
        public void ImportStudentAccumulation()
        {
            Session session = this.Session;
            string  tempStudentFolderPath;
            string  tempStudentFile;
            string  tempStudentLogFile;

            if (HttpContext.Current != null)
            {
                tempStudentFolderPath = HttpContext.Current.Request.MapPath("~/tempFolder");
                tempStudentFile       = HttpContext.Current.Request.MapPath("~/tempFolder/" + CsvFile.FileName);
                tempStudentLogFile    = HttpContext.Current.Request.MapPath("~/tempFolder/" + 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/", CsvFile.FileName);
                tempStudentLogFile    = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder/", CsvFile.FileName + "-log.txt");
            }

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

            Dictionary <string, int>    columnIndexs = new Dictionary <string, int>();
            Dictionary <string, string> valueIndexs  = new Dictionary <string, string>();

            valueIndexs.Add("NHHK", "");
            valueIndexs.Add("MSSV", "");
            valueIndexs.Add("HO", "");
            valueIndexs.Add("TEN", "");
            valueIndexs.Add("TONGTCHK", "");
            valueIndexs.Add("DTBHK10", "");
            valueIndexs.Add("DTBHK4", "");
            valueIndexs.Add("TONGTCTL", "");
            valueIndexs.Add("DTBTL10", "");
            valueIndexs.Add("DTBTL4", "");

            columnIndexs.Add("NHHK", -1);
            columnIndexs.Add("MSSV", -1);
            columnIndexs.Add("HO", -1);
            columnIndexs.Add("TEN", -1);
            columnIndexs.Add("TONGTCHK", -1);
            columnIndexs.Add("DTBHK10", -1);
            columnIndexs.Add("DTBHK4", -1);
            columnIndexs.Add("TONGTCTL", -1);
            columnIndexs.Add("DTBTL10", -1);
            columnIndexs.Add("DTBTL4", -1);

            using (System.IO.FileStream fileStream = new FileStream(tempStudentFile, FileMode.OpenOrCreate))
            {
                using (System.IO.StreamWriter fileStreamlog = new StreamWriter(tempStudentLogFile, true))
                {
                    CsvFile.SaveToStream(fileStream);
                    fileStream.Position = 0;
                    StreamReader r = new StreamReader(fileStream);
                    string       newLine;
                    bool         foundHeader = false;
                    int          iLine       = 1;

                    try
                    {
                        //Tìm dòng chứa TEN cột
                        while ((newLine = r.ReadLine()) != null)
                        {
                            string[] row = newLine.Split(new string[] { "~" }, StringSplitOptions.None);
                            if (!foundHeader)
                            {
                                for (int i = 0; i < row.Length; i++)
                                {
                                    if (columnIndexs.ContainsKey(row[i].ToUpper().Trim()))
                                    {
                                        columnIndexs[row[i].ToUpper().Trim()] = i; //Đã 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;
                                    break;
                                }
                                else
                                {
                                    for (int i = 0; i < row.Length; i++)
                                    {
                                        if (columnIndexs.ContainsKey(row[i].ToUpper().Trim()))
                                        {
                                            columnIndexs[row[i].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");
                        }
                        //Các dòng sau đó đều là dòng dữ liệu
                        IsImported = true;
                        //Các dòng sau đó đều là dòng dữ liệu
                        while ((newLine = r.ReadLine()) != null)
                        {
                            iLine++;
                            using (NestedUnitOfWork uow = Session.BeginNestedUnitOfWork())
                            {
                                uow.BeginTransaction();
                                try
                                {
                                    string[] row = newLine.Split(new string[] { "~" }, StringSplitOptions.None);

                                    foreach (var column in columnIndexs)
                                    {
                                        valueIndexs[column.Key] = row[column.Value];
                                    }

                                    //tìm sinh viên
                                    Student student = session.FindObject <Student>(new BinaryOperator("StudentCode", valueIndexs["MSSV"]));
                                    if (student == null)
                                    {
                                        fileStreamlog.WriteLine(string.Format("Cannot find student: \"{0} - {1} {2} \" on line \"{3}\" on {4:dd-mm-yy HH:MM:ss}",
                                                                              valueIndexs["MSSV"], valueIndexs["HO"], valueIndexs["TEN"], iLine, DateTime.Now));
                                        continue;
                                    }
                                    //FOUND STUDENT

                                    //TIM SEMESTER
                                    Semester semester = session.FindObject <Semester>(CriteriaOperator.Parse("SemesterName = " + valueIndexs["NHHK"]));
                                    if (semester == null) //create new semester
                                    {
                                        semester = new Semester(session)
                                        {
                                            SemesterName = valueIndexs["NHHK"]
                                        };
                                        semester.Save();
                                        fileStreamlog.WriteLine(string.Format("Create Semester:{0} -  on line \"{1}\" on {2:dd-mm-yy HH:MM:ss} - CANNOT IMPORT THIS LINE",
                                                                              valueIndexs["NHHK"], iLine, DateTime.Now));
                                    }

                                    try
                                    {
                                        StudentAccumulation acc = new StudentAccumulation(session)
                                        {
                                            Student               = student,
                                            Semester              = semester,
                                            SemesterCredit        = Convert.ToDouble(valueIndexs["TONGTCHK"]),
                                            SemesterAvgMark10     = Convert.ToDouble(valueIndexs["DTBHK10"]),
                                            SemesterAvgMark4      = Convert.ToDouble(valueIndexs["DTBHK4"]),
                                            TotalAccumulateCredit = Convert.ToDouble(valueIndexs["TONGTCTL"]),
                                            AccumulateAvgMark10   = Convert.ToDouble(valueIndexs["DTBTL10"]),
                                            AccumulateAvgMark4    = Convert.ToDouble(valueIndexs["DTBTL4"])
                                        };
                                        acc.Save();
                                        fileStreamlog.WriteLine(string.Format("Create StudentAccumulation with TotalAccumulateCredit {0} for student: \"{1}\"-\"{2}\" on {3:dd-mm-yy HH:MM:ss} - line {4}",
                                                                              valueIndexs["TONGTCTL"], student.StudentCode, student.FullName, DateTime.Now, iLine

                                                                              ));
                                    }
                                    catch (Exception ex)
                                    {
                                        fileStreamlog.WriteLine(string.Format("Cannot create Transaction for student \"{0}\"-{1} on {2:dd-mm-yy HH:MM:ss} - Line {3}",
                                                                              student.StudentCode, student.FullName, DateTime.Now, iLine));
                                        fileStreamlog.WriteLine(ex.Message + ex.StackTrace);
                                    }

                                    uow.CommitTransaction();
                                }
                                catch (Exception ex)
                                {
                                    fileStreamlog.WriteLine(string.Format("Error Line \"{0}\": \r\n {1}\r\n {1} on {1:dd-mm-yy HH:MM:ss}", iLine, ex.Message, ex.StackTrace, DateTime.Now));
                                }
                            }
                        }
                        fileStreamlog.WriteLine(string.Format("Create \"{0}\" all transaction on {1:dd-mm-yy HH:MM:ss}", iLine, DateTime.Now));
                    }
                    catch (UserFriendlyException ex)
                    {
                        fileStreamlog.WriteLine(string.Format("Error Line \"{0}\": \"{1}\" on {1:dd-mm-yy HH:MM:ss}", iLine, ex.StackTrace, DateTime.Now));
                        fileStream.Close();
                        fileStreamlog.Close();
                        throw ex;
                    }
                    finally
                    {
                        fileStream.Close();
                        fileStreamlog.Close();
                    }
                }
            }
        }
Exemplo n.º 2
0
        public override void UpdateDatabaseAfterUpdateSchema()
        {
            base.UpdateDatabaseAfterUpdateSchema();
            NestedUnitOfWork UOW = this.Session.BeginNestedUnitOfWork();

            UOW.BeginTransaction();
            //khoi tao quan tai khoan quan tri he thong (mau)
            User systemAmdmin = UOW.FindObject <User>(new BinaryOperator("UserName", "SystemAdmin"));

            if (systemAmdmin == null)
            {
                systemAmdmin          = new User(UOW);
                systemAmdmin.UserName = "******";
                systemAmdmin.SetPassword("SystemAdmin");
            }
            //khoi tao quan tai khoan sinh vien (mau)
            Student student = UOW.FindObject <Student>(new BinaryOperator("UserName", "SampleStudent"));

            if (student == null)
            {
                student          = new Student(UOW);
                student.UserName = "******";
                student.SetPassword("SampleStudent");
            }
            User guest = UOW.FindObject <User>(new BinaryOperator("UserName", "guest"));

            if (guest == null)
            {
                guest          = new User(UOW);
                guest.UserName = "******";
                guest.SetPassword("guest");
            }
            //khoi tao quan tai khoan quan quan ly dao tao
            User dataAdmin = UOW.FindObject <User>(new BinaryOperator("UserName", "DataAdmin"));

            if (dataAdmin == null)
            {
                dataAdmin          = new User(UOW);
                dataAdmin.UserName = "******";
                dataAdmin.SetPassword("DataAdmin");
            }



            // If a role with the Administrators name does not exist in the database, create this role
            Role adminRole = UOW.FindObject <Role>(new BinaryOperator("Name", "Administrators"));

            if (adminRole == null)
            {
                adminRole      = new Role(UOW);
                adminRole.Name = "Administrators";
            }
            // If a role with the Users name does not exist in the database, create this role
            Role userRole = UOW.FindObject <Role>(new BinaryOperator("Name", "Users"));

            if (userRole == null)
            {
                userRole      = new Role(UOW);
                userRole.Name = "Users";
            }

            // If a role with the Users name does not exist in the database, create this role
            Role dataRole = UOW.FindObject <Role>(new BinaryOperator("Name", "DataAdmins"));

            if (dataRole == null)
            {
                dataRole      = new Role(UOW);
                dataRole.Name = "DataAdmins";
            }

            Role studentRole = UOW.FindObject <Role>(new BinaryOperator("Name", "Students"));

            if (studentRole == null)
            {
                studentRole      = new Role(UOW);
                studentRole.Name = "Students";
            }

            //Delete all permissions assigned to the Administrators and Users roles

            while (adminRole.PersistentPermissions.Count > 0)
            {
                UOW.Delete(adminRole.PersistentPermissions[0]);
            }
            while (userRole.PersistentPermissions.Count > 0)
            {
                UOW.Delete(userRole.PersistentPermissions[0]);
            }
            while (dataRole.PersistentPermissions.Count > 0)
            {
                UOW.Delete(dataRole.PersistentPermissions[0]);
            }
            while (studentRole.PersistentPermissions.Count > 0)
            {
                UOW.Delete(studentRole.PersistentPermissions[0]);
            }
            UOW.PurgeDeletedObjects();


            // Allow full access to all objects to the Administrators role
            adminRole.AddPermission(new ObjectAccessPermission(typeof(object), ObjectAccess.AllAccess));
            // Allow editing the Application Model to the Administrators role
            adminRole.AddPermission(new EditModelPermission(ModelAccessModifier.Allow));
            // Save the Administrators role to the database
            adminRole.Save();

            // Allow full access to all objects to the DataAdmins role
            dataRole.AddPermission(new ObjectAccessPermission(typeof(object), ObjectAccess.AllAccess));
            // Allow editing the Application Model to the Administrators role
            dataRole.AddPermission(new EditModelPermission(ModelAccessModifier.Allow));
            // Save the Administrators role to the database
            dataRole.Save();

            AddRoleToUser(userRole);
            // Allow full access to all objects to the Users role

            userRole.Save();
            AddRoleToStudent(studentRole);
            studentRole.Save();
            // Add the Administrators role to the user1
            systemAmdmin.Roles.Add(adminRole);
            dataAdmin.Roles.Add(dataRole);
            student.Roles.Add(studentRole);
            guest.Roles.Add(userRole);
            systemAmdmin.Save();
            dataAdmin.Save();
            student.Save();
            guest.Save();

            UOW.CommitTransaction();

            //First Mynote
            MyNote mynote = this.Session.FindObject <MyNote>(new BinaryOperator("Title", "Welcome"));

            if ((mynote == null))
            {
                mynote             = new MyNote(Session);
                mynote.Title       = "Welcome";
                mynote.Intro       = "Welcome all to visit our website!!! ";
                mynote.FullContent = "Change full content here!!! ";
                mynote.Save();
            }

            //create report
            CreateReport("Bảng điểm nhóm MH");
            CreateReport("Bảng điểm nhóm MH (tách lớp sv)");
            CreateReport("Bảng điểm nhóm MH (theo nhóm lớp)");
            CreateReport("Danh sách lớp biên chế");
            CreateReport("Danh sách sinh viên theo lớp");
            CreateReport("Điểm học kỳ");
            CreateReport("Điểm học tập");
            CreateReport("Điểm tích lũy");
            CreateReport("DTBHKReport");
            CreateReport("Giao dịch học phí sinh viên");
            CreateReport("Kết quả ĐK 1 SV");
            CreateReport("Kết quả ĐK tất cả SV");
            CreateReport("Kết quả KT ĐK lớp biên chế");
            CreateReport("Kết quả KT ĐK tất cả SV");
            CreateReport("Kết quả học tập");
            CreateReport("Lịch giảng viên");
            CreateReport("Lịch lớp biên chế");
            CreateReport("Lịch môn học");
            CreateReport("Lịch phòng học cơ sở");
            CreateReport("Lịch phòng học");
            CreateReport("Lịch sinh viên");
            CreateReport("Tỉ lệ nợ lớp biên chế NHHK");
            CreateReport("Tỉ lệ nợ sinh viên lớp biên chế");
            CreateParam();
        }
Exemplo n.º 3
0
        //[Action(ToolTip = "Import Students TuitionFee Transaction to Database",TargetObjectsCriteria="IsImported = false")]
        public void ImportStudentTuitionFee()
        {
            if (this.Note == "")
            {
                throw new UserFriendlyException("Vui lòng thêm thông tin Ghi chú trước khi import!!!");
            }
            Session session = this.Session;
            string  tempStudentFolderPath;
            string  tempStudentFile;
            string  tempStudentLogFile;

            if (HttpContext.Current != null)
            {
                tempStudentFolderPath = HttpContext.Current.Request.MapPath("~/tempFolder");
                tempStudentFile       = HttpContext.Current.Request.MapPath("~/tempFolder/" + CsvFile.FileName);
                tempStudentLogFile    = HttpContext.Current.Request.MapPath("~/tempFolder/" + 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/", CsvFile.FileName);
                tempStudentLogFile    = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder/", CsvFile.FileName + "-log.txt");
            }

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

            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);

            using (System.IO.FileStream fileStream = new FileStream(tempStudentFile, FileMode.OpenOrCreate))
            {
                using (System.IO.StreamWriter fileStreamlog = new StreamWriter(tempStudentLogFile, true))
                {
                    // open xls file
                    CsvFile.SaveToStream(fileStream);
                    fileStream.Close();
                    Workbook  book  = Workbook.Open(tempStudentFile);
                    Worksheet sheet = book.Worksheets[0];


                    bool foundHeader = false;
                    int  iLine;

                    //Tìm dòng chứa TEN cột
                    for (iLine = sheet.Cells.FirstRowIndex;
                         iLine <= sheet.Cells.LastRowIndex && !foundHeader; iLine++)
                    {
                        Row 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");
                    }
                    //Các dòng sau đó đều là dòng dữ liệu
                    IsImported = true;
                    //Các dòng sau đó đều là dòng dữ liệu

                    for (; iLine <= sheet.Cells.LastRowIndex; iLine++)
                    {
                        using (NestedUnitOfWork uow = Session.BeginNestedUnitOfWork())
                        {
                            uow.BeginTransaction();
                            try
                            {
                                Row row = sheet.Cells.GetRow(iLine);
                                foreach (var column in columnIndexs)
                                {
                                    Cell cell = row.GetCell(column.Value);
                                    valueIndexs[column.Key] = cell.Value;
                                }
                                // tìm sinh viên
                                Student student = session.FindObject <Student>(new BinaryOperator("StudentCode", valueIndexs["MSSV"].ToString()));
                                if (student == null)
                                {
                                    fileStreamlog.WriteLine(string.Format("Cannot find student: \"{0}\" on line \"{1}\" on {2:dd-mm-yy HH:MM:ss}", valueIndexs["MSSV"], iLine + 1, DateTime.Now));
                                }
                                else
                                {
                                    if (student.FirstName.Trim() != valueIndexs["HOLOT"].ToString().Trim() ||
                                        student.LastName.Trim() != valueIndexs["TEN"].ToString().Trim())
                                    {
                                        fileStreamlog.WriteLine(string.Format("ERROR Found StudentCode: \"{0}\" but Full Name \"{1} \" is not like \"{2} {3}\" on {4:dd-mm-yy HH:MM:ss} - line {5} - DONOT IMPORT DATA",
                                                                              student.StudentCode, student.FullName, valueIndexs["HOLOT"],
                                                                              valueIndexs["TEN"], DateTime.Now, iLine + 1));
                                    }
                                    else
                                    {
                                        try
                                        {
                                            double             date = Double.Parse(valueIndexs["NGAYNOP"].ToString());
                                            AccountTransaction acc  = new AccountTransaction(session)
                                            {
                                                Student = student,

                                                MoneyAmount = Convert.ToDecimal(valueIndexs["SOTIEN"]),
                                                //TransactingDate = Convert.ToDateTime(valueIndexs["NGAYNOP"]),
                                                TransactingDate = new DateTime(1900, 1, 1).AddDays(
                                                    date - 2),
                                                Description       = valueIndexs["DIENGIAI"].ToString(),
                                                DateCreated       = DateTime.Now,
                                                DateModified      = DateTime.Now,
                                                ImportDescription = this.Note
                                            };
                                            acc.Save();
                                            fileStreamlog.WriteLine(string.Format("Create transaction with money amount {0} for student: \"{1}\"-\"{2}\" on {3:dd-mm-yy HH:MM:ss} - line {4}",
                                                                                  valueIndexs["SOTIEN"], student.StudentCode, student.FullName,
                                                                                  DateTime.Now, iLine + 1));
                                        }
                                        catch (Exception ex)
                                        {
                                            fileStreamlog.WriteLine(string.Format("ERROR: Cannot create Transaction for student \"{0}\"-{1} on {2:dd-mm-yy HH:MM:ss} - Line {3}",
                                                                                  student.StudentCode, student.FullName, DateTime.Now, iLine + 1));
                                            fileStreamlog.WriteLine(ex.Message + ex.StackTrace);
                                        }
                                    }
                                }
                                session.CommitTransaction();
                            }
                            catch (Exception ex)
                            {
                                fileStreamlog.WriteLine(string.Format("ERROR: Line \"{0}\": \r\n {1}\r\n {1} on {1:dd-mm-yy HH:MM:ss}", iLine + 1, ex.Message, ex.StackTrace, DateTime.Now));
                            }
                            uow.CommitChanges();
                        }
                    }
                }
            }

            #region Importdata
            //using (System.IO.FileStream fileStream = new FileStream(tempStudentFile, FileMode.OpenOrCreate))
            //{
            //    using (System.IO.StreamWriter fileStreamlog = new StreamWriter(tempStudentLogFile, true))
            //    {
            //        CsvFile.SaveToStream(fileStream);
            //        fileStream.Position = 0;
            //        StreamReader r = new StreamReader(fileStream);
            //        string newLine;
            //        bool foundHeader = false;
            //        int iLine = 1;

            //        try
            //        {

            //            //Tìm dòng chứa TEN cột
            //            while ((newLine = r.ReadLine()) != null)
            //            {
            //                string[] row = newLine.Split(new string[] { "~" }, StringSplitOptions.None);
            //                if (!foundHeader)
            //                {
            //                    for (int i = 0; i < row.Length; i++)
            //                        if (columnIndexs.ContainsKey(row[i].ToUpper().Trim()))
            //                        {
            //                            columnIndexs[row[i].ToUpper().Trim()] = i; //Đã 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;
            //                        break;
            //                    }
            //                    else
            //                    {
            //                        for (int i = 0; i < row.Length; i++)
            //                            if (columnIndexs.ContainsKey(row[i].ToUpper().Trim()))
            //                            {
            //                                columnIndexs[row[i].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");
            //            //Các dòng sau đó đều là dòng dữ liệu
            //            IsImported = true;
            //            //Các dòng sau đó đều là dòng dữ liệu
            //            while ((newLine = r.ReadLine()) != null)
            //            {
            //                iLine++;
            //                session.BeginTransaction();
            //                try
            //                {
            //                    string[] row = newLine.Split(new string[] { "~" }, StringSplitOptions.None);

            //                    foreach (var column in columnIndexs)
            //                    {
            //                        valueIndexs[column.Key] = row[column.Value];
            //                    }

            //                     //tìm sinh viên
            //                    Student student = session.FindObject<Student>(new BinaryOperator("StudentCode", valueIndexs["MSSV"]));
            //                    if (student == null)
            //                    {
            //                        fileStreamlog.WriteLine(string.Format("Cannot find student: \"{0}\" on line \"{1}\" on {2:dd-mm-yy HH:MM:ss}", valueIndexs["MSSV"], iLine, DateTime.Now));
            //                    }
            //                    else
            //                    {
            //                        try
            //                        {
            //                            AccountTransaction acc = new AccountTransaction(session)
            //                            {
            //                                Student = student,
            //                                MoneyAmount = Convert.ToDecimal(valueIndexs["SOTIEN"]),
            //                                TransactingDate = Convert.ToDateTime(valueIndexs["NGAYNOP"]),
            //                                Description = valueIndexs["DIENGIAI"]
            //                            };
            //                            acc.Save();
            //                            fileStreamlog.WriteLine(string.Format("Create transaction with money amount {0} for student: \"{1}\"-\"{2}\" on {3:dd-mm-yy HH:MM:ss} - line {4}",
            //                                valueIndexs["SOTIEN"], student.StudentCode, student.FullName, DateTime.Now, iLine

            //                                ));
            //                        }
            //                        catch (Exception ex)
            //                        {
            //                            fileStreamlog.WriteLine(string.Format("Cannot create Transaction for student \"{0}\"-{1} on {2:dd-mm-yy HH:MM:ss} - Line {3}",
            //                                student.StudentCode, student.FullName, DateTime.Now, iLine));
            //                            fileStreamlog.WriteLine(ex.Message + ex.StackTrace);
            //                        }
            //                    }
            //                    session.CommitTransaction();
            //                }
            //                catch (Exception ex)
            //                {
            //                    fileStreamlog.WriteLine(string.Format("Error Line \"{0}\": \r\n {1}\r\n {1} on {1:dd-mm-yy HH:MM:ss}", iLine, ex.Message, ex.StackTrace, DateTime.Now));
            //                }
            //            }
            //            fileStreamlog.WriteLine(string.Format("Create \"{0}\" all transaction on {1:dd-mm-yy HH:MM:ss}", iLine, DateTime.Now));
            //        }
            //        catch (UserFriendlyException ex)
            //        {
            //            fileStreamlog.WriteLine(string.Format("Error Line \"{0}\": \"{1}\" on {1:dd-mm-yy HH:MM:ss}", iLine, ex.StackTrace, DateTime.Now));
            //            fileStream.Close();
            //            fileStreamlog.Close();
            //            throw ex;
            //        }
            //        finally
            //        {
            //            fileStream.Close();
            //            fileStreamlog.Close();
            //        }
            //    }
            //}
            #endregion
        }
Exemplo n.º 4
0
        //[Action(ToolTip = "Import Students Semester Result to Database", TargetObjectsCriteria="IsImported=false")]
        public void ImportStudentResult()
        {
            Session session = this.Session;
            string  tempStudentFolderPath;
            string  tempStudentFile;
            string  tempStudentLogFile;
            string  filename = CsvFile.FileName + DateTime.Now.ToString("dd-MM-yyyy-HHmmss") + "-log.html";

            if (HttpContext.Current != null)
            {
                tempStudentFolderPath = HttpContext.Current.Request.MapPath("~/tempFolder");
                tempStudentFile       = HttpContext.Current.Request.MapPath("~/tempFolder/" + CsvFile.FileName);
                tempStudentLogFile    = HttpContext.Current.Request.MapPath("~/tempFolder/" + filename);
            }
            else
            {
                tempStudentFolderPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder");
                tempStudentFile       = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder/", CsvFile.FileName);
                tempStudentLogFile    = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "tempFolder/", filename);
            }

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

            Dictionary <string, int>    columnIndexs = new Dictionary <string, int>();
            Dictionary <string, string> valueIndexs  = new Dictionary <string, string>();

            valueIndexs.Add("NHHK", "");
            valueIndexs.Add("MSSV", "");
            valueIndexs.Add("HO", "");
            valueIndexs.Add("TEN", "");
            //valueIndexs.Add("NGAYSINH", "");
            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("NGAYSINH", -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);

            using (System.IO.FileStream fileStream = new FileStream(tempStudentFile, FileMode.OpenOrCreate))
            {
                using (System.IO.StreamWriter fileStreamlog = new StreamWriter(tempStudentLogFile, true))
                {
                    fileStreamlog.WriteLine("<html><header><title>" + CsvFile.FileName + DateTime.Now.ToString("dd-MM-yyyy-HHmmss") + "-log </title>	"+
                                            "<meta http-equiv=\"content-type\" content=\"text/html; charset=UTF-8\" />" +
                                            "</head><body>");
                    CsvFile.SaveToStream(fileStream);
                    fileStream.Position = 0;
                    StreamReader r = new StreamReader(fileStream);
                    string       newLine;
                    bool         foundHeader = false;
                    int          iLine       = 1;

                    try
                    {
                        //Tìm dòng chứa TEN cột
                        while ((newLine = r.ReadLine()) != null)
                        {
                            string[] row = newLine.Split(new string[] { "~" }, StringSplitOptions.None);
                            if (!foundHeader)
                            {
                                for (int i = 0; i < row.Length; i++)
                                {
                                    if (columnIndexs.ContainsKey(row[i].ToUpper().Trim()))
                                    {
                                        columnIndexs[row[i].ToUpper().Trim()] = i; //Đã 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;
                                    break;
                                }
                                else
                                {
                                    for (int i = 0; i < row.Length; i++)
                                    {
                                        if (columnIndexs.ContainsKey(row[i].ToUpper().Trim()))
                                        {
                                            columnIndexs[row[i].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
                                        }
                                    }
                                }
                            }
                        }
                        ResultLink = "./tempFolder/" + CsvFile.FileName + DateTime.Now.ToString("dd-MM-yyyy-HHmmss") + "-log.html";
                        if (!foundHeader)
                        {
                            throw new UserFriendlyException("Lỗi cấu trúc file");
                        }
                        //Các dòng sau đó đều là dòng dữ liệu
                        IsImported = true;

                        List <Student>  listStudent  = new List <Student>();
                        List <Lesson>   listLessons  = new List <Lesson>();
                        List <Subject>  listSubject  = new List <Subject>();
                        List <Semester> listSemester = new List <Semester>();
                        while ((newLine = r.ReadLine()) != null)
                        {
                            iLine++;
                            using (NestedUnitOfWork uow = Session.BeginNestedUnitOfWork())
                            {
                                uow.BeginTransaction();
                                try
                                {
                                    string[] row = newLine.Split(new string[] { "~" }, StringSplitOptions.None);

                                    foreach (var column in columnIndexs)
                                    {
                                        valueIndexs[column.Key] = row[column.Value];
                                    }

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

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

                                        if (subject != null)
                                        {
                                            if (subject.SubjectName != valueIndexs["TENMH"])
                                            {
                                                fileStreamlog.WriteLine(string.Format("WARNING: Found Subject \"{0}\" for lesson {1} but Name {2} not same {3} on line \"{4}\" on {5:dd-mm-yy HH:MM:ss} <br/>",
                                                                                      valueIndexs["MAMH"], valueIndexs["NHOMLOPMH"], subject.SubjectName, valueIndexs["TENMH"], iLine, DateTime.Now));
                                            }
                                            if (!listSubject.Contains(subject))
                                            {
                                                listSubject.Add(subject);
                                            }
                                        }
                                        else//create new subject
                                        {
                                            subject = new Subject(session)
                                            {
                                                SubjectCode = valueIndexs["MAMH"],
                                                SubjectName = valueIndexs["TENMH"],
                                                Credit      = Convert.ToDouble(valueIndexs["SOTC"])
                                            };
                                            subject.Save();
                                            fileStreamlog.WriteLine(string.Format("Create Subject:{0} - {1} ({2}TC)  on line \"{3}\" on {4:dd-mm-yy HH:MM:ss} <br/>",
                                                                                  valueIndexs["MAMH"], valueIndexs["TENMH"], valueIndexs["SOTC"], iLine, DateTime.Now));
                                            listSubject.Add(subject);
                                        }



                                        lesson = new Lesson(session)
                                        {
                                            Semester    = semester,
                                            Subject     = subject,
                                            LessonCode  = nhomlop,
                                            CanRegister = false,
                                            LessonNote  = "Tạo mới cho phân hệ điểm",
                                            ClassIDs    = student.StudentClass.ClassCode
                                        };
                                        lesson.Save();
                                        fileStreamlog.WriteLine(string.Format("Create Lesson :{0} - {1} ({2}TC)  on line \"{3}\" on {4:dd-mm-yy HH:MM:ss} <br/>",
                                                                              nhomlop, valueIndexs["MAMH"], valueIndexs["NHHK"], iLine, DateTime.Now));
                                        listLessons.Add(lesson);
                                    }

                                    try
                                    {
                                        StudentResult studResult = session.FindObject <StudentResult>(CriteriaOperator.Parse("Student = ? and Lesson=?", student, lesson));
                                        if (studResult == null)
                                        {
                                            studResult = new StudentResult(session)
                                            {
                                                Student   = student,
                                                Lesson    = lesson,
                                                AvgMark10 = Convert.ToDouble(valueIndexs["DTB10"]),
                                                AvgMark4  = Convert.ToDouble(valueIndexs["DTB4"]),
                                                AvgChar   = valueIndexs["DIEMCHU"]
                                            };

                                            studResult.Save();
                                            fileStreamlog.WriteLine(string.Format("Create StudentResult Lesson {0} with Subject Code {1} for student: \"{2}\"-\"{3}\" on {4:dd-mm-yy HH:MM:ss} - line {5} <br/>",
                                                                                  lesson.LessonCode, lesson.Subject.SubjectCode, student.StudentCode, student.FullName, DateTime.Now, iLine));
                                        }
                                        else
                                        {
                                            studResult.AvgMark10 = Convert.ToDouble(valueIndexs["DTB10"]);
                                            studResult.AvgMark4  = Convert.ToDouble(valueIndexs["DTB4"]);
                                            studResult.AvgChar   = valueIndexs["DIEMCHU"];
                                            studResult.Save();
                                            fileStreamlog.WriteLine(string.Format("Update StudentResult Lesson {0} with Subject Code {1} for student: \"{2}\"-\"{3}\" on {4:dd-mm-yy HH:MM:ss} - line {5} <br/>",
                                                                                  lesson.LessonCode, lesson.Subject.SubjectCode, student.StudentCode, student.FullName, DateTime.Now, iLine));
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        fileStreamlog.WriteLine(string.Format("Cannot create StudentResult for student \"{0}\"-{1} on {2:dd-mm-yy HH:MM:ss} - Line {3} <br/>",
                                                                              student.StudentCode, student.FullName, DateTime.Now, iLine));
                                        fileStreamlog.WriteLine(ex.Message + ex.StackTrace);
                                    }

                                    uow.CommitTransaction();
                                }
                                catch (Exception ex)
                                {
                                    fileStreamlog.WriteLine(string.Format("Error Line \"{0}\": \r\n {1}\r\n {1} on {1:dd-mm-yy HH:MM:ss} <br/>", iLine, ex.Message, ex.StackTrace, DateTime.Now));
                                }
                            }
                        }
                        fileStreamlog.WriteLine(string.Format("Create \"{0}\" all StudentResult on {1:dd-mm-yy HH:MM:ss} <br/>", iLine, DateTime.Now));
                    }
                    catch (UserFriendlyException ex)
                    {
                        fileStreamlog.WriteLine(string.Format("Error Line \"{0}\": \"{1}\" on {1:dd-mm-yy HH:MM:ss} <br/>", iLine, ex.StackTrace, DateTime.Now));
                        fileStreamlog.WriteLine("</body></html>");
                        fileStream.Close();
                        fileStreamlog.Close();
                        throw ex;
                    }
                    finally
                    {
                        fileStreamlog.WriteLine("</body></html>");
                        fileStream.Close();
                        fileStreamlog.Close();
                    }
                }
            }
        }