Exemple #1
0
 public static void RegisterAutoMapper(this IServiceCollection services)
 {
     services.AddAutoMapper(typeof(CleanArch.Application.AutoMapper.AutoMapperConfiguration));
     AutoMapperConfiguration.RegisterMappings();
 }
Exemple #2
0
 public ToUserTests()
 {
     Mapper = AutoMapperConfiguration.Create();
     Faker  = new Faker();
 }
Exemple #3
0
 public static void InitializeAutoMapper(TestContext testContext)
 {
     Mapper.Reset();
     AutoMapperConfiguration.Initialize();
 }
Exemple #4
0
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            AutoMapperConfiguration.Configure();
        }
 public TravelFamilyService(TradeUnionCommitteeContext context, AutoMapperConfiguration mapperService, HashIdConfiguration hashIdUtilities)
 {
     _context         = context;
     _mapperService   = mapperService;
     _hashIdUtilities = hashIdUtilities;
 }
Exemple #6
0
        static async Task DoWork()
        {
            char input;

            AutoMapperConfiguration.Configure();
            do
            {
                ShowMenu();

                input = Console.ReadLine().First();
                switch (input)
                {
                case 'Q':
                    break;

                case 'T':
                    List <TestResult> testResults = new List <TestResult>();

                    Console.WriteLine("# of Test Runs:");
                    NumRuns = int.Parse(Console.ReadLine());

                    //Gather Details for Test
                    Console.WriteLine("# of Sports per Run: ");
                    NumSports = int.Parse(Console.ReadLine());

                    Console.WriteLine("# of Teams per Sport: ");
                    NumTeams = int.Parse(Console.ReadLine());

                    Console.WriteLine("# of Players per Team: ");
                    NumPlayers = int.Parse(Console.ReadLine());

                    Console.WriteLine("# of kids per Player: ");
                    NumKids = int.Parse(Console.ReadLine());


                    List <SportDTO>  sports  = Generator.GenerateSports(NumSports);
                    List <TeamDTO>   teams   = new List <TeamDTO>();
                    List <PlayerDTO> players = new List <PlayerDTO>();
                    List <KidDTO>    kids    = new List <KidDTO>();
                    foreach (var sport in sports)
                    {
                        var newTeams = Generator.GenerateTeams(sport.Id, NumTeams);
                        teams.AddRange(newTeams);
                        foreach (var team in newTeams)
                        {
                            var newPlayers = Generator.GeneratePlayers(team.Id, NumPlayers);
                            players.AddRange(newPlayers);
                            foreach (var player in newPlayers)
                            {
                                var newKids = Generator.GenerateKids(player.Id, NumKids);
                                kids.AddRange(newKids);
                            }
                        }
                    }

                    Database.Reset();
                    Database.Load(sports, teams, players, kids);

                    for (int i = 0; i < NumRuns; i++)
                    {
                        //EntityFrameworkDTO efTestDTO = new EntityFrameworkDTO();
                        //testResults.AddRange(await RunTests(i, Framework.EntityFrameworkDTO, efTestDTO));

                        EntityFramework efTest = new EntityFramework();
                        testResults.AddRange(await RunTests(i, Framework.EntityFramework, efTest));
                    }
                    ProcessResults(testResults);

                    break;
                }
            }while (input != 'Q');
        }
        public void Initialize()
        {
            AutoMapperConfiguration.Configure();
            FakeUnitOfWork unitOfWork = new FakeUnitOfWork();

            ratings = new Dictionary <Guid, Rating>();
            ratings.Clear();
            Guid id = new Guid("ee4cd8a2-eb0e-453d-a3b5-081b9165942e");

            Guid id1 = new Guid("911b3163-0401-49e8-8589-68b86153bb68");
            Guid id2 = new Guid("cd6aa915-6044-4354-8958-befc3bdfe02e");

            Rating rating1 = new Rating
            {
                Id     = id1,
                Value  = 2,
                UserId = new Guid("93297545-6aff-44cf-911c-fc4b5a88b404"),
                AdId   = id
            };
            Rating rating2 = new Rating
            {
                Id     = id2,
                Value  = 4,
                UserId = new Guid("13297545-6aff-44cf-911c-fc4b5a88b404"),
                AdId   = id
            };

            ratings.Add(id1, rating1);
            ratings.Add(id2, rating2);

            unitOfWork.Ratings = ratings;
            controller         = new RatingsController(unitOfWork)
            {
                Request = new HttpRequestMessage()
                {
                    Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }
                }
            };


            ads = new Dictionary <Guid, Ad>();
            ads.Clear();


            Ad ad1 = new Ad
            {
                Id          = id,
                Name        = "ad1",
                Description = "test",
                Email       = "*****@*****.**",
                Location    = "test",
                CityId      = Guid.NewGuid(),
                CategoryId  = Guid.NewGuid(),
                UserId      = Guid.NewGuid(),
                AvgRate     = 3,
                VoteCounter = 2
            };

            ads.Add(id, ad1);

            unitOfWork.Ads = ads;
            controllerA    = new AdsController(unitOfWork)
            {
                Request = new HttpRequestMessage()
                {
                    Properties = { { HttpPropertyKeys.HttpConfigurationKey, new HttpConfiguration() } }
                }
            };
        }
Exemple #8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext <ApplicationContext>(builder =>
            {
                if (_hostingEnvironment.IsEnvironment("Test"))
                {
                    #pragma warning disable CS0618 // Type or member is obsolete
                    var options = builder
                                  .UseInMemoryDatabase(databaseName: Guid.NewGuid().ToString())
                    #pragma warning restore CS0618 // Type or member is obsolete
                                  .Options;
                }
                else
                {
                    string useSqLite = Configuration["Data:useSqLite"];
                    if (useSqLite != "true")
                    {
                        var connStr = Configuration["Data:SqlServerConnectionString"];
                        builder.UseSqlServer(connStr);
                    }
                    else
                    {
                        // Note this path has to have full  access for the Web user in order
                        // to create the DB and write to it.
                        var connStr = "Data Source=" +
                                      Path.Combine(_hostingEnvironment.ContentRootPath, "AKData.sqlite");
                        builder.UseSqlite(connStr);
                    }
                }
            });

            var appSettingsSection = Configuration.GetSection("AppSettings");
            services.Configure <AppSettings>(appSettingsSection);

            // configure jwt authentication
            var appSettings = appSettingsSection.Get <AppSettings>();
            var key         = Encoding.ASCII.GetBytes(appSettings.Secret);
            services.AddAuthentication(x =>
            {
                x.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                x.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(x =>
            {
                x.RequireHttpsMetadata      = false;
                x.SaveToken                 = true;
                x.TokenValidationParameters = new TokenValidationParameters
                {
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(key),
                    ValidateIssuer           = false,
                    ValidateAudience         = false
                };
            });

            //services.AddAuthenticationCore();


            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            //services.AddScoped<IPrincipal>(provider => provider.GetService<IHttpContextAccessor>().HttpContext.User);
            services.AddScoped <IAppPrincipal, AppPrincipal>();

            // Make configuration available for EF configuration
            services.AddSingleton <IConfigurationRoot>(Configuration);
            services.AddSingleton <IConfiguration>(Configuration);

            services.AddTransient <IDbContext, ApplicationContext>();

            services.AddScoped(typeof(IRepository <>), typeof(EfRepository <>));

            services.AddTransient <ISecurityService, SecurityService>();
            services.AddTransient <IInventoryService, InventoryService>();
            services.AddTransient <IFinancialService, FinancialService>();
            services.AddTransient <IPurchasingService, PurchasingService>();
            services.AddTransient <ISalesService, SalesService>();
            services.AddTransient <ITaxService, TaxService>();

            //Log.Logger = new LoggerConfiguration()
            //        .WriteTo.RollingFile(pathFormat: "logs\\log-{Date}.log")
            //        .CreateLogger();
            //services.AddSingleton(Log.Logger);

            services.AddScoped <ApiExceptionFilter>();

            // Automapper Configuration
            //AutoMapperConfiguration.Configure();
            //services.AddAutoMapper();
            //services.AddSingleton(new Mapper(new MapperConfiguration(cfg => cfg.AddProfile<Models.Mappings.ModelMappingProfile>())));
            var config = new MapperConfiguration(cfg =>
            {
                //cfg.AddProfile(new ModelMappingProfile());
                cfg.AddMaps(GetType().Assembly);
            });

            //register
            AutoMapperConfiguration.Init(config);

            services.AddSwaggerGen(options =>
            {
                options.SwaggerDoc("v1", new OpenApiInfo {
                    Title = "ak api", Version = "v1"
                });
                options.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    Description = "JWT Authorization header using the Bearer scheme. Example: \"Authorization: Bearer {token}\"",
                    Name        = "Authorization",
                    In          = ParameterLocation.Header, // "header",
                    Type        = SecuritySchemeType.ApiKey //"apiKey"
                });
                //https://github.com/domaindrivendev/Swashbuckle/issues/581#issuecomment-235053027
                options.DocInclusionPredicate((docName, apiDesc) =>
                {
                    if (apiDesc.HttpMethod == null)
                    {
                        return(false);
                    }
                    return(true);
                });
                options.CustomSchemaIds(x => x.FullName);
            });

            // Cors policy is added to controllers via [EnableCors("CorsPolicy")]
            // or .UseCors("CorsPolicy") globally
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder
                                                    // required if AllowCredentials is set also
                                  .SetIsOriginAllowed(s => true)
                                                    //.AllowAnyOrigin()
                                  .AllowAnyMethod() // doesn't work for DELETE!
                                  .WithMethods("DELETE")
                                  .AllowAnyHeader()
                                  .AllowCredentials()
                                  );
            });

            services.AddControllers()
            .AddNewtonsoftJson(opt =>
            {
                opt.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                var resolver = opt.SerializerSettings.ContractResolver;
                //if (resolver != null)
                //{
                //    var res = resolver as DefaultContractResolver;
                //    res.NamingStrategy = null;
                //}

                if (_hostingEnvironment.IsDevelopment())
                {
                    opt.SerializerSettings.Formatting = Newtonsoft.Json.Formatting.Indented;
                }
            })
            .AddFluentValidation(fvc => fvc.RegisterValidatorsFromAssemblyContaining <Startup>());

            //services.AddMvc(options => options.EnableEndpointRouting = false);
        }
Exemple #9
0
 public void Insert(MailServer entity)
 {
     using (var dbcontext = new FAXPECContext())
     {
         try
         {
             MAILSERVERS m = AutoMapperConfiguration.FromMailServerToDto(entity, true);
             dbcontext.MAILSERVERS.Add(m);
             dbcontext.SaveChanges();
             //param out
             double iNewID = default(double);
             iNewID = dbcontext.MAILSERVERS.OrderByDescending(c => c.ID_SVR).FirstOrDefault().ID_SVR;
             //todo.. MIGLIORARE
             if (iNewID != default(double))
             {
                 entity.Id = decimal.Parse(iNewID.ToString());
             }
             else
             {
                 throw new Exception(DalExMessages.ID_NON_RESTITUITO);
             }
         }
         catch (InvalidOperationException ioex)
         {
             //Allineamento log - Ciro
             if (ioex.GetType() != typeof(ManagedException))
             {
                 ManagedException mEx = new ManagedException(DalExMessages.RUBRICA_NON_INSERITA + ioex.Message,
                                                             "DAL_RUB_002",
                                                             string.Empty,
                                                             string.Empty,
                                                             ioex);
                 ErrorLogInfo er = new ErrorLogInfo(mEx);
                 log.Error(er);
                 throw mEx;
             }
             else
             {
                 throw;
             }
             //throw new ManagedException(DalExMessages.RUBRICA_NON_INSERITA, "DAL_RUB_002", "", "", "", "", "", ioex);
         }
         catch (SqlException oex)
         {
             //Allineamento log - Ciro
             if (oex.GetType() != typeof(ManagedException))
             {
                 ManagedException mEx = new ManagedException(DalExMessages.RUBRICA_NON_INSERITA + oex.Message,
                                                             "DAL_RUB_001",
                                                             string.Empty,
                                                             string.Empty,
                                                             oex);
                 ErrorLogInfo er = new ErrorLogInfo(mEx);
                 log.Error(er);
                 throw mEx;
             }
             else
             {
                 throw;
             }
             //throw new ManagedException(DalExMessages.RUBRICA_NON_INSERITA, "DAL_RUB_001", "", "", "", "", "", oex);
         }
     }
 }
Exemple #10
0
 public BaseApp(IUnitOfWork unitOfWork)
 {
     _unitOfWork = unitOfWork;
     AutoMapperConfiguration.Configure();
 }
 private static void CreateMap()
 {
     AutoMapperConfiguration.CreateMap();
     Mapper.Instance.ConfigurationProvider.BuildExecutionPlan(typeof(ID4EFM.Client), typeof(ID4M.Client));
 }
Exemple #12
0
        public static void AddAa(this IServiceCollection services, NameValueCollection dbInfo)
        {
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            EngineContext.Create();

            var assemblys = AppDomain.CurrentDomain.GetAssemblies();
            var binPath   = AppContext.BaseDirectory;

            string[] dllPaths = Directory.GetFiles(binPath, "*.dll", SearchOption.TopDirectoryOnly);

            var loadedAssemblyNames = new List <string>();

            foreach (var a in assemblys)
            {
                loadedAssemblyNames.Add(a.FullName);
            }
            foreach (var dllPath in dllPaths)
            {
                try
                {
                    var an = AssemblyName.GetAssemblyName(dllPath);
                    if (!loadedAssemblyNames.Contains(an.FullName))
                    {
                        AppDomain.CurrentDomain.Load(an);
                    }
                }
                catch (BadImageFormatException ex)
                {
                    Trace.TraceError(ex.ToString());
                }
            }
            assemblys = AppDomain.CurrentDomain.GetAssemblies();
            //automapper
            var configurationActions = new List <Action <IMapperConfigurationExpression> >();

            foreach (var assembly in assemblys)
            {
                var instancesMapper = assembly.GetTypes().Where(x => x.GetInterface("IMapperConfiguration") != null)
                                      .Select(mapper => (IMapperConfiguration)Activator.CreateInstance(mapper));

                foreach (var instance in instancesMapper)
                {
                    configurationActions.Add(instance.GetConfiguration());
                }
            }
            AutoMapperConfiguration.Init(configurationActions);
            ObjectMapManager.ObjectMapper = new AutoMapperObjectMapper();
            //AA.Dapper
            Action <FluentMapConfiguration> action = null;

            foreach (var assembly in assemblys)
            {
                var instancesMapper = assembly.GetTypes().Where(x => x.GetInterface("IMapConfiguration") != null)
                                      .Select(mapper => (IMapConfiguration)Activator.CreateInstance(mapper));

                foreach (var instance in instancesMapper)
                {
                    action = instance.GetConfiguration();
                }
            }
            IDbDatasource dbDatasource = new DbDataSource();

            dbDatasource.Init(dbInfo);
            services.AddScoped <IDapperContext, DapperContext>();

            if (action == null)
            {
                throw new Exception("FluentMapConfiguration is null");
            }
            else
            {
                MapConfiguration.Init(action);
            }
        }
Exemple #13
0
 public void Setup()
 {
     AutoMapperConfiguration.Configure();
 }
Exemple #14
0
 public AutoMapperConfigurationTester()
 {
     AutoMapperConfiguration.Configure();
 }
Exemple #15
0
        protected void SetUp()
        {
            var config = new AutoMapperConfiguration();

            Mapper = config.Configure().CreateMapper();
        }
        /// <summary>
        /// Register dependencies
        /// </summary>
        /// <param name="config">Config</param>
        protected virtual void RegisterDependencies(NopConfig config)
        {
            var builder = new ContainerBuilder();

            //dependencies
            var typeFinder = new WebAppTypeFinder();

            //builder.RegisterInstance(config).As<NopConfig>().SingleInstance();

            builder.RegisterInstance(this).As <IEngine>().SingleInstance();
            builder.RegisterInstance(typeFinder).As <ITypeFinder>().SingleInstance();

            //register dependencies provided by other assemblies
            var drTypes     = typeFinder.FindClassesOfType <IDependencyRegistrar>();
            var drInstances = new List <IDependencyRegistrar>();

            foreach (var drType in drTypes)
            {
                drInstances.Add((IDependencyRegistrar)Activator.CreateInstance(drType));
            }
            //sort
            drInstances = drInstances.AsQueryable().OrderBy(t => t.Order).ToList();
            foreach (var dependencyRegistrar in drInstances)
            {
                dependencyRegistrar.Register(builder, typeFinder, config);
            }

            //dependencies
            //var typeFinder = new WebAppTypeFinder();
            //====================================================================
            //register mapper configurations provided by other assemblies
            var mcTypes     = typeFinder.FindClassesOfType <IMapperConfiguration>();
            var mcInstances = new List <IMapperConfiguration>();

            foreach (var mcType in mcTypes)
            {
                mcInstances.Add((IMapperConfiguration)Activator.CreateInstance(mcType));
            }
            //sort
            mcInstances = mcInstances.AsQueryable().OrderBy(t => t.Order).ToList();
            //get configurations
            var configurationActions = new List <Action <IMapperConfigurationExpression> >();

            foreach (var mc in mcInstances)
            {
                configurationActions.Add(mc.GetConfiguration());
            }
            //register
            AutoMapperConfiguration.Init(configurationActions);

            builder.Register(c => AutoMapperConfiguration.Mapper).SingleInstance();
            builder.Register(c => AutoMapperConfiguration.MapperConfiguration).SingleInstance();
            //====================================================================

            var container = builder.Build();

            this._containerManager = new ContainerManager(container);

            //set dependency resolver
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
        }
Exemple #17
0
 protected override void OnStartup(StartupEventArgs e)
 {
     base.OnStartup(e);
     AutoMapperConfiguration.Configure();
 }
Exemple #18
0
 public AwardEmployeesService(TradeUnionCommitteeContext context, AutoMapperConfiguration mapperService, HashIdConfiguration hashIdUtilities)
 {
     _context         = context;
     _mapperService   = mapperService;
     _hashIdUtilities = hashIdUtilities;
 }
        protected override void OnApplicationStarted(object sender, EventArgs e)
        {
            base.OnApplicationStarted(sender, e);

            AutoMapperConfiguration.Configure();
        }
Exemple #20
0
        public void AssertAutoMapperConfigurationIsValid()
        {
            var mapper = AutoMapperConfiguration.Configure();

            mapper.ConfigurationProvider.AssertConfigurationIsValid();
        }
Exemple #21
0
 public RoomBUSTests()
 {
     AutoMapperConfiguration.Configure();
 }
 public AutoMapperConfigurationFixture()
 {
     AutoMapperConfiguration.Configure();
 }
Exemple #23
0
 protected void Application_Start()
 {
     AutoMapperConfiguration.Configure();
     GlobalConfiguration.Configure(WebApiConfig.Register);
 }
 public void Execute()
 {
     AutoMapperConfiguration.Init();
 }
 public static void Run()
 {
     SetAutofacContainer();
     AutoMapperConfiguration.Configure();
 }
Exemple #26
0
 public static void Run()
 {
     AutofacWebapiConfig.Initialize(GlobalConfiguration.Configuration);
     AutoMapperConfiguration.Configure();
 }
Exemple #27
0
 public static void Run()
 {
     AutoMapperConfiguration.Configure();
 }
        public void ValidMappings()
        {
            MapperConfiguration config = AutoMapperConfiguration.RegisterMappings();

            config.AssertConfigurationIsValid();
        }
 public AppBaseModel()
 {
     AutoMapperConfiguration.Configure();
 }
Exemple #30
0
 public CategoryService(IUnitOfWork unitOfWork, IRepository <Category> repository)
 {
     this._unitOfWork = unitOfWork;
     _mapper          = AutoMapperConfiguration.GetMapper();
     _repository      = repository;
 }