Exemplo n.º 1
0
        public static XPBaseObject GetXpObjectByKeyValue(XPObjectSpace oSpace, string value, Type type) {
            if (string.IsNullOrEmpty(value))
                return null;

            if (!type.IsSubclassOf(typeof(XPBaseObject)))
                return null;

            var defaultMember = GetDefaultMember(type);
            object result;
            value.TryToChange(defaultMember.MemberType, out result);
            var criteriaOperator = GetDefaultCriteria(defaultMember, result);
            var item = (XPBaseObject)oSpace.FindObject(type,criteriaOperator,true);
            if (item != null)
                return item;

            var nestedObjectSpace = oSpace.CreateNestedObjectSpace();
            item = (XPBaseObject)nestedObjectSpace.CreateObject(type);
            defaultMember.SetValue(item, value);

            item.Save();
            nestedObjectSpace.CommitChanges();

            return oSpace.GetObject(item);

        }
Exemplo n.º 2
0
        public IList <IStateMachine> GetStateMachines()
        {
            List <IStateMachine> result = new List <IStateMachine>();

            result.Add(new WorkflowCaseStatusStateMachine(XPObjectSpace.FindObjectSpaceByObject(this)));
            return(result);
        }
Exemplo n.º 3
0
        void OnCurrentObjectChanged(object sender, EventArgs eventArgs)
        {
            IObjectSpace objectSpace = XPObjectSpace.FindObjectSpaceByObject(_propertyEditor.CurrentObject);

            objectSpace.ObjectChanged += ObjectSpaceOnObjectChanged;
            UpdateEditor(((ISupportEditControl)_propertyEditor).GetControl());
        }
        public void ProccesExcellRows( XPObjectSpace objectSpace, DoWorkEventArgs e, Type type){
            var workerArgs = ((WorkerArgs) e.Argument);
            var records = workerArgs.Rows;
            int i = 0;
            var props = objectSpace.FindXPClassInfo(type).PersistentProperties.OfType<XPMemberInfo>().ToList();
            string keyPropertyName = objectSpace.GetKeyPropertyName(type);
            foreach (Row excelRow in records){
                ++i;
                if (i <= workerArgs.HeaderRows) continue;
                if (_bgWorker.CancellationPending){
                    e.Cancel = true;
                    break;
                }


                string message;

                ProcessSingleRow(objectSpace, e, type, keyPropertyName, excelRow, props, i, out message);

                if (i%50 == 0)
                    objectSpace.CommitChanges();

                _bgWorker.ReportProgress(1, message);
                Application.DoEvents();
            }
            objectSpace.CommitChanges();
        }
Exemplo n.º 5
0
        private static EvaluatorContextDescriptor GetEvaluatorContextDescriptor(Type objectType, object targetObject)
        {
            var objectSpace = XPObjectSpace.FindObjectSpaceByObject(targetObject);

            return(objectSpace != null?objectSpace.GetEvaluatorContextDescriptor(objectType)
                       : new EvaluatorContextDescriptorDefault(objectType));
        }
Exemplo n.º 6
0
Arquivo: Util.cs Projeto: ewin66/dev
        public static DateTime GetServerTime(XPObjectSpace xpObjectSpace)
        {
            CriteriaOperator funcNow    = new FunctionOperator(FunctionOperatorType.Now);
            DateTime         serverTime = (DateTime)xpObjectSpace.Session.Evaluate(typeof(XPObjectType), funcNow, null);

            return(serverTime);
        }
Exemplo n.º 7
0
        public static void CreateDbObjects(XPObjectSpace os)
        {
            var conn = os.Session.Connection as SqlConnection;

            if (conn == null)
            {
                return;
            }

            var resourcePaths = new List <string>();

            resourcePaths.Add(CashDiscipline.Common.Constants.CashDiscSqlCreatePurgeJobPath);

            resourcePaths.Add(CashDiscipline.Common.Constants.CashDiscSqlInstallScriptPath);
            resourcePaths.Add(CashDiscipline.Common.Constants.CashDiscSqlCashFlowFixProcsPath);
            resourcePaths.Add(CashDiscipline.Common.Constants.CashDiscSqlCashFlowRevalProcsPath);
            resourcePaths.Add(CashDiscipline.Common.Constants.CashDiscSqlDimDateProcsPath);
            resourcePaths.Add(CashDiscipline.Common.Constants.CashDiscSqlCreateReindexCashFlowJobPath);

            foreach (var resourcePath in resourcePaths)
            {
                var          stream = typeof(CashDiscipline.Module.AssemblyInfo).Assembly.GetManifestResourceStream(resourcePath);
                StreamReader reader = new StreamReader(stream);
                var          script = reader.ReadToEnd();
                DbUtils.ExecuteNonQueryCommand(os, script, false);
            }

            // select current database
            //DbUtils.ExecuteNonQueryCommand(os, "USE CashDiscipline", false);
        }
Exemplo n.º 8
0
 public ClassAtrributeGenerator(ClassGeneratorInfo classGeneratorInfo, string navigationPath)
 {
     _persistentClassInfo = classGeneratorInfo.PersistentClassInfo;
     _dbTable             = classGeneratorInfo.DbTable;
     _navigationPath      = navigationPath;
     _objectSpace         = XPObjectSpace.FindObjectSpaceByObject(_persistentClassInfo);
 }
Exemplo n.º 9
0
 public ApInvoiceBalanceMapper(XPObjectSpace objspace)
 {
     this.objSpace = objspace;
     this.mapper   = new Mapper <ApInvoiceBalanceMapping>(objspace, "ApInvoiceBalance", GetMapSetCommandTextList);
     mapper.MapCommandTextListByObjectSqlTemplate = MapCommandTextListByObjectSqlTemplate;
     mapper.MapCommandTextListSqlTemplate         = string.Empty;
 }
        public void ProccesExcellRows(IEnumerable<Row> records, XPObjectSpace objectSpace, DoWorkEventArgs e, Type type){
            int i = 0;
            List<XPMemberInfo> props = objectSpace.FindXPClassInfo(type).PersistentProperties
                .OfType<XPMemberInfo>().ToList();

            //get key property name of the object type being imported
            string keyPropertyName = objectSpace.GetKeyPropertyName(type);

            //for every row in excel sheet
            foreach (Row excelRow in records){
                ++i;
                if (i == 1) continue;
                if (_bgWorker.CancellationPending){
                    e.Cancel = true;
                    break;
                }


                string message;

                ProcessSingleRow(objectSpace, e, type, keyPropertyName, excelRow, props, i, out message);

                if (i%50 == 0)
                    objectSpace.CommitChanges();

                _bgWorker.ReportProgress(1, message);
                Application.DoEvents();
            }
            objectSpace.CommitChanges();
        }
Exemplo n.º 11
0
        public void setup_context()
        {
            var objectSpaceProvider =
                new XPObjectSpaceProvider(new MemoryDataStoreProvider());


            application = new TestApplication();
            var testModule = new ModuleBase();

            beforeSetup(testModule);
            application.Modules.Add(testModule);

            application.DatabaseUpdateMode = DatabaseUpdateMode.UpdateDatabaseAlways;

            application.Setup("TestApplication", objectSpaceProvider);
            objectSpace          = objectSpaceProvider.CreateObjectSpace() as XPObjectSpace;
            XpoDefault.DataLayer = objectSpace.Session.DataLayer;
            //Do test-specific tasks in the context method

            ImageLoader.Reset();
            if (!ImageLoader.IsInitialized)
            {
                ImageLoader.Init(new AssemblyResourceImageSource(GetType().Assembly.FullName, "Images1"));
            }

            context();
        }
Exemplo n.º 12
0
        public static void SupportCompositeKeyPersistentObjects(this IPersistentAssemblyInfo persistentAssemblyInfo)
        {
            var keys =
                persistentAssemblyInfo.PersistentClassInfos.SelectMany(info => info.OwnMembers)
                .OfType <IPersistentReferenceMemberInfo>()
                .Where(
                    memberInfo =>
                    memberInfo.ReferenceClassInfo.CodeTemplateInfo.CodeTemplate.TemplateType ==
                    TemplateType.Struct);
            var dictionary  = new Dictionary <IPersistentClassInfo, ITemplateInfo>();
            var objectSpace = XPObjectSpace.FindObjectSpaceByObject(persistentAssemblyInfo);

            foreach (var key in keys)
            {
                if (!dictionary.ContainsKey(key.Owner))
                {
                    var info = objectSpace.Create <ITemplateInfo>();
                    info.Name = SupportPersistentObjectsAsAPartOfACompositeKey;
                    key.Owner.TemplateInfos.Add(info);
                    dictionary.Add(key.Owner, info);
                }
                ITemplateInfo templateInfo = dictionary[key.Owner];
                templateInfo.TemplateCode = @"protected override void OnLoaded() {
                                                base.OnLoaded();
                                                " + GetCode(key) + @"
                                            }";
            }
        }
        public ForexSettleFifoAlgorithm(XPObjectSpace objSpace, ForexSettleFifoParam paramObj)
        {
            this.objSpace = objSpace;
            this.paramObj = paramObj;

            if (paramObj.FromDate <= SqlDateTime.MinValue.Value)
            {
                this.fromDate = SqlDateTime.MinValue.Value;
            }
            else
            {
                this.fromDate = paramObj.FromDate;
            }

            if (paramObj.ToDate <= SqlDateTime.MinValue.Value)
            {
                this.toDate = SqlDateTime.MaxValue.Value;
            }
            else
            {
                this.toDate = paramObj.ToDate;
            }

            this.currentSnapshot = CashFlowHelper.GetCurrentSnapshot(objSpace.Session);
        }
Exemplo n.º 14
0
 public ColumnMapper(DataTypeMapper dataTypeMapper, AttributeMapper attributeMapper)
 {
     _dataTypeMapper   = dataTypeMapper;
     _attributeMapper  = attributeMapper;
     _objectSpace      = _attributeMapper.ObjectSpace;
     _extraInfoBuilder = new ExtraInfoBuilder(_objectSpace, _attributeMapper);
 }
Exemplo n.º 15
0
        public virtual void MapValueToObjectProperty(XPObjectSpace objectSpace, XPMemberInfo prop, string value,
                                                     ref IXPSimpleObject newObj)
        {
            object convertedValue = null;

            //if simple property
            if (prop.ReferenceType == null)
            {
                bool isNullable = prop.MemberType.IsGenericType &&
                                  prop.MemberType.GetGenericTypeDefinition().IsNullableType();

                if (prop.MemberType == null)
                {
                    return;
                }


                convertedValue = isNullable ? MapStringToNullable(prop, value) : MapStringToValueType(prop, value);
            }

            //if referenced property
            else if (prop.ReferenceType != null)
            {
                convertedValue = MapStringToReferenceType(objectSpace, prop, value);
            }

            if (convertedValue != null)
            {
                convertedValue = AppllyDoubleValueRounding(convertedValue);
            }

            prop.SetValue(newObj, convertedValue);
        }
Exemplo n.º 16
0
        public static int ExecuteNonQueryCommand(XPObjectSpace os, string commandText, bool silent)
        {
            var conn = (SqlConnection)os.Session.Connection;

            if (conn == null)
            {
                return(-1);
            }

            Tracing.Tracer.LogText("ExecuteNonQueryCommand: '{0}', silent={1}", new object[]
            {
                commandText,
                silent
            });

            int result;

            try
            {
                Server server = new Server(new ServerConnection(conn));
                result = server.ConnectionContext.ExecuteNonQuery(commandText);
            }
            catch (Exception exception)
            {
                Tracing.Tracer.LogError(exception);
                if (!silent)
                {
                    throw;
                }
                result = -1;
            }
            return(result);
        }
Exemplo n.º 17
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);
        }
Exemplo n.º 18
0
        public IList <IStateMachine> GetStateMachines()
        {
            List <IStateMachine> result = new List <IStateMachine>();

            result.Add(new ClaimTrxsStateMachine(XPObjectSpace.FindObjectSpaceByObject(this)));
            return(result);
        }
Exemplo n.º 19
0
        public static void ReleaseSequence(ISupportSequenceObject supportSequenceObject)
        {
            var typeName    = supportSequenceObject.Prefix + supportSequenceObject.GetType().FullName;
            var objectSpace = (XPObjectSpace)XPObjectSpace.FindObjectSpaceByObject(supportSequenceObject);

            ReleaseSequence(objectSpace.Session, typeName, supportSequenceObject.Sequence);
        }
Exemplo n.º 20
0
        public override void Update()
        {
            if (Session.FindObject <PersistentAssemblyInfo>(info => info.Name == DynamicAssemblyCalculatedField.AttributeRegistrator.MasterDetailDynamicAssembly) == null)
            {
                IPersistentAssemblyInfo persistentAssemblyInfo = new DynamicAssemblyBuilder(Session).Build(DynamicAssemblyCalculatedField.AttributeRegistrator.DMDCustomer, DMDOrder,
                                                                                                           DMDOrderLine, DynamicAssemblyCalculatedField.AttributeRegistrator.MasterDetailDynamicAssembly);
                IPersistentClassInfo persistentClassInfo =
                    persistentAssemblyInfo.PersistentClassInfos.Single(info => info.Name == DynamicAssemblyCalculatedField.AttributeRegistrator.DMDCustomer);
                var persistentCoreTypeMemberInfo = new PersistentCoreTypeMemberInfo(persistentClassInfo.Session);
                persistentCoreTypeMemberInfo.TypeAttributes.Add(new PersistentVisibleInDetailViewAttribute(persistentCoreTypeMemberInfo.Session));
                persistentCoreTypeMemberInfo.TypeAttributes.Add(new PersistentVisibleInListViewAttribute(persistentCoreTypeMemberInfo.Session));
                persistentCoreTypeMemberInfo.TypeAttributes.Add(new PersistentVisibleInLookupListViewAttribute(persistentCoreTypeMemberInfo.Session));
                persistentCoreTypeMemberInfo.TypeAttributes.Add(new PersistentPersistentAliasAttribute(persistentCoreTypeMemberInfo.Session)
                {
                    AliasExpression = "DMDOrders.Min(OrderDate)"
                });
                persistentCoreTypeMemberInfo.Name     = "FirstOrderDate";
                persistentCoreTypeMemberInfo.DataType = DBColumnType.DateTime;
                var codeTemplateInfo = new CodeTemplateInfo(persistentCoreTypeMemberInfo.Session);
                var codeTemplate     = new CodeTemplate(codeTemplateInfo.Session)
                {
                    TemplateType = TemplateType.XPCalculatedPropertyMember
                };
                codeTemplate.SetDefaults();
                codeTemplate.Name             = "CalculatedProperty";
                codeTemplateInfo.TemplateInfo = codeTemplate;

                persistentCoreTypeMemberInfo.CodeTemplateInfo = codeTemplateInfo;
                persistentClassInfo.OwnMembers.Add(persistentCoreTypeMemberInfo);
                XPObjectSpace.FindObjectSpaceByObject(persistentClassInfo).CommitChanges();
            }
        }
Exemplo n.º 21
0
        public static bool NeedReload(this XPObjectSpace objectSpace, object currentObject)
        {
            XPMemberInfo optimisticLockFieldInfo;
            XPClassInfo  classInfo = GetClassInfo(objectSpace, currentObject, out optimisticLockFieldInfo);
            Boolean      isObjectChangedByAnotherUser = false;

            if (!objectSpace.IsDisposedObject(currentObject) && !objectSpace.IsNewObject(currentObject) && (optimisticLockFieldInfo != null))
            {
                Object keyPropertyValue = objectSpace.GetKeyValue(currentObject);
                Object lockFieldValue   = optimisticLockFieldInfo.GetValue(currentObject);

                if (lockFieldValue != null)
                {
                    if (objectSpace.Session.FindObject(currentObject.GetType(), new GroupOperator(
                                                           new BinaryOperator(objectSpace.GetKeyPropertyName(currentObject.GetType()), keyPropertyValue),
                                                           new BinaryOperator(classInfo.OptimisticLockFieldName, lockFieldValue)), true) == null)
                    {
                        isObjectChangedByAnotherUser = true;
                    }
                }
                else
                {
                    if (objectSpace.Session.FindObject(currentObject.GetType(), new GroupOperator(
                                                           new BinaryOperator(objectSpace.GetKeyPropertyName(currentObject.GetType()), keyPropertyValue),
                                                           new NullOperator(classInfo.OptimisticLockFieldName)), true) == null)
                    {
                        isObjectChangedByAnotherUser = true;
                    }
                }
            }
            return(isObjectChangedByAnotherUser);
        }
Exemplo n.º 22
0
        void CreateMappedAssemblyInfo(XPObjectSpace objectSpace, IPersistentAssemblyInfo persistentAssemblyInfo, LogonObject logonObject, string[] selectedTables)
        {
            var assemblyInfo = objectSpace.GetObject(persistentAssemblyInfo);

            new AssemblyGenerator(logonObject, assemblyInfo, selectedTables).Create();
            objectSpace.CommitChanges();
        }
Exemplo n.º 23
0
 static void CreateXpandCustomMemberInfo(IModelMemberEx modelMemberEx, XPObjectSpace objectSpace) {
     try {
         Type classType = modelMemberEx.ModelClass.TypeInfo.Type;
         XPClassInfo xpClassInfo = XpandModuleBase.Dictiorary.GetClassInfo(classType);
         lock (xpClassInfo) {
             var customMemberInfo = xpClassInfo.FindMember(modelMemberEx.Name) as XPCustomMemberInfo;
             if (customMemberInfo == null) {
                 customMemberInfo= CreateMemberInfo(modelMemberEx, xpClassInfo);
                 ((IModelTypesInfoProvider) modelMemberEx.Application).TypesInfo.RefreshInfo(classType);
                 AddAttributes(modelMemberEx, customMemberInfo);
             }
             var xpandCustomMemberInfo = customMemberInfo as XpandCustomMemberInfo;
             if (xpandCustomMemberInfo != null) {
                 CreateColumn(modelMemberEx as IModelMemberPersistent, objectSpace, xpandCustomMemberInfo);
                 CreateForeignKey(modelMemberEx as IModelMemberOneToManyCollection, objectSpace, xpandCustomMemberInfo);
                 UpdateMember(modelMemberEx, customMemberInfo);
             }
         }
     }
     catch (Exception exception) {
         throw new Exception(
             ExceptionLocalizerTemplate<SystemExceptionResourceLocalizer, ExceptionId>.GetExceptionMessage(
                 ExceptionId.ErrorOccursWhileAddingTheCustomProperty,
                 modelMemberEx.MemberInfo.MemberType,
                 ((IModelClass) modelMemberEx.Parent).Name,
                 modelMemberEx.Name,
                 exception.Message));
     }
 }
Exemplo n.º 24
0
 public TableMapper(XPObjectSpace objectSpace, Database database, AttributeMapper attributeMapper)
 {
     _objectSpace      = objectSpace;
     _database         = database;
     _attributeMapper  = attributeMapper;
     _extraInfoBuilder = new ExtraInfoBuilder(_objectSpace, _attributeMapper);
 }
Exemplo n.º 25
0
 static void CreateXpandCustomMemberInfo(IModelMemberEx modelMemberEx, XPObjectSpace objectSpace)
 {
     try {
         Type        classType   = modelMemberEx.ModelClass.TypeInfo.Type;
         XPClassInfo xpClassInfo = XpandModuleBase.Dictiorary.GetClassInfo(classType);
         lock (xpClassInfo) {
             var customMemberInfo = xpClassInfo.FindMember(modelMemberEx.Name) as XPCustomMemberInfo;
             if (customMemberInfo == null)
             {
                 customMemberInfo = CreateMemberInfo(modelMemberEx, xpClassInfo);
                 ((IModelTypesInfoProvider)modelMemberEx.Application).TypesInfo.RefreshInfo(classType);
                 AddAttributes(modelMemberEx, customMemberInfo);
             }
             var xpandCustomMemberInfo = customMemberInfo as XpandCustomMemberInfo;
             if (xpandCustomMemberInfo != null)
             {
                 CreateColumn(modelMemberEx as IModelMemberPersistent, objectSpace, xpandCustomMemberInfo);
                 CreateForeignKey(modelMemberEx as IModelMemberOneToManyCollection, objectSpace, xpandCustomMemberInfo);
                 UpdateMember(modelMemberEx, customMemberInfo);
             }
         }
     }
     catch (Exception exception) {
         throw new Exception(
                   ExceptionLocalizerTemplate <SystemExceptionResourceLocalizer, ExceptionId> .GetExceptionMessage(
                       ExceptionId.ErrorOccursWhileAddingTheCustomProperty,
                       modelMemberEx.MemberInfo.MemberType,
                       ((IModelClass)modelMemberEx.Parent).Name,
                       modelMemberEx.Name,
                       exception.Message));
     }
 }
Exemplo n.º 26
0
        public void ProccesExcellRows(XPObjectSpace objectSpace, Row[] rows, Type type, int?headerRows, CancellationToken token, Utils.Threading.IProgress <string> progress)
        {
            var    records         = rows;
            int    i               = 0;
            var    props           = objectSpace.FindXPClassInfo(type).PersistentProperties.OfType <XPMemberInfo>().ToList();
            string keyPropertyName = objectSpace.GetKeyPropertyName(type);

            foreach (Row excelRow in records)
            {
                ++i;
                if (i <= headerRows)
                {
                    continue;
                }
                token.ThrowIfCancellationRequested();
                string message;
                ProcessSingleRow(objectSpace, type, keyPropertyName, excelRow, props, i, out message, progress.Report);
                if (i % TransactionSize == 0)
                {
                    objectSpace.CommitChanges();
                    progress.Report(string.Format(Resources.SuccessProcessingRecord, i - 1));
                }
            }
            progress.Report(string.Format(Resources.SuccessProcessingRecord, i - 1));
            objectSpace.CommitChanges();
        }
Exemplo n.º 27
0
        public static void SetupDetailViewController(XafApplication application, XPObjectSpace objSpace, ViewController controller, IXPObject currentObject)
        {
            controller.Application = application;
            var view = application.CreateDetailView(objSpace, currentObject);

            controller.SetView(view);
        }
Exemplo n.º 28
0
        private void ProcessSingleRow(XPObjectSpace objectSpace, Type type, string keyPropertyName, Row excelRow, List <XPMemberInfo> props, int i, out string message, Action <string> notify)
        {
            IXPSimpleObject newObj = GetExistingOrCreateNewObject(objectSpace, keyPropertyName, excelRow, type);

            message = null;
            if (newObj == null)
            {
                message = string.Format(Resources.newObjectError, i);
                return;
            }
            foreach (Mapping mapping in ImportMap.Mappings)
            {
                XPMemberInfo prop = props.First(p => p.Name == mapping.MapedTo);

                try{
                    Cell val = excelRow[mapping.Column];

                    if (val != null)
                    {
                        _propertyValueMapper(objectSpace, prop, val.Value, ref newObj);
                    }
                }

                catch (Exception ee) {
                    message = string.Format(Resources.ErrorProcessingRecord,
                                            i - 1, ee);
                    notify(message);
                }
            }

            objectSpace.Session.Save(newObj);
        }
Exemplo n.º 29
0
        static XPClassInfo GetClassInfo(this XPObjectSpace objectSpace, object currentObject, out XPMemberInfo optimisticLockFieldInfo)
        {
            XPClassInfo classInfo = FindObjectXPClassInfo(currentObject, objectSpace.Session);

            optimisticLockFieldInfo = classInfo.OptimisticLockFieldInDataLayer;
            return(classInfo);
        }
Exemplo n.º 30
0
        public TController Create(ViewType viewType)
        {
            XafTypesInfo.Instance.RegisterEntity(typeof(TObject));

            _controller = new TController();
            _controller.Active[STR_ControllerFactory] = false;

            var unitOfWork    = new UnitOfWork(Session.DefaultSession.DataLayer);
            var XPObjectSpace = new XPObjectSpace(unitOfWork, XafTypesInfo.Instance);

            var xafApplication = Isolate.Fake.Instance <XafApplication>();

            Isolate.WhenCalled(() => _controller.Application).WillReturn(xafApplication);
            Isolate.WhenCalled(() => xafApplication.CreateObjectSpace()).WillReturn(XPObjectSpace);

            var  currentObject = (TObject)XPObjectSpace.CreateObject(typeof(TObject));
            View view          = viewType == ViewType.DetailView ? (View)createDetailView(XPObjectSpace, currentObject) : createListView(XPObjectSpace);

            view.CurrentObject = currentObject;
            _controller.SetView(view);

            var frame = new Frame(_controller.Application, TemplateContext.View);

            frame.SetView(_controller.View);
            Isolate.WhenCalled(() => _controller.Frame).WillReturn(frame);
            return(_controller);
        }
Exemplo n.º 31
0
        public static XPBaseObject GetXpObjectByKeyValue(XPObjectSpace oSpace, string value, Type type)
        {
            if (string.IsNullOrEmpty(value))
            {
                return(null);
            }

            if (!type.IsSubclassOf(typeof(XPBaseObject)))
            {
                return(null);
            }

            var    defaultMember = GetDefaultMember(type);
            object result;

            value.TryToChange(defaultMember.MemberType, out result);
            var criteriaOperator = GetDefaultCriteria(defaultMember, result);
            var item             = (XPBaseObject)oSpace.FindObject(type, criteriaOperator, true);

            if (item != null)
            {
                return(item);
            }

            var nestedObjectSpace = oSpace.CreateNestedObjectSpace();

            item = (XPBaseObject)nestedObjectSpace.CreateObject(type);
            defaultMember.SetValue(item, value);

            item.Save();
            nestedObjectSpace.CommitChanges();

            return(oSpace.GetObject(item));
        }
Exemplo n.º 32
0
        public IList <IStateMachine> GetStateMachines()
        {
            List <IStateMachine> result = new List <IStateMachine>();

            result.Add(new TSDataKeluhan(XPObjectSpace.FindObjectSpaceByObject(this)));
            return(result);
        }
Exemplo n.º 33
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));
        }
Exemplo n.º 34
0
 public static void ValidateAndCommitChanges(this Session session) {
     var unitOfWork = ((UnitOfWork)session);
     var objectSpace = new XPObjectSpace(XafTypesInfo.Instance, XpoTypesInfoHelper.GetXpoTypeInfoSource(), () => unitOfWork);
     var result = Validator.RuleSet.ValidateAllTargets(objectSpace, session.GetObjectsToSave(), ContextIdentifier.Save);
     if (result.ValidationOutcome == ValidationOutcome.Error)
         throw new Exception(result.GetFormattedErrorMessage());
     unitOfWork.CommitChanges();
 }
Exemplo n.º 35
0
        public static CriteriaOperator GetTotalCriteria(this ListView xpandListView)
        {
            xpandListView.SaveModel();
            List <CriteriaOperator> operators = xpandListView.CollectionSource.Criteria.GetValues();

            operators.Add(CriteriaOperator.Parse(xpandListView.Model.Filter));
            return(XPObjectSpace.CombineCriteria(operators.ToArray()));
        }
Exemplo n.º 36
0
 public IPersistentAssemblyInfo Build(string customer, string order, string orderLine, string masterDetailDynamicAssembly) {
     var objectSpace = new XPObjectSpace(XafTypesInfo.Instance, XpandModuleBase.XpoTypeInfoSource, () => new UnitOfWork(_session.DataLayer));
     var persistentAssemblyBuilder = PersistentAssemblyBuilder.BuildAssembly(objectSpace, masterDetailDynamicAssembly);
     IClassInfoHandler classInfoHandler = persistentAssemblyBuilder.CreateClasses(GetClassNames(customer, order, orderLine));
     classInfoHandler.CreateTemplateInfos(persistentClassInfo => GetTemplateInfos(persistentClassInfo, customer, order));
     classInfoHandler.SetInheritance(info => GetInheritance(info));
     classInfoHandler.CreateReferenceMembers(classInfo => GetReferenceMembers(classInfo, customer, order, orderLine), true);
     objectSpace.CommitChanges();
     return persistentAssemblyBuilder.PersistentAssemblyInfo;
 }
Exemplo n.º 37
0
        public override void SaveDifference(ModelApplicationBase model) {
            if (model != null) {
                _objectSpace = _application.CreateObjectSpace(typeof(ModelDifferenceObject)) as XPObjectSpace;
                ModelDifferenceObject modelDifferenceObject =
                    GetActiveDifferenceObject(model.Id) ??
                    GetNewDifferenceObject(_objectSpace)
                    .InitializeMembers(model.Id == "Application" ? Application.Title : model.Id, Application.Title, Application.GetType().FullName);

                OnDifferenceObjectSaving(modelDifferenceObject, model);
            }
        }
Exemplo n.º 38
0
        public static void ShowAllReport(string reportId, XPObjectSpace xpObjectSpace)
        {
            CustomReportData reportData = xpObjectSpace.Session.FindObject<CustomReportData>(new BinaryOperator("ReportId", reportId));
            if (reportData == null)
            {
                XtraMessageBox.Show(string.Format("找不到此报表号码{0}, 请通知系统管理员!!", reportId));
                return;
            }

            XafReport xafReport = (XafReport)reportData.LoadReport(xpObjectSpace);
            xafReport.ShowPreview();
        }
Exemplo n.º 39
0
        public ExcelImportWizard(XPObjectSpace objectSpace, ITypeInfo typeInfo, CollectionSourceBase collectionSourceBase, XafApplication application) {
            _application = application;
            //set local variable values
            if (objectSpace == null)
                throw new ArgumentNullException("objectSpace", Resources.ExcelImportWizard_ExcelImportWizard_ObjectSpace_cannot_be_NULL);

            ObjectSpace = objectSpace;
            CurrentCollectionSource = collectionSourceBase;

            Type = typeInfo.Type;

            InitializeComponent();

            ImportMapLookUp.Properties.DataSource = ImportMapsCollection.ToList();

            //disable next, until file and other info is selected
            welcomeWizardPage1.AllowNext = false;
            wizardPage1.AllowNext = false;



            gridLookUpEdit1.Properties.View.OptionsBehavior.AutoPopulateColumns = true;
            gridLookUpEdit1.Properties.DataSource = MappableColumns;

            //var col = gridLookUpEdit2View.Columns.ColumnByFieldName("Mapped");
            //if (col != null) {
            //    col.Visible = false;
            //    col.FilterInfo =
            //        new ColumnFilterInfo(new BinaryOperator("Mapped", false));

            //}

            var mappablePropertyClassInfo
                = objectSpace.Session.GetClassInfo(typeof(MappableProperty));


            foreach (GridColumn column in gridLookUpEdit2View.Columns) {

                column.Caption = mappablePropertyClassInfo
                                    .GetMember(column.FieldName).DisplayName;
                if (column.FieldName == "Mapped") {
                    column.Visible = false;
                }
            }

            //col = gridLookUpEdit2View.Columns.ColumnByFieldName("Oid");
            //if (col != null)
            //    col.Visible = false;

        }
Exemplo n.º 40
0
        public static XafReport GetReport(string reportId)
        {
            using (UnitOfWork uow = new UnitOfWork())
            {
                XPObjectSpace objectSpace = new XPObjectSpace(uow, XafTypesInfo.Instance);
                CustomReportData reportData = uow.FindObject<CustomReportData>(new BinaryOperator("ReportId", reportId));

                if (reportData == null)
                    return null;

                XafReport xafReport = (XafReport)reportData.LoadReport(objectSpace);
                return xafReport;
            }
        }
Exemplo n.º 41
0
        public static void ShowSingleReport(string reportId, Guid Oid, XPObjectSpace xpObjectSpace)
        {
            // http://www.devexpress.com/Support/Center/Question/Details/Q433737
            CustomReportData reportData = xpObjectSpace.Session.FindObject<CustomReportData>(new BinaryOperator("ReportId", reportId));

            if (reportData == null)
            {
                XtraMessageBox.Show(string.Format("找不到此报表号码{0}, 请通知系统管理员!!", reportId));
                return;
            }

            XafReport xafReport = (XafReport)reportData.LoadReport(xpObjectSpace);
            xafReport.FilterString = string.Format("Oid = '{0}'", Oid);
            xafReport.ShowPreview();
        }
 private IXPSimpleObject GetExistingOrCreateNewObject(XPObjectSpace objectSpace, string keyPropertyName,
     Row excelRow, Type type){
     Mapping idMapping = ImportMap.Mappings.SingleOrDefault(p => p.MapedTo == keyPropertyName);
     IXPSimpleObject newObj = null;
     if (idMapping != null && ImportUtils.GetQString(excelRow[idMapping.Column].Value) != string.Empty){
         try{
             //find existing object
             Cell val = excelRow[idMapping.Column];
             var gwid = new Guid(ImportUtils.GetQString(val.Value));
             newObj =
                 objectSpace.FindObject(type, new BinaryOperator(keyPropertyName, gwid), true) as IXPSimpleObject;
         }
         catch{
         }
     }
     return newObj ?? (objectSpace.CreateObject(type) as IXPSimpleObject);
 }
Exemplo n.º 43
0
        public static XPBaseObject GetXpObjectByKeyValue(XPObjectSpace oSpace, string value, Type type)
        {
            if (string.IsNullOrEmpty(value))
                return null;

            if (!type.IsSubclassOf(typeof(XPBaseObject)))
                return null;

            var keyPropertyName = oSpace.Session.GetClassInfo(type).
                        PersistentProperties.
                        OfType<XPMemberInfo>().
                        Where(p => p.HasAttribute(typeof(KeyPropertyAttribute))).
                        Select(p => p.Name).
                        FirstOrDefault() ??

                    oSpace.Session.GetClassInfo(type).
                        PersistentProperties.
                        OfType<XPMemberInfo>().
                        Where(p => p.Name == "Name" || p.Name == "Code")
                        .Select(p => p.Name)
                        .FirstOrDefault() ??
                    "Oid";

            var item = (XPBaseObject)oSpace.FindObject(
                                type,
                                new BinaryOperator(keyPropertyName, value),
                                true);
            if (item != null)
                return item;

            var nestedObjectSpace = oSpace.CreateNestedObjectSpace();
            item = (XPBaseObject)nestedObjectSpace.CreateObject(type);
            var firstOrDefault = item.ClassInfo
                                    .PersistentProperties
                                    .OfType<XPMemberInfo>()
                                    .FirstOrDefault(p => p.Name == keyPropertyName);
            if (firstOrDefault != null)
                firstOrDefault.SetValue(item, value);

            item.Save();
            nestedObjectSpace.CommitChanges();

            return oSpace.GetObject(item);

        }
Exemplo n.º 44
0
        public ExcelImportWizard(XPObjectSpace objectSpace, ITypeInfo typeInfo, CollectionSourceBase collectionSourceBase, XafApplication application,
            ExcelImportWizardStringToPropertyMap propertyValueMapper = null) {
            _application = application;
            _propertyValueMapper = propertyValueMapper ?? new StringValueMapper().MapValueToObjectProperty;
            //set local variable values
            if (objectSpace == null)
                throw new ArgumentNullException("objectSpace", Resources.ExcelImportWizard_ExcelImportWizard_ObjectSpace_cannot_be_NULL);

            ObjectSpace = objectSpace;
            CurrentCollectionSource = collectionSourceBase;

            Type = typeInfo.Type;

            InitializeComponent();

            ImportMapLookUp.Properties.DataSource = ImportMapsCollection.ToList();

            //disable next, until file and other info is selected
            welcomeWizardPage1.AllowNext = false;
            wizardPage1.AllowNext = false;



            gridLookUpEdit1.Properties.View.OptionsBehavior.AutoPopulateColumns = true;
            gridLookUpEdit1.Properties.DataSource = MappableColumns;


            var mappablePropertyClassInfo
                = objectSpace.Session.GetClassInfo(typeof(MappableProperty));


            foreach (GridColumn column in gridLookUpEdit2View.Columns) {

                column.Caption = mappablePropertyClassInfo
                                    .GetMember(column.FieldName).DisplayName;
                if (column.FieldName == @"Mapped")
                    column.Visible = false;
            }
        }
        private void ProcessSingleRow(XPObjectSpace objectSpace, DoWorkEventArgs e, Type type, string keyPropertyName,
            Row excelRow, List<XPMemberInfo> props, int i, out string message){
            IXPSimpleObject newObj = GetExistingOrCreateNewObject(objectSpace, keyPropertyName, excelRow, type);

            if (newObj == null){
                message = string.Format(Resources.newObjectError, i);
                return;
            }
            foreach (Mapping mapping in ImportMap.Mappings){
                if (_bgWorker.CancellationPending){
                    e.Cancel = true;
                    break;
                }
                Application.DoEvents();

                XPMemberInfo prop = props.Single(p => p.Name == mapping.MapedTo);

                try{
                    Cell val = excelRow[mapping.Column];

                    if (val != null)
                        _propertyValueMapper(objectSpace, prop, val.Value, ref newObj);
                }

                catch (Exception ee){
                    message = string.Format(Resources.ErrorProcessingRecord,
                        i - 1, ee);
                    _bgWorker.ReportProgress(0, message);
                }

                if (CurrentCollectionSource != null)
                    AddNewObjectToCollectionSource(CurrentCollectionSource, newObj, ObjectSpace);
            }

            objectSpace.Session.Save(newObj);
            message = string.Format(Resources.SuccessProcessingRecord, i - 1);
        }
Exemplo n.º 46
0
        public virtual void MapValueToObjectProperty(XPObjectSpace objectSpace, XPMemberInfo prop, string value,
            ref IXPSimpleObject newObj){
            object convertedValue = null;

            //if simple property
            if (prop.ReferenceType == null){
                bool isNullable = prop.MemberType.IsGenericType &&
                                  prop.MemberType.GetGenericTypeDefinition().IsNullableType();

                if (prop.MemberType == null) return;


                convertedValue = isNullable ? MapStringToNullable(prop, value) : MapStringToValueType(prop, value);
            }

                //if referenced property
            else if (prop.ReferenceType != null)
                convertedValue = MapStringToReferenceType(objectSpace, prop, value);

            if (convertedValue != null)
                convertedValue = AppllyDoubleValueRounding(convertedValue);

            prop.SetValue(newObj, convertedValue);
        }
Exemplo n.º 47
0
        private void AddNewObjectToCollectionSource(CollectionSourceBase currentCollectionSource, object newObject, XPObjectSpace objectSpace) {
            var newObjectTypeInfo = XafTypesInfo.Instance.FindTypeInfo(newObject.GetType());
            if ((currentCollectionSource == null) ||
                !currentCollectionSource.ObjectTypeInfo.IsAssignableFrom(newObjectTypeInfo)) return;

            if (objectSpace == currentCollectionSource.ObjectSpace)
                currentCollectionSource.Add(newObject);
            else {
                var propertyCollectionSource = (currentCollectionSource as PropertyCollectionSource);
                if ((propertyCollectionSource != null) && (propertyCollectionSource.MasterObject != null)) {
                    Object collectionOwner;
                    IMemberInfo memberInfo = null;
                    if (propertyCollectionSource.MemberInfo.GetPath().Count > 1) {
                        collectionOwner = ImportUtils.GetCollectionOwner(propertyCollectionSource.MasterObject,
                            propertyCollectionSource.MemberInfo);
                        if (collectionOwner != null)
                            memberInfo =
                                XafTypesInfo.Instance.FindTypeInfo(collectionOwner.GetType())
                                    .FindMember(propertyCollectionSource.MemberInfo.LastMember.Name);
                    }
                    else {
                        collectionOwner = propertyCollectionSource.MasterObject;
                        memberInfo = propertyCollectionSource.MemberInfo;
                    }
                    if ((collectionOwner != null) &&
                        XafTypesInfo.Instance.FindTypeInfo(collectionOwner.GetType()).IsPersistent) {
                        var collectionSource = _application.CreatePropertyCollectionSource(objectSpace, null,
                            objectSpace.GetObject(collectionOwner), memberInfo, "", CollectionSourceMode.Normal);
                        collectionSource.Add(newObject);
                    }
                }
            }
        }
Exemplo n.º 48
0
 //Extra constructor to enable Value mapping customisation
 public ExcelImportWizard(XPObjectSpace objectSpace, ITypeInfo typeInfo,
     CollectionSourceBase collectionSourceBase, XafApplication application,
     StringValueMapper valueMapper)
     : this(objectSpace, typeInfo, collectionSourceBase, application, valueMapper.MapValueToObjectProperty) {
 }
Exemplo n.º 49
0
        public static void PrintShipmentOrder(IBindingList shipmentList, XPObjectSpace os)
        {
            //XafReport report = ReportHelper.GetReport("Shipment");
            //report.DataSource = shipmentList;
            //report.ShowPreview();

            ReportHelper.ShowSingleReport("Shipment", shipmentList, os);
        }
Exemplo n.º 50
0
        public static void PrintShipmentOrder(DateTime sDate, XPObjectSpace os)
        {
            using (UnitOfWork uow = (UnitOfWork)os.Session)
            {
                Dictionary<Customer, IBindingList> dictShipment = new Dictionary<Customer, IBindingList>();
                BindingList<Shipment> bShipment;
                XPCollection<Shipment> Shipments = new XPCollection<Shipment>(uow);
                Shipments.Criteria = DevExpress.Data.Filtering.CriteriaOperator.Parse("getdate(ShippedDate) = ?", new DateTime(sDate.Year, sDate.Month, sDate.Day));

                foreach (Shipment shipment in Shipments)
                {
                    if (dictShipment.ContainsKey(shipment.SalesOrderLine.SalesOrder.Customer))
                    {
                        bShipment = (BindingList<Shipment>)dictShipment[shipment.SalesOrderLine.SalesOrder.Customer];
                        bShipment.Add(shipment);
                    }
                    else
                    {
                        bShipment = new BindingList<Shipment>();
                        bShipment.Add(shipment);
                        dictShipment.Add(shipment.SalesOrderLine.SalesOrder.Customer, bShipment);
                    }
                }

                foreach (KeyValuePair<Customer, IBindingList> kvp in dictShipment)
                {
                    Shipment.PrintShipmentOrder(kvp.Value, os );
                }
            }
        }
Exemplo n.º 51
0
 private static void AddNewObjectToCollectionSource(CollectionSourceBase currentCollectionSource, object newObject, XPObjectSpace objectSpace) {
     var newObjectTypeInfo = XafTypesInfo.Instance.FindTypeInfo(newObject.GetType());
     if ((currentCollectionSource != null) && currentCollectionSource.ObjectTypeInfo.IsAssignableFrom(newObjectTypeInfo)) {
         if (objectSpace == currentCollectionSource.ObjectSpace) {
             currentCollectionSource.Add(newObject);
         } else {
             var propertyCollectionSource = (currentCollectionSource as PropertyCollectionSource);
             if ((propertyCollectionSource != null) && (propertyCollectionSource.MasterObject != null)) {
                 Object collectionOwner;
                 if (propertyCollectionSource.MemberInfo.GetPath().Count > 1) {
                     collectionOwner = GetCollectionOwner(propertyCollectionSource.MasterObject, propertyCollectionSource.MemberInfo);
                     if (collectionOwner != null) {
                         XafTypesInfo.Instance.FindTypeInfo(collectionOwner.GetType()).FindMember(propertyCollectionSource.MemberInfo.LastMember.Name);
                     }
                 } else {
                     collectionOwner = propertyCollectionSource.MasterObject;
                 }
                 if ((collectionOwner != null)
                         && XafTypesInfo.Instance.FindTypeInfo(collectionOwner.GetType()).IsPersistent) {
                     //TODO: Fix this
                     throw new NotImplementedException("Feature not completely implemented. Import win Create Collection Source");
                     //var collectionSource = Application.CreatePropertyCollectionSource(
                     //    objectSpace, null, objectSpace.GetObject(collectionOwner), memberInfo, "", CollectionSourceMode.Normal);
                     //collectionSource.Add(newObject);
                 }
             }
         }
     }
 }
Exemplo n.º 52
0
 private IDataStoreSchemaExplorer GetDataStoreSchemaExplorer(XPObjectSpace xpObjectSpace){
     var connectionProvider = ((BaseDataLayer)xpObjectSpace.Session.DataLayer).ConnectionProvider;
     var multiDataStoreProxy = connectionProvider as MultiDataStoreProxy;
     if (multiDataStoreProxy != null)
         return (IDataStoreSchemaExplorer) multiDataStoreProxy.DataStore;
     return connectionProvider as IDataStoreSchemaExplorer;
 }
Exemplo n.º 53
0
        public static void ShowSingleReport(string reportId, System.Collections.IList viewSelectedObjects, XPObjectSpace xpObjectSpace)
        {
            CustomReportData reportData = xpObjectSpace.Session.FindObject<CustomReportData>(new BinaryOperator("ReportId", reportId));

            if (reportData == null)
            {
                throw new Exception(string.Format("找不到此报表号码{0}, 请通知系统管理员!!", reportId));
                //XtraMessageBox.Show(string.Format("找不到此报表号码{0}, 请通知系统管理员!!", reportId));
                //return;
            }

            XafReport xafReport = (XafReport)reportData.LoadReport(xpObjectSpace);

            StringBuilder sbLog = new StringBuilder();

            foreach (CustomBaseObject baseObject in viewSelectedObjects)
            {
                sbLog.Append(string.Format("Oid = '{0}' OR ", baseObject.Oid));
            }

            xafReport.FilterString = sbLog.ToString().Substring(0, sbLog.Length - 3);
            xafReport.ShowPreview();
        }
Exemplo n.º 54
0
 /// <summary>
 ///     Specifies the rules and actions how to convert string to a referenced type
 /// </summary>
 /// <param name="objectSpace">OS used to lookup refecenced object</param>
 /// <param name="prop">property that needs the converted value</param>
 /// <param name="value">string value to be converted</param>
 protected virtual object MapStringToReferenceType(XPObjectSpace objectSpace, XPMemberInfo prop, string value){
     //if other referenced type
     if (prop.MemberType.IsSubclassOf(typeof (XPBaseObject))){
         string text = value;
         Type type = prop.MemberType;
         try{
             XPBaseObject mval = Helper.GetXpObjectByKeyValue(objectSpace, text, type);
             return objectSpace.GetObject(mval);
         }
         catch (Exception e){
             Trace.TraceWarning(Resources.RefTypeConversionError, value, prop.MemberType.Name, e);
         }
     }
     return null;
 }
Exemplo n.º 55
0
 public DbMapper(XPObjectSpace objectSpace, IPersistentAssemblyInfo persistentAssemblyInfo, IDataStoreLogonObject dataStoreLogonObject) {
     _objectSpace = objectSpace;
     _persistentAssemblyInfo = persistentAssemblyInfo;
     _dataStoreLogonObject = dataStoreLogonObject;
 }
 private ModelDifferenceObject GetDifferenceFromPermission(XPObjectSpace space) {
     return new QueryModelDifferenceObject(space.Session).GetModelDifferences(GetNames()).SingleOrDefault();
 }
Exemplo n.º 57
0
        public static void PrintInvoice(string invNo, XPObjectSpace os)
        {
            using (UnitOfWork uow = (UnitOfWork)os.Session)
            {
                Dictionary<string, IBindingList> dictInvoice = new Dictionary<string, IBindingList>();
                BindingList<Shipment> bShipment = new BindingList<Shipment>();
                XPCollection<Shipment> Shipments = new XPCollection<Shipment>(uow);
                Shipments.Criteria = DevExpress.Data.Filtering.CriteriaOperator.Parse(string.Format("InvoiceNo = '{0}' ", invNo));

                foreach (Shipment shipment in Shipments)
                {
                    bShipment.Add(shipment);
                }
                ReportHelper.ShowSingleReport("Invoice", bShipment, os);
            }
        }
Exemplo n.º 58
0
        public void ProccesExcellRows(IEnumerable records, XPObjectSpace objectSpace, DoWorkEventArgs e) {

            var i = 0;

            //for every row in excell sheet
            foreach (Row record in records) {
                ++i;
                if (i == 1) continue;
                if (_BgWorker.CancellationPending) { e.Cancel = true; break; }

                //var os = new ObjectSpace(objectSpace, XafTypesInfo.Instance);
                object newObj = null;

                //chech if row contains Oid

                //get key property name of the object type being imported
                var kp = objectSpace.GetKeyPropertyName(Type);
                //check if it exists in excel and is mapped ?
                var idMapping = ImportMap.Mappings.FirstOrDefault(p => p.MapedTo == kp);
                if (idMapping != null && GetQString(record[idMapping.Column].Value) != string.Empty) {
                    try {
                        //find existing object
                        var val = record[idMapping.Column];
                        var gwid = new Guid(GetQString(val.Value));
                        newObj = objectSpace.FindObject(Type, new BinaryOperator(kp, gwid), true);
                    } catch {

                    }
                }
                if (newObj == null) //create a new instance
                    newObj = objectSpace.CreateObject(Type) as IXPSimpleObject;

                string message;
                if (newObj != null) {
                    var props = ((IXPSimpleObject)newObj).ClassInfo.PersistentProperties
                        .OfType<XPMemberInfo>().ToList();


                    foreach (var mapping in ImportMap.Mappings) {
                        if (_BgWorker.CancellationPending) { e.Cancel = true; break; }
                        Application.DoEvents();

                        var mapping1 = mapping;
                        var prop = props.FirstOrDefault(p => p.Name == mapping1.MapedTo);

                        try {
                            var val = record[mapping.Column];
                            // continue;

                            if (val != null) {
                                //if simple property
                                if (prop.ReferenceType == null && !prop.MemberType.IsEnum) {
                                    var isNullable = prop.MemberType.IsGenericType && prop.MemberType.GetGenericTypeDefinition() == typeof(Nullable<>);
                                    object convertedValue = null;

                                    if (prop.MemberType == null) return;

                                    if (isNullable) {
                                        if (prop.StorageType == typeof(int)) {
                                            int number;
                                            if (val.Value != String.Empty && Int32.TryParse(val.Value, out number))
                                                convertedValue = number;

                                        } else if (prop.StorageType == typeof(DateTime)) {
                                            if (val.Value != string.Empty) {
                                                //Include validate
                                                var dt = DateTime.FromOADate(Convert.ToDouble(val.Value));
                                                convertedValue = dt;
                                            }
                                        } else if (prop.StorageType == typeof(double)) {
                                            double number;
                                            var rez = Double.TryParse(val.Value, out number);
                                            if (rez) convertedValue = number;
                                        }
                                    } else {
                                        if (prop.MemberType.IsEnum) {
                                            prop.SetValue(newObj, Enum.Parse(prop.MemberType, val.Value));
                                        } else if (prop.MemberType == typeof(char))
                                            convertedValue = Convert.ChangeType(GetQString(val.Value), prop.MemberType);
                                        else if (prop.StorageType == typeof(int)) {
                                            int number;
                                            if (val.Value != String.Empty && Int32.TryParse(val.Value, out number))
                                                convertedValue = number;
                                            else
                                                convertedValue = 0;
                                        } else if (prop.MemberType == typeof(Guid))
                                            convertedValue = new Guid(GetQString(val.Value));
                                        else if (prop.StorageType == typeof(DateTime)) {
                                            if (val.Value != string.Empty) {
                                                //Include validate
                                                var dt = DateTime.FromOADate(Convert.ToDouble(val.Value));
                                                convertedValue = dt;
                                            }
                                        } else if (prop.MemberType == typeof(double)) {
                                            double number;
                                            //  Application.CurrentCulture.NumberFormat.NumberDecimalSeparator = ".";
                                            var rez = Double.TryParse(val.Value, NumberStyles.Number, new NumberFormatInfo { NumberDecimalSeparator = "." }, out number);
                                            if (rez) convertedValue = number;
                                        } else if (prop.MemberType == typeof(bool)) {
                                            if (val.Value != string.Empty && (val.Value.Length == 1 || val.Value.ToLower() == "true" || val.Value.ToLower() == "false")) {
                                                bool truefalse;
                                                if (val.Value.ToLower() == "true" || val.Value.ToLower() == "false")
                                                    truefalse = Convert.ToBoolean(val.Value);
                                                else
                                                    truefalse = Convert.ToBoolean(Convert.ToInt32(val.Value));
                                                convertedValue = truefalse;
                                            }
                                        } else
                                            convertedValue = Convert.ChangeType(val.Value, prop.MemberType);
                                    }

                                    if (convertedValue != null) {
                                        if (convertedValue is double)
                                            convertedValue = Math.Round((double)convertedValue, 2, MidpointRounding.ToEven);

                                        prop.SetValue(newObj, convertedValue);
                                    }
                                }
                                //if referenced property
                                if (prop.ReferenceType != null) {

                                    //if other referenced type
                                    if (prop.MemberType.IsSubclassOf(typeof(XPBaseObject))) {
                                        var text = val.Value;
                                        var typ = prop.MemberType;
                                        var mval = ImportWizard.Helper.GetXpObjectByKeyValue(objectSpace, text, typ);
                                        prop.SetValue(newObj, objectSpace.GetObject(mval));
                                    }
                                }

                            }

                        } catch (Exception ee) {
                            message = string.Format(Resources.ExcelImportWizard_ProccesExcellRows_Error_processing_record__0____1_, i - 1, ee);
                            _BgWorker.ReportProgress(0, message);
                        }

                        if (CurrentCollectionSource != null)
                            AddNewObjectToCollectionSource(CurrentCollectionSource, newObj, ObjectSpace);
                        ObjectSpace.Session.Save(newObj);
                    }
                }

                objectSpace.CommitChanges();
                message = string.Format(Resources.ExcelImportWizard_ProccesExcellRows_Importing_record__0__succesfull_, i - 1);
                _BgWorker.ReportProgress(1, message);
                Application.DoEvents();
            }
        }
Exemplo n.º 59
0
 public ColumnMapper(DataTypeMapper dataTypeMapper, AttributeMapper attributeMapper) {
     _dataTypeMapper = dataTypeMapper;
     _attributeMapper = attributeMapper;
     _objectSpace = _attributeMapper.ObjectSpace;
     _extraInfoBuilder = new ExtraInfoBuilder(_objectSpace, _attributeMapper);
 }
Exemplo n.º 60
0
 private void btnPrint_Click(object sender, EventArgs e)
 {
     using (UnitOfWork uow = new UnitOfWork(XpoDefault.DataLayer))
     {
         XPObjectSpace os = new XPObjectSpace(uow, XafTypesInfo.Instance);
         ReportHelper.ShowSingleReport("SubPurchOrderReceive", poReceives, os);
     }
 }