public static void InitializeDefaultSolution(IObjectSpace os)
 {
     var enumerable = ReflectionHelper.FindTypeDescendants(ReflectionHelper.FindTypeInfoByName(typeof(I单据编号).FullName));
     var dictionary = os.GetObjects<单据编号方案>(null, true).ToDictionary(p => p.应用单据);
     foreach (ITypeInfo info2 in enumerable)
     {
         if (!info2.IsAbstract && info2.IsPersistent)
         {
             var key = info2.Type;
             单据编号方案 i单据编号方案 = null;
             if (dictionary.ContainsKey(key))
             {
                 i单据编号方案 = dictionary[key];
             }
             else
             {
                 i单据编号方案 = os.CreateObject<单据编号方案>();
                 i单据编号方案.名称 = key.FullName;
                 i单据编号方案.应用单据 = info2.Type;
                 var item = os.CreateObject<单据编号自动编号规则>();
                 item.格式化字符串 = "00000";
                 i单据编号方案.编号规则.Add(item);
                 dictionary.Add(key, i单据编号方案);
             }
         }
     }
     os.CommitChanges();
 }
Exemplo n.º 2
0
 public static DevExpress.DashboardCommon.Dashboard CreateDashBoard(this IDashboardDefinition template, IObjectSpace objectSpace, FilterEnabled filterEnabled) {
     var dashboard = new DevExpress.DashboardCommon.Dashboard();
     try {
         if (!string.IsNullOrEmpty(template.Xml)) {
             dashboard = LoadFromXml(template);
             dashboard.ApplyModel(filterEnabled, template, objectSpace);
         }
         foreach (var typeWrapper in template.DashboardTypes.Select(wrapper => new { wrapper.Type, Caption = GetCaption(wrapper) })) {
             var wrapper = typeWrapper;
             var dsource = dashboard.DataSources.FirstOrDefault(source => source.Name.Equals(wrapper.Caption));
             var objects = objectSpace.CreateDashboardDataSource(wrapper.Type);
             if (dsource != null) {
                 dsource.Data = objects;
             }
             else if (!dashboard.DataSources.Contains(ds => ds.Name.Equals(wrapper.Caption))) {
                 dashboard.AddDataSource(typeWrapper.Caption, objects);
             }
         }
     }
     catch (Exception e) {
         dashboard.Dispose();
         Tracing.Tracer.LogError(e);
     }
     return dashboard;
 }
Exemplo n.º 3
0
 private static ModuleArtifact CreateArtifact(ModuleChild moduleChild, ModuleArtifactType moduleArtifactType,IObjectSpace objectSpace, Type type){
     var moduleArtifact = objectSpace.CreateObject<ModuleArtifact>();
     moduleArtifact.Name = type.Name;
     moduleArtifact.Type = moduleArtifactType;
     moduleArtifact.ModuleChilds.Add(moduleChild);
     return moduleArtifact;
 }
Exemplo n.º 4
0
        private static void CriteriaOperator_UserValueToString(Object sender, UserValueProcessingEventArgs e)
        {
            if (!e.Handled && (e.Value != null))
            {
                ITypeInfo typeInfo = typesInfo.FindTypeInfo(e.Value.GetType());
                if ((typeInfo != null) && typeInfo.IsPersistent)
                {

                    IObjectSpace objectSpace = null;
                    if (e.Value is IObjectSpaceLink)
                    {
                        objectSpace = ((IObjectSpaceLink)e.Value).ObjectSpace;
                    }
                    if (objectSpace == null)
                    {
                        objectSpace = ParseCriteriaScope.currentObjectSpace;
                    }
                    if (objectSpace != null)
                    {
                        e.Data = objectSpace.GetObjectHandle(e.Value);
                        e.Tag = objectTag;
                        e.Handled = true;
                    }
                    else
                    {
                        e.Data = ObjectHandleHelper.CreateObjectHandle(typesInfo, typeInfo.Type, NHObjectSpace.GetKeyValueAsString(typesInfo, e.Value));
                        e.Tag = objectTag;
                        e.Handled = true;
                    }
                }
            }
        }
Exemplo n.º 5
0
        /// <summary>
        /// Creates the output package.
        /// </summary>
        /// <param name="objectSpace">The object space.</param>
        /// <param name="recipient">The recipient.</param>
        /// <param name="packageType">Type of the package.</param>
        /// <returns>Output package</returns>
        public Package CreateOutputPackage(IObjectSpace objectSpace, ReplicationNode recipient, PackageType packageType)
        {
            var result = objectSpace.CreateObject<Package>();

            result.ApplicationName = XafDeltaModule.XafApp.ApplicationName;
            result.SenderNodeId = Owner.CurrentNodeId;
            result.RecipientNodeId = recipient.NodeId;
            result.PackageType = packageType;

            // for broadcast package recipient node Id is "AllNodes"
            if (result.SenderNodeId == result.RecipientNodeId)
                result.RecipientNodeId = ReplicationNode.AllNodes;

            // assign package id
            if (packageType == PackageType.Snapshot)
            {
                recipient.SnapshotDateTime = DateTime.UtcNow;
                recipient.LastSavedSnapshotNumber++;
                result.PackageId = recipient.LastSavedSnapshotNumber;
            }
            else
            {
                recipient.LastSavedPackageNumber++;
                result.PackageId = recipient.LastSavedPackageNumber;
            }

            return result;
        }
 public ListView CreateListView(XafApplication application, IObjectSpace objectSpace, ISupportSequenceObject supportSequenceObject) {
     var nestedObjectSpace = (XPNestedObjectSpace)objectSpace.CreateNestedObjectSpace();
     var objectType = XafTypesInfo.Instance.FindBussinessObjectType<ISequenceReleasedObject>();
     var collectionSource = application.CreateCollectionSource(nestedObjectSpace, objectType, application.FindListViewId(objectType));
     collectionSource.Criteria["ShowReleasedSequences"] = CriteriaOperator.Parse("TypeName=?", supportSequenceObject.Prefix + supportSequenceObject.ClassInfo.FullName);
     return application.CreateListView(nestedObjectSpace, objectType, true);
 }
 public override object Authenticate(IObjectSpace objectSpace) {
     object user = objectSpace.FindObject(UserType, findUserCriteria);
     if (user == null) {
         throw new AuthenticationException(findUserCriteria.ToString());
     }
     return user;
 }
Exemplo n.º 8
0
        /// <summary>
        /// Downloads XafDelta messages into replication storage database.
        /// </summary>
        /// <param name="xafDeltaModule">The xaf delta module.</param>
        /// <param name="objectSpace">The object space.</param>
        /// <param name="worker">The worker.</param>
        public void Download(XafDeltaModule xafDeltaModule, IObjectSpace objectSpace, ActionWorker worker)
        {
            worker.ReportProgress(Localizer.DownloadStarted);

            var transportList = (from m in xafDeltaModule.ModuleManager.Modules
                                where m is IXafDeltaTransport && ((IXafDeltaTransport) m).UseForDownload
                                select m).Cast<IXafDeltaTransport>().ToList();

            worker.ReportProgress(string.Format(Localizer.TransportFound, transportList.Count()));
            foreach (var transport in transportList.TakeWhile(x => !worker.CancellationPending))
            {
                worker.ReportProgress(string.Format(Localizer.DownloadUsing, transport));
                try
                {
                    worker.ReportProgress(string.Format(Localizer.OpenTransport, transport));
                    transport.Open(TransportMode.Download, worker);

                    var existingReplicaNames = from c in objectSpace.GetObjects<Package>() select c.FileName;

                    var fileNames = transport.GetFileNames(worker,
                        @"(" + Ticket.FileMask + "|" + Package.FileMask + ")").ToList();

                    fileNames = fileNames.Except(existingReplicaNames).ToList();

                    worker.ReportProgress(string.Format(Localizer.FilesForDownload, fileNames.Count));
                    foreach (var fileName in fileNames.TakeWhile(x => !worker.CancellationPending))
                    {
                        // worker.ReportProgress(string.Format(Localizer.DownloadFile, fileName));
                        var fileData = transport.DownloadFile(fileName, worker);
                        if(fileData != null && fileData.Length > 0)
                        {
                            if (fileName.EndsWith(Package.PackageFileExtension))
                            {
                                var replica = Package.ImportFromBytes(objectSpace, fileName, fileData);
                                replica.Save();
                            }
                            else
                            {
                                var replicaTicket = Ticket.ImportTicket(objectSpace, fileData);
                                replicaTicket.Save();
                            }
                            if (!fileName.Contains(ReplicationNode.AllNodes))
                                transport.DeleteFile(fileName, worker);
                            objectSpace.CommitChanges();
                        }
                    }
                }
                catch (Exception exception)
                {
                    objectSpace.Rollback();
                    worker.ReportError(Localizer.DownloadError, exception.Message);
                }
                finally
                {
                    worker.ReportProgress(Localizer.CloseTransport, transport);
                    transport.Close();
                }
            }
            worker.ReportProgress(Color.Blue, Localizer.DownloadFinished);
        }
 public StateMachineCollectionSource(IObjectSpace objectSpace, IStateMachineRepository repository, Type type)
     : base(objectSpace) {
     _objectSpace = objectSpace;
     _repository = repository;
     _type = type;
     objectTypeInfoCore = XafTypesInfo.Instance.FindTypeInfo(typeof(IStateMachine));
 }
Exemplo n.º 10
0
 public MemberAttributeGenerator(MemberGeneratorInfo memberGeneratorInfo, ClassGeneratorInfo classGeneratorInfo) {
     _objectSpace = XPObjectSpace.FindObjectSpaceByObject(memberGeneratorInfo.PersistentMemberInfo);
     _persistentMemberInfo = memberGeneratorInfo.PersistentMemberInfo;
     _column = memberGeneratorInfo.DbColumn;
     _isPrimaryKey = CalculatePrimaryKey(memberGeneratorInfo, classGeneratorInfo);
     _dbTable = classGeneratorInfo.DbTable;
 }
Exemplo n.º 11
0
 public static void CreateWizardView(this ActionBaseEventArgs e, IObjectSpace objectSpace, object newObject, View sourceView){
     e.ShowViewParameters.TargetWindow = TargetWindow.NewModalWindow;
     e.ShowViewParameters.Context = "WizardDetailViewForm";
     if (e.ShowViewParameters.CreatedView == null){
         e.ShowViewParameters.CreatedView = e.Action.Application.CreateDetailView(objectSpace, newObject, sourceView);
     }
 }
Exemplo n.º 12
0
 public AssemblyGenerator(LogonObject logonObject, IPersistentAssemblyInfo persistentAssemblyInfo, string[] tables) {
     _persistentAssemblyInfo = persistentAssemblyInfo;
     var dataStoreSchemaExplorer = ((IDataStoreSchemaExplorer)XpoDefault.GetConnectionProvider(logonObject.ConnectionString, AutoCreateOption.None));
     _storageTables = dataStoreSchemaExplorer.GetStorageTables(tables).Where(table => table.PrimaryKey != null).ToArray();
     _logonObject = logonObject;
     _objectSpace = ObjectSpace.FindObjectSpaceByObject(persistentAssemblyInfo);
 }
 public void Setup(IObjectSpace objectSpace, XafApplication application) {
     if (helper == null) {
         helper = new ObjectEditorHelper(MemberInfo.MemberTypeInfo, Model);
     }
     _application = application;
     _objectSpace = objectSpace;
 }
Exemplo n.º 14
0
 private object AuthenticateActiveDirectory(IObjectSpace objectSpace) {
     var windowsIdentity = WindowsIdentity.GetCurrent();
     if (windowsIdentity != null) {
         string userName = windowsIdentity.Name;
         var user = (IAuthenticationActiveDirectoryUser)objectSpace.FindObject(UserType, new BinaryOperator("UserName", userName));
         if (user == null) {
             if (_createUserAutomatically) {
                 var args = new CustomCreateUserEventArgs(objectSpace, userName);
                 if (!args.Handled) {
                     user = (IAuthenticationActiveDirectoryUser)objectSpace.CreateObject(UserType);
                     user.UserName = userName;
                     if (Security != null) {
                         //Security.InitializeNewUser(objectSpace, user);
                         Security.CallMethod("InitializeNewUser", new object[]{objectSpace, user});
                     }
                 }
                 objectSpace.CommitChanges();
             }
         }
         if (user == null) {
             throw new AuthenticationException(userName);
         }
         return user;
     }
     return null;
 }
 public XPObjectSpaceAwareControlInitializer(IXPObjectSpaceAwareControl control, IObjectSpace objectSpace)
 {
     Guard.ArgumentNotNull(control, "control");
     Guard.ArgumentNotNull(objectSpace, "objectSpace");
     control.UpdateDataSource(objectSpace);
     objectSpace.Reloaded += (sender, args) => control.UpdateDataSource(objectSpace);
 }
Exemplo n.º 16
0
 public override object Authenticate(IObjectSpace objectSpace)
 {
     string systemUserName = WindowsIdentity.GetCurrent().Name;
     string enteredUserName = ((AuthenticationStandardLogonParameters)LogonParameters).UserName;
     if (string.IsNullOrEmpty(enteredUserName))
     {
         throw new ArgumentException(SecurityExceptionLocalizer.GetExceptionMessage(SecurityExceptionId.UserNameIsEmpty));
     }
     if (!String.Equals(systemUserName, enteredUserName))
     {
         throw new AuthenticationException(enteredUserName, "Invalid user name");
     }
     object user = objectSpace.FindObject(UserType, new BinaryOperator("UserName", systemUserName));
     if (user == null)
     {
         user = objectSpace.CreateObject(UserType);
         ((IAuthenticationActiveDirectoryUser)user).UserName = systemUserName;
         bool strictSecurityStrategyBehavior = SecurityModule.StrictSecurityStrategyBehavior;
         SecurityModule.StrictSecurityStrategyBehavior = false;
         objectSpace.CommitChanges();
         SecurityModule.StrictSecurityStrategyBehavior = strictSecurityStrategyBehavior;
     }
     if (!((IAuthenticationStandardUser)user).ComparePassword(((AuthenticationStandardLogonParameters)LogonParameters).Password))
     {
         throw new AuthenticationException(systemUserName, SecurityExceptionLocalizer.GetExceptionMessage(SecurityExceptionId.RetypeTheInformation));
     }
     return user;
 }
Exemplo n.º 17
0
        public static DevExpress.DashboardCommon.Dashboard CreateDashBoard(this IDashboardDefinition template, IObjectSpace objectSpace, bool filter)
        {
            var dashboard = new DevExpress.DashboardCommon.Dashboard();
            try {
                LoadFromXml(template.Xml, dashboard);

                foreach (ITypeWrapper typeWrapper in template.DashboardTypes) {
                    ITypeWrapper wrapper = typeWrapper;
                    if (dashboard.DataSources.Contains(ds => ds.Name.Equals(wrapper.Caption))) {
                        Type dashBoardObjectType = DashBoardObjectType(template, dashboard, typeWrapper);
                        if (dashBoardObjectType != null) {
                            ITypeWrapper wrapper1 = typeWrapper;
                            var dataSource = dashboard.DataSources.First(ds => ds.Name.Equals(wrapper1.Caption));
                            dataSource.Data = GetObjects(objectSpace, dashBoardObjectType);
                        }
                    }
                    else if (!dashboard.DataSources.Contains(ds => ds.Name.Equals(wrapper.Caption)))
                        dashboard.DataSources.Add(new DashboardObjectDataSource(typeWrapper.Caption, GetObjects(objectSpace, typeWrapper.Type)));
                }
                if (filter)
                    Filter(template, dashboard);
            }
            catch (Exception e) {
                dashboard.Dispose();
                Tracing.Tracer.LogError(e);
            }
            return dashboard;
        }
Exemplo n.º 18
0
 protected override void OnActivated(){
     base.OnActivated();
     _objectSpace = Application.CreateObjectSpace();
     SchedulerStorage.Instance.AppointmentChanging += SchedulerStorageAppointmentChanging;
     SchedulerStorage.Instance.ReminderAlert += ShowReminderAlerts;
     RestoreAppointments();
 }
 public FilterWindowView(IObjectSpace objectSpace, IModelView model, bool isRoot, List<FilterColumn> list)
     : base(isRoot)
 {
     this.objectSpace = objectSpace;
     base.model = model;
     control = new FilterWindowControl(list);
 }
Exemplo n.º 20
0
 public static void SynchronizeModel(this DevExpress.DashboardCommon.Dashboard dashboard, IObjectSpace objectSpace, IDashboardDefinition template) {
     var dataSources = GetDataSources(dashboard, FilterEnabled.Always, template, objectSpace);
     foreach (var dataSource in dataSources){
         var filter = dataSource.ModelDataSource as IModelDashboardDataSourceFilter;
         if (filter != null)
             dataSource.DataSource.Filter = filter.SynchronizeFilter(dataSource.DataSource.Filter);
     }
 }
Exemplo n.º 21
0
        public SmartIDEWorkspace(IObjectSpace objectSpace)
        {
            this.Workspace = new AdhocWorkspace();// MSBuildWorkspace.Create();
            this.objectSpace = objectSpace;
            CreateSolution();

            InitializeKeywordItems();
        }
        public override void ShowWizard(IObjectSpace objectSpace) {
            var wiz = new ExcelImportWizard(
                            (ObjectSpace)objectSpace,
                            View.ObjectTypeInfo,
                            this.GetCurrentCollectionSource());

            wiz.ShowDialog();
        }
Exemplo n.º 23
0
 void AddRoles(IModelRegistration modelRegistration, ITypeInfo userTypeInfo, ISecurityUserWithRoles securityUserWithRoles,
                      IObjectSpace objectSpace) {
     var roles = (XPBaseCollection) userTypeInfo.FindMember("Roles").GetValue(securityUserWithRoles);
     var roleType = modelRegistration.RoleModelClass.TypeInfo.Type;
     var criteria = CriteriaOperator.Parse(modelRegistration.RoleCriteria);
     var objects = objectSpace.GetObjects(roleType, criteria);
     roles.BaseAddRange(objects);
 }
Exemplo n.º 24
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LoadPackageContext"/> class.
 /// </summary>
 /// <param name="package">The package.</param>
 /// <param name="worker">The worker.</param>
 /// <param name="objectSpace">The object space.</param>
 /// <param name="currentNodeId">The current node id.</param>
 public LoadPackageContext(Package package, ActionWorker worker, 
     IObjectSpace objectSpace, string currentNodeId)
 {
     CurrentNodeId = currentNodeId;
     Package = package;
     Worker = worker;
     ObjectSpace = objectSpace;
 }
Exemplo n.º 25
0
        IClassInfoGraphNode CreateComplexNode(IMemberInfo memberInfo, IObjectSpace objectSpace) {
            NodeType nodeType = memberInfo.MemberTypeInfo.IsPersistent ? NodeType.Object : NodeType.Collection;
            IClassInfoGraphNode classInfoGraphNode = CreateClassInfoGraphNode(objectSpace, memberInfo, nodeType);
            classInfoGraphNode.SerializationStrategy = GetSerializationStrategy(memberInfo, SerializationStrategy.SerializeAsObject);
            Generate(objectSpace, ReflectionHelper.GetType(classInfoGraphNode.TypeName));
            return classInfoGraphNode;

        }
Exemplo n.º 26
0
 object GetObjectKey(ViewShortcut shortcut, Type type, IObjectSpace objectSpace) {
     var objectKey = GetObjectKey(objectSpace, type, shortcut);
     if (objectKey != null)
         return objectKey;
     return shortcut.ObjectKey.StartsWith("@")
                     ? ParametersFactory.CreateParameter(shortcut.ObjectKey.Substring(1)).CurrentValue
                     : CriteriaWrapper.ParseCriteriaWithReadOnlyParameters(shortcut.ObjectKey, type);
 }
Exemplo n.º 27
0
        private void Action_Executed(object sender, ActionBaseEventArgs e) {
            var newObject = _newObject;
            var sourceView = View;
            e.CreateWizardViewInternal(_objectSpace, newObject, sourceView);

            _objectSpace = null;
            _newObject = null;
        }
Exemplo n.º 28
0
 /// <summary>
 /// Creates for package session.
 /// </summary>
 /// <param name="objectSpace">The object space.</param>
 /// <param name="packageSession">The package session.</param>
 /// <returns>New external protocol session</returns>
 public static ExternalProtocolSession CreateForPackageSession(IObjectSpace objectSpace, PackageSession packageSession)
 {
     var result = objectSpace.CreateObject<ExternalProtocolSession>();
     result.SessionId = packageSession.SessionId;
     result.Route = packageSession.Route;
     result.StartedOn = packageSession.StartedOn;
     return result;
 }
Exemplo n.º 29
0
 private object AuthenticateStandard(IObjectSpace objectSpace) {
     if (string.IsNullOrEmpty(logonParameters.UserName))
         throw new ArgumentException(SecurityExceptionLocalizer.GetExceptionMessage(SecurityExceptionId.UserNameIsEmpty));
     var user = (IAuthenticationStandardUser)objectSpace.FindObject(UserType, new BinaryOperator("UserName", logonParameters.UserName));
     if (user == null || !user.ComparePassword(logonParameters.Password)) {
         throw new AuthenticationException(logonParameters.UserName, SecurityExceptionLocalizer.GetExceptionMessage(SecurityExceptionId.RetypeTheInformation));
     }
     return user;
 }
Exemplo n.º 30
0
 public void Setup(IObjectSpace objectSpace, XafApplication application) {
     if (_helper == null) {
         _helper = new LookupEditorHelper(application, objectSpace, MemberInfo.MemberTypeInfo, Model) {
             SmallCollectionItemCount = 0x989680
         };
     }
     _helper.SetObjectSpace(objectSpace);
     _helper.ObjectSpace.Reloaded += ObjectSpace_Reloaded;
 }
 public static ImportApPmtDistnParam GetInstance(IObjectSpace objectSpace)
 {
     return(BaseObjectHelper.GetInstance <ImportApPmtDistnParam>(objectSpace));
 }
Exemplo n.º 32
0
        private void MiniNavigationAction_Execute(object sender, SingleChoiceActionExecuteEventArgs e)
        {
            if (e.CurrentObject == null)
            {
                return;
            }

            if (MiniNavigationAction.SelectedItem == null)
            {
                return;
            }

            object currentObj = e.CurrentObject;

            Frame  frame = Frame;
            View   view  = View;
            string path  = e.SelectedChoiceActionItem.Id;
            //if (selId == path) return;
            String selId = path;

            if ((view as DetailView) != null & selId == "This")
            {
                return;
            }

            BaseObject obj = GetObjectOnPathEnd(path, (BaseObject)currentObj);

            if (obj == null)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show(
                    CommonMethods.GetMessage(MiniNavigatorControllerMessages.SHOWING_OBJECT_NOT_DEFINED),
                    messageCaption,
                    System.Windows.Forms.MessageBoxButtons.OK,
                    System.Windows.Forms.MessageBoxIcon.Exclamation);
                return;
            }

            Type   ChoiceType = (System.Type)(obj.GetType());             //.UnderlyingSystemType;   //typeof(object);
            string ViewID     = Application.FindDetailViewId(ChoiceType); // По умолчанию - DetailView

            // Считывание из модели view, через которое надо показать объект и оно задано
            IModelView modelView = null;

            DevExpress.ExpressApp.ListView   listView   = view as DevExpress.ExpressApp.ListView;
            DevExpress.ExpressApp.DetailView detailView = view as DevExpress.ExpressApp.DetailView;

            //if (IsMiniNavigationDefined) {
            //    // Узел в модели
            //    IModelView node = null;
            //    node = View.Model.Application.Views[((listView != null) ? listView.Id : "") + ((detailView != null) ? detailView.Id : "")];
            //    if (node != null) {
            //        // Перебираем все подузлы
            //        // node.GetNode(1)	{ModelListViewFilters}	DevExpress.ExpressApp.Model.IModelNode {ModelListViewFilters}
            //        for (int i = 0; i < node.NodeCount; i++) {
            //IModelMiniNavigations miniNavigationNode = node.GetNode(i) as IModelMiniNavigations;
            IModelMiniNavigations miniNavigationNode = FindMiniNavigationModel(View);

            if (miniNavigationNode != null)
            {
                foreach (IModelMiniNavigationItem miniNavigationItem in miniNavigationNode.GetNodes <IModelMiniNavigationItem>())
                {
                    if (miniNavigationItem.NavigationPath == selId)
                    {
                        modelView = miniNavigationItem.View;
                        break;
                    }
                }
                //break;
            }
            //        }
            //    }
            //}


            Frame        resultFrame = frame; // Application.CreateFrame("new");
            TargetWindow openMode    = (TargetWindow)e.SelectedChoiceActionItem.Data;

            // Сбрасываем состояние списка
            MiniNavigationAction.SelectedItem  = null;
            MiniNavigationAction.SelectedIndex = 0;

            // Небольшая разборка с сочетанием значений openMode и типа текущего View - List или Detail - в целях
            // определения фрейма, в который грузить
            if (MasterDetailViewFrame != null && (openMode == TargetWindow.Current & (view as ListView) != null & ((frame as NestedFrame) != null | !view.IsRoot)))
            {
                // Тогда Current трактуем как корневое окно
                resultFrame = MasterDetailViewFrame;
                {
                    //IObjectSpace objectSpace = resultFrame.View.ObjectSpace;
                    IObjectSpace objectSpace       = resultFrame.Application.CreateObjectSpace(); // Всё равно предыдущий ObjectSpace теряется в этом случае
                    object       representativeObj = objectSpace.GetObject(obj);

                    View dv = null;

                    if (modelView != null)
                    {
                        if ((modelView as IModelDetailView) != null)
                        {
                            ViewID = (modelView as IModelDetailView).Id;
                            dv     = resultFrame.Application.CreateDetailView(objectSpace, ViewID, true, representativeObj) as DetailView;
                        }
                        else if ((modelView as IModelListView) != null)
                        {
                            ViewID = (modelView as IModelListView).Id;
                            //ListView dv = resultFrame.Application.CreateListView(objectSpace, ChoiceType, true);
                            CollectionSource colSource = new CollectionSource(objectSpace, ChoiceType);
                            if (!colSource.IsLoaded)
                            {
                                colSource.Reload();
                            }
                            dv = resultFrame.Application.CreateListView((modelView as IModelListView), colSource, true) as ListView;
                        }
                    }
                    else
                    {
                        ViewID = Application.FindDetailViewId(ChoiceType);
                        dv     = resultFrame.Application.CreateDetailView(objectSpace, ViewID, true, representativeObj) as DetailView;
                    }

                    resultFrame.SetView(dv, true, resultFrame);
                }
                return;
            }

            // Общий алгоритм
            {
                IObjectSpace objectSpace = null;

                // Анализ того, какой ObjectSpace нужен
                if ((frame as NestedFrame) != null | !view.IsRoot)
                {
                    objectSpace = resultFrame.View.ObjectSpace.CreateNestedObjectSpace();
                }
                //objectSpace = resultFrame.View.ObjectSpace.CreateNestedObjectSpace();
                if (objectSpace == null)
                {
                    objectSpace = resultFrame.Application.CreateObjectSpace();
                }

                object representativeObj = objectSpace.GetObject(obj);

                //ViewID = Application.FindDetailViewId(ChoiceType);
                //DetailView dv = frame.Application.CreateDetailView(objectSpace, ViewID, true, representativeObj);

                View dv = null;

                if (modelView != null)
                {
                    if ((modelView as IModelDetailView) != null)
                    {
                        ViewID = (modelView as IModelDetailView).Id;
                        dv     = resultFrame.Application.CreateDetailView(objectSpace, ViewID, true, representativeObj) as DetailView;
                    }
                    else if ((modelView as IModelListView) != null)
                    {
                        ViewID = (modelView as IModelListView).Id;
                        //ListView dv = resultFrame.Application.CreateListView(objectSpace, ChoiceType, true);
                        //objectSpace = resultFrame.Application.CreateObjectSpace();
                        CollectionSource colSource = new CollectionSource(objectSpace, ChoiceType);
                        if (!colSource.IsLoaded)
                        {
                            colSource.Reload();
                        }
                        dv = resultFrame.Application.CreateListView((modelView as IModelListView), colSource, true) as ListView;
                    }
                }
                else
                {
                    ViewID = Application.FindDetailViewId(ChoiceType);
                    dv     = resultFrame.Application.CreateDetailView(objectSpace, ViewID, true, representativeObj) as DetailView;
                }

                ShowViewParameters svp = new ShowViewParameters();
                svp.CreatedView          = dv;
                svp.TargetWindow         = openMode;
                svp.Context              = TemplateContext.View;
                svp.CreateAllControllers = true;

                e.ShowViewParameters.Assign(svp);
            }
        }
Exemplo n.º 33
0
 public void Setup(IObjectSpace objectSpace, XafApplication application)
 {
     this.os  = objectSpace;
     this.app = application;
 }
Exemplo n.º 34
0
        public override IEnumerable <ModuleUpdater> GetModuleUpdaters(IObjectSpace objectSpace, Version versionFromDB)
        {
            ModuleUpdater updater = new DatabaseUpdate.Updater(objectSpace, versionFromDB);

            return(new ModuleUpdater[] { updater });
        }
Exemplo n.º 35
0
 protected abstract DetailView CreateDetailView(IObjectSpace objectSpace);
Exemplo n.º 36
0
        private static void GetDevelopment(DataTable sheet, personnel_master personnel, IObjectSpace objectSpace)
        {
            for (int objInx = 17; objInx < sheet.Rows.Count; objInx++)
            {
                if (sheet.Rows[objInx][0].ToString() == "Possible Career Development")
                {
                    personnel.possible_career_development_emp     = sheet.Rows[objInx + 2][0].ToString();
                    personnel.possible_career_development_manager = sheet.Rows[objInx + 10][0].ToString();
                    personnel.possible_career_development_how     = sheet.Rows[objInx + 18][0].ToString();
                    break;
                }
                if (sheet.Rows[objInx][0].ToString() == string.Empty)
                {
                    continue;
                }
                development dev = objectSpace.CreateObject <development>();
                dev.personnel_id    = personnel;
                dev.gap_description = sheet.Rows[objInx][0].ToString();
                if (DateTime.TryParse(sheet.Rows[objInx][9].ToString(), out DateTime reviewDate))
                {
                    dev.review_date = reviewDate;
                }

                dev.how_10 = sheet.Rows[objInx][3].ToString();
                dev.how_20 = sheet.Rows[objInx + 1][3].ToString();
                dev.how_70 = sheet.Rows[objInx + 2][3].ToString();

                if (DateTime.TryParse(sheet.Rows[objInx][8].ToString(), out DateTime date10))
                {
                    dev.date_10 = date10;
                }
                if (DateTime.TryParse(sheet.Rows[objInx + 1][8].ToString(), out DateTime date20))
                {
                    dev.date_20 = date20;
                }
                if (DateTime.TryParse(sheet.Rows[objInx + 2][8].ToString(), out DateTime date70))
                {
                    dev.date_70 = date70;
                }

                objInx += 2;
            }
        }
Exemplo n.º 37
0
 public Updater(IObjectSpace objectSpace, Version currentDBVersion) :
     base(objectSpace, currentDBVersion)
 {
 }
Exemplo n.º 38
0
 public static IModifier CreateModifierPermission <T>(this IObjectSpace objectSpace, Modifier modifier) where T : IModifier
 {
     return(CreateModifierPermission(objectSpace, modifier, typeof(T)));
 }
Exemplo n.º 39
0
 public static ISecurityUserWithRoles GetUser(this IObjectSpace objectSpace, string userName, string passWord = "", params ISecurityRole[] roles)
 {
     return((ISecurityUserWithRoles)objectSpace.FindObject(SecuritySystem.UserType, new BinaryOperator("UserName", userName)) ??
            CreateUser(objectSpace, userName, passWord, roles));
 }
 public static void SetSequence(this IObjectSpace objectSpace, Type sequenceType, string sequenceMember,
                                Type customSequence = null, long firstSequence = 0, Type sequenceStorageType = null)
 => objectSpace.SetSequence(sequenceType, sequenceMember, customSequence?.FullName, firstSequence,
                            sequenceStorageType);
Exemplo n.º 41
0
 public override IEnumerable <ModuleUpdater> GetModuleUpdaters(IObjectSpace objectSpace, Version versionFromDB)
 {
     return(ModuleUpdater.EmptyModuleUpdaters);
 }
Exemplo n.º 42
0
 public void Setup(IObjectSpace objectSpace, XafApplication application)
 {
     theObjectSpace = objectSpace;
     theApplication = application;
 }
Exemplo n.º 43
0
 protected virtual void QualifyCompleted(Lead lead, IObjectSpace os)
 {
     CreatedCustomer = (Customer)os.GetObject(CreatedCustomer);
 }
Exemplo n.º 44
0
        public DashboardDataSourceWizardViewBase(ScriptDashboardWizardParameters parameters, IObjectSpace objectSpace, XafApplication application)
        {
            ObjectSpace      = objectSpace;
            WizardParameters = parameters;
            Application      = application;

            ParamsObjectSpace = application.CreateObjectSpace();
            paramsView        = CreateDetailView(ParamsObjectSpace);
            paramsView.CreateControls();
            paramsView.LayoutManager.CustomizationEnabled = false;
            panelBaseContent.Controls.Add((XafLayoutControl)paramsView.LayoutManager.Container);
        }
Exemplo n.º 45
0
 public static Identificadores GetInstance(IObjectSpace objectSpace)
 {
     return(GetInstance((( XPObjectSpace )objectSpace).Session));
 }
Exemplo n.º 46
0
 public NestedUnityXPObjectSpace(IObjectSpace parentObjectSpace) : base(parentObjectSpace)
 {
 }
Exemplo n.º 47
0
        private void worker_DoWork(object sender, DoWorkEventArgs e)
        {
            IObjectSpace objectSpace = Application.CreateObjectSpace();

            BusinessObjects.Appraisaldb.options option = SqlOp.GetOptionalue(objectSpace, Types.OptionsType.FilesPath.ToString());

            ObservableCollection <UpdateFile> fileslst = new ObservableCollection <UpdateFile>();

            ShowDialog(fileslst);
            string[] files = Directory.GetFiles(option.option_value, "*.xlsx", SearchOption.AllDirectories);
            ProgressMax   = files.Length;
            ProgressValue = 0;

            foreach (string file in files)
            {
                fileslst.Add(new UpdateFile(file));
            }


            foreach (UpdateFile file in fileslst)
            {
                ProgressValue = ProgressValue + 1;
                try
                {
                    //1 Personal, 3 Behaviours, 4 Objectives, 5 Development, 6 ObjectivesNy
                    //0 Personal, 1 Behaviours, 2 Objectives, 3 Development, 4 ObjectivesNy
                    List <DataTable> sheets = ExcelApi.LoadExcelFile_VBA(file.FilePath, new[] { 1, 3, 4, 5, 7 });

                    //Personal
                    int personnelId;// = Convert.ToInt32(sheets[0].Rows[12][2]);
                    if (!int.TryParse(sheets[0].Rows[12][2].ToString(), out personnelId))
                    {
                        personnelId = (DateTime.Now.Year + DateTime.Now.Month + DateTime.Now.Day + DateTime.Now.Second +
                                       DateTime.Now.Millisecond) * -1;
                    }
                    personnel_master personnel = objectSpace.GetObjectByKey <personnel_master>(personnelId);
                    if (personnel == null)
                    {
                        personnel = objectSpace.CreateObject <personnel_master>();
                        personnel.personnel_id = personnelId;
                    }
                    personnel.personnel_name       = sheets[0].Rows[11][2].ToString();
                    personnel.job_name             = sheets[0].Rows[13][2].ToString();
                    personnel.time_in_current_role = sheets[0].Rows[16][5].ToString();
                    if (DateTime.TryParse(sheets[0].Rows[14][5].ToString(), out DateTime reviewDate))
                    {
                        personnel.review_date = reviewDate;
                    }
                    personnel.job_description = sheets[0].Rows[17][5].ToString();
                    if (int.TryParse(sheets[0].Rows[12][7].ToString(), out int managerId))
                    {
                        personnel.manager_id = managerId;
                    }
                    personnel.manager_name     = sheets[0].Rows[11][7].ToString();
                    personnel.last_update_date = DateTime.Now;
                    personnel.file_path        = file.FilePath;

                    //Delete before insert
                    objectSpace.Delete(personnel.objectives);
                    objectSpace.Delete(personnel.objective_next_years);
                    objectSpace.Delete(personnel.developments);

                    //Behaviours
                    GetBehaviours(personnel, sheets);
                    //Objectives
                    GetObjectives(sheets, personnel, objectSpace);
                    //Development
                    GetDevelopment(sheets[3], personnel, objectSpace);
                    //ObjectivesNy
                    GetObjectivesNy(sheets[4], personnel, objectSpace);

                    objectSpace.CommitChanges();
                    file.OpResult = Types.OperationResult.Success;
                    Refresh();
                }
                catch (Exception exception)
                {
                    Console.WriteLine(exception);
                    file.OpResult  = Types.OperationResult.Fail;
                    file.ResultMsg = exception.Message;
                }
            }
        }
Exemplo n.º 48
0
        /// <summary>
        /// Downloads XafDelta messages into replication storage database.
        /// </summary>
        /// <param name="xafDeltaModule">The xaf delta module.</param>
        /// <param name="objectSpace">The object space.</param>
        /// <param name="worker">The worker.</param>
        public void Download(XafDeltaModule xafDeltaModule, IObjectSpace objectSpace, ActionWorker worker)
        {
            worker.ReportProgress(Localizer.DownloadStarted);

            var transportList = (from m in xafDeltaModule.ModuleManager.Modules
                                 where m is IXafDeltaTransport && ((IXafDeltaTransport)m).UseForDownload
                                 select m).Cast <IXafDeltaTransport>().ToList();

            worker.ReportProgress(string.Format(Localizer.TransportFound, transportList.Count()));
            foreach (var transport in transportList.TakeWhile(x => !worker.CancellationPending))
            {
                worker.ReportProgress(string.Format(Localizer.DownloadUsing, transport));
                try
                {
                    worker.ReportProgress(string.Format(Localizer.OpenTransport, transport));
                    transport.Open(TransportMode.Download, worker);

                    var existingReplicaNames = from c in objectSpace.GetObjects <Package>() select c.FileName;

                    var fileNames = transport.GetFileNames(worker,
                                                           @"(" + Ticket.FileMask + "|" + Package.FileMask + ")").ToList();

                    fileNames = fileNames.Except(existingReplicaNames).ToList();

                    worker.ReportProgress(string.Format(Localizer.FilesForDownload, fileNames.Count));
                    foreach (var fileName in fileNames.TakeWhile(x => !worker.CancellationPending))
                    {
                        // worker.ReportProgress(string.Format(Localizer.DownloadFile, fileName));
                        var fileData = transport.DownloadFile(fileName, worker);
                        if (fileData != null && fileData.Length > 0)
                        {
                            if (fileName.EndsWith(Package.PackageFileExtension))
                            {
                                var replica = Package.ImportFromBytes(objectSpace, fileName, fileData);
                                replica.Save();
                            }
                            else
                            {
                                var replicaTicket = Ticket.ImportTicket(objectSpace, fileData);
                                replicaTicket.Save();
                            }
                            if (!fileName.Contains(ReplicationNode.AllNodes))
                            {
                                transport.DeleteFile(fileName, worker);
                            }
                            objectSpace.CommitChanges();
                        }
                    }
                }
                catch (Exception exception)
                {
                    objectSpace.Rollback();
                    worker.ReportError(Localizer.DownloadError, exception.Message);
                }
                finally
                {
                    worker.ReportProgress(Localizer.CloseTransport, transport);
                    transport.Close();
                }
            }
            worker.ReportProgress(Color.Blue, Localizer.DownloadFinished);
        }
Exemplo n.º 49
0
        private static void GetObjectivesNy(DataTable sheet, personnel_master personnel, IObjectSpace objectSpace)
        {
            for (int objInx = 11; objInx < sheet.Rows.Count; objInx++)
            {
                if (sheet.Rows[objInx][0].ToString() == string.Empty)
                {
                    continue;
                }
                objective_next_year obv = objectSpace.CreateObject <objective_next_year>();
                obv.objective        = sheet.Rows[objInx][0].ToString();
                obv.personnel_id     = personnel;
                obv.base_start_point = sheet.Rows[objInx][6].ToString();
                obv.method_actions   = sheet.Rows[objInx][9].ToString();
                if (DateTime.TryParse(sheet.Rows[objInx][13].ToString(), out DateTime timeInCurrentRole))
                {
                    obv.timing_to_complete = timeInCurrentRole;
                }
                if (TryParse(sheet.Rows[objInx][14].ToString(), out short rating))
                {
                    obv.rating = rating;
                }
                objInx += 3;
                //obv.Save();
            }


            //for (int objInx = 8; objInx < sheet.Rows.Count; objInx++)
            //{
            //    if (sheet.Rows[objInx][0].ToString() != "Objective")
            //        continue;
            //    if (sheet.Rows[objInx + 2][0].ToString().Trim() == string.Empty)
            //        continue;
            //    objInx += 2;
            //    objective_next_year obv = objectSpace.CreateObject<objective_next_year>();
            //    obv.objective = sheet.Rows[objInx][0].ToString();
            //    obv.personnel_id = personnel;
            //    obv.base_start_point = sheet.Rows[objInx][6].ToString();
            //    obv.method_actions = sheet.Rows[objInx][9].ToString();
            //    if (DateTime.TryParse(sheet.Rows[objInx][13].ToString(), out DateTime timeInCurrentRole))
            //        obv.timing_to_complete = timeInCurrentRole;
            //    if (TryParse(sheet.Rows[objInx][14].ToString(), out short rating))
            //        obv.rating = rating;
            //}
        }
 public static ISequenceStorage GetSequenceStorage(this IObjectSpace objectSpace, Type objectType,
                                                   bool customSequenceLookup = true, Type sequenceStorageType = null)
 => objectSpace.UnitOfWork().GetSequenceStorage(objectType, customSequenceLookup, sequenceStorageType);
 public InvoiceFactory(IObjectSpace objectSpace)
 {
     this.objectSpace = objectSpace;
 }
 public static void SetSequence(this IObjectSpace objectSpace, Type sequenceType, string sequenceMember,
                                string customSequence = null, long firstSequence = 0, Type sequenceStorageType = null)
 => SetSequence(sequenceStorageType, sequenceType, objectSpace.UnitOfWork(), sequenceMember, customSequence, firstSequence);
Exemplo n.º 53
0
        private static void GetObjectives(IReadOnlyList <DataTable> sheets, personnel_master personnel, IObjectSpace objectSpace)
        {
            for (int objInx = 0; objInx < sheets[2].Rows.Count; objInx++)
            {
                if (sheets[2].Rows[objInx][0].ToString() == "Appraisee: Describe your overall performance over the past year")
                {
                    objInx++;
                    personnel.emp_past_year_description_appraisee = sheets[2].Rows[objInx][0].ToString();
                    objInx += 12;
                    if (TryParse(sheets[2].Rows[objInx][9].ToString(), out short empRating))
                    {
                        personnel.emp_rating = empRating;
                    }
                    objInx += 13;
                    personnel.manager_past_year_description_appraisee = sheets[2].Rows[objInx][0].ToString();
                    objInx += 12;
                    if (TryParse(sheets[2].Rows[objInx][9].ToString(), out short managerRating))
                    {
                        personnel.manager_rating = managerRating;
                    }
                    objInx += 12;
                    personnel.appraisee_comments = sheets[2].Rows[objInx][0].ToString();

                    break;
                }
                if (sheets[2].Rows[objInx][0].ToString() != "Objective")
                {
                    continue;
                }
                objInx++;
                while (sheets[2].Rows[objInx][0].ToString().Trim() == string.Empty)
                {
                    objInx++;
                }
                //if (sheets[2].Rows[objInx + 1][0].ToString().Trim() == string.Empty)
                //    continue;
                //objInx++;
                objective obv = objectSpace.CreateObject <objective>();
                obv.objective1       = sheets[2].Rows[objInx][0].ToString();
                obv.personnel_id     = personnel;
                obv.base_start_point = sheets[2].Rows[objInx][6].ToString();
                obv.method_actions   = sheets[2].Rows[objInx][9].ToString();
                if (TryParse(sheets[2].Rows[objInx][14].ToString(), out double weight))
                {
                    obv.weight = weight;
                }
                if (DateTime.TryParse(sheets[2].Rows[objInx][15].ToString(), out DateTime timeInCurrentRole))
                {
                    obv.timing_to_complete = timeInCurrentRole;
                }
                if (TryParse(sheets[2].Rows[objInx][16].ToString(), out short rating))
                {
                    obv.rating = rating;
                }
                objInx += 7;
                obv.employee_comment = sheets[2].Rows[objInx][0].ToString();
                obv.manager_comment  = sheets[2].Rows[objInx][6].ToString();
            }
        }
Exemplo n.º 54
0
 public static ISecurityRole GetDefaultRole(this IObjectSpace objectSpace)
 {
     return(objectSpace.GetDefaultRole("Default"));
 }
Exemplo n.º 55
0
 public void Setup(IObjectSpace objectSpace, XafApplication application)
 {
     _objectSpace            = objectSpace;
     _objectSpace.Committed += ObjectSpaceOnCommitted;
 }
Exemplo n.º 56
0
        private bool StartImport(Worksheet ws, IModelClass bo, IObjectSpace os)
        {
            //开始导入:
            //1.先使用表头的标题找到属性名称
            Dictionary <int, IModelMember> fields = new Dictionary <int, IModelMember>();
            List <SheetRowObject>          objs   = new List <SheetRowObject>();
            //var ws = _spreadsheet.Document.Worksheets[0];
            var columnCount = ws.Columns.LastUsedIndex;

            var updateImport = bo.TypeInfo.FindAttribute <UpdateImportAttribute>();
            var findObjectProviderAttribute = bo.TypeInfo.FindAttribute <FindObjectProviderAttribute>();

            if (findObjectProviderAttribute != null)
            {
                findObjectProviderAttribute.Reset();
            }

            var isUpdateImport = updateImport != null;

            var          keyColumn   = 0;
            var          headerError = false;
            IModelMember keyField    = null;

            for (int c = 1; c <= columnCount; c++)
            {
                var fieldCaption = ws.Cells[1, c].DisplayText;
                var fieldName    = bo.AllMembers.SingleOrDefault(x => x.Caption == fieldCaption);
                if (fieldName != null)
                {
                    fields.Add(c, fieldName);
                    if (isUpdateImport && fieldName.Name == updateImport.KeyMember)
                    {
                        keyColumn = c;
                        keyField  = fieldName;
                    }
                }
                else
                {
                    ws.Cells[1, c].FillColor = Color.Red;
                    headerError = true;
                }
            }

            var sheetContext = new SheetContext(ws, fields.ToDictionary(x => x.Value.Name, x => x.Key));

            var rowCount = ws.Rows.LastUsedIndex;

            ws.Workbook.BeginUpdate();
            //清理上次的结果.
            for (int r = 2; r <= rowCount; r++)
            {
                //ws.Cells[r, 0].ClearContents();

                for (int c = 1; c <= columnCount; c++)
                {
                    var cel = ws.Cells[r, c];
                    if (cel.FillColor != Color.Empty)
                    {
                        cel.FillColor = Color.Empty;
                    }

                    if (cel.Font.Color != Color.Empty)
                    {
                        cel.Font.Color = Color.Empty;
                    }
                }

                var errorCell = ws.Cells[r, 0];
                if (!errorCell.Value.IsEmpty)
                {
                    errorCell.Clear();
                }
            }

            ws.Workbook.EndUpdate();
            if (headerError)
            {
                ws.Cells[0, 4].SetValue("表头有错误,请查看被标红色的表头,确认行中没有对应的数据。");
                return(false);
            }



            var updateStep = rowCount / 100;

            if (updateStep == 0)
            {
                updateStep = 1;
            }

            var numberTypes = new[]
            {
                typeof(Int16), typeof(Int32), typeof(Int64), typeof(UInt16), typeof(UInt32), typeof(UInt64), typeof(decimal), typeof(float), typeof(double),
                typeof(byte), typeof(sbyte)
            };

            ws.Workbook.BeginUpdate();
            for (int r = 2; r <= rowCount; r++)
            {
                XPBaseObject obj = null;
                if (isUpdateImport)
                {
                    var cdvalue = Convert.ChangeType(ws.Cells[r, keyColumn].Value.ToObject(), keyField.Type);
                    var cri     = new BinaryOperator(updateImport.KeyMember, cdvalue);
                    if (findObjectProviderAttribute != null)
                    {
                        var t = findObjectProviderAttribute.FindObject(os, bo.TypeInfo.Type, cri, true);
                        if (t.Count > 0)
                        {
                            obj = t[0] as XPBaseObject;
                        }
                        else
                        {
                            t = null;
                        }
                    }
                    else
                    {
                        obj = os.FindObject(bo.TypeInfo.Type, cri) as XPBaseObject;
                    }

                    if (obj == null)
                    {
                        obj = os.CreateObject(bo.TypeInfo.Type) as XPBaseObject;
                    }
                }
                else
                {
                    obj = os.CreateObject(bo.TypeInfo.Type) as XPBaseObject;
                }

                var result = new SheetRowObject(sheetContext)
                {
                    Object = obj, Row = r, RowObject = ws.Rows[r]
                };

                //var vle = ws.Cells[r, c];
                for (int c = 1; c <= columnCount; c++)
                {
                    var field = fields[c];
                    var cell  = ws.Cells[r, c];

                    if (!cell.Value.IsEmpty)
                    {
                        object value = null;
                        //引用类型
                        //兼容DC类型
                        var memberType = field.MemberInfo.MemberType;
                        if (memberType.IsValueType && memberType.IsGenericType)
                        {
                            if (memberType.GetGenericTypeDefinition() == typeof(Nullable <>))
                            {
                                memberType = memberType.GetGenericArguments()[0];
                            }
                        }

                        if (typeof(XPBaseObject).IsAssignableFrom(memberType) || field.MemberInfo.MemberTypeInfo.IsDomainComponent)
                        {
                            #region 引用类型
                            var conditionValue = cell.Value.ToObject();
                            //如果指定了查找条件,就直接使用
                            var idf       = field.MemberInfo.FindAttribute <ImportDefaultFilterCriteria>();
                            var condition = idf == null ? "" : idf.Criteria;

                            #region 查找条件

                            if (string.IsNullOrEmpty(condition))
                            {
                                //没指定查找条件,主键不是自动生成的,必定为手工输入
                                if (!field.MemberInfo.MemberTypeInfo.KeyMember.IsAutoGenerate)
                                {
                                    condition = field.MemberInfo.MemberTypeInfo.KeyMember.Name + " = ?";
                                }
                            }

                            if (string.IsNullOrEmpty(condition))
                            {
                                //还是没有,找设置了唯一规则的
                                var ufield =
                                    field.MemberInfo.MemberTypeInfo.Members.FirstOrDefault(
                                        x => x.FindAttribute <RuleUniqueValueAttribute>() != null
                                        );
                                if (ufield != null)
                                {
                                    condition = ufield.Name + " = ? ";
                                }
                            }

                            if (string.IsNullOrEmpty(condition))
                            {
                                //还是没有,用defaultproperty指定的
                                var ufield = field.MemberInfo.MemberTypeInfo.DefaultMember;
                                if (ufield != null)
                                {
                                    condition = ufield.Name + " = ? ";
                                }
                            }

                            #endregion

                            #region p

                            if (string.IsNullOrEmpty(condition))
                            {
                                result.AddErrorMessage(
                                    string.Format(
                                        "错误,没有为引用属性{0}设置查找条件,查询过程中出现了错误,请修改查询询条!",
                                        field.MemberInfo.Name), cell);
                            }
                            else
                            {
                                try
                                {
                                    var @operator = CriteriaOperator.Parse(condition, new object[] { conditionValue });


                                    IList list = null;
                                    if (findObjectProviderAttribute != null)
                                    {
                                        list = findObjectProviderAttribute.FindObject(os, field.MemberInfo.MemberType,
                                                                                      @operator, true);
                                    }
                                    else
                                    {
                                        list = os.GetObjects(field.MemberInfo.MemberType, @operator, true);
                                    }
                                    if (field.Caption == "办事处")
                                    {
                                        Debug.WriteLine(list.Count + "," + field.Caption, @operator.ToString());
                                    }
                                    if (list.Count != 1)
                                    {
                                        result.AddErrorMessage(
                                            string.Format(
                                                "错误,在查找“{0}”时,使用查找条件“{1}”,输入值是:“{3}”,查询过程中出现了错误,请修改查询询条!错误详情:{2}",
                                                field.MemberInfo.MemberType.FullName, condition,
                                                "找到了" + list.Count + "条记录", conditionValue), cell);
                                    }
                                    else
                                    {
                                        value = list[0];
                                    }
                                }
                                catch (Exception exception1)
                                {
                                    result.AddErrorMessage(
                                        string.Format("错误,在查找“{0}”时,使用查找条件“{1}”,查询过程中出现了错误,请修改查询询条!错误详情:{2}",
                                                      field.MemberInfo.MemberType.FullName, condition, exception1.Message),
                                        cell);
                                }
                            }

                            #endregion

                            #endregion
                        }
                        else if (memberType == typeof(DateTime))
                        {
                            if (!cell.Value.IsDateTime)
                            {
                                result.AddErrorMessage(string.Format("字段:{0},要求输入日期!", field.Name), cell);
                            }
                            else
                            {
                                value = cell.Value.DateTimeValue;
                            }
                        }
                        else if (numberTypes.Contains(memberType))
                        {
                            if (!cell.Value.IsNumeric)
                            {
                                result.AddErrorMessage(string.Format("字段:{0},要求输入数字!", field.Name), cell);
                            }
                            else
                            {
                                value = Convert.ChangeType(cell.Value.NumericValue, field.MemberInfo.MemberType);
                            }
                        }
                        else if (memberType == typeof(bool))
                        {
                            if (!cell.Value.IsBoolean)
                            {
                                result.AddErrorMessage(string.Format("字段:{0},要求输入布尔值!", field.Name), cell);
                            }
                            else
                            {
                                value = cell.Value.BooleanValue;
                            }
                        }
                        else if (memberType == typeof(string))
                        {
                            var v = cell.Value.ToObject();
                            if (v != null)
                            {
                                value = v.ToString();
                            }
                        }
                        else if (memberType.IsEnum)
                        {
                            #region 枚举
                            if (cell.Value.IsNumeric)
                            {
                                #region 填写的是数字
                                var vle = Convert.ToInt64(cell.Value.NumericValue);
                                var any =
                                    Enum.GetValues(field.MemberInfo.MemberType)
                                    .OfType <object>()
                                    .Any(
                                        x =>
                                {
                                    return(object.Equals(Convert.ToInt64(x), vle));
                                }
                                        );


                                if (any)
                                {
                                    value = Enum.ToObject(field.MemberInfo.MemberType, vle);
                                    // cell.Value.NumericValue;
                                }
                                else
                                {
                                    result.AddErrorMessage(string.Format("字段:{0},所填写的枚举值,没在定义中出现!", field.Name), cell);
                                }
                                #endregion
                            }
                            else
                            {
                                #region 填写的是字符
                                var names = field.MemberInfo.MemberType.GetEnumNames();
                                if (names.Contains(cell.Value.TextValue))
                                {
                                    value = Enum.Parse(field.MemberInfo.MemberType, cell.Value.TextValue);
                                }
                                else
                                {
                                    result.AddErrorMessage(string.Format("字段:{0},所填写的枚举值,没在定义中出现!", field.Name), cell);
                                }
                                #endregion
                            }
                            #endregion
                        }
                        else
                        {
                            value = cell.Value.ToObject();
                        }
                        obj.SetMemberValue(field.Name, value);
                    }
                }

                objs.Add(result);
                if ((r - 2) % updateStep == 0)
                {
                    Debug.WriteLine("Process:" + r);
                    if (DoApplicationEvent != null)
                    {
                        DoApplicationEvent();

                        this.option.Progress = ((r / (decimal)rowCount) + 0.01m);
                        //Debug.WriteLine(this.option.Progress);
                        //var progress = ws.Cells[r, 0];
                        //progress.SetValue("完成");
                    }
                }
            }
            ws.Workbook.EndUpdate();
            if (objs.All(x => !x.HasError))
            {
                try
                {
                    Validator.RuleSet.ValidateAll(os, objs.Select(x => x.Object), "Save");
                    return(true);
                }
                catch (ValidationException msgs)
                {
                    var rst = true;
                    ws.Workbook.BeginUpdate();
                    foreach (var item in msgs.Result.Results)
                    {
                        if (item.Rule.Properties.ResultType == ValidationResultType.Error && item.State == ValidationState.Invalid)
                        {
                            var r = objs.FirstOrDefault(x => x.Object == item.Target);
                            if (r != null)
                            {
                                r.AddErrorMessage(item.ErrorMessage, item.Rule.UsedProperties);
                            }
                            rst &= false;
                        }
                    }
                    ws.Workbook.EndUpdate();
                    return(rst);
                }
            }


            return(false);
        }
 public SerializationConfigurationObserver(IObjectSpace objectSpace)
     : base(objectSpace)
 {
 }
Exemplo n.º 58
0
        /// <summary>
        /// Uploads pending XafDelta messages to intermidiate net storages.
        /// </summary>
        /// <param name="xafDeltaModule">The xaf delta module.</param>
        /// <param name="objectSpace">The object space.</param>
        /// <param name="worker">The worker.</param>
        public void Upload(XafDeltaModule xafDeltaModule, IObjectSpace objectSpace, ActionWorker worker)
        {
            worker.ReportProgress(Localizer.UploadStarted);

            var transportList = (from m in XafDeltaModule.XafApp.Modules
                                 where m is IXafDeltaTransport && ((IXafDeltaTransport)m).UseForUpload
                                 select m).Cast <IXafDeltaTransport>().ToList().AsReadOnly();

            if (transportList.Count > 0)
            {
                var replicas = (from r in objectSpace.GetObjects <Package>() where r.IsOutput &&
                                r.GetEventDateTime(PackageEventType.Sent) == DateTime.MinValue
                                orderby r.PackageDateTime
                                select r).ToList();

                var tickets = (from t in objectSpace.GetObjects <Ticket>(CriteriaOperator.Parse("IsNull(ProcessingDateTime)"), true)
                               where t.Package != null && t.Package.IsInput
                               orderby t.TicketDateTime select t).ToList();

                var messages = replicas.Cast <IReplicationMessage>().Union(tickets.Cast <IReplicationMessage>()).ToList();

                var uploadData = new Dictionary <IXafDeltaTransport, List <IReplicationMessage> >();

                worker.ReportProgress(string.Format(Localizer.FoundForUpload, messages.Count()));
                foreach (var message in messages.TakeWhile(x => !worker.CancellationPending))
                {
                    var args = new SelectUploadTransportArgs(message, transportList[0]);
                    Owner.OnSelectUploadTransport(args);
                    if (args.Transport != null)
                    {
                        List <IReplicationMessage> list;
                        if (!uploadData.TryGetValue(args.Transport, out list))
                        {
                            list = new List <IReplicationMessage>();
                            uploadData.Add(args.Transport, list);
                        }
                        list.Add(message);
                    }
                }

                if (!worker.CancellationPending && uploadData.Keys.Count > 0)
                {
                    foreach (var transport in uploadData.Keys.TakeWhile(x => !worker.CancellationPending))
                    {
                        try
                        {
                            worker.ReportProgress(string.Format(Localizer.OpenTransport, transport));
                            transport.Open(TransportMode.Upload, worker);
                            var messageList = uploadData[transport];
                            foreach (var message in messageList)
                            {
                                var recipientAddress = message.RecipientAddress;
                                // worker.ReportProgress(string.Format(Localizer.UploadingFile, message));
                                transport.UploadFile(message.ToString(), message.GetData(), recipientAddress, worker);
                                if (message is Package)
                                {
                                    ((Package)message).CreateLogRecord(PackageEventType.Sent);
                                }
                                else
                                {
                                    ((Ticket)message).ProcessingDateTime = DateTime.Now;
                                }

                                objectSpace.CommitChanges();
                            }
                        }
                        catch (Exception exception)
                        {
                            objectSpace.Rollback();
                            worker.ReportError(Localizer.UploadError, exception.Message);
                        }
                        finally
                        {
                            worker.ReportProgress(string.Format(Localizer.CloseTransport, transport));
                            transport.Close();
                        }
                    }
                }
            }
            else
            {
                worker.ReportProgress(Color.BlueViolet, Localizer.UploadTransportNotFound);
            }
            worker.ReportProgress(Color.Blue, Localizer.UploadFinished);
        }
 public static void SetSequence <T>(this IObjectSpace objectSpace, Expression <Func <T, long> > sequenceMember,
                                    Type customSequence = null, long firstSequence = 0, Type sequenceStorageType = null)
     where T : class, IXPSimpleObject
 => objectSpace.SetSequence(sequenceMember, firstSequence, customSequence?.FullName, sequenceStorageType);
 public static void SetSequence <T>(this IObjectSpace objectSpace, Expression <Func <T, long> > sequenceMember,
                                    long firstSequence = 0, string customSequence = null, Type sequenceStorageType = null) where T : class, IXPSimpleObject
 => objectSpace.UnitOfWork().SetSequence(typeof(T), ((MemberExpression)sequenceMember.Body).Member.Name, customSequence, firstSequence, sequenceStorageType);