Пример #1
0
        static object GetObjectByKeyCore(Type classType, object objectKey, Session session)
        {
            NestedUnitOfWork nested       = session as NestedUnitOfWork;
            Session          parent       = nested != null ? nested.Parent : session;
            object           parentObject = parent.GetObjectByKey(classType, objectKey);

            if (parentObject == null)
            {
                foreach (PersistentBase item in parent.GetObjectsToSave())
                {
                    if (item.IsDeleted)
                    {
                        continue;
                    }
                    if (parent.GetKeyValue(item).Equals(objectKey))
                    {
                        parentObject = item;
                        break;
                    }
                }
            }
            if (parentObject == null)
            {
                return(null);
            }
            return(nested == null ? parentObject : nested.GetNestedObject(parentObject));
        }
Пример #2
0
 protected override void DisposeManaged()
 {
     VideoRentObject = null;
     NestedSession.Dispose();
     NestedSession = null;
     base.DisposeManaged();
 }
Пример #3
0
 int ImportObjects(XDocument document, UnitOfWork unitOfWork)
 {
     _unitOfWork = unitOfWork;
     if (document.Root != null)
     {
         foreach (XElement element in document.Root.Nodes().OfType <XElement>())
         {
             using (NestedUnitOfWork nestedUnitOfWork = unitOfWork.BeginNestedUnitOfWork()) {
                 ITypeInfo typeInfo = GetTypeInfo(element);
                 if (typeInfo != null)
                 {
                     var keys = GetKeys(element);
                     CriteriaOperator objectKeyCriteria = GetObjectKeyCriteria(typeInfo, keys);
                     if (!ReferenceEquals(objectKeyCriteria, null))
                     {
                         CreateObject(element, nestedUnitOfWork, typeInfo, objectKeyCriteria);
                         nestedUnitOfWork.CommitChanges();
                     }
                 }
             }
         }
         unitOfWork.CommitChanges();
     }
     return(0);
 }
Пример #4
0
 public void UpdatePaymentsAction()
 {
     using (NestedUnitOfWork uow = this.Session.BeginNestedUnitOfWork()) {
         crmDealWithoutStageVersion deal = uow.GetNestedObject <crmDealWithoutStageVersion>(this);
         deal.UpdatePayments();
         uow.CommitChanges();
     }
 }
Пример #5
0
 public void UpdatePaymentsAction()
 {
     using (NestedUnitOfWork uow = this.Session.BeginNestedUnitOfWork()) {
         crmStage stage = uow.GetNestedObject <crmStage>(this);
         stage.UpdatePayments();
         uow.CommitChanges();
     }
 }
Пример #6
0
 public XpoUnitOfWork(ISessionFactory sessionFactory)
 {
     this.sessionFactory = sessionFactory;
     if (OuterUnitOfWork != this)
     {
         nestedUnitOfWOrk = Session.BeginNestedUnitOfWork();
     }
 }
Пример #7
0
        public void SessionHelper_GetObjectByKey()
        {
            Movie            movie  = new Movie(Session);
            NestedUnitOfWork nested = Session.BeginNestedUnitOfWork();

            Assert.IsNotNull(SessionHelper.GetObjectByKey <Movie>(movie.Oid, nested));
            nested.CommitChanges();
        }
Пример #8
0
 protected override void Dispose(bool disposing)
 {
     if (nestedUnitOfWOrk != null)
     {
         nestedUnitOfWOrk.CommitChanges();
         nestedUnitOfWOrk = null;
     }
     base.Dispose(disposing);
 }
Пример #9
0
 protected override void UpdateOverride()
 {
     if (NestedSession != null)
     {
         throw new InvalidOperationException();
     }
     NestedSession   = AddVRObjectEditObjectParent.GetNestedSession();
     VideoRentObject = CreateObjectOverride();
 }
Пример #10
0
 protected override void Dispose(bool disposing)
 {
     if (nestedDataContext != null)
     {
         nestedDataContext.CommitChanges();
         nestedDataContext = null;
     }
     base.Dispose(disposing);
 }
Пример #11
0
 protected override void Dispose(bool disposing)
 {
     if (nestedUnitOfWOrk != null)
     {
         nestedUnitOfWOrk.CommitChanges();
         nestedUnitOfWOrk = null;
     }
     base.Dispose(disposing);
 }
Пример #12
0
 protected override void Dispose(bool disposing)
 {
     if (nestedDataContext != null)
     {
         nestedDataContext.CommitChanges();
         nestedDataContext = null;
     }
     base.Dispose(disposing);
 }
Пример #13
0
        /// <summary>
        /// Casts the reference to parent.
        /// </summary>
        /// <param name="nestedUnitOfWork">The nested unit of work.</param>
        /// <param name="source">The source.</param>
        /// <returns></returns>
        private object castReferenceToParent(NestedUnitOfWork nestedUnitOfWork, object source)
        {
            var result = source;

            if (source != null && source is IXPObject)
            {
                if ((source as IXPObject).Session != nestedUnitOfWork.Parent)
                {
                    result = nestedUnitOfWork.GetParentObject(source);
                }
            }
            return(result);
        }
Пример #14
0
 private void Reload()
 {
     DisableButtons();
     try {
         if (UOW != null)
         {
             UOW.ObjectChanged -= Session_ObjectChanged;
         }
         UOW = Session.BeginNestedUnitOfWork();
         UOW.ObjectChanged += Session_ObjectChanged;
         OrdersBindingSource.DataSource = Order == null ? new Order(UOW) : UOW.GetNestedObject(Order);
     } finally { EnableButtons(); }
 }
Пример #15
0
 public FrmCrearEmpleado(Empleado empleado, XPCollection xpcEmpleado, XPCollection xpcDepartamento, XPCollection xpcTipoNomina, XPCollection xpcPuesto, XPCollection xpcTipoEmpleado, XPCollection xpcGrupoEmpleado, XPCollection xpcPercepcion, XPCollection xpcDeduccion, XPCollection xpcConcepto,XPCollection xpcCuentaContable, UnitOfWork uow)
     : this()
 {
     this.Empleado = empleado;
     this.uow = uow;
     this.xpcEmpleado = xpcEmpleado;
     this.xpcDepartamento = xpcDepartamento;
     this.xpcTipoNomina = xpcTipoNomina;
     this.xpcPuesto = xpcPuesto;
     this.xpcTipoEmpleado = xpcTipoEmpleado;
     this.xpcGrupoEmpleado = xpcGrupoEmpleado;
     this.xpcPercepcion = xpcPercepcion;
     this.xpcDeduccion = xpcDeduccion;
     this.xpcDepartamento.Session = uow;
     this.xpcTipoNomina.Session = uow;
     this.xpcPuesto.Session = uow;
     this.xpcTipoEmpleado.Session = uow;
     this.xpcGrupoEmpleado.Session = uow;
     this.xpcPercepcion.Session = uow;
     this.xpcDeduccion.Session = uow;
     this.xpcConcepto = xpcConcepto;
     this.xpcConcepto.Session = uow;
     this.xpcCuentaContable = xpcCuentaContable;
     this.xpcCuentaContable.Session = uow;
     this.uowAnidada = uow.BeginNestedUnitOfWork();
     this.xpcConceptoAnidada = new XPCollection(uowAnidada, xpcConcepto);
     this.xpcPercepcionAnidada = new XPCollection(uowAnidada, xpcPercepcion, new GroupOperator(GroupOperatorType.And, new BinaryOperator("Empleado", empleado, BinaryOperatorType.Equal)));
     xpcPercepcionAnidada.DisplayableProperties = "This;Concepto.Descripcion;Importe;Referencia;Referencia1";
     this.xpcCuentaContableAnidada = new XPCollection(uowAnidada, xpcCuentaContable);
     ///xpcCuentaContableAnidada.DisplayableProperties = "This;Concepto.Descripcion;Importe;Referencia;Referencia1";
     gridPercepcion.DataSource = xpcPercepcionAnidada;
     grdPercepcion.Columns.Clear();
     grdPercepcion.Columns.AddVisible("Concepto.Descripcion", "Concepto");
     grdPercepcion.Columns.AddVisible("Importe", "Importe");
     grdPercepcion.Columns.AddVisible("Referencia", "Referencia");
     grdPercepcion.Columns.AddVisible("Referencia1", "Referencia1");
     grdPercepcion.BestFitColumns();
     this.xpcDeduccionAnidada = new XPCollection(uowAnidada, xpcDeduccion, new GroupOperator(GroupOperatorType.And, new BinaryOperator("Empleado", empleado, BinaryOperatorType.Equal)));
     xpcDeduccionAnidada.DisplayableProperties = "This;Concepto.Descripcion;Fecha;Importe;Descuento;Adeudo;Referencia;Referencia1;CuentaContable.Descripcion";
     gridDeduccion.DataSource = xpcDeduccionAnidada;
     grdDeduccion.Columns.Clear();
     grdDeduccion.Columns.AddVisible("Concepto.Descripcion","Concepto");
     grdDeduccion.Columns.AddVisible("Fecha", "Fecha");
     grdDeduccion.Columns.AddVisible("Importe", "Importe");
     grdDeduccion.Columns.AddVisible("Descuento", "Descuento");
     grdDeduccion.Columns.AddVisible("Adeudo", "Adeudo");
     grdDeduccion.Columns.AddVisible("Referencia", "Referencia");
     grdDeduccion.BestFitColumns();
     RellenarCombos();
 }
Пример #16
0
        public void GenerateCustomerId()
        {
            using (NestedUnitOfWork nuow = Session.BeginNestedUnitOfWork()) {
                new Owner(nuow, "First", "Owner");
                nuow.CommitChanges();
            }
            Session.CommitChanges();
            int firstId = Session.FindObject <Owner>(CriteriaOperator.Parse("FullName = ?", "First Owner")).CustomerId;

            using (NestedUnitOfWork nuow = Session.BeginNestedUnitOfWork()) {
                new Owner(nuow, "Second", "Owner");
                nuow.CommitChanges();
            }
            Session.CommitChanges();
            int secondId = Session.FindObject <Owner>(CriteriaOperator.Parse("FullName = ?", "Second Owner")).CustomerId;

            Assert.AreEqual(1, secondId - firstId);
        }
Пример #17
0
 public FrmPercepcionBase(XPCollection xpcPercepcionBase, UnitOfWork uow, XPCollection xpcCuentaContable, XPCollection xpcConceptoDetalle,Concepto concepto,XPCollection xpcConceptoDetalleAnidada, NestedUnitOfWork uowAnidada)
 {
     InitializeComponent();
     this.uow = uow;
     this.uowAnidada = uowAnidada;
     this.xpcPercepcionBase = xpcPercepcionBase;
     this.xpcPercepcionBase.Session = uow;
     this.xpcCuentaContable = xpcCuentaContable;
     this.xpcCuentaContable.Session = uow;
     this.xpcConceptoDetalle = xpcConceptoDetalle;
     this.xpcConceptoDetalle.Session = uow;
     this.xpcConceptoDetalleAnidada = xpcConceptoDetalleAnidada;
     this.xpcConceptoDetalleAnidada.Session = uowAnidada;
     gridPercepcionBase.DataSource = this.xpcPercepcionBase;
     this.concepto = concepto;
     UpdateMenu();
     RefreshGrid();
 }
Пример #18
0
 //
 void UpdateAll()
 {
     if (!IsFirstUpdate)
     {
         IsFirstUpdate = true;
         using (NestedUnitOfWork uow = this.Session.BeginNestedUnitOfWork()) {
             crmDeliveryItem item = uow.GetNestedObject <crmDeliveryItem>(this);
             item.UpdateCost();
             item.UpdateNDS();
             item.UpdateFull();
             uow.CommitChanges();
         }
         IsFirstUpdate = false;
     }
     else
     {
         UpdateCost();
         UpdateNDS();
         UpdateFull();
     }
 }
Пример #19
0
 public FrmCrearConcepto(Concepto concepto, XPCollection xpcConcepto, UnitOfWork uow,XPCollection xpcCuentaContable,XPCollection xpcPercepcionBase,XPCollection xpcConceptoDetalle)
     : this()
 {
     this.uow = uow;
     this.uowAnidada = uow.BeginNestedUnitOfWork();
     this.xpcCuentaContable = xpcCuentaContable;
     this.xpcCuentaContable.Session = uow;
     this.Concepto = concepto;
     this.xpcConcepto = xpcConcepto;
     this.xpcConcepto.Session = uow;
     this.xpcPercepcionBase = xpcPercepcionBase;
     this.xpcPercepcionBase.Session = uow;
     this.xpcConceptoDetalle = xpcConceptoDetalle;
     this.xpcConceptoDetalle.Session = uow;
     xpcConceptoDetalleAnidada = new XPCollection(uowAnidada, xpcConceptoDetalle, new GroupOperator(GroupOperatorType.And, new BinaryOperator("Concepto", concepto, BinaryOperatorType.Equal)));
     xpcConceptoDetalleAnidada.DisplayableProperties="This;PercepcionBase.Descripcion";
     lkpCuentaContable.Properties.DataSource = xpcCuentaContable;
     lkpCuentaContable.Properties.ValueMember = "This";
     lkpCuentaContable.Properties.DisplayMember = "Cuenta";
     gridConceptoDetalle.DataSource = xpcConceptoDetalleAnidada;
     grdConceptoDetalle.Columns.Clear();
     grdConceptoDetalle.Columns.AddVisible("PercepcionBase.Descripcion");
 }
Пример #20
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();
                    }
                }
            }
        }
Пример #21
0
        public void CreateAllReferencesOnlyTest()
        {
            UnitOfWork uow = new UnitOfWork(Common.dataLayer);

            csCountry country = Prepare_csCountry(uow, "");
            csAddress address = Prepare_csAddress(uow, "", country);

            csCountry country1 = Prepare_csCountry(uow, "1");
            csAddress address1 = Prepare_csAddress(uow, "1", country1);

            csCountry country2 = Prepare_csCountry(uow, "2");
            csAddress address2 = Prepare_csAddress(uow, "2", country2);

            csCountry country3 = Prepare_csCountry(uow, "3");
            csAddress address3 = Prepare_csAddress(uow, "3", country3);

            csCountry country4 = Prepare_csCountry(uow, "4");
            csAddress address4 = Prepare_csAddress(uow, "4", country4);

            uow.CommitChanges();

            // Изменение какого-либо поля. Если вложенный uow читал бы снова из БД, то это изменение было бы проигнорировано
            address.Region = "ХРЕНОВЫЙ РЕГИОН";

            // Организуем коллецию
            XPCollection <csAddress> addressCoollection = new XPCollection <csAddress>(uow);


            NestedUnitOfWork nuow = uow.BeginNestedUnitOfWork();

            XPCollection <csAddress> nestedAddressCoollectionBEFORECHANGE = new XPCollection <csAddress>(nuow);

            csAddress nestedAddress = nuow.GetObjectByKey <csAddress>(address.Oid);

            nestedAddress.City = "Абракадабра";

            XPCollection <csAddress> nestedAddressCoollectionAFTERCHANGE = new XPCollection <csAddress>(nuow);


            XPClassInfo addressClassInfo = uow.GetClassInfo(typeof(csAddress));
            //var AddrKeyCollection = from addr in addressCoollection select addr.Oid;
            List <System.Guid> AddrKeyCollection = new List <System.Guid>();

            foreach (csAddress addr in addressCoollection)
            {
                ((IList)AddrKeyCollection).Add(addr.Oid);
            }

            //ICollection nestedAddressCoollectionFromDB = nuow.GetObjectsByKey(addressClassInfo, AddrKeyCollection as IList, true);
            // И/ИЛИ :
            ICollection nestedAddressCoollectionFromDS = nuow.GetObjectsByKey(addressClassInfo, AddrKeyCollection as IList, false);


            string xxx = nuow.ToString();

            nuow.CommitChanges();

            uow.CommitChanges();



            // **********************************************************************************************************************

            /*
             *
             * 1. После создания вложенного uow в нём ничего нет. Если же csAddress nestedAddress = nuow.GetObjectByKey<csAddress>(address.Oid);
             * то во вложенном uow окажется не только объект адрес, но и объект страна, которая является свойством объекта адреса
             *
             * 2. При измеениее объекта во вложенном uow он в родительском не меняется, пока изменения не утверждены.
             *
             * 3. При получении объекта, находящегося в корневм uow, во вложенном, объект оказывается во вложенном uow со всеми своими изменениями,
             * сделанными в корневом uow, даже если они не утверждены.
             *
             * Чтение и передача коллекций.
             *
             * 4. Коллекция во вложенном uow может быть прочитана в двух режимах: из БД и из datastore. В любом случае изменение сделанное
             * с объектом в корневом uow будет присутствовать в объекте из коллекции во вложенном uow (из-за кэширования, т.е. реальное чтение
             * БД не происходит в данном контрольном примере). Изменениеже сделанное в объекте в рамках вложенного uow будет учтено только в
             * режиме чтения datastore (т.е. опять же чтение будет прроисходить из кэша, где уже произведено изменение данных).
             *
             * 5. Вложенный uow после создания не содержит объектов. Объекты могут попасть во вложенный uow путём передачи из корневого со всеми
             * изменениями, сделанными в корневом uow.
             */
            // **********************************************************************************************************************
        }
Пример #22
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();
                    }
                }
            }
        }
Пример #23
0
        private string GetNewIdentity()
        {
            string Identity = "";

            CriteriaOperator cop = new BinaryOperator("Oid", CommonType.Oid);
            CommonTrType     ct  = (CommonTrType)mySession.FindObject(typeof(CommonTrType), cop);

            if (ct != null)
            {
                Sorszam talaltSorszam = null;

                // Ha a tranzakció típusa évfüggő
                if (ct.DateDepended)
                {
                    UInt16 year = Convert.ToUInt16(RecordingDate.Year);

                    CriteriaOperator copSr = new GroupOperator(GroupOperatorType.And, new BinaryOperator("Type", ct), new BinaryOperator("Year", year));
                    talaltSorszam = (Sorszam)mySession.FindObject(typeof(Sorszam), copSr);
                }
                // Ha a tranzakció típusa NEM évfüggő
                else
                {
                    CriteriaOperator copSr = new GroupOperator(GroupOperatorType.And, new BinaryOperator("Type", ct), new BinaryOperator("Year", 0));
                    talaltSorszam = (Sorszam)mySession.FindObject(typeof(Sorszam), copSr);
                }


                if (talaltSorszam == null)
                {
                    using (NestedUnitOfWork uow = mySession.BeginNestedUnitOfWork())
                    {
                        CriteriaOperator copType = new BinaryOperator("Type", CommonType);
                        CommonTrType     ctType  = uow.FindObject <CommonTrType>(copType);

                        Sorszam newsr = new Sorszam(uow);
                        newsr.Type = ctType;

                        if (ctType.DateDepended)
                        {
                            newsr.Year = Convert.ToUInt16(RecordingDate.Year);
                        }
                        else
                        {
                            newsr.Year = 0;
                        }
                        uow.CommitChanges();

                        talaltSorszam = newsr;
                    }
                }


                talaltSorszam.LastNum++;
                Int32         newNumber = talaltSorszam.LastNum;
                StringBuilder sb        = new StringBuilder();
                sb.Append(ct.Prefix);
                sb.Append("/");
                sb.AppendFormat(String.Format("{0:D6}", newNumber));

                Identity = sb.ToString();
            }

            return(Identity);
        }
Пример #24
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();
        }
Пример #25
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
        }
Пример #26
0
 /// <summary>
 /// Casts the reference to parent.
 /// </summary>
 /// <param name="nestedUnitOfWork">The nested unit of work.</param>
 /// <param name="source">The source.</param>
 /// <returns></returns>
 private object castReferenceToParent(NestedUnitOfWork nestedUnitOfWork, object source)
 {
     var result = source;
     if(source != null && source is IXPObject)
     {
         if ((source as IXPObject).Session != nestedUnitOfWork.Parent)
             result = nestedUnitOfWork.GetParentObject(source);
     }
     return result;
 }