Exemplo n.º 1
0
        public void Test()
        {
            var person = new Person
            {
                Id          = 1,
                Name        = "zhangsan",
                Addr        = "地球",
                IdentityNo  = "111111",
                Sex         = EnumSex.FeMale,
                Birth       = DateTime.Now.AddYears(-10),
                Description = "哈哈",
                Age         = 20,
                Nick        = "aaa",
                QQ          = "123",
                Email       = "*****@*****.**",
                Phone       = "13845614789",
                WeiXin      = "14563298785",
                Picture     = "http://asdasd.jpg",
                Intro       = "bb",
                Score       = 21.00,
                Books       = new List <string> {
                    "斗罗大陆"
                },
                CreateDate = DateTime.Now,
                UpdateDate = DateTime.Now
            };
            var personDto = MapperExtension.GetMapper <Person, PersonDto>(person);

            System.Diagnostics.Debug.WriteLine(JsonConvert.SerializeObject(personDto));
        }
Exemplo n.º 2
0
        public void MapTo_When_Not_Mapper_Return_Must_ThrowExceprion()
        {
            var entity = new TrackRawDataEntity {
                ProductId = (sbyte)ProductEnum.ERP, CreateTime = DateTime.Now
            };

            Assert.Throws <AutoMapperMappingException>(() => { MapperExtension.MapTo <TrackRawDataDto, TrackRawDataEntity>(entity); }, message: " Missing type map configuration or unsupported mapping.");
        }
Exemplo n.º 3
0
        public void MapTo_When_Mapped_Return_Must_Not_Be_Bull()
        {
            var entity = new TrackRawDataDto {
                Product = ProductEnum.ERP, CreateTime = DateTime.Now
            };
            var result = MapperExtension.MapTo <TrackRawDataEntity, TrackRawDataDto>(entity);

            Assert.IsNotNull(result);
            Assert.AreEqual(result.ProductId, (sbyte)entity.Product);
            Assert.AreEqual(result.CreateTime, entity.CreateTime.Date);
        }
        public static bool Delete <TAdapter>(this IDbConnection connection, object entityToDelete, Type type, IDbTransaction transaction = null, int?commandTimeout = null)
            where TAdapter : IDatabaseAdapter
        {
            if (entityToDelete == null)
            {
                throw new ArgumentException("Cannot Delete null Object", nameof(entityToDelete));
            }

            if (type.IsArray)
            {
                type = type.GetElementType();
            }
            else if (type.IsGenericType)
            {
                type = type.GetGenericArguments()[0];
            }

            var keyProperties = MapperExtension.GetKeyPropertiesCache(type).ToList();

            if (keyProperties.Count == 0)
            {
                throw new ArgumentException("Entity must have at least one [Key]");
            }

            var tableAttr = type.GetCustomAttributes(false)
                            .SingleOrDefault(attr => attr.GetType() == typeof(TableAttribute)) as dynamic;
            var tableName = tableAttr?.Name;

            if (string.IsNullOrEmpty(tableName))
            {
                throw new Exception("Table atribute not found");
            }

            var sb = new StringBuilder();

            sb.AppendFormat("delete from {0} where ", tableName);

            var adapter = Activator.CreateInstance <TAdapter>() as IDatabaseAdapter;

            for (var i = 0; i < keyProperties.Count; i++)
            {
                var property = keyProperties[i];
                adapter.AppendColumnNameEqualsValue(sb, property.Name.ToLower());
                if (i < keyProperties.Count - 1)
                {
                    sb.AppendFormat(" and ");
                }
            }
            var deleted = connection.Execute(sb.ToString(), entityToDelete, transaction, commandTimeout);

            return(deleted > 0);
        }
Exemplo n.º 5
0
        public static void Test()
        {
            MapperExtension.CreateMapperByAssembly(new string[] { "ConsoleTest" });
            var entity = new TrackRawDataDto {
                Product = ProductEnum.ERP, CreateTime = DateTime.Now
            };
            var list = new List <TrackRawDataDto>();

            list.Add(entity);
            list.Add(entity);
            var result  = MapperExtension.MapTo <TrackRawDataEntity, TrackRawDataDto>(entity);
            var result1 = MapperExtension.MapTo <TrackRawDataEntity, TrackRawDataDto>(list);
        }
Exemplo n.º 6
0
        public async Task <PaginationResult <TContract> > PaginateAsync <TEntity, TContract, TSearch>(IQueryable <TEntity> query, TSearch searchObject, PagingInstruction pagingInstruction, Expression <Func <TEntity, bool> > predicate = null, string prefix = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            var results    = PaginateInternal(query, searchObject, pagingInstruction, predicate, prefix);
            var totalCount = pagingInstruction.TotalRowCount;
            var data       = await ToListAsync(MapperExtension.ProjectTo <TEntity, TContract>(results.Item2), cancellationToken);

            return(new PaginationResult <TContract>
                   (
                       data,
                       pagingInstruction.PageIndex,
                       pagingInstruction.PageSize,
                       totalCount
                   ));
        }
Exemplo n.º 7
0
        static Task Main(string[] args)
        {
            MapperExtension.InstantiateMapper();

            using IHost host = CreatHostBuilder(args).Build().SeedDatabase();
            var run = host.RunAsync();

            Globals.Services = host.Services;

            Menu          = host.Services.GetService <Menu>();
            Globals.Exit += (o, e) => { host.StopAsync(); Environment.Exit(0); };
            Menu.Start();

            return(run);
        }
Exemplo n.º 8
0
        public static T ToObj <T>(this IDictionary <string, string> dict) where T : class, new()
        {
            var props   = typeof(T).GetProperties();
            var newItem = new T();

            foreach (var item in dict)
            {
                foreach (var p in props)
                {
                    if (p.Name == item.Key)
                    {
                        p.SetValue(newItem, MapperExtension.ConvertValue(item.Value, p.PropertyType));
                    }
                }
            }
            return(newItem);
        }
Exemplo n.º 9
0
        public PaginationResult <TContract> Paginate <TEntity, TContract, TSearch>(IQueryable <TEntity> query, TSearch searchObject, PagingInstruction pagingInstruction, Expression <Func <TEntity, bool> > predicate = null, string prefix = null)
        {
            var results    = PaginateInternal(query, searchObject, pagingInstruction, predicate, prefix);
            var totalCount = pagingInstruction.TotalRowCount;

            var data = MapperExtension
                       .ProjectTo <TEntity, TContract>(results.Item2)
                       .ToList();

            return(new PaginationResult <TContract>
                   (
                       data,
                       pagingInstruction.PageIndex,
                       pagingInstruction.PageSize,
                       totalCount
                   ));
        }
Exemplo n.º 10
0
        public void BatchTest()
        {
            var person = new Person
            {
                Id          = 1,
                Name        = "zhangsan",
                Addr        = "地球",
                IdentityNo  = "111111",
                Sex         = EnumSex.FeMale,
                Description = "哈哈",
                Age         = 20,
                Nick        = "aaa",
                Email       = "*****@*****.**",
                Picture     = "http://asdasd.jpg",
                Intro       = "bb",
                Score       = 21.00,
                CreateDate  = DateTime.Now,
                UpdateDate  = DateTime.Now
            };
            PersonDto dto   = null;
            var       func  = MapperExtension.GetMapperFunc <Person, PersonDto>();
            var       count = 50;
            var       st    = new Stopwatch();

            st.Start();
            for (var i = 0; i < count; i++)
            {
                var st1 = new Stopwatch();
                st1.Start();
                for (var j = 0; j < 10000; j++)
                {
                    dto = func(person);
                }
                st1.Stop();
                System.Diagnostics.Debug.WriteLine($"第{(i + 1)}次:{st1.ElapsedMilliseconds} 毫秒");
            }
            st.Stop();
            System.Diagnostics.Debug.WriteLine($"表达式树 总耗时:{st.ElapsedMilliseconds} 毫秒 平均:{st.ElapsedMilliseconds / count} 毫秒");
        }
Exemplo n.º 11
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, IServiceProvider serviceProvider, IApplicationLifetime applicationLifetime)
        {
            loggerFactory.AddNLog();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseHsts();
            }

            MapperExtension.Init(serviceProvider.GetService <IMapper>());

            app.UseStaticFiles();

            app.UseSwagger()
            .UseSwaggerUI(c =>
            {
                c.SwaggerEndpoint("/swagger/v1/swagger.json", "Catalog HTTP API V1");
            });

            app.UseCors("CorsPolicy");
            app.UseAuthentication();
            app.UseHttpsRedirection();
            app.UseMvc();

            applicationLifetime.ApplicationStarted.Register(() => { LogManager.GetCurrentClassLogger().Info("====APPLICATION STARTED===="); });
            applicationLifetime.ApplicationStopping.Register(() => { LogManager.GetCurrentClassLogger().Info("====APPLICATION STOPPING===="); });
            applicationLifetime.ApplicationStopped.Register(() => { LogManager.GetCurrentClassLogger().Info("====APPLICATION STOPPED===="); });

            app.Run(async(context) =>
            {
                await context.Response.WriteAsync("Catalog HTTP API");
            });
        }
Exemplo n.º 12
0
 static ContainerDrivenScenario()
 {
     MapperExtension.RegisterProfiles();
 }
        public static int Insert <TAdapter>(this IDbConnection connection, object entity, Type type, IDbTransaction transaction = null, int?commandTimeout = null)
            where TAdapter : IDatabaseAdapter
        {
            var isList = false;

            if (type.IsArray)
            {
                isList = true;
                type   = type.GetElementType();
            }
            else if (type.IsGenericType && type.GetTypeInfo().ImplementedInterfaces.Any(ti =>
                                                                                        ti.IsGenericType && ti.GetGenericTypeDefinition() == typeof(IEnumerable <>)))
            {
                isList = true;
                type   = type.GetGenericArguments()[0];
            }

            var tableAttr = type.GetCustomAttributes(false)
                            .SingleOrDefault(attr => attr.GetType() == typeof(TableAttribute)) as dynamic;
            var tableName = tableAttr?.Name;

            var adapter       = Activator.CreateInstance <TAdapter>() as IDatabaseAdapter;
            var sbColumnList  = new StringBuilder(null);
            var allProperties = MapperExtension.GetTypeProperties(type);
            var keyProperties = MapperExtension.GetKeyPropertiesCache(type).ToList();
            var allPropertiesExceptKeyAndComputed = allProperties.Except(keyProperties).ToList();

            for (var i = 0; i < allPropertiesExceptKeyAndComputed.Count; i++)
            {
                var property = allPropertiesExceptKeyAndComputed[i];
                adapter.AppendColumnName(sbColumnList, property.Name.ToLower());
                if (i < allPropertiesExceptKeyAndComputed.Count - 1)
                {
                    sbColumnList.Append(", ");
                }
            }

            var sbParameterList = new StringBuilder(null);

            for (var i = 0; i < allPropertiesExceptKeyAndComputed.Count; i++)
            {
                var property = allPropertiesExceptKeyAndComputed[i];
                sbParameterList.AppendFormat("@{0}", property.Name.ToLower());
                if (i < allPropertiesExceptKeyAndComputed.Count - 1)
                {
                    sbParameterList.Append(", ");
                }
            }

            int returnVal;
            var wasClosed = connection.State == ConnectionState.Closed;

            if (wasClosed)
            {
                connection.Open();
            }

            if (!isList)
            {
                returnVal = adapter.Insert(connection, transaction, commandTimeout, tableName, sbColumnList.ToString(),
                                           sbParameterList.ToString(), keyProperties, entity);
            }
            else
            {
                var cmd = $"insert into {tableName} ({sbColumnList}) values ({sbParameterList})";
                returnVal = connection.Execute(cmd, entity, transaction, commandTimeout);
            }
            if (wasClosed)
            {
                connection.Close();
            }
            return(returnVal);
        }
Exemplo n.º 14
0
 public static IMapper GetMapper()
 {
     return(MapperExtension.GetConfiguredMapper());
 }
Exemplo n.º 15
0
 public void FixtureSetUp()
 {
     MapperExtension.CreateMapperByAssembly(new string[] { "OneOne.UnitTest" });
 }
Exemplo n.º 16
0
 public static IMapper GetMapper(IConfiguration configuration)
 {
     return(MapperExtension.GetConfiguredMapper(configuration));
 }
 public static IMapper GetMapper() => MapperExtension.GetMapper();
Exemplo n.º 18
0
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
            // Azure Active Directory Authentication
            services.AddAuthentication(sharedOptions =>
            {
                sharedOptions.DefaultScheme = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddAzureAdBearer(options => Configuration.Bind("AzureAd", options));

            // MVC
            services.AddMvc(setup =>
            {
                if (!HostingEnvironment.IsDevelopment())
                {
                    var policy = new AuthorizationPolicyBuilder()
                                 .RequireAuthenticatedUser()
                                 .Build();

                    setup.Filters.Add(new AuthorizeFilter(policy));
                }
            });

            // Compression
            services.Configure <GzipCompressionProviderOptions>(options => options.Level = System.IO.Compression.CompressionLevel.Optimal);
            services.AddResponseCompression();

            // Cors
            services.AddCors();

            // Register the Swagger generator, defining 1 or more Swagger documents
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title = "Northwind BackOffice Web API", Version = "v1"
                });
            });

            Runtime.ConnectionString = Configuration.GetConnectionString("DefaultConnection");

            MapperExtension.RegisterProfiles();

            // Add DbContext
            services.AddDbContext <IntegrationEventLogContext>(options =>
                                                               options.UseSqlServer(Runtime.ConnectionString));

            services.AddDbContext <SalesDbContext>(options =>
                                                   options.UseSqlServer(Runtime.ConnectionString));

            // Add Configuration
            services.AddSingleton <IConfiguration>(Configuration);

            // Add RabittMq Settings
            services.AddSingleton(service =>
            {
                var settings = Configuration.GetSection("RabbitMqSettings");
                var bus      = Bus.Factory.CreateUsingRabbitMq(cfg =>
                {
                    cfg.ExchangeType = ExchangeType.Direct;
                    cfg.Durable      = true;
                    cfg.AutoDelete   = false;
                    cfg.Host(new Uri(settings.GetValue <string>("RabbitMqUri")), host =>
                    {
                        host.Username(settings.GetValue <string>("UserName"));
                        host.Password(settings.GetValue <string>("Password"));
                    });
                });

                ApplicationLifetime.ApplicationStopped.Register(bus.Stop);

                TaskUtil.Await(() => bus.StartAsync());

                return(bus);
            });

            services.AddTransient <Func <DbConnection, IntegrationEventLogService> >(
                sp => (DbConnection c) => new IntegrationEventLogService(c));

            services.AddTransient <IntegrationEventLogService>();

            services.AddTransient <IProductIntegrationEventService, ProductIntegrationEventService>();
        }