示例#1
0
        private void EjecutarConsultaActionOnExecute(object sender, SimpleActionExecuteEventArgs e)
        {
            var objectSpace = (XPObjectSpace)Application.CreateObjectSpace();

            var objetoParametros = (IConsultaStoredProcedure)View.CurrentObject;
            var xpClassInfo      =
                XpoTypesInfoHelper.GetXpoTypeInfoSource().XPDictionary.QueryClassInfo(objetoParametros.ClaseResultados);

            var objectsFromSproc = objectSpace.Session.GetObjectsFromSproc(xpClassInfo,
                                                                           objetoParametros.NombreStoredProcedure, objetoParametros.Parametros);
            var collectionSource = new CollectionSource(objectSpace, objetoParametros.ClaseResultados);

            foreach (var item in objectsFromSproc)
            {
                collectionSource.Add(item);
            }

            var view = Application.CreateListView(Application.Model.BOModel[xpClassInfo.FullName].DefaultListView,
                                                  collectionSource, true);

            view.Editor.AllowEdit = false;
            Application.MainWindow.SetView(view);

            e.ShowViewParameters.TargetWindow = TargetWindow.NewWindow;
            e.ShowViewParameters.Context      = TemplateContext.ApplicationWindow;
        }
        private void popupWindowShowAction1_CustomizePopupWindowParams(object sender, CustomizePopupWindowParamsEventArgs e)
        {
            IObjectSpace         objectSpace      = Application.CreateObjectSpace(typeof(BusinessClass2));
            CollectionSourceBase collectionSource = new CollectionSource(objectSpace, typeof(BusinessClass2));

            e.View = Application.CreateListView(Application.FindListViewId(typeof(BusinessClass2)), collectionSource, true);
        }
示例#3
0
        private void PopupWindowShowAction_PrevewMessages_CustomizePopupWindowParams(object sender, CustomizePopupWindowParamsEventArgs e)
        {
            var os   = Application.CreateObjectSpace() as XPObjectSpace;
            var list = ViewCurrentObject.GenerateMessages(os.Session, true);

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

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

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

            listView.CreateControls();

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

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

            e.DialogController.SaveOnAccept = false;
            DialogController dc = Application.CreateController <DialogController>();

            e.View = listView;
        }
示例#4
0
        protected virtual void ShowAuditInfo(SimpleActionExecuteEventArgs e)
        {
            XPCollection <AuditDataItemPersistent> auditInfo = GetAuditInfo(((ObjectSpace)View.ObjectSpace).Session, View.ObjectTypeInfo.Type);

            if (auditInfo != null)
            {
                CollectionSourceBase cs = new CollectionSource(View.ObjectSpace, typeof(AuditDataItemPersistent));
                e.ShowViewParameters.CreatedView = Application.CreateListView(
                    Application.FindListViewId(typeof(AuditDataItemPersistent)),
                    cs,
                    false
                    );
                e.ShowViewParameters.CreatedView.Caption = String.Format("{0} History", e.ShowViewParameters.CreatedView.ObjectTypeInfo.Name);
                cs.Criteria["AllAuditInfo"] = new InOperator(View.ObjectSpace.GetKeyPropertyName(typeof(AuditDataItemPersistent)), auditInfo);
                EnumDescriptor ed = new EnumDescriptor(typeof(AuditOperationType));
                cs.Criteria["DeletedOnly"] = CriteriaOperator.Parse(
                    "OperationType = ? OR OperationType = ?",
                    ed.GetCaption(AuditOperationType.ObjectDeleted),
                    ed.GetCaption(AuditOperationType.RemovedFromCollection)
                    );
                e.ShowViewParameters.Context      = TemplateContext.View;
                e.ShowViewParameters.TargetWindow = TargetWindow.NewModalWindow;
            }
            else
            {
                XtraMessageBox.Show(String.Format("There is no audit info for the {0} type", View.ObjectTypeInfo.Type.Name), "Show Audit Info", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Information);
            }
        }
示例#5
0
        private T createController <T>(Type objectType, bool activate, XPObjectSpace XPObjectSpace, HandleInfo handleInfo) where T : ViewController
        {
            XafTypesInfo.Instance.RegisterEntity(objectType);
            var source     = new CollectionSource(XPObjectSpace, objectType);
            var listEditor = Isolate.Fake.Instance <ListEditor>();

            Isolate.WhenCalled(() => listEditor.RequiredProperties).WillReturn(new string[0]);
            var listView = new ListView(source, listEditor);

            Isolate.WhenCalled(() => listView.ObjectTypeInfo).WillReturn(XafTypesInfo.CastTypeToTypeInfo(objectType));
            Isolate.WhenCalled(() => listView.ObjectSpace).WillReturn(XPObjectSpace);
            var controller = Isolate.Fake.Instance <T>(Members.CallOriginal, ConstructorWillBe.Called);

            Isolate.WhenCalled(() => controller.Application).WillReturn(Isolate.Fake.Instance <XafApplication>());

            controller.Active[""] = false;
            controller.SetView(listView);
            View view = controller.View;

            Isolate.WhenCalled(() => view.ObjectSpace).WillReturn(XPObjectSpace);
            if (activate)
            {
                Activate(controller, handleInfo);
            }

            return(controller);
        }
        public override void ViewDidAppear(bool animated)
        {
            base.ViewDidAppear(animated);


            var postIds = new List <int>();

            string mode = Mode.ToString().ToLower();

            postIds = Database.GetInstance().GetDbCon().Table <PostMode>()
                      .Where(q => q.Mode == mode).AsEnumerable().Select(q => q.PostId).ToList();

            posts = Database.GetInstance().GetDbCon().Table <Post>()
                    .Where(q => postIds.Contains(q.Id))
                    .OrderByDescending(q => q.PublishDate);

            source = new CollectionSource(posts.ToList(), this, CollectionView);

            CollectionView.RegisterNibForCell(PostCollectionViewCell1.Nib, PostCollectionViewCell1.Key);



            var flow = new UICollectionViewFlowLayout();

            flow.EstimatedItemSize = new CGSize(View.Frame.Width - 10, 160);
            flow.ScrollDirection   = UICollectionViewScrollDirection.Vertical;
            flow.SectionInset      = new UIEdgeInsets(5, 5, 5, 5);
            CollectionView.SetCollectionViewLayout(flow, true);

            CollectionView.DataSource = source;
            CollectionView.ReloadData();
        }
 private void DownStyleChange(Label label)
 {
     if (label == null)
     {
         CollectionStack.SelectItem = CollectionSource.First();
     }
     else
     {
         int index = CollectionSource.ToList().IndexOf(label);
         if (index != CollectionSource.Count() - 1)
         {
             int offset = GetScrollViewerOffset();
             if (offset + 9 == index)
             {
                 SetScrollViewerOffset(offset + 1);
             }
             else if (offset > index || offset + 9 < index)
             {
                 SetScrollViewerOffset(index + 1);
             }
             StyleChange(label);
             CollectionStack.SelectItem = CollectionSource.ElementAt(index + 1);
         }
     }
 }
示例#8
0
        private void AddDataSource(IDocumentDataSource dataSource, bool isInplaceDataSource)
        {
            CriteriaOperator criteria = isInplaceDataSource ? inPlaceCriteria : null;

            if (!String.IsNullOrEmpty(dataSource.Criteria))
            {
                CriteriaOperator dataSourceCriteria = CriteriaEditorHelper.GetCriteriaOperator(dataSource.Criteria, dataSource.DataType, objectSpace);
                if (ReferenceEquals(criteria, null))
                {
                    criteria = dataSourceCriteria;
                }
                else
                {
                    criteria = new GroupOperator(GroupOperatorType.And, criteria, dataSourceCriteria);
                }
            }
            CollectionSource collectionSource = new CollectionSource(objectSpace, dataSource.DataType, CollectionSourceDataAccessMode.Client, CollectionSourceMode.Proxy);

            collectionSource.Criteria["SnapDataSourceFiler"] = criteria;
            if (document.DataSources[dataSource.Name] != null)
            {
                document.DataSources[dataSource.Name].DataSource = collectionSource.Collection;
            }
            else
            {
                document.DataSources.Add(dataSource.Name, collectionSource.Collection);
            }
        }
        public void SaveValidScriptTest()
        {
            using (var application = XpoInMemoryXafApplication.CreateInstance())
                using (var objectSpace = application.CreateObjectSpace())
                {
                    var collectionSource = new CollectionSource(objectSpace, typeof(DashboardDataExtract));
                    var listView         = new ListView(collectionSource, application, true);

                    var controller = application.CreateController <DashboardDataExtractController>();
                    controller.SetView(listView);

                    controller.Active.Clear();
                    controller.Active["Test"] = true;

                    var dataExtract = objectSpace.CreateObject <DashboardDataExtract>();
                    dataExtract.Script = @"
					public class MyClass
					{
						public int MyMethod() { return 42; }
					}"                    ;
                    objectSpace.CommitChanges();

                    Assert.Single(objectSpace.GetObjects <DashboardDataExtract>());
                }
        }
        public static void ShowPopupListView(
            this ViewController controller,
            IObjectSpace objectSpace,
            ActionBaseEventArgs e, Type type,
            CriteriaOperator criteria,
            string viewId,
            EventHandler <DialogControllerAcceptingEventArgs> dcOnAccepting = null,
            EventHandler dcOnCancelling = null,
            SelectionDependencyType selectionDependencyType = SelectionDependencyType.Independent)
        {
            var polizaItems = new CollectionSource(objectSpace, type, true);

            polizaItems.Criteria["fixed"] = criteria;

            e.ShowViewParameters.CreatedView  = controller.Application.CreateListView(viewId, polizaItems, false);
            e.ShowViewParameters.TargetWindow = TargetWindow.NewModalWindow;
            e.ShowViewParameters.Context      = TemplateContext.PopupWindow;

            var dc = controller.Application.CreateController <DialogController>();

            dc.AcceptAction.SelectionDependencyType = selectionDependencyType;
            dc.SaveOnAccept = false;
            dc.Accepting   += dcOnAccepting;
            dc.Cancelling  += dcOnCancelling;

            e.ShowViewParameters.Controllers.Add(dc);
        }
示例#11
0
        ListView createListView(XPObjectSpace XPObjectSpace)
        {
            var source     = new CollectionSource(XPObjectSpace, typeof(TObject));
            var listEditor = Isolate.Fake.Instance <ListEditor>();

            Isolate.WhenCalled(() => listEditor.RequiredProperties).WillReturn(new string[0]);
            return(new ListView(source, listEditor));
        }
示例#12
0
 private void ClearCurrentQuery()
 {
     Query = string.Empty;
     SortBy.Clear();
     SpatialQuery.Clear();
     ClearQueryError();
     Suggestions.Clear();
     CollectionSource.Clear();
 }
示例#13
0
        private void ActionOnExecute(object sender, SimpleActionExecuteEventArgs args)
        {
            ObjectSpace space = Application.CreateObjectSpace();

            var source = new CollectionSource(space, typeof(Term));
            source.Criteria["Query"] = ((TaxonomyQuery)args.CurrentObject).ParseCriteria();

            args.ShowViewParameters.CreatedView = Application.CreateListView(Application.GetListViewId(typeof(Term)), source, false);
            args.ShowViewParameters.TargetWindow = TargetWindow.NewModalWindow;
        }
示例#14
0
        async Task LoadMovie(int id)
        {
            Item = await TMDbService.GetDetailedFilmAsync(id);

            Item.poster_path   = "";
            Item.backdrop_path = "";

            PosterSource.Clear();
            foreach (var posterItem in Item.images.posters)
            {
                PosterSource.Add(posterItem);
            }

            BackdropSource.Clear();
            foreach (var backdropItem in Item.images.backdrops)
            {
                BackdropSource.Add(backdropItem);
            }

            ReviewSource.Clear();
            foreach (var reviewItem in Item.reviews.results)
            {
                ReviewSource.Add(reviewItem);
            }

            CollectionSource.Clear();
            if (Item.belongs_to_collection != null && Item.collection_films != null)
            {
                foreach (var collectionItem in Item.collection_films)
                {
                    CollectionSource.Add(collectionItem);
                }
            }

            RecommendationsSource.Clear();
            foreach (var recommendationItem in Item.recommendations.results)
            {
                RecommendationsSource.Add(recommendationItem);
            }

            CastSource.Clear();
            foreach (var castItem in Item.credits.cast)
            {
                CastSource.Add(castItem);
            }

            CrewSource.Clear();
            foreach (var crewItem in Item.credits.crew)
            {
                CrewSource.Add(crewItem);
            }

            LoadCompleted();
        }
        void showDocumentsAction_CustomizePopupWindowParams(object sender, CustomizePopupWindowParamsEventArgs e)
        {
            try
            {
                IObjectSpace objectSpace = Application.CreateObjectSpace();

                var o     = (System.Data.Objects.DataClasses.EntityObject)e.Action.SelectionContext.CurrentObject;
                var c     = ((DevExpress.ExpressApp.EF.EFObjectSpace)objectSpace).ObjectContext;
                var table = NKD.Module.BusinessObjects.BusinessObjectHelper.GetTableName(c, e.Action.SelectionContext.CurrentObject.GetType());
                var value = (Guid)o.EntityKey.EntityKeyValues[0].Value;


                CollectionSource collectionSource = new CollectionSource(objectSpace, typeof(FileData));
                CriteriaOperator c1 = new BinaryOperator(
                    new OperandProperty("TableType"), table,
                    BinaryOperatorType.Equal
                    );
                CriteriaOperator c2 = new BinaryOperator(
                    new OperandProperty("ReferenceID"), value,
                    BinaryOperatorType.Equal
                    );
                CriteriaOperator co = c1 & c2;
                collectionSource.Criteria.Add("Refences", co);
                //Do this for manual data lists
                //if ((collectionSource.Collection as XPBaseCollection) != null)
                //{
                //    ((XPBaseCollection)collectionSource.Collection).LoadingEnabled = false;
                //}
                ListView view = Application.CreateListView(Application.GetListViewId(typeof(FileData)), collectionSource, false);
                view.Editor.AllowEdit = true;
                foreach (var k in view.AllowNew.GetKeys())
                {
                    view.AllowNew[k] = false;
                }
                foreach (var k in view.AllowDelete.GetKeys())
                {
                    view.AllowDelete[k] = false;
                }
                foreach (var k in view.AllowEdit.GetKeys())
                {
                    view.AllowEdit[k] = false;
                }
                foreach (var k in e.DialogController.AcceptAction.Enabled.GetKeys())
                {
                    e.DialogController.AcceptAction.Enabled[k] = false;
                }
                e.DialogController.AcceptAction.Enabled.SetItemValue("Item.Enabled", false);
                e.View = view;
                e.DialogController.SaveOnAccept = false;
            }
            catch (Exception ex)
            { }
        }
示例#16
0
        private void WybierzFakturyAction_CustomizePopupWindowParams(object sender, CustomizePopupWindowParamsEventArgs e)
        {
            IObjectSpace         objectSpace      = Application.CreateObjectSpace();
            var                  roz              = objectSpace.GetObject(ViewCurrentObject);
            var                  kli              = objectSpace.GetObject(roz.Wplata.Klient);
            CriteriaOperator     co               = CriteriaOperator.Parse("WartoscBrutto > SumaWplat And Klient = ?", kli);
            CollectionSourceBase collectionSource = new CollectionSource(objectSpace, typeof(Faktura));

            collectionSource.Criteria["FakturyDoSplaty"] = co;
            string fakturaListViewId = Application.FindLookupListViewId(typeof(Faktura));

            e.View = Application.CreateListView(fakturaListViewId, collectionSource, true);
        }
示例#17
0
        private void RemoveParticipantAction_CustomizePopupWindowParams(object sender, CustomizePopupWindowParamsEventArgs e)
        {
            //string participantListId = Application.FindLookupListViewId(typeof(ScheduleParticipant));
            //IObjectSpace objectSpace = Application.CreateObjectSpace();
            //Schedule master = (Schedule)objectSpace.GetObject(View.CurrentObject);
            //CollectionSource cs = new CollectionSource(objectSpace, typeof(ScheduleParticipant));
            //cs.Criteria["ScheduleParticipantFilter"] = new InOperator("Oid", master.ScheduleParticipants);
            //e.View = Application.CreateListView(participantListId, cs, false);

            //IObjectSpace objectSpace = Application.CreateObjectSpace(typeof(ScheduleParticipant));
            //Schedule currentSchedule = (Schedule)objectSpace.GetObject(View.CurrentObject);
            //string participantListId = Application.FindLookupListViewId(typeof(ScheduleParticipant));
            //CollectionSourceBase collectionSource = Application.CreatePropertyCollectionSource(objectSpace, typeof(Schedule), currentSchedule, XafTypesInfo.Instance.FindTypeInfo(typeof(Schedule)).FindMember("ScheduleParticipants"), participantListId);
            //e.View = Application.CreateListView(participantListId, collectionSource, false);


            IObjectSpace     objectSpace       = Application.CreateObjectSpace(typeof(TemporaryScheduleParticipant));
            string           participantListId = Application.FindLookupListViewId(typeof(TemporaryScheduleParticipant));
            CollectionSource collectionSource  = new CollectionSource(objectSpace, typeof(TemporaryScheduleParticipant));
            Schedule         currentSchedule   = (Schedule)View.CurrentObject;

            foreach (ScheduleParticipant detail in currentSchedule.ScheduleParticipants)
            {
                TemporaryScheduleParticipant tempParticipant = objectSpace.CreateObject <TemporaryScheduleParticipant>();
                tempParticipant.Participant = objectSpace.GetObjectByKey <People>(detail.Participant.Oid);
                collectionSource.Add(tempParticipant);
            }


            e.View         = Application.CreateListView(participantListId, collectionSource, false);
            e.View.Caption = "Remove Participant";
            e.Context      = TemplateContext.FindPopupWindow;
            //var listView = Application.CreateListView(ObjectSpace, typeof(ScheduleParticipant), false);
            //if (this.View is ListView)
            //{
            //   foreach (object obj in ((ListView)this.View).CollectionSource.List)
            //   {
            //      listView.CollectionSource.List.Add(obj);
            //   }
            //}
            //if (((Schedule)View.CurrentObject).ScheduleParticipants.Count > 0)
            //{
            //   foreach(object detail in ((Schedule)View.CurrentObject).ScheduleParticipants)
            //   {
            //      listView.CollectionSource.Add(detail);
            //   }
            //}
            //e.View = listView;
            //e.Context = TemplateContext.LookupWindow;
            //e.DialogController.SaveOnAccept = false;
        }
 private void SetPopup(Label label)
 {
     if (label != null)
     {
         int index    = CollectionSource.ToList().IndexOf(label);
         int offset   = GetScrollViewerOffset();
         int interval = index - offset;
         ItemPopup.PlacementTarget  = window;
         ItemPopup.Placement        = PlacementMode.Absolute;
         ItemPopup.HorizontalOffset = window.Left + 344;
         ItemPopup.VerticalOffset   = window.Top + 69 + interval * 20;
         SetPopupOpen(label);
     }
 }
示例#19
0
        void showDocumentsAction_CustomizePopupWindowParams(object sender, CustomizePopupWindowParamsEventArgs e) {

            try
            {
                IObjectSpace objectSpace = Application.CreateObjectSpace();

                var o = (System.Data.Objects.DataClasses.EntityObject)e.Action.SelectionContext.CurrentObject;
                var c = ((DevExpress.ExpressApp.EF.EFObjectSpace)objectSpace).ObjectContext;
                var table = NKD.Module.BusinessObjects.BusinessObjectHelper.GetTableName(c, e.Action.SelectionContext.CurrentObject.GetType());
                var value = (Guid)o.EntityKey.EntityKeyValues[0].Value;

                
                CollectionSource collectionSource = new CollectionSource(objectSpace, typeof(FileData));
                CriteriaOperator c1 = new BinaryOperator(
                    new OperandProperty("TableType"), table,
                    BinaryOperatorType.Equal
                );
                CriteriaOperator c2 = new BinaryOperator(
                    new OperandProperty("ReferenceID"), value,
                    BinaryOperatorType.Equal
                );
                CriteriaOperator co = c1 & c2;
                collectionSource.Criteria.Add("Refences", co);
                //Do this for manual data lists
                //if ((collectionSource.Collection as XPBaseCollection) != null)
                //{
                //    ((XPBaseCollection)collectionSource.Collection).LoadingEnabled = false;
                //}
                ListView view = Application.CreateListView(Application.GetListViewId(typeof(FileData)), collectionSource, false);
                view.Editor.AllowEdit = true;
                foreach (var k in view.AllowNew.GetKeys())
                    view.AllowNew[k] = false;
                foreach (var k in view.AllowDelete.GetKeys())
                    view.AllowDelete[k] = false;
                foreach (var k in view.AllowEdit.GetKeys())
                    view.AllowEdit[k] = false;
                foreach (var k in e.DialogController.AcceptAction.Enabled.GetKeys())
                    e.DialogController.AcceptAction.Enabled[k] = false;
                e.DialogController.AcceptAction.Enabled.SetItemValue("Item.Enabled", false);
                e.View = view;
                e.DialogController.SaveOnAccept = false;
                
            }
            catch (Exception ex)
            { }


        }
示例#20
0
        private void PagoAplicarCuota_Execute(object sender, SimpleActionExecuteEventArgs e)
        {
            var cuotasConSaldo = new CollectionSource(ObjectSpace, typeof(ComprobanteCuota), true);

            SetupCollectionSource(cuotasConSaldo);

            SetupShowViewParameters(e, cuotasConSaldo);

            var dialogController = Application.CreateController <DialogController>( );

            e.ShowViewParameters.CreateAllControllers = true;
            dialogController.SaveOnAccept             = false;
            dialogController.Accepting          += PagoAplicarCuota_DialogController_Accepting;
            e.ShowViewParameters.CreatedView.Tag = View;
            e.ShowViewParameters.Controllers.Add(dialogController);
        }
示例#21
0
        private void buscarCPAAction_Execute(object sender, CustomizePopupWindowParamsEventArgs e)
        {
            var dir = ((PersonaDireccion)View.CurrentObject).Direccion;
            var loc = dir.Localidad != null ? dir.Localidad.Nombre : dir.LocalidadOtra;

            if (dir.Provincia == null)
            {
                throw new UserFriendlyException("Debe indicar primero la provincia.");
            }

            var prov = dir.Provincia.Codigo;

            IList <CPA.LocalidadResultItem> locs;

            if (prov == "C")
            {
                locs = new List <CPA.LocalidadResultItem>
                {
                    new CPA.LocalidadResultItem
                    {
                        Codigo          = 5001,
                        CodigoProvincia = "C",
                        Nombre          = "Ciudad Autonoma de Buenos Aires"
                    }
                };
            }
            else
            {
                locs = CPA.ObtenerLocalidades(prov, loc);
            }

            var collectionSource = new CollectionSource(ObjectSpace, typeof(CPA.LocalidadResultItem));

            foreach (var loci in locs)
            {
                collectionSource.Add(loci);
            }

            var view = Application.CreateListView(Application.GetListViewId(typeof(CPA.LocalidadResultItem)),
                                                  collectionSource, false);

            view.Editor.AllowEdit = false;
            e.View = view;

            e.DialogController.SaveOnAccept = false;
            e.DialogController.Accepting   += DialogController_Execute;
        }
示例#22
0
        void Setup(Type targetType, TColumnViewEditor gridListEditor)
        {
            XpoTypesInfoHelper.ForceInitialize();
            var xpObjectSpace    = new XPObjectSpace(XafTypesInfo.Instance, ((XpoTypeInfoSource)XafTypesInfo.PersistentEntityStore), () => null);
            var collectionSource = new CollectionSource(xpObjectSpace, targetType);

            gridListEditor.Setup(collectionSource, new EditorsXafApplication());
            gridListEditor.ColumnCreated += (sender, args) => {
                var column = args.Column;
                if (column.ColumnEdit != null)
                {
                    column.ColumnEdit.Name = column.Name;
                    column.ColumnEdit.Site = new MySite(gridListEditor.Grid.MainView, column);
                }
            };
            gridListEditor.CreateControls();
        }
 private void OnScrollChanged(object sender, ScrollChangedEventArgs e)
 {
     if (CollectionStack.SelectItem != null)
     {
         int offset   = GetScrollViewerOffset();
         int index    = CollectionSource.ToList().IndexOf(CollectionStack.SelectItem);
         int interval = index - offset;
         if (index >= offset && index <= offset + 9)
         {
             ItemPopup.VerticalOffset = window.Top + 69 + interval * 20;
         }
         else
         {
             RemovePopup();
         }
     }
 }
示例#24
0
        private void SelectProfile(object sender, SingleChoiceActionExecuteEventArgs e)
        {
            // create list view and filter by ObjectTypeName
            IObjectSpace objectSpace      = Application.CreateObjectSpace();
            var          collectionSource = new CollectionSource(objectSpace, typeof(ImportParamBase));

            collectionSource.Criteria["ObjectTypeFilter"] = CriteriaOperator.Parse("ObjectTypeName == ?", View.ObjectTypeInfo.Name);
            var listViewId = Application.FindListViewId(typeof(ImportParamBase));
            var listView   = Application.CreateListView(
                listViewId,
                collectionSource,
                true);

            // show view in new window
            var svp = e.ShowViewParameters;

            svp.TargetWindow = TargetWindow.NewWindow;
            svp.CreatedView  = listView;
        }
示例#25
0
        private void RemoveCategory_CustomizePopupWindowParams(object sender, CustomizePopupWindowParamsEventArgs e)
        {
            IObjectSpace     objectSpace       = Application.CreateObjectSpace(typeof(TemporaryResourceCategory));
            string           participantListId = Application.FindLookupListViewId(typeof(TemporaryResourceCategory));
            CollectionSource collectionSource  = new CollectionSource(objectSpace, typeof(TemporaryResourceCategory));
            ResourceLibrary  currentSchedule   = (ResourceLibrary)View.CurrentObject;

            foreach (ResourceCategory detail in currentSchedule.ResourceCategories)
            {
                TemporaryResourceCategory tempCategory = objectSpace.CreateObject <TemporaryResourceCategory>();
                tempCategory.Category = objectSpace.GetObjectByKey <ResourceCategory>(detail.Oid);
                collectionSource.Add(tempCategory);
            }


            e.View         = Application.CreateListView(participantListId, collectionSource, false);
            e.View.Caption = "Remove Category";
            e.Context      = TemplateContext.FindPopupWindow;
        }
        private void OnKeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            Label label = CollectionStack.SelectItem;

            if (CollectionSource.Count() != 0)
            {
                if (e.KeyCode == System.Windows.Forms.Keys.Up)
                {
                    UpStyleChange(label);
                    SetPopup(CollectionStack.SelectItem);
                    e.Handled = true;
                }
                if (e.KeyCode == System.Windows.Forms.Keys.Down)
                {
                    DownStyleChange(label);
                    SetPopup(CollectionStack.SelectItem);
                    e.Handled = true;
                }
            }
        }
 private void UpStyleChange(Label label)
 {
     if (label != null)
     {
         int index = CollectionSource.ToList().IndexOf(label);
         if (index != 0)
         {
             int offset = GetScrollViewerOffset();
             if (offset == index)
             {
                 SetScrollViewerOffset(offset - 1);
             }
             else if (offset > index || offset + 9 < index)
             {
                 SetScrollViewerOffset(index - 1);
             }
             StyleChange(label);
             CollectionStack.SelectItem = CollectionSource.ElementAt(index - 1);
         }
     }
 }
        private void CreateLayoutListView(ShowViewParameters svp, string listViewId, LayoutPopupListViewController controller)
        {
            IObjectSpace objectSpace = Application.CreateObjectSpace();

            var collectionSource = new CollectionSource(objectSpace, typeof(PivotGridSavedLayout));

            collectionSource.Criteria["UIFilter"] = SavedLayoutUICriteria;

            var listView = Application.CreateListView(
                listViewId,
                collectionSource,
                true);

            svp.TargetWindow = TargetWindow.NewModalWindow;


            controller.PivotGridLayoutController = this;
            svp.Controllers.Add(controller);

            svp.CreatedView = listView;
        }
示例#29
0
        private void createFilterSingleChoiceAction_Execute(object sender, SingleChoiceActionExecuteEventArgs e)
        {
            var filtersByCollectionWrapper = ((FiltersByCollectionWrapper)e.SelectedChoiceActionItem.Data);

            IModelListView       memberSearchWrapper = GetNodeMemberSearchWrapper(filtersByCollectionWrapper);
            var                  objectSpace         = Application.CreateObjectSpace();
            var                  classType           = filtersByCollectionWrapper.BinaryOperatorLastMemberClassType;
            CollectionSourceBase newCollectionSource = new CollectionSource(objectSpace, classType, memberSearchWrapper.UseServerMode);

            SetActiveFilter(memberSearchWrapper, filtersByCollectionWrapper.PropertyPathFilter);

            ListView listView = Application.CreateListView(memberSearchWrapper.Id, newCollectionSource, false);

            e.ShowViewParameters.CreatedView  = listView;
            e.ShowViewParameters.Context      = TemplateContext.PopupWindow;
            e.ShowViewParameters.TargetWindow = TargetWindow.NewModalWindow;
            var dialogController = new DialogController();

            dialogController.AcceptAction.Execute += (sender1, e1) => AcceptFilter(filtersByCollectionWrapper);
            dialogController.Accepting            += DialogControllerOnAccepting;
            e.ShowViewParameters.Controllers.Add(dialogController);
        }
        // TODO: check if collectionsource is the right way to create list view
        public void ShowView(string listViewId)
        {
            var objSpace = _objSpace ?? _app.CreateObjectSpace();

            _svp = new ShowViewParameters();
            var collectionSource = new CollectionSource(objSpace, _objType);

            _svp.CreatedView = _app.CreateListView(listViewId, collectionSource, true);

            _svp.TargetWindow         = TargetWindow.NewModalWindow;
            _svp.Context              = TemplateContext.PopupWindow;
            _svp.CreateAllControllers = true;

            if (Accepting != null)
            {
                _dc.Accepting += DialogController_Accepting;
            }

            _svp.Controllers.Add(_dc);

            _app.ShowViewStrategy.ShowView(_svp, new ShowViewSource(null, null));
        }
        public void SaveInvalidScriptTest()
        {
            using (var application = XpoInMemoryXafApplication.CreateInstance())
                using (var objectSpace = application.CreateObjectSpace())
                {
                    var collectionSource = new CollectionSource(objectSpace, typeof(DashboardDataExtract));
                    var listView         = new ListView(collectionSource, application, true);

                    var controller = application.CreateController <DashboardDataExtractController>();
                    controller.SetView(listView);

                    controller.Active.Clear();
                    controller.Active["Test"] = true;

                    var dataExtract = objectSpace.CreateObject <DashboardDataExtract>();
                    dataExtract.Script = "invalid script";

                    var exception = Assert.Throws <UserFriendlyException>(() => objectSpace.CommitChanges());

                    Assert.Empty(objectSpace.GetObjects <DashboardDataExtract>());
                }
        }
 private void OnWindowKeyDown(object sender, KeyEventArgs e)
 {
     if (e.Key == Key.Escape)
     {
         this.Close();
     }
     if (e.Key == Key.Enter)
     {
         if (CollectionSource.Count() != 0)
         {
             Label label = CollectionStack.SelectItem;
             if (label != null)
             {
                 if (label.Content as string != oldText)
                 {
                     InstructionInputTextBox.Tag = "true";
                     string[] words = InstructionInputTextBox.Text.Split(' ');
                     words[words.Length - 1]      = label.Content as string;
                     InstructionInputTextBox.Text = words[0];
                     for (int i = 1; i < words.Length; i++)
                     {
                         InstructionInputTextBox.Text += " " + words[i];
                     }
                     InstructionInputTextBox.SelectionStart = InstructionInputTextBox.Text.Length;
                     //InstructionInputTextBox.Text = label.Content as string;
                 }
                 else
                 {
                     ResetStatus(label);
                 }
             }
         }
         else
         {
             EnsureButton.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
         }
     }
 }
        void ImportSubjectAction_Execute(object sender, DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs e)
        {
            ObjectSpace objectSpace = Application.CreateObjectSpace();
            CollectionSource collectionSource = new CollectionSource(objectSpace, typeof(MyImportResult));
            int count = 0;
            int iLine=0;
            if ((collectionSource.Collection as XPBaseCollection) != null)
            {
                ((XPBaseCollection)collectionSource.Collection).LoadingEnabled = false;
            }

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

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

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

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

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

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

                    bool foundHeader = false;

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

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

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

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

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

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

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

                                }
                                objectSpace.CommitChanges();
                                count++;
                            }
                            catch (Exception ex)
                            {
                                fileStreamlog.WriteLine("<TR><td>{0}</td><td>{1}</td><td>{2}</td></tr>", iLine, "ERROR",
                                    ex.Message + ex.StackTrace);
                            }
                        }
                        fileStreamlog.WriteLine("</table></body></html>");
                        fileStreamlog.Close();
                    }

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

                    View.ObjectSpace.CommitChanges();

                }
            }
            PopUpMessage ms;
            DialogController dc;

            ms = objectSpace.CreateObject<PopUpMessage>();
            ms.Title = "Kết quả import";
            ms.Message = string.Format("Đã thực hiện import {0} kết quả cho {1} dòng trong file\r\n Vui lòng xem link kết quả", count, iLine);
            e.ShowViewParameters.CreatedView = Application.CreateDetailView(
                 objectSpace, ms);
            e.ShowViewParameters.TargetWindow = TargetWindow.NewModalWindow;
            e.ShowViewParameters.CreatedView.Caption = "Thông báo";
            dc = Application.CreateController<DialogController>();
            dc.AcceptAction.Active.SetItemValue("object", false);
            dc.CancelAction.Caption = "Đóng";
            dc.SaveOnAccept = false;
            e.ShowViewParameters.Controllers.Add(dc);
        }
        private void SelectRegister_Execute(object sender, SimpleActionExecuteEventArgs args)
        {
            ObjectSpace objectSpace = Application.CreateObjectSpace();
            ConstrainstParameter cpNHHK = objectSpace.FindObject<ConstrainstParameter>(
                           new BinaryOperator("Code", "REGISTERSEMESTER"));
            if (cpNHHK == null || cpNHHK.Value == 0 || cpNHHK.Value.ToString().Length!=5)
                throw new UserFriendlyException("Người Quản trị chưa thiết lập NHHK để ĐKMH, vui lòng liên hệ quản trị viên.");

            CriteriaOperatorCollection c = new CriteriaOperatorCollection();

            dicStudentRegDetail = new Dictionary<string, List<string>>();

            CollectionSource newCollectionSource = new CollectionSource(objectSpace, typeof(Lesson));
            listVacancies = new List<Vacancy>();
            foreach (StudentClass studentClass in View.SelectedObjects)
            {
                foreach (Student student in studentClass.Students)
                {
                    if (!dicStudentRegDetail.ContainsKey(student.StudentCode))
                        dicStudentRegDetail.Add(student.StudentCode, new List<string>());

                    foreach (RegisterDetail regDetail in student.RegisterDetails)
                    {
                        foreach (TkbSemester tkbsem in regDetail.Lesson.TKBSemesters)
                        {
                            listVacancies.Add( new Vacancy(tkbsem.Day, tkbsem.Period, tkbsem.Weeks, (tkbsem.Classroom == null ? "" : tkbsem.Classroom.ClassroomCode)));
                        }
                        dicStudentRegDetail[student.StudentCode].Add(regDetail.Lesson.Subject.SubjectCode);

                        newCollectionSource.Criteria[regDetail.Lesson.Subject.SubjectCode] =
                            new BinaryOperator("Subject.SubjectCode", regDetail.Lesson.Subject.SubjectCode, BinaryOperatorType.NotEqual);
                    }
                    //listStudentCode.Add(student.StudentCode);
                }
            }

            using (XPCollection xpLesson = new XPCollection(objectSpace.Session, typeof(Lesson)))
            {
                Vacancy vc;
                foreach (Lesson lesson in xpLesson)
                {
                    if ((Convert.ToInt32(lesson.Semester.SemesterName) <= cpNHHK.Value) || (lesson.NumRegistration >= lesson.NumExpectation))
                    {
                        //không đăng ký, quá sĩ số, khác nhhk
                        newCollectionSource.Criteria[lesson.Oid.ToString()] = new BinaryOperator("Oid", lesson.Oid, BinaryOperatorType.NotEqual);

                    }
                    //vi phạm thời khóa biểu
                    foreach (TkbSemester tkbsem in lesson.TKBSemesters)
                    {
                        vc = new Vacancy(tkbsem.Day, tkbsem.Period, tkbsem.Weeks, (tkbsem.Classroom == null ? "" : tkbsem.Classroom.ClassroomCode));
                        if (Utils.IsConfictTKB(listVacancies, vc))
                        {
                            newCollectionSource.Criteria[lesson.Oid.ToString()] = new BinaryOperator("Oid", lesson.Oid, BinaryOperatorType.NotEqual);
                            break;
                        }
                    }

                }
            }

            ListView lv = Application.CreateListView(
                Application.FindListViewId(typeof(Lesson)),
                newCollectionSource, true);
            lv.Editor.AllowEdit = false;
            lv.Editor.ControlsCreated += Editor_ControlsCreated;

            args.ShowViewParameters.CreatedView = lv;
            args.ShowViewParameters.TargetWindow = TargetWindow.NewModalWindow;
            args.ShowViewParameters.CreateAllControllers = true;
            DialogController selectAcception = new DialogController();
            args.ShowViewParameters.Controllers.Add(selectAcception);
            selectAcception.Accepting += selectAcception_AcceptingAdmin;
        }
        private void SelectRegister_Execute(object sender, SimpleActionExecuteEventArgs args)
        {
            ObjectSpace os = Application.CreateObjectSpace();

            if (SecuritySystem.CurrentUser is Student)
            {
                #region student
                ObjectSpace objectSpace = Application.CreateObjectSpace();
                CriteriaOperatorCollection c = new CriteriaOperatorCollection();

                CollectionSource newCollectionSource = new CollectionSource(objectSpace, typeof(Lesson));
                listVacancies = new List<Vacancy>();
                foreach (RegisterDetail regDetail in ((ProxyCollection)((DevExpress.ExpressApp.ListView)View).CollectionSource.Collection))
                {
                    foreach (TkbSemester tkbsem in regDetail.Lesson.TKBSemesters)
                    {
                        listVacancies.Add(new Vacancy(tkbsem.Day, tkbsem.Period, tkbsem.Weeks, tkbsem.Classroom.ClassroomCode));
                    }
                    //newCollectionSource.Criteria[regDetail.Lesson.Oid.ToString()] =
                    //    new BinaryOperator("Oid", regDetail.Lesson.Oid, BinaryOperatorType.NotEqual);
                }

                using (XPCollection xpLesson = new XPCollection(objectSpace.Session, typeof(Lesson)))
                {
                    Vacancy vc;
                    foreach (Lesson lesson in xpLesson)
                    {
                        if ((!lesson.CanRegister) || (lesson.NumRegistration >= lesson.NumExpectation))
                        {
                            //quá sĩ số
                            newCollectionSource.Criteria[lesson.Oid.ToString()] = new BinaryOperator("Oid", lesson.Oid, BinaryOperatorType.NotEqual);

                        }
                        //vi phạm thời khóa biểu
                        foreach (TkbSemester tkbsem in lesson.TKBSemesters)
                        {
                            vc = new Vacancy(tkbsem.Day, tkbsem.Period, tkbsem.Weeks, (tkbsem.Classroom == null ? "" : tkbsem.Classroom.ClassroomCode));
                            if (Utils.IsConfictTKB(listVacancies, vc))
                            {
                                newCollectionSource.Criteria[lesson.Oid.ToString()] = new BinaryOperator("Oid", lesson.Oid, BinaryOperatorType.NotEqual);
                                break;
                            }
                        }

                    }
                }

                DevExpress.ExpressApp.ListView lv = Application.CreateListView(
                    Application.FindListViewId(typeof(Lesson)),
                    newCollectionSource, true);
                lv.Editor.AllowEdit = false;
                lv.Editor.ControlsCreated += Editor_ControlsCreated;

                args.ShowViewParameters.CreatedView = lv;
                args.ShowViewParameters.TargetWindow = TargetWindow.NewModalWindow;
                args.ShowViewParameters.CreateAllControllers = true;
                DialogController selectAcception = new DialogController();
                args.ShowViewParameters.Controllers.Add(selectAcception);
                selectAcception.Accepting += selectAcception_AcceptingStudent;
                #endregion
            }
            else
            {
                ObjectSpace objectSpace = Application.CreateObjectSpace();
                CriteriaOperatorCollection c = new CriteriaOperatorCollection();
                listStudentCode = new List<string>();
                CollectionSource newCollectionSource = new CollectionSource(objectSpace, typeof(Lesson));
                listVacancies = new List<Vacancy>();
                foreach (Student student in View.SelectedObjects)
                {
                    foreach (RegisterDetail regDetail in student.RegisterDetails)
                    {
                        foreach (TkbSemester tkbsem in regDetail.Lesson.TKBSemesters)
                        {
                            listVacancies.Add(new Vacancy(tkbsem.Day, tkbsem.Period, tkbsem.Weeks, tkbsem.Classroom.ClassroomCode));
                        }
                        //newCollectionSource.Criteria[regDetail.Lesson.Oid.ToString()] =
                        //    new BinaryOperator("Oid", regDetail.Lesson.Oid, BinaryOperatorType.NotEqual);
                    }
                    listStudentCode.Add(student.StudentCode);
                }
                using (XPCollection xpLesson = new XPCollection(objectSpace.Session, typeof(Lesson)))
                {
                    Vacancy vc;
                    foreach (Lesson lesson in xpLesson)
                    {
                        if ((!lesson.CanRegister) || (lesson.NumRegistration >= lesson.NumExpectation))
                        {
                            //quá sĩ số
                            newCollectionSource.Criteria[lesson.Oid.ToString()] = new BinaryOperator("Oid", lesson.Oid, BinaryOperatorType.NotEqual);

                        }
                        //vi phạm thời khóa biểu
                        foreach (TkbSemester tkbsem in lesson.TKBSemesters)
                        {
                            vc = new Vacancy(tkbsem.Day, tkbsem.Period, tkbsem.Weeks, (tkbsem.Classroom == null ? "" : tkbsem.Classroom.ClassroomCode));
                            if (Utils.IsConfictTKB(listVacancies, vc))
                            {
                                newCollectionSource.Criteria[lesson.Oid.ToString()] = new BinaryOperator("Oid", lesson.Oid, BinaryOperatorType.NotEqual);
                                break;
                            }
                        }

                    }
                }

                DevExpress.ExpressApp.ListView lv = Application.CreateListView(
                    Application.FindListViewId(typeof(Lesson)),
                    newCollectionSource, true);
                lv.Editor.AllowEdit = false;
                lv.Editor.ControlsCreated += Editor_ControlsCreated;

                args.ShowViewParameters.CreatedView = lv;
                args.ShowViewParameters.TargetWindow = TargetWindow.NewModalWindow;
                args.ShowViewParameters.CreateAllControllers = true;
                DialogController selectAcception = new DialogController();
                args.ShowViewParameters.Controllers.Add(selectAcception);
                selectAcception.Accepting += selectAcception_AcceptingAdmin;
            }
        }
        void ImportTransactionDataAction_Execute(object sender, DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs e)
        {
            ObjectSpace objectSpace = Application.CreateObjectSpace();
            //ObjectSpace objectSpace =  ObjectSpaceInMemory.CreateNew();
            CollectionSource collectionSource = new CollectionSource(objectSpace, typeof(MyImportResult));
            if ((collectionSource.Collection as XPBaseCollection) != null)
            {
                ((XPBaseCollection)collectionSource.Collection).LoadingEnabled = false;
            }
            actFilesSelect.Clear();
            foreach (AccountTransactionFile actFile in View.SelectedObjects)
            {
                if (actFile.Note == "")
                    throw new UserFriendlyException("Vui lòng thêm thông tin Ghi chú trước khi import!!!");
                if (actFile.Semester ==null)
                    throw new UserFriendlyException("Vui lòng thêm thông tin NHHK trước khi import!!!");

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

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

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

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

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

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

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

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

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

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

                        try
                        {
                            decimal money = Decimal.Parse(valueIndexs["SOTIEN"].ToString());
                        }
                        catch
                        {
                            myImportResult.CanImport = false;
                            myImportResult.Status = "LỖI";
                            myImportResult.Message += (myImportResult.Message == "" ? "" : ",") +
                                string.Format("Cannot convert to Decimal value:{0}",valueIndexs["SOTIEN"]);

                        }
                        collectionSource.List.Add(myImportResult);
                    }
                }
            }
            ListView view = Application.CreateListView(Application.GetListViewId(typeof(MyImportResult)),
                collectionSource, false);
            view.Editor.AllowEdit = false;
            e.ShowViewParameters.CreatedView = view;
            e.ShowViewParameters.TargetWindow = TargetWindow.NewModalWindow;
            e.ShowViewParameters.CreateAllControllers = true;
            //args.ShowViewParameters.Context = TemplateContext.View;
            DialogController selectAcception = new DialogController();
            e.ShowViewParameters.Controllers.Add(selectAcception);

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

            selectAcception.AcceptAction.Caption = "Import";
            selectAcception.CancelAction.Caption = "Bỏ qua";
        }
        private void SetValues()
        {
            Edit.Items.List.Clear();
            IList<TagSourceAttribute> tagSources = MemberInfo.FindAttributes<TagSourceAttribute>().ToList();
            var settingsAttribute = MemberInfo.FindAttribute<TagSettingsAttribute>();
            if (settingsAttribute != null)
            {
                Edit.Delimeter = String.Concat(settingsAttribute.ValueSeparator);
                Edit.AllowAddCustomValues = settingsAttribute.AllowNew;
                Edit.AllowSelectValues = settingsAttribute.AllowSelect;
            }

            IMemberInfo info;
            #region Set values from tag sources
            foreach (var tagSource in tagSources)
            {
                switch (tagSource.Kind)
                {
                    case TagSourceKind.TypeSource:
                        if (typeof(Enum).IsAssignableFrom(tagSource.Type)) {
                            IList<String> Names = Enum.GetNames(tagSource.Type);
                            Array Values = Enum.GetValues(tagSource.Type);
                            String format = String.Concat(tagSource.ValueFormat);
                            if (format == "")
                                format = "{0}";

                            for (int i = 0; i < Names.Count; i++)
                            {
                                String imageName = Helpers.GetXafImageName((Enum)Values.GetValue(i));
                                if (Edit.Items.List.Where(f => f.Text == String.Format(format, Names[i])).Count() == 0)
                                {
                                    var item = Edit.Items.Add();
                                    var displayText = Helpers.GetXafDisplayName((Enum)Values.GetValue(i));
                                    item.Text = String.Format(format, displayText);
                                    item.Value = String.Concat(Values.GetValue(i));
                                    if (imageName == "")
                                        imageName = String.Concat(tagSource.ImageName);
                                }
                            }
                        } else {
                            var tagSourceType = tagSource.Type;
                            if (tagSourceType == typeof(SecuritySystemUser))
                                tagSourceType = SecuritySystem.UserType;

                            IObjectSpace os = ObjectSpace;

                            CollectionSource cs = new CollectionSource(os, tagSourceType);
                            if (tagSource.Criteria != null)
                            {
                                cs.Criteria["Criteria"] = PrepareCriteria(tagSource.Criteria);
                            }

                            String format = String.Concat(tagSource.ValueFormat);
                            if (format == "")
                            {
                                ITypeInfo TypeInfo = XafTypesInfo.Instance.FindTypeInfo(tagSourceType);
                                if (TypeInfo != null)
                                {
                                    ObjectCaptionFormatAttribute attr = TypeInfo.FindAttribute<ObjectCaptionFormatAttribute>();
                                    if (attr != null)
                                        format = attr.FormatString;
                                    else
                                    {
                                        var defPropAttr = TypeInfo.FindAttribute<XafDefaultPropertyAttribute>();
                                        if (defPropAttr != null)
                                            format = "{0:" + defPropAttr.Name + "}";
                                    }
                                }
                            }

                            IList list = null;

                            switch (String.Concat(tagSource.Sorting).ToLower())
                            {
                                case "asc":
                                case "ascending":
                                    list = cs.List.OfType<object>().OrderBy(f => String.Format(new ObjectFormatter(), format, f)).ToList();
                                    break;
                                case "desc":
                                case "descending":
                                    list = cs.List.OfType<object>().OrderByDescending(f => String.Format(new ObjectFormatter(), format, f)).ToList();
                                    break;
                                default:
                                    list = cs.List;
                                    break;
                            }

                            foreach (object obj in list)
                            {
                                var text = String.Format(new ObjectFormatter(), format, obj);
                                if (Edit.Items.List.Where(f => f.Text == text).Count() == 0)
                                {
                                    var item = Edit.Items.Add();
                                    item.Text = String.Format(new ObjectFormatter(), format, obj);
                                    item.Value = String.Concat(ObjectFormatValues.GetValueRecursive(tagSource.Key, obj, out info));
                                }
                            }
                        }
                        break;
                    case TagSourceKind.Values:
                        String Items = "";
                        try
                        {
                            Boolean IsProperty = false;
                            var property = ObjectFormatValues.GetValueRecursive(tagSource.CommaValues, CurrentObject, out info);
                            IObjectSpace os = ObjectSpace;

                            if (property is IEnumerable)
                            {
                                var coll = (property as IEnumerable);

                                var format = "";

                                if (info.MemberTypeInfo != null)
                                {
                                    var attr = info.MemberTypeInfo.FindAttribute<ObjectCaptionFormatAttribute>();
                                    if (attr != null)
                                        format = attr.FormatString;
                                    else
                                    {
                                        var defPropAttr = info.MemberTypeInfo.FindAttribute<XafDefaultPropertyAttribute>();
                                        if (defPropAttr != null)
                                            format = "{0:" + defPropAttr.Name + "}";
                                    }
                                }

                                Items = String.Join("*;*", coll.OfType<object>().Select(f => String.Format("{0}|{1}"
                                    , (format == "" ? f : String.Format(new ObjectFormatter(), format, f))
                                    , f is String ? String.Concat(f).Trim() : ObjectFormatValues.GetValueRecursive(os.GetKeyPropertyName(f.GetType()), f, out info))));
                                IsProperty = true;

                                if (String.Concat(tagSource.ValueFormat) != "")
                                    format = tagSource.ValueFormat;

                                var selectCollection = coll.OfType<object>().Select(f => new
                                {
                                    text = (format == "" ? f : String.Format(new ObjectFormatter(), format, f)),
                                    value = f is String ? String.Concat(f).Trim() : ObjectFormatValues.GetValueRecursive(String.Concat(tagSource.Key) == "" ? os.GetKeyPropertyName(f.GetType()) : tagSource.Key, f, out info)
                                }).GroupBy(f => f).Select(f => new { f.Key.text, f.Key.value }).OrderBy(f => f.text);

                                foreach (var item in selectCollection)
                                {
                                    var tagItem = Edit.Items.Add();
                                    tagItem.Text = String.Concat(item.text).Trim();
                                    tagItem.Value = String.Concat(item.value).Trim();
                                }
                            }
                            else
                            {
                                Items = String.Concat(property);

                                foreach (var item in String.Concat(tagSource.CommaValues).Split(',').Where(f => String.Concat(f) != ""))
                                {
                                    if (Edit.Items.List.Where(f => f.Text == item.Split('|')[0]).Count() == 0)
                                    {
                                        var tagItem = Edit.Items.Add();
                                        tagItem.Text = item.Split('|')[0];
                                        if (item.Split('|').Count() > 1)
                                            tagItem.Value = item.Split('|')[1];

                                        String imageName = tagSource.ImageName;
                                        if (item.Split('|').Count() > 2)
                                            imageName = item.Split('|')[2];
                                        if (imageName != "")
                                            tagItem.ImageUrl = DevExpress.ExpressApp.Utils.ImageLoader.Instance.GetImageInfo(tagSource.ImageName).ImageUrl;
                                    }
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Items = tagSource.CommaValues;
                        }

                        break;
                }
                foreach (var item in Edit.Items.List.ToList())
                    if (String.Concat(item.Text) == "" && String.Concat(item.Value) == "")
                        Edit.Items.List.Remove(item);
            }
            #endregion
        }
        void ImportStudentResultAction_Execute(object sender, DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs e)
        {
            ObjectSpace objectSpace = Application.CreateObjectSpace();
            //ObjectSpace objectSpace =  ObjectSpaceInMemory.CreateNew();
            CollectionSource collectionSource = new CollectionSource(objectSpace, typeof(MyImportResult));
            int count = 0;
            int iLine=0;
            if ((collectionSource.Collection as XPBaseCollection) != null)
            {
                ((XPBaseCollection)collectionSource.Collection).LoadingEnabled = false;
            }

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

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

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

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

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

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

                    bool foundHeader = false;

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

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

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

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

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

                                        semester = objectSpace.CreateObject<Semester>();

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

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

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

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

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

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

                                    lesson = objectSpace.CreateObject<Lesson>();

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

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

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

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

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

                    View.ObjectSpace.CommitChanges();

                }
            }
            PopUpMessage ms;
            DialogController dc;

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

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

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

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

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

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

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

                    bool foundHeader = false;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    View.ObjectSpace.CommitChanges();

                }
            }
            PopUpMessage ms;
            DialogController dc;

            ms = objectSpace.CreateObject<PopUpMessage>();
            ms.Title = "Kết quả import";
            ms.Message = string.Format("Đã thực hiện import {0} kết quả cho {1} dòng trong file\r\n Vui lòng xem link kết quả", count, iLine);
            e.ShowViewParameters.CreatedView = Application.CreateDetailView(
                 objectSpace, ms);
            e.ShowViewParameters.TargetWindow = TargetWindow.NewModalWindow;
            e.ShowViewParameters.CreatedView.Caption = "Thông báo";
            dc = Application.CreateController<DialogController>();
            dc.AcceptAction.Active.SetItemValue("object", false);
            dc.CancelAction.Caption = "Đóng";
            dc.SaveOnAccept = false;
            e.ShowViewParameters.Controllers.Add(dc);
        }
        private void SelectRegister_Execute(object sender, SimpleActionExecuteEventArgs args)
        {
            PopUpMessage ms;
            DialogController dc;
            ObjectSpace objectSpace = Application.CreateObjectSpace();
            {
                ConstrainstParameter cpNHHK = objectSpace.FindObject<ConstrainstParameter>(
                           new BinaryOperator("Code", "REGISTERSEMESTER"));

                if (cpNHHK == null || cpNHHK.Value == 0)
                    throw new UserFriendlyException("Người Quản trị chưa thiết lập NHHK để ĐKMH, vui lòng liên hệ quản trị viên.");

                if (SecuritySystem.CurrentUser is Student)
                {
                    #region student

                    CriteriaOperatorCollection c = new CriteriaOperatorCollection();

                    if (!IsInBookTime((Student)SecuritySystem.CurrentUser))
                    {
                        ms = objectSpace.CreateObject<PopUpMessage>();
                        ms.Title = "Không đăng ký được";
                        //ms.Message = string.Format("Chỉ đăng ký được trong khoảng thời gian qui định");
                        ms.Message = string.Format("Chỉ chọn được trong khoảng thời gian qui định\r\n từ ngày {0:dd-MM-yyyy} đến ngày {1:dd-MM-yyyy}",
                                StartConfirmDate, EndConfirmDate);
                        args.ShowViewParameters.CreatedView = Application.CreateDetailView(
                             objectSpace, ms);
                        args.ShowViewParameters.TargetWindow = TargetWindow.NewModalWindow;
                        args.ShowViewParameters.CreatedView.Caption = "Thông báo";
                        dc = Application.CreateController<DialogController>();
                        dc.AcceptAction.Active.SetItemValue("object", false);
                        dc.CancelAction.Caption = "Đóng";
                        args.ShowViewParameters.Controllers.Add(dc);

                        dc.SaveOnAccept = false;

                        return;
                    }

                    decimal deptAmount = 0m;
                    if (IsInDeptStudent(objectSpace, (Student)SecuritySystem.CurrentUser, out deptAmount))
                    {
                        ms = objectSpace.CreateObject<PopUpMessage>();
                        ms.Title = "Không đăng ký được";
                        ms.Message = string.Format("Không đăng ký được vì bạn đang nợ học phí số tiền {0:0,0}", deptAmount);
                        args.ShowViewParameters.CreatedView = Application.CreateDetailView(
                             objectSpace, ms);
                        args.ShowViewParameters.TargetWindow = TargetWindow.NewModalWindow;
                        args.ShowViewParameters.CreatedView.Caption = "Thông báo";
                        dc = Application.CreateController<DialogController>();
                        dc.AcceptAction.Active.SetItemValue("object", false);
                        dc.CancelAction.Caption = "Đóng";
                        args.ShowViewParameters.Controllers.Add(dc);
                        dc.SaveOnAccept = false;
                        return;
                    }

                    CollectionSource newCollectionSource = new CollectionSource(objectSpace, typeof(Lesson));
                    newCollectionSource.Criteria[cpNHHK.Value.ToString()] = new BinaryOperator(
                        "Semester.SemesterName", cpNHHK.Value, BinaryOperatorType.Greater);

                    listVacancies = new List<Vacancy>();
                    ASPxGridListEditor listEditor = ((ListView)View).Editor as ASPxGridListEditor;
                    ASPxGridView gv = listEditor.Grid;
                    gv.Selection.SelectAll();

                    foreach (RegisterDetail regDetail in ((ListView)View).SelectedObjects)
                    {
                        foreach (TkbSemester tkbsem in regDetail.Lesson.TKBSemesters)
                        {
                            listVacancies.Add(new Vacancy(tkbsem.Day, tkbsem.Period, tkbsem.Weeks, tkbsem.Classroom.ClassroomCode));
                        }
                        newCollectionSource.Criteria[regDetail.Lesson.Subject.SubjectCode] =
                               new BinaryOperator("Subject.SubjectCode", regDetail.Lesson.Subject.SubjectCode, BinaryOperatorType.NotEqual);

                        //newCollectionSource.Criteria[regDetail.Lesson.Oid.ToString()] =
                        //    new BinaryOperator("Oid", regDetail.Lesson.Oid, BinaryOperatorType.NotEqual);
                    }

                    using (XPCollection xpLesson = new XPCollection(objectSpace.Session, typeof(Lesson)))
                    {
                        Vacancy vc;
                        foreach (Lesson lesson in xpLesson)
                        {
                            if ((!lesson.CanRegister) || (lesson.NumRegistration >= lesson.NumExpectation)) //||(Convert.ToInt32(lesson.Semester.SemesterName)<=cpNHHK.Value)
                            {
                                //quá sĩ số
                                newCollectionSource.Criteria[lesson.Oid.ToString()] = new BinaryOperator("Oid", lesson.Oid, BinaryOperatorType.NotEqual);

                            }
                            //vi phạm thời khóa biểu
                            foreach (TkbSemester tkbsem in lesson.TKBSemesters)
                            {
                                vc = new Vacancy(tkbsem.Day, tkbsem.Period, tkbsem.Weeks, (tkbsem.Classroom == null ? "" : tkbsem.Classroom.ClassroomCode));
                                if (Utils.IsConfictTKB(listVacancies, vc))
                                {
                                    newCollectionSource.Criteria[lesson.Oid.ToString()] = new BinaryOperator("Oid", lesson.Oid, BinaryOperatorType.NotEqual);
                                    break;
                                }
                            }

                        }
                    }

                    ListView lv = Application.CreateListView(
                        Application.FindListViewId(typeof(Lesson)),
                        newCollectionSource, true);
                    lv.Editor.AllowEdit = false;
                    lv.Editor.ControlsCreated += Editor_ControlsCreated;

                    args.ShowViewParameters.CreatedView = lv;
                    args.ShowViewParameters.TargetWindow = TargetWindow.NewModalWindow;
                    args.ShowViewParameters.CreateAllControllers = true;
                    DialogController selectAcception = new DialogController();
                    args.ShowViewParameters.Controllers.Add(selectAcception);
                    selectAcception.AcceptAction.Caption = "Chọn";
                    selectAcception.CancelAction.Caption = "Bỏ qua";
                    selectAcception.Accepting += selectAcception_AcceptingStudent;
                    #endregion
                }
                else
                {

                    CriteriaOperatorCollection c = new CriteriaOperatorCollection();

                    dicStudentRegDetail = new Dictionary<string, List<string>>();

                    CollectionSource newCollectionSource = new CollectionSource(objectSpace, typeof(Lesson));
                    newCollectionSource.Criteria[cpNHHK.Value.ToString()] = new BinaryOperator(
                       "Semester.SemesterName", cpNHHK.Value, BinaryOperatorType.Greater);
                    listVacancies = new List<Vacancy>();
                    foreach (Student student in View.SelectedObjects)
                    {
                        if (!dicStudentRegDetail.ContainsKey(student.StudentCode))
                            dicStudentRegDetail.Add(student.StudentCode, new List<string>());

                        foreach (RegisterDetail regDetail in student.RegisterDetails)
                        {
                            foreach (TkbSemester tkbsem in regDetail.Lesson.TKBSemesters)
                            {
                                listVacancies.Add(new Vacancy(tkbsem.Day, tkbsem.Period, tkbsem.Weeks, tkbsem.Classroom.ClassroomCode));
                            }
                            dicStudentRegDetail[student.StudentCode].Add(regDetail.Lesson.Subject.SubjectCode);

                            newCollectionSource.Criteria[regDetail.Lesson.Subject.SubjectCode] =
                                new BinaryOperator("Subject.SubjectCode", regDetail.Lesson.Subject.SubjectCode, BinaryOperatorType.NotEqual);
                        }
                        //listStudentCode.Add(student.StudentCode);
                    }

                    using (XPCollection xpLesson = new XPCollection(objectSpace.Session, typeof(Lesson)))
                    {
                        Vacancy vc;
                        foreach (Lesson lesson in xpLesson)
                        {
                            if ((lesson.NumRegistration >= lesson.NumExpectation))//(Convert.ToInt32(lesson.Semester.SemesterName) <= cpNHHK.Value) ||
                            {
                                //quá sĩ số
                                newCollectionSource.Criteria[lesson.Oid.ToString()] = new BinaryOperator("Oid", lesson.Oid, BinaryOperatorType.NotEqual);

                            }
                            //vi phạm thời khóa biểu
                            foreach (TkbSemester tkbsem in lesson.TKBSemesters)
                            {
                                vc = new Vacancy(tkbsem.Day, tkbsem.Period, tkbsem.Weeks, (tkbsem.Classroom == null ? "" : tkbsem.Classroom.ClassroomCode));
                                if (Utils.IsConfictTKB(listVacancies, vc))
                                {
                                    newCollectionSource.Criteria[lesson.Oid.ToString()] = new BinaryOperator("Oid", lesson.Oid, BinaryOperatorType.NotEqual);
                                    break;
                                }
                            }

                        }
                    }

                    ListView lv = Application.CreateListView(
                        Application.FindListViewId(typeof(Lesson)),
                        newCollectionSource, true);
                    lv.Editor.AllowEdit = false;
                    lv.Editor.ControlsCreated += Editor_ControlsCreated;

                    args.ShowViewParameters.CreatedView = lv;
                    args.ShowViewParameters.TargetWindow = TargetWindow.NewModalWindow;
                    args.ShowViewParameters.CreateAllControllers = true;
                    //args.ShowViewParameters.Context = TemplateContext.View;
                    DialogController selectAcception = new DialogController();
                    args.ShowViewParameters.Controllers.Add(selectAcception);
                    selectAcception.Accepting += selectAcception_AcceptingAdmin;

                    selectAcception.AcceptAction.Caption = "Chọn";
                    selectAcception.CancelAction.Caption = "Bỏ qua";

                }
            }
        }
        void ImportTeacherAction_Execute(object sender, DevExpress.ExpressApp.Actions.SimpleActionExecuteEventArgs e)
        {
            ObjectSpace objectSpace = Application.CreateObjectSpace();
            CollectionSource collectionSource = new CollectionSource(objectSpace, typeof(MyImportResult));
            int count = 0;
            int iLine=0;
            if ((collectionSource.Collection as XPBaseCollection) != null)
            {
                ((XPBaseCollection)collectionSource.Collection).LoadingEnabled = false;
            }

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

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

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

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

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

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

                    bool foundHeader = false;

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

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

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

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

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

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

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

                    View.ObjectSpace.CommitChanges();

                }
            }
            PopUpMessage ms;
            DialogController dc;

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