public static TProjection Traduzir <TProjection>(this ViewModelBase item) where TProjection : class, new() { var adapter = TypeAdapterFactory.CreateAdapter(); return(adapter.Adapt <TProjection>(item)); }
public ProdutoDTO FindProduto(int ProdutoId) { try { if (ProdutoId <= 0) { throw new Exception("Id do usuário inválido."); } var Produto = _produtoRepository.Get(ProdutoId); if (Produto == null) { throw new Exception("Usuário não encontrado."); } var adapter = TypeAdapterFactory.CreateAdapter(); return(adapter.Adapt <Produto, ProdutoDTO>(Produto)); } catch (ApplicationValidationErrorsException ex) { throw ex; } catch (Exception ex) { LoggerFactory.CreateLog().LogError(ex); throw new Exception("O servidor não respondeu."); } }
static void ConfigureFactories() { LoggerFactory.SetCurrent(new Log4netFactory());//ʹÓÃlog4net var typeAdapterFactory = _currentContainer.Resolve <ITypeAdapterFactory>(); TypeAdapterFactory.SetCurrent(typeAdapterFactory); }
public UsuarioDTO AddUsuario(UsuarioDTO usuarioDTO) { try { if (usuarioDTO == null) { throw new Exception("Objeto não instânciado."); } var usuario = UsuarioFactory.CreateUsuario( usuarioDTO.Permissao, usuarioDTO.NomeUsuario, usuarioDTO.Senha, usuarioDTO.Ativo ); SalvarUsuario(usuario); var adapter = TypeAdapterFactory.CreateAdapter(); return(adapter.Adapt <Usuario, UsuarioDTO>(usuario)); } catch (ApplicationValidationErrorsException ex) { throw ex; } catch (Exception ex) { LoggerFactory.CreateLog().LogError(ex); throw new Exception("O servidor não respondeu."); } }
public static IServiceCollection AddDependencies(this IServiceCollection services) { services .AddSingleton <ITypeAdapterFactory, AutoMapperTypeAdapterFactory>() .AddSingleton <ITypeAdapter, AutoMapperTypeAdapter>() .AddDbContext <PizzariaContext>() .AddScoped <IUnitOfWork, UnitOfWork>() .AddTransient <IClienteAppService, ClienteAppService>() .AddTransient <IClienteService, ClienteService>() .AddTransient <IClienteRepository, ClienteRepository>() .AddTransient <IPedidoAppService, PedidoAppService>() .AddTransient <IPedidoService, PedidoService>() .AddTransient <IPedidoRepository, PedidoRepository>() .AddTransient <IPizzaAppService, PizzaAppService>() .AddTransient <IPizzaService, PizzaService>() .AddTransient <IPizzaRepository, PizzaRepository>() .AddTransient <IItemPedidoAppService, ItemPedidoAppService>() .AddTransient <IItemPedidoService, ItemPedidoService>() .AddTransient <IItemPedidoRepository, ItemPedidoRepository>(); var sp = services.BuildServiceProvider(); TypeAdapterFactory.SetCurrent(sp.GetService <ITypeAdapterFactory>()); return(services); }
public void EnumerableSoftwareToListSoftwareDtoAdapter() { //Arrange var software = new Software("the title", "The description", "AB001"); software.ChangeUnitPrice(10); software.IncrementStock(10); software.GenerateNewIdentity(); var softwares = new List <Software>() { software }; //Act var adapter = TypeAdapterFactory.CreateAdapter(); var softwaresDto = adapter.Adapt <IEnumerable <Software>, List <SoftwareDto> >(softwares); //Assert Assert.AreEqual(softwares[0].Id, softwaresDto[0].Id); Assert.AreEqual(softwares[0].Title, softwaresDto[0].Title); Assert.AreEqual(softwares[0].Description, softwaresDto[0].Description); Assert.AreEqual(softwares[0].AmountInStock, softwaresDto[0].AmountInStock); Assert.AreEqual(softwares[0].UnitPrice, softwaresDto[0].UnitPrice); Assert.AreEqual(softwares[0].LicenseCode, softwaresDto[0].LicenseCode); }
public UsuarioDTO FindUsuario(int usuarioId) { try { if (usuarioId <= 0) { throw new Exception("Id do usuário inválido."); } var usuario = _usuarioRepository.Get(usuarioId); if (usuario == null) { throw new Exception("Usuário não encontrado."); } //usuario.Nome = Encryption.DecryptToString(usuario.Nome); var adapter = TypeAdapterFactory.CreateAdapter(); return(adapter.Adapt <Usuario, UsuarioDTO>(usuario)); } catch (ApplicationValidationErrorsException ex) { throw ex; } catch (Exception ex) { LoggerFactory.CreateLog().LogError(ex); throw new Exception("O servidor não respondeu."); } }
public void BlogEnumerableToBlogDTOList() { //Arrange var blog = BlogFactory.CreateBlog("Name", "Url", 0); IEnumerable <Blog> blogs = new List <Blog>() { blog }; //Act ITypeAdapter adapter = TypeAdapterFactory.CreateAdapter(); var dtos = adapter.Adapt <IEnumerable <Blog>, List <BlogDTO> >(blogs); //Assert Assert.NotNull(dtos); Assert.True(dtos.Any()); Assert.True(dtos.Count == 1); var dto = dtos[0]; Assert.Equal(blog.BlogId, dto.BlogId); Assert.Equal(blog.Name, dto.Name); Assert.Equal(blog.Url, dto.Url); Assert.Equal(blog.Rating, dto.Rating); }
public static void InitializeApplication() { var builder = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true); Configuration = builder.Build(); var services = new ServiceCollection() .AddLogging(configure => configure.AddSerilog()); services.AddElasticsearch(Configuration); services.AddScoped <IElasticsearchService, ElasticsearchService>(); services.AddScoped <IBuildingRepository, BuildingRepository>(); services.AddSingleton <ITypeAdapterFactory, AutomapperTypeAdapterFactory>(); var serviceProvider = services.BuildServiceProvider(); var typeAdapterFactory = serviceProvider.GetService <ITypeAdapterFactory>(); if (typeAdapterFactory == null) { throw new Exception("TypeAdapterFactory has not been added"); } TypeAdapterFactory.SetCurrent(typeAdapterFactory); var service = serviceProvider.GetService <IElasticsearchService>(); UploadData(service); }
public ConverterUpdateCommandShould() { var adapterFactory = this.TestHelper.MakeMock <ITypeAdapterFactory>( x => x.Setup(y => y.Create()).Returns(new AutomapperTypeAdapter())); TypeAdapterFactory.SetCurrent(adapterFactory); }
public PessoaDTO FindPessoa(int pessoaId) { try { if (pessoaId <= 0) { throw new Exception("Id do usuário inválido."); } var spec = PessoaSpecifications.Consulta(); var pessoa = _pessoaRepository.Get(pessoaId); if (pessoa == null) { throw new Exception("Usuário não encontrado."); } // pessoa.Nome = Encryption.DecryptToString(pessoa.Nome); var adapter = TypeAdapterFactory.CreateAdapter(); return(adapter.Adapt <Pessoa, PessoaDTO>(pessoa)); } catch (ApplicationValidationErrorsException ex) { throw ex; } catch (Exception ex) { LoggerFactory.CreateLog().LogError(ex); throw new Exception("O servidor não respondeu."); } }
private void ConfigureInfra(IServiceCollection services) { var sp = services.BuildServiceProvider(); var typeAdapterFactory = sp.GetService <ITypeAdapterFactory>(); TypeAdapterFactory.SetCurrent(typeAdapterFactory); }
protected void Initialize() { //initialize engine context EngineContext.Initialize(false); //set dependency resolver var dependencyResolver = new MVCDependencyResolver(); DependencyResolver.SetResolver(dependencyResolver); // initialize cache Cache.InitializeWith(new CacheProviderFactory(ConfigurationManager.AppSettings["CacheProvider"])); ////initialize AutoMapper //Mapper.Initialize(x => x.AddProfile<AutoMapperProfile>()); var typeAdapterFactory = EngineContext.Current.Resolve <ITypeAdapterFactory>(); TypeAdapterFactory.SetCurrent(typeAdapterFactory); // Mapper.AssertConfigurationIsValid(); ConfigureFluentValidation(); }
public static List <TProjection> TraduzirLista <TProjection>(this IEnumerable <ViewModelBase> items) where TProjection : class, new() { var adapter = TypeAdapterFactory.CreateAdapter(); return(adapter.Adapt <List <TProjection> >(items)); }
public void Register(IUnityContainer container) { container.ArgumentNotNull("container"); Log.Trace(Resources.InitializeContainerTask_ConfiguringContainer); container.AddNewExtension <Interception>(); ////container.RegisterTypeAsSingleton<IDeploymentManager, DeploymentManager>(); ////container.RegisterTypePerRequest<IAgentInfoService, DeploymentAgentService>( //// new InterceptionBehavior<PolicyInjectionBehavior>(), //// new Interceptor<InterfaceInterceptor>()); ////container.RegisterTypePerRequest<IDeploymentService, DeploymentAgentService>( //// new InterceptionBehavior<PolicyInjectionBehavior>(), //// new Interceptor<InterfaceInterceptor>()); Log.Trace(Resources.InitializeContainerTask_InitializeServiceLocator); ServiceLocator.SetLocatorProvider(() => new UnityServiceLocator(container)); container.RegisterInstance(ServiceLocator.Current); Log.Trace(Resources.InitializeContainerTask_InitializeProjection); Mapper.AssertConfigurationIsValid(); var factory = new AutoMapperTypeAdapterFactory(); TypeAdapterFactory.SetCurrent(factory); }
public UsoSoloDTO AddUsoSolo(UsoSoloDTO usoSoloDTO) { try { if (usoSoloDTO == null) { throw new ArgumentNullException("UsoSoloDTO"); } var usoSolo = UsoSoloFactory.CreateUsoSolo( usoSoloDTO.Iptu, usoSoloDTO.ImovelRual, usoSoloDTO.EnderecoRural, usoSoloDTO.Complemento, usoSoloDTO.Rua, usoSoloDTO.Quadra, usoSoloDTO.Lote, usoSoloDTO.Bairro, usoSoloDTO.Cnae, usoSoloDTO.Escritorio, usoSoloDTO.Observacoes, DateTime.Now, usoSoloDTO.ResponsavelId ); SalvarUsoSolo(usoSolo); var adapter = TypeAdapterFactory.CreateAdapter(); return(adapter.Adapt <UsoSolo, UsoSoloDTO>(usoSolo)); } catch (Exception ex) { throw ManipuladorDeExcecao.TrateExcecao(ex); } }
public void EnumerableBookToListBookDtoAdapter() { //Arrange var book = new Book("the title", "The description", "Krasis Press", "ABD12"); book.ChangeUnitPrice(10); book.IncrementStock(10); book.GenerateNewIdentity(); var books = new List <Book>() { book }; //Act var adapter = TypeAdapterFactory.CreateAdapter(); var booksDto = adapter.Adapt <IEnumerable <Book>, List <BookDto> >(books); //Assert Assert.AreEqual(books[0].Id, booksDto[0].Id); Assert.AreEqual(books[0].Title, booksDto[0].Title); Assert.AreEqual(books[0].Description, booksDto[0].Description); Assert.AreEqual(books[0].AmountInStock, booksDto[0].AmountInStock); Assert.AreEqual(books[0].UnitPrice, booksDto[0].UnitPrice); Assert.AreEqual(books[0].Isbn, booksDto[0].Isbn); Assert.AreEqual(books[0].Publisher, booksDto[0].Publisher); }
public MarcaProdutoDTO AddMarcaProduto(MarcaProdutoDTO MarcaProdutoDTO) { try { if (MarcaProdutoDTO == null) { throw new Exception("Objeto não instânciado."); } var marcaProduto = ProdutoFactory.CreateMarcaProduto(MarcaProdutoDTO.Nome ); SalvarMarcaProduto(marcaProduto); var adapter = TypeAdapterFactory.CreateAdapter(); return(adapter.Adapt <MarcaProduto, MarcaProdutoDTO>(marcaProduto)); } catch (ApplicationValidationErrorsException ex) { throw ex; } catch (Exception ex) { LoggerFactory.CreateLog().LogError(ex); throw new Exception("O servidor não respondeu."); } }
/// <summary> /// Project a type using a DTO /// </summary> /// <typeparam name="TProjection">The dto projection</typeparam> /// <param name="entity">The source entity to project</param> /// <returns>The projected type</returns> public static TProjection ProjectedAs <TProjection>(this Entity item) where TProjection : class, new() { var adapter = TypeAdapterFactory.CreateAdapter(); return(adapter.Adapt <TProjection>(item)); }
/// <summary> /// projected a enumerable collection of items /// </summary> /// <typeparam name="TProjection"></typeparam> /// <typeparam name="TID"></typeparam> /// <param name="items"></param> /// <returns></returns> public static List <TProjection> ProjectedAsCollection <TProjection, TID>(this IEnumerable <EntityBase <TID> > items) where TProjection : class, new() { var adapter = TypeAdapterFactory.CreateAdapter(); return(adapter.Adapt <List <TProjection> >(items)); }
public UsuarioDTO FindUsuario(string nomeUsuario) { try { if (string.IsNullOrWhiteSpace(nomeUsuario)) { throw new ApplicationValidationErrorsException("Informe o email."); } var usuario = _usuarioRepository.GetFiltered(c => c.NomeUsuario == nomeUsuario).SingleOrDefault(); if (usuario == null) { throw new ApplicationValidationErrorsException("Usuário não encontrado."); } //usuario.Senha = Encryption.DecryptToString(usuario.Senha); var adapter = TypeAdapterFactory.CreateAdapter(); return(adapter.Adapt <Usuario, UsuarioDTO>(usuario)); } catch (ApplicationValidationErrorsException ex) { throw ex; } catch (Exception ex) { LoggerFactory.CreateLog().LogError(ex); throw new Exception("O servidor não respondeu."); } }
public void AdaptEnumerableBankActivityToListBankActivityDTO() { //Arrange BankAccountActivity activity = new BankAccountActivity(); activity.GenerateNewIdentity(); activity.Date = DateTime.Now; activity.Amount = 1000; activity.ActivityDescription = "transfer..."; IEnumerable <BankAccountActivity> activities = new List <BankAccountActivity>() { activity }; //Act ITypeAdapter adapter = TypeAdapterFactory.CreateAdapter(); var activitiesDTO = adapter.Adapt <IEnumerable <BankAccountActivity>, List <BankActivityDTO> >(activities); //Assert Assert.NotNull(activitiesDTO); Assert.True(activitiesDTO.Count() == 1); Assert.Equal(activity.Date, activitiesDTO[0].Date); Assert.Equal(activity.Amount, activitiesDTO[0].Amount); Assert.Equal(activity.ActivityDescription, activitiesDTO[0].ActivityDescription); }
public void CountryEnumerableToCountryDTOList() { //Arrange var country = new Country("Spain", "es-ES"); country.GenerateNewIdentity(); IEnumerable <Country> countries = new List <Country>() { country }; //Act ITypeAdapter adapter = TypeAdapterFactory.CreateAdapter(); var dtos = adapter.Adapt <IEnumerable <Country>, List <CountryDTO> >(countries); //Assert Assert.NotNull(dtos); Assert.True(dtos.Any()); Assert.True(dtos.Count == 1); var dto = dtos[0]; Assert.Equal(country.Id, dto.Id); Assert.Equal(country.CountryName, dto.CountryName); Assert.Equal(country.CountryISOCode, dto.CountryISOCode); }
public void AdaptBankAccountToBankAccountDTO() { //Arrange var country = new Country("Spain", "es-ES"); country.GenerateNewIdentity(); var customer = CustomerFactory.CreateCustomer("jhon", "el rojo", "+3441", "company", country, new Address("", "", "", "")); customer.GenerateNewIdentity(); BankAccount account = new BankAccount(); account.GenerateNewIdentity(); account.BankAccountNumber = new BankAccountNumber("4444", "5555", "3333333333", "02"); account.SetCustomerOwnerOfThisBankAccount(customer); account.DepositMoney(1000, "reason"); account.Lock(); //Act ITypeAdapter adapter = TypeAdapterFactory.CreateAdapter(); var bankAccountDTO = adapter.Adapt <BankAccount, BankAccountDTO>(account); //Assert Assert.Equal(account.Id, bankAccountDTO.Id); Assert.Equal(account.Iban, bankAccountDTO.BankAccountNumber); Assert.Equal(account.Balance, bankAccountDTO.Balance); Assert.Equal(account.Customer.FirstName, bankAccountDTO.CustomerFirstName); Assert.Equal(account.Customer.LastName, bankAccountDTO.CustomerLastName); Assert.Equal(account.Locked, bankAccountDTO.Locked); }
public static List <TProjection> ProjectedAs <TProjection>(this IEnumerable <object> items) where TProjection : class, new() { var adapter = TypeAdapterFactory.CreateAdapter(); return(adapter.Adapt <List <TProjection> >(items)); }
/// <summary> /// projected a enumerable collection of items /// </summary> /// <typeparam name="TProjection">The dtop projection type</typeparam> /// <param name="items">the collection of entity items</param> /// <returns>Projected collection</returns> public static List <TProjection> ProjectedAsCollection <TProjection>(this IList items) where TProjection : class, new() { var adapter = TypeAdapterFactory.CreateAdapter(); return(adapter.Adapt <List <TProjection> >(items)); }
public List <ProdutoDTO> FindProdutos <KProperty>(string texto, Expression <Func <Produto, KProperty> > orderByExpression, bool ascending, int pageIndex, int pageCount) { try { if (pageIndex <= 0 || pageCount <= 0) { throw new Exception("Argumentos da paginação inválidos."); } var spec = ProdutoSpecifications.ConsultaProduto(texto); List <Produto> Produtos = _produtoRepository.GetPaged <KProperty>(pageIndex, pageCount, spec, orderByExpression, ascending).ToList(); var adapter = TypeAdapterFactory.CreateAdapter(); return(adapter.Adapt <List <Produto>, List <ProdutoDTO> >(Produtos)); } catch (ApplicationValidationErrorsException ex) { throw ex; } catch (Exception ex) { LoggerFactory.CreateLog().LogError(ex); throw new Exception("O servidor não respondeu."); } }
public void EnumerableProductToListProductDTOAdapter() { //Arrange var software = new Software("the title", "The description", "AB001"); software.ChangeUnitPrice(10); software.IncrementStock(10); software.GenerateNewIdentity(); var products = new List <Software>() { software }; //Act ITypeAdapter adapter = TypeAdapterFactory.CreateAdapter(); var productsDTO = adapter.Adapt <IEnumerable <Product>, List <ProductDTO> >(products); //Assert Assert.Equal(products[0].Id, productsDTO[0].Id); Assert.Equal(products[0].Title, productsDTO[0].Title); Assert.Equal(products[0].Description, productsDTO[0].Description); Assert.Equal(products[0].AmountInStock, productsDTO[0].AmountInStock); Assert.Equal(products[0].UnitPrice, productsDTO[0].UnitPrice); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddSingleton(Configuration); services.AddTransient <IFlightRepository, FlightRepository>(); services.AddTransient <IAirportRepository, AirportRepository>(); services.AddTransient <IFlightDistanceCalculatorService, FlightDistanceCalculatorService>(); services.AddTransient <IFlightService, FlightService>(); TypeAdapterFactory.SetCurrent(new AutomapperTypeAdapterFactory()); services.AddMvc(); services.AddSwaggerGen(c => { c.SwaggerDoc("v1", new Info { Title = "Flight Service", Version = "v1" }); }); services.AddIdentity <User, Role>().AddDefaultTokenProviders(); services.ConfigureApplicationCookie(cfg => cfg.Events = new CookieAuthenticationEvents { OnRedirectToLogin = ctx => { if (ctx.Request.Path.StartsWithSegments("/api")) { ctx.Response.StatusCode = (int)System.Net.HttpStatusCode.Unauthorized; } return(Task.FromResult(0)); } }); }
static void Initialize() { try { EngineContext.Initialize(false); Log.Info("初始化成功!"); //set dependency resolver //var dependencyResolver = new GrouponDependencyResolver(); //DependencyResolver.SetResolver(dependencyResolver); // initialize cache //普通缓存(可以是EntLib、Memcached Or Redis) //Cache.InitializeWith(new CacheProviderFactory(ConfigurationManager.AppSettings["CacheProvider"])); //分布式缓存(Memcached Or Redis) //DistributedCache.InitializeWith(new CacheProviderFactory(ConfigurationManager.AppSettings["DistributedCacheProvider"])); Config.SetSystemCode("S012"); var typeAdapterFactory = EngineContext.Current.Resolve <ITypeAdapterFactory>(); TypeAdapterFactory.SetCurrent(typeAdapterFactory); } catch (Exception ex) { Log.Exception(ex.InnerException == null ? ex : ex.InnerException); } }