Exemplo n.º 1
0
        public void Map_ValueType_Deep()
        {
	        var item = new
	        {
		        value = new
		        {
			        Id = 1,
			        Name = "one",
			        Dbl = 2.2,
			        KeyValue = new KeyValuePair<string, string>("key", "value")
		        }
	        };

	        var mapper = new DefaultMapper();
	        var snapshot = mapper.Map(item, SnapshotOptions.Default);

	        var sb = string.Join(Environment.NewLine, new[]
	        {
				"value:",
		        "  Dbl: 2.2",
		        "  Id: 1",
		        "  KeyValue:",
				"    Key: key",
				"    Value: value",
				"  Name: one"
			});

	        snapshot.ToString().Should().BeEquivalentTo(sb);
        }
Exemplo n.º 2
0
            public void Must_assign_all_settable_properties_picked_up_by_convention()
            {
                var sourceFoo = new Foo();
                var targetBar = new Bar();

                sourceFoo.A             = "SourceA";
                sourceFoo.B             = "SourceB";
                sourceFoo.C             = 1;
                sourceFoo.Color         = Color.Red;
                sourceFoo.NullableColor = null;
                sourceFoo.RefType       = new SimpleRefType
                {
                    Id = Guid.NewGuid()
                };

                targetBar.A             = "WrongA";
                targetBar.B             = "WrongB";
                targetBar.C             = 0;
                targetBar.Color         = ColorType.Blue;
                targetBar.NullableColor = ColorType.Green;
                targetBar.RefType       = null;

                var systemUnderTest = new DefaultMapper <Foo, Bar>();

                systemUnderTest.Map(sourceFoo, targetBar);

                Assert.That(targetBar.A, Is.EqualTo(sourceFoo.A));
                Assert.That(targetBar.B, Is.EqualTo(sourceFoo.B));
                Assert.That(targetBar.C, Is.EqualTo(sourceFoo.C));
                Assert.That(targetBar.Color, Is.EqualTo(ColorType.Red));
                Assert.That(targetBar.NullableColor, Is.EqualTo(null));
                Assert.That(targetBar.RefType, Is.Not.Null);
                Assert.That(targetBar.RefType.Id, Is.Not.Null);
                Assert.That(targetBar.RefType.Id, Is.EqualTo(sourceFoo.RefType.Id));
            }
Exemplo n.º 3
0
            public void Must_perform_acceptably()
            {
                var sourceFoo = new Foo();
                var targetBar = new Bar();

                sourceFoo.A       = "SourceA";
                sourceFoo.B       = "SourceB";
                sourceFoo.C       = 1;
                sourceFoo.RefType = new SimpleRefType
                {
                    Id = Guid.NewGuid()
                };

                targetBar.A       = "WrongA";
                targetBar.B       = "WrongB";
                targetBar.C       = 0;
                targetBar.RefType = null;

                const int numberOfMappings = 10000000;
                var       systemUnderTest  = new DefaultMapper <Foo, Bar>();
                var       milliseconds     = (long)StopwatchContext.Timed(() =>
                {
                    for (int i = 0; i < numberOfMappings; i++)
                    {
                        systemUnderTest.Map(sourceFoo, targetBar);
                    }
                }).TotalMilliseconds;

                Console.WriteLine("{0:0.000000000000000}", milliseconds / numberOfMappings);
            }
Exemplo n.º 4
0
        public void Map_Nested_List()
        {
	        var item = new
	        {
		        value = new
		        {
			        Items = new []
			        {
						new { Value = "one"},
						new { Value = "two"}
					}
		        }
	        };

	        var mapper = new DefaultMapper();
	        var snapshot = mapper.Map(item, SnapshotOptions.Default);

	        var sb = string.Join(Environment.NewLine, new[]
	        {
		        "value:",
		        "  Items:",
		        "    Value: one",
		        "    Value: two"
	        });

	        snapshot.ToString().Should().BeEquivalentTo(sb);
        }
Exemplo n.º 5
0
        internal static TBiz SaveAsUser <TBiz, TDal>(TBiz item, int userId)
            where TDal : D.EntityObject, IQpEntityObject
            where TBiz : EntityObject
        {
            var entities = QPContext.EFContext;
            var dalItem  = DefaultMapper.GetDalObject <TDal, TBiz>(item);

            if (item.ForceId != 0)
            {
                dalItem.Id = item.ForceId;
            }

            DateTime current;

            using (new QPConnectionScope())
            {
                current = Common.GetSqlDate(QPConnectionScope.Current.DbConnection);
            }

            dalItem.Created        = current;
            dalItem.Modified       = current;
            dalItem.LastModifiedBy = userId;
            entities.AddObject(GetSetNameByType(typeof(TDal)), dalItem);
            entities.SaveChanges();

            return(DefaultMapper.GetBizObject <TBiz, TDal>(dalItem));
        }
Exemplo n.º 6
0
        public override bool SetOptions(Properties opts)
        {
            bool ret = base.SetOptions(opts);

            if (opts.Contains(ConfigParser.paramSplit))
            {
                string splitFileName = opts.GetProperty(ConfigParser.paramSplit);
                splitSet = MakeSplitSet(splitFileName);
            }
            CcTagset = PropertiesUtils.GetBool(opts, ConfigParser.paramCCTagset, false);
            treebank = new MemoryTreebank(new FrenchXMLTreeReaderFactory(CcTagset), FrenchTreebankLanguagePack.FtbEncoding);
            if (lexMapper == null)
            {
                lexMapper = new DefaultMapper();
                lexMapper.Setup(null, lexMapOptions.Split(","));
            }
            if (pathsToMappings.Count != 0)
            {
                if (posMapper == null)
                {
                    posMapper = new DefaultMapper();
                }
                foreach (File path in pathsToMappings)
                {
                    posMapper.Setup(path);
                }
            }
            return(ret);
        }
Exemplo n.º 7
0
 /// <summary>
 /// 获取业务员所属业务区域
 /// </summary>
 /// <param name="userId"></param>
 /// <returns></returns>
 public IList <ParamItemModel> GetSaleOwnAreaByUserId(int userId)
 {
     //Hashtable ht = new Hashtable();
     //ht.Add("UserId", userId);
     //ht.Add("ParamCode", CMSCommon.Constants.SysParamType.SaleAreaCode);
     return(DefaultMapper.GetMapper().SelectList <ParamItemModel>("Sales.GetSaleOwnAreaByUserId", userId));
 }
Exemplo n.º 8
0
        /// <summary>
        /// 通过用户ID得到一个对象实体.
        /// </summary>
        //public IList<SalesManageDepartModel> GetByUserId(int UserId)
        //{
        //    return null;
        //    //return DBProvider.dbMapper.SelectList<SalesManageDepartModel>("Sales_ManageDepart.GetByUserId", UserId);
        //}

        /// <summary>
        /// 管理的用户
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="orgCode"></param>
        /// <returns></returns>
        public IList <UserModel> GetManageUserByUserId(int userId, string orgCode)
        {
            Hashtable ht = new Hashtable();

            ht["UserId"]  = userId;
            ht["OrgCode"] = orgCode;
            return(DefaultMapper.GetMapper().SelectList <UserModel>("Sales_ManageDepart.GetManageUserByUserId", ht));
        }
Exemplo n.º 9
0
        public void MapMethodThrowsIfOptionsAreNull()
        {
            Assert.Throws <ArgumentNullException>(() =>
            {
                var mapper = new DefaultMapper();

                mapper.Map(Enumerable.Empty <string>(), null);
            });
        }
Exemplo n.º 10
0
        public void MapMethodThrowsIfArgumentsAreNull()
        {
            Assert.Throws <ArgumentNullException>(() =>
            {
                var mapper = new DefaultMapper();

                mapper.Map(null);
            });
        }
Exemplo n.º 11
0
        public void GetMapperResultThrowsIfObjectNotRegistered()
        {
            var mapper = new DefaultMapper();

            mapper.RegistrationService.Register <Options>();

            Assert.Throws <ArgumentException>(() =>
            {
                mapper.GetMapperResult <OtherOptions>();
            });
        }
Exemplo n.º 12
0
        /// <summary>
        ///     Maps the passed arguments to the specified type
        /// </summary>
        /// <param name="arguments">
        ///    The arguments mapped to the specified type
        /// </param>
        /// <typeparam name="T">
        ///    The type to whom the arguments are mapped
        /// </typeparam>
        /// <returns>
        ///    An instance of the specified type with all
        ///     properties mapped to the passed arguments
        /// </returns>
        private static IMapperResult <T> MapArgumentsToType <T>(string arguments) where T : class, new()
        {
            var mapper = new DefaultMapper();

            mapper.RegistrationService.Register <T>();

            mapper.Map(arguments.SimpleSplitArguments());

            var result = mapper.GetMapperResult <T>();

            return(result);
        }
Exemplo n.º 13
0
        public IClassMapper GetMap(Type entityType)
        {
            if (!_classMaps.TryGetValue(entityType, out IClassMapper map))
            {
                var mapType = GetMapType(entityType) ?? DefaultMapper.MakeGenericType(entityType);

                map = Activator.CreateInstance(mapType) as IClassMapper;
                _classMaps[entityType] = map;
            }

            return(map);
        }
Exemplo n.º 14
0
        public void DefaultMapper_Map_NoSetter()
        {
            var mapper = new DefaultMapper();

            var context = new MapperContext(mapper, new Snapshot(), new SnapshotOptions(), 0);

            var item = new OnlyGetter();

            mapper.Map(context, item);

            Assert.AreEqual(1, context.Snapshot.Count);
        }
 public static ToType ToModel <FromType, ToType>(this FromType fromObject, out ToType toObject) where FromType : class, new() where ToType : class, new()
 {
     if (typeof(ToType) is IMapper <FromType, ToType> customMapper)
     {
         toObject = customMapper.Convert(fromObject, Config.ServiceProvider);
     }
     else
     {
         toObject = new DefaultMapper <FromType, ToType>().Convert(fromObject, Config.ServiceProvider);
     }
     return(toObject);
 }
Exemplo n.º 16
0
        public void DefaultMapper_Map_IgnoreIndexers()
        {
            var mapper = new DefaultMapper();

            var context = new MapperContext(mapper, new Snapshot(), new SnapshotOptions(), 0);

            var item = new WithIndexer();

            mapper.Map(context, item);

            Assert.AreEqual(0, context.Snapshot.Count);
        }
Exemplo n.º 17
0
        /// <summary>
        /// 增加一条数据
        /// </summary>
        public void AddManageDepart(int userId, int orgId, string orgCode)
        {
            Hashtable ht = new Hashtable();

            //int orgId = DefaultMapper.GetMapper().SelectObject<UserManageDepartModel>("User_ManageDepart.GetMaxIdModel", "").OrgId + 1;
            ht.Add("OrgId", orgId);
            ht.Add("UserID", userId);
            //ht.Add("JobNo", jobNo);
            ht.Add("OrgCode", orgCode);

            DefaultMapper.GetMapper().Insert("User_ManageDepart.InsertManageDepart", ht);
        }
Exemplo n.º 18
0
        public IClassMapper GetMap(Type entityType)
        {
            if (_classMaps.TryGetValue(entityType, out IClassMapper map))
            {
                return(map);
            }
            Type mapType = GetMapType(entityType) ?? DefaultMapper.MakeGenericType(entityType);

            map = Activator.CreateInstance(mapType, new[] { _loggerFactory.CreateLogger(entityType) }) as IClassMapper;
            _classMaps[entityType] = map;

            return(map);
        }
Exemplo n.º 19
0
        /// <summary>
        ///     Maps the passed arguments to the specified types
        /// </summary>
        /// <param name="arguments">
        ///    The arguments to map
        /// </param>
        /// <typeparam name="TFirst">
        ///    The first type to map
        /// </typeparam>
        /// <typeparam name="TSecond">
        ///    The second type to map
        /// </typeparam>
        /// <returns>
        ///    The mapper that contains the result of the operation
        /// </returns>
        private static ICommandLineMapper MapArgumentsToTwoTypes <TFirst, TSecond>(string arguments)
            where TFirst : class, new()
            where TSecond : class, new()
        {
            var mapper = new DefaultMapper();

            mapper.RegistrationService.Register <TFirst>();
            mapper.RegistrationService.Register <TSecond>();

            mapper.Map(arguments.SimpleSplitArguments());

            return(mapper);
        }
Exemplo n.º 20
0
        public void SingleObjectPropertyIsNotFound()
        {
            var expectedUnmappedArg = new Argument("-", "-foo", "200");

            var mapper = new DefaultMapper();

            mapper.RegistrationService.Register <IntegratedTypesOptions>();
            mapper.Map("-stringProperty C:\\some\\file\\path -foo 200".SimpleSplitArguments());

            var unmapped = mapper.UnmappedArguments.ToList()[0];

            Assert.AreEqual(expectedUnmappedArg, unmapped);
        }
Exemplo n.º 21
0
        static void Main(string[] args)
        {
            CompanyInfo info = new CompanyInfo
            {
                Addr          = "山东省青岛市",
                IsSupper      = "1",
                Name          = "李大富",
                Phone         = "15020986697",
                EmployeeInfos = new List <EmployeeInfo> {
                    new EmployeeInfo {
                        EmployeeName  = "员工A",
                        EmployeePhone = "17863968705"
                    },
                    new EmployeeInfo {
                        EmployeeName  = "员工B",
                        EmployeePhone = "17645825698"
                    },
                },
                boss = new BossInfo {
                    BossName   = "大Boos",
                    BossPhone  = "6666",
                    CreateDate = "2020-04-01 18:00:00"
                }
            };
            string sql = info.BuildSql();
            int    aa  = 0;

            List <MyListDemo> listDemos    = new List <MyListDemo>();
            string            className    = "MyListDemo";
            string            namespaceStr = "Test.Entity";
            var model = Assembly.GetExecutingAssembly().CreateInstance(string.Join(".", new object[] { namespaceStr, className }));

            PropertyInfo[] pros = model.GetType().GetProperties();
            foreach (var item in pros)
            {
                item.SetValue(model, "123456", null);
            }
            var modelList = Activator.CreateInstance(typeof(List <>).MakeGenericType(new Type[] { model.GetType() }));
            var addMethod = modelList.GetType().GetMethod("Add");

            addMethod.Invoke(modelList, new object[] { model });
            listDemos = (List <MyListDemo>)modelList;

            DatabaseFactoryF dbcontext = DatabaseSimpleFactoryL.GetInstance("Data Source=.;database=AhFApi;User ID=sa;Password=123456;", "SQLSERVER");
            DataSet          ds        = dbcontext.GetDataSet($"SELECT '五菱宏光PLUS' as SPPM,'WLHG-201904200014G' as SPXH,'上海柳州汽车制造厂' as CJ,'Y' as IsSale,'0.89' as ZHEKOU,'69800' as Price from OrgDemo;SELECT OrgName as PNAME,OrgType as PVALUE from OrgDemo ");
            IStandardMapper  mapper    = new DefaultMapper();
            Car        car             = mapper.ToEntity <Car>(ds);
            List <Car> cars            = mapper.ToEntity <List <Car> >(ds);

            Console.ReadLine();
        }
Exemplo n.º 22
0
        public void Map_ComplexObject()
        {
            var item = new
            {
                value = 1,
                obj = new
                {
                    sub = new
                    {
                        value = "sum"
                    }
                },
                data = "this is a test",
                list = new[]
                {
                    new
                    {
                        value = "1"
                    },
                    new
                    {
                        value = "2"
                    },
                },
                strings = new List<string>
                {
                    "value 1",
                    "value 2"
                }
            };

            var mapper = new DefaultMapper();
            var snapshot = mapper.Map(item, SnapshotOptions.Default);

            var sb = string.Join(Environment.NewLine, new[]
            {
                "data: this is a test",
                "list:",
                "  value: 1",
                "  value: 2",
                "obj:",
                "  sub:",
                "    value: sum",
                "strings:",
                "  value 1",
                "  value 2",
                "value: 1"
            });

            snapshot.ToString().Should().BeEquivalentTo(sb);
        }
Exemplo n.º 23
0
        public Startup(IHostingEnvironment env)
        {
            //appsetting
            var builder = new ConfigurationBuilder()
                          .SetBasePath(env.ContentRootPath)
                          .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
                          .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

            builder.AddEnvironmentVariables();
            Configuration = builder.Build();

            //初始化映射关系
            DefaultMapper.Initialize();
        }
Exemplo n.º 24
0
        internal static TBiz Update <TBiz, TDal>(TBiz item)
            where TDal : class, IQpEntityObject
            where TBiz : EntityObject
        {
            var dalItem  = DefaultMapper.GetDalObject <TDal, TBiz>(item);
            var entities = QPContext.EFContext;

            dalItem.LastModifiedBy = QPContext.CurrentUserId;

            using (new QPConnectionScope())
            {
                dalItem.Modified = Common.GetSqlDate(QPConnectionScope.Current.DbConnection);
            }

            entities.Entry(dalItem).State = EntityState.Modified;
            entities.SaveChanges();
            return(DefaultMapper.GetBizObject <TBiz, TDal>(dalItem));
        }
        public IClassMapper GetMap(Type entityType)
        {
            IClassMapper map;

            if (!_classMaps.TryGetValue(entityType, out map))
            {
                Type mapType = GetMapType(entityType);
                if (mapType == null)
                {
                    mapType = DefaultMapper.MakeGenericType(entityType);
                }

                map = Activator.CreateInstance(mapType) as IClassMapper;
                _classMaps[entityType] = map;
            }

            return(map);
        }
Exemplo n.º 26
0
        internal static TBiz Update <TBiz, TDal>(TBiz item)
            where TDal : D.EntityObject, IQpEntityObject
            where TBiz : EntityObject
        {
            var dalItem  = DefaultMapper.GetDalObject <TDal, TBiz>(item);
            var entities = QPContext.EFContext;

            dalItem.LastModifiedBy = QPContext.CurrentUserId;

            using (new QPConnectionScope())
            {
                dalItem.Modified = Common.GetSqlDate(QPConnectionScope.Current.DbConnection);
            }

            entities.AttachTo(GetSetNameByType(typeof(TDal)), dalItem);
            entities.ObjectStateManager.ChangeObjectState(dalItem, EntityState.Modified);
            entities.SaveChanges();
            return(DefaultMapper.GetBizObject <TBiz, TDal>(dalItem));
        }
        public virtual IMongoDbMapper GetMapper <T>()
        {
            lock (_mutex)
            {
                if (!_mappers.TryGetValue(typeof(T), out var mapper))
                {
                    //automap all derived entities
                    if (!BsonClassMap.IsClassMapRegistered(typeof(T)))
                    {
                        BsonClassMap.RegisterClassMap <T>(cm => { cm.AutoMap(); });
                    }

                    mapper = new DefaultMapper <T>();
                    _mappers.Add(typeof(T), mapper);
                }

                return(mapper);
            }
        }
        public IClassMapper GetMap(Type entityType)
        {
            IClassMapper map;

            if (!_classMaps.TryGetValue(entityType, out map))
            {
                Type mapType = GetMapType(entityType);
                if (mapType == null)
                {
                    mapType = DefaultMapper.MakeGenericType(entityType);
                }

                map = Activator.CreateInstance(mapType) as IClassMapper;
                var plusitem = map.Properties.Where(p => p.ColumnName.Contains('.')).FirstOrDefault();
                map.Properties.Remove(plusitem);
                _classMaps[entityType] = map;
            }

            return(map);
        }
Exemplo n.º 29
0
        public void Map_ValueType_Top()
        {
	        var item = new
	        {
		        Id = 1,
		        Name = "one",
		        Dbl = 2.2
	        };

	        var mapper = new DefaultMapper();
	        var snapshot = mapper.Map(item, SnapshotOptions.Default);

	        var sb = string.Join(Environment.NewLine, new[]
	        {
		        "Dbl: 2.2",
		        "Id: 1",
		        "Name: one"
	        });

	        snapshot.ToString().Should().BeEquivalentTo(sb);
        }
Exemplo n.º 30
0
        public void Map_IEnumerable()
        {
	        var list = new List<MapItem>
	        {
		        new MapItem {Value = "one"},
		        new MapItem {Value = "two"},
		        new MapItem {Value = "three"}
	        };

	        var mapper = new DefaultMapper();
	        var snapshot = mapper.Map(list.Select(i => new { i.Value }), SnapshotOptions.Default);

	        var sb = string.Join(Environment.NewLine, new[]
	        {
		        "Value: one",
		        "Value: two",
		        "Value: three"
	        });

	        snapshot.ToString().Should().BeEquivalentTo(sb);
		}