Create an object instance by Activator.Createinstancefrom C#

Asked

Viewed 166 times

0

I need to instantiate the Paismapper class with the following scenario.

DLL running: Projeto.ERP.Desktop

In Formuláriopal I execute the method _repositorioPais.MapperEntity.ToEntityForToEntityGrid(paises).ToList();

Inside the Mapperentity property that is in the Repositoriobase class, I need to create an instance of the Paismapper class, as I could do this?

I tried that way, but it didn’t work.

// I was able to get the instance that way.

private RepositorioMapperBase<TEntity, TEntityModel, TEntityGrid> _mapperEntity = null;
        public RepositorioMapperBase<TEntity, TEntityModel, TEntityGrid> MapperEntity
        {
            get
            {
                if (_mapperEntity == null)
                {
                    string nomeClasseMapper = "Projeto.ERP.Repositorio.Cadastros.Localidade." + typeof(TEntity).Name + "Mapper"; // Fica PaisMapper
                    var b = Activator.CreateInstanceFrom("Projeto.ERP.Repositorio.dll", "Projeto.ERP.Repositorio.Cadastros.Localidade.PaisMapper");
                    _mapperEntity = b.Unwrap() as dynamic;
                }

                return _mapperEntity;
            }
        }

Formulyriac

namespace Projeto.ERP.Desktop.Cadastros.Localidade
{
    public partial class FormularioPais : FormularioBase, IMetodosFormularioBase<Pais>
    {
        public FormularioPais()
        {
            InitializeComponent();
            ConfigurarEventosFormularioBase();

            this.Text = "CADASTRO DE PAISES";
        }

        RepositorioPais _repositorioPais = new RepositorioPais();

        public void LoadFormulario()
        {

        }

        public void BotaoNovo()
        {
            bsPais.Clear();
            bsPais.AddNew();
        }

        public void BotaoEditar()
        {

        }

        public void BotaoSalvar()
        {
            if (bsPais.Current != null)
            {
                Pais paisCurrent = (bsPais.Current as Pais);

                ExecuteValidateModel(paisCurrent);

                if (State == System.Data.Entity.EntityState.Added)
                {
                    _repositorioPais.Inserir(paisCurrent);
                    var registro = _repositorioPais.GetByHandle(paisCurrent.Handle);
                    var registroGrid = _repositorioPais.MapperEntity.ToEntityForToEntityGrid(registro);                        
                    bsGrid.PosicionarRegistroAposInsercao(registroGrid);
                }
                else if (State == System.Data.Entity.EntityState.Modified)
                {
                    _repositorioPais.Atualizar(paisCurrent);
                    var registro = _repositorioPais.GetByHandle(paisCurrent.Handle);
                    var registroGrid = _repositorioPais.MapperEntity.ToEntityForToEntityGrid(registro);
                    bsGrid.PosicionarRegistroAposEdicao(registroGrid);
                }
            }
        }

        public void BotaoCancelar()
        {
            PopularRegistroCorrente();
        }

        public void BotaoExcluir()
        {
            if (bsPais.Current != null)
            {
                long paisHandle = (bsPais.Current as Pais).Handle;                

                if (_repositorioPais.DeletarByHandle(paisHandle))
                {
                    bsPais.RemoveCurrent();
                    bsGrid.RemoveCurrent();
                }
            }
        }

        public void BotaoPesquisar()
        {
            var paises = _repositorioPais.GetAll().ToList();
            var paisesGrid = _repositorioPais.MapperEntity.ToEntityForToEntityGrid(paises).ToList();                
            bsGrid.DataSource = paisesGrid;
        }

        public void LimparCamposUsadosParaNovoCadastro()
        {
            bsPais.Clear();
        }

        public void BsGridCurrentChanged()
        {
            PopularRegistroCorrente();
        }

        private void PopularRegistroCorrente()
        {
            if (bsGrid.Current != null)
             {
                Pais paisCurrent = _repositorioPais.MapperEntity.ToEntityGridForToEntity(bsGrid.Current as PaisGrid);                                    

                bsPais.DataSource = paisCurrent;

                 if (paisCurrent.DataAlteracao == null)
                     Utils.Forms.PreencherFormatarCamposDate(dtAlteracao, null);
             }
        }

        public void ConfigurarCamposGrid()
        {
            CamposGrid.Add("Handle", "Handle");
            CamposGrid.Add("Descricao", "Descrição");
            CamposGrid.Add("DescricaoFormal", "Descrição Formal");
            CamposGrid.Add("SiglaISO2", "Sigla ISO 2");
            CamposGrid.Add("SiglaISO3", "Sigla ISO 3");
            CamposGrid.Add("NumeroISO", "Número ISO");
            CamposGrid.Add("CodigoArea", "Cód. de Área");            
            CamposGrid.Add("DataCadastro", "Dt. Cadastro");
            CamposGrid.Add("DataAlteracao", "Dt. Alteração");
        }

        public void ConfigurarEventosFormularioBase()
        {
            this.EventBotaoNovo += this.BotaoNovo;
            this.EventBotaoEditar += this.BotaoEditar;
            this.EventBotaoSalvar += this.BotaoSalvar;
            this.EventBotaoCancelar += this.BotaoCancelar;
            this.EventBotaoExcluir += this.BotaoExcluir;
            this.EventBotaoPesquisar += this.BotaoPesquisar;            
            this.EventLoadFormulario += this.LoadFormulario;
            this.EventBsGridCurrentChanged += this.BsGridCurrentChanged;
            this.EventLimparCamposUsadosParaNovoCadastro += this.LimparCamposUsadosParaNovoCadastro;
            this.EventPopularPropriedadeCamposGrid += this.ConfigurarCamposGrid;
        }

        private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (MessageBox.Show(string.Format("Essa rotina pegará o arquivo Paises.json para cadastrar ou atualizar todos os paises. {0} {1}Deseja realmente continuar?", Environment.NewLine, Environment.NewLine), "Atenção", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == System.Windows.Forms.DialogResult.Yes)
            {
                try
                {
                    ConsumirPaises.CadastrarOuAtualizarPaisesPorArquivoJson();
                    MessageBox.Show("Atualização realizada com sucesso", "Aviso", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception erro)
                {
                    throw new Exception(erro.Message);
               }
            }
        }

        public void ExecuteValidateModel(Pais entity)
        {
            //_repositorioPais.IsValidateModel(_mapper.Map<Pais, PaisModel>(entity));
        }
    }
}

Repository class, where the executed method is.

namespace Projeto.ERP.Repositorio.Cadastros.Localidade
{
    public partial class RepositorioPais : RepositorioBase<Pais, PaisModel, PaisGrid>
    {
        public override IQueryable<Pais> FindWithDependences(Expression<Func<Pais, bool>> where)
        {
            throw new NotImplementedException();
        }

        public override IQueryable<Pais> GetAllWithDependences()
        {
            throw new NotImplementedException();
        }

        public override Pais GetByHandleWithDependences(long handle)
        {
            throw new NotImplementedException();
        }

    }
}

Repositoriobase class, where I open the instance of the class where the executed method is.

namespace Projeto.ERP.Repositorio.Base
{
    public abstract class RepositorioBase<TEntity, TEntityModel, TEntityGrid> : 
        IDisposable, 
        IRepositorioValidacoes, 
        IRepositorioCRUD<TEntity, TEntityModel>, 
        IRepositioSQL<TEntity>, 
        IRepositorioSQLWithDependences<TEntity>

        where TEntity : EntityBase
        where TEntityModel : class
        where TEntityGrid : class
    {
        public RepositorioBase()
        {
            Context = new ProjetoContext();
        }

        public ProjetoContext Context;

        private RepositorioMapperBase<TEntity, TEntityModel, TEntityGrid> _mapperEntity = null;
        public RepositorioMapperBase<TEntity, TEntityModel, TEntityGrid> MapperEntity
        {
            get
            {
                if (_mapperEntity == null)
                {
                    Assembly assembly = Assembly.GetAssembly(this.GetType());
                    string nomeAssembly = assembly.FullName;
                    string nomeClasseMapper = typeof(TEntity).Name + "Mapper";
                    _mapperEntity = Activator.CreateInstanceFrom(nomeAssembly, nomeClasseMapper) as dynamic;
                }

                return _mapperEntity;
            }
        }

        public virtual void IsValidateModel(TEntityModel entity)
        {
            try
            {
                if (entity != null)
                {
                    string message = string.Empty;

                    var resultadoValidacao = new List<ValidationResult>();
                    var contexto = new ValidationContext(entity, null, null);
                    Validator.TryValidateObject(entity, contexto, resultadoValidacao, true);

                    foreach (var erro in resultadoValidacao)
                        message += string.Format(erro.ErrorMessage + "{0}", Environment.NewLine);

                    if (!string.IsNullOrEmpty(message))
                        throw new Exception(message);
                }                
            }
            catch
            {
                throw;
            }
        }

        public virtual long GetNextHandle()
        {
            try
            {
                var instance = Activator.CreateInstance<TEntity>();
                var tabela = instance.GetType().Name.ToUpper();
                var handle = Context.Database.SqlQuery<long>("SELECT (COALESCE(MAX(HANDLE),0) + 1) HANDLE FROM " + tabela).ToArray();
                return Convert.ToInt64(handle[0]);
            }
            catch (Exception erro)
            {
                throw new Exception(erro.GetException());
            }          
        }

        public virtual long Inserir(TEntity entity)
        {
            try
            {
                entity.Handle = GetNextHandle();
                entity.DataAlteracao = null;
                entity.DataCadastro = DateTime.Now;

                Context.Set<TEntity>().Attach(entity);
                Context.Entry(entity).State = System.Data.Entity.EntityState.Added;
                Context.IsValidateModel();

                return Context.SaveChanges();
            }
            catch (Exception erro)
            {
                throw new Exception(erro.GetException());
            }
        }

        public virtual bool Atualizar(TEntity entity)
        {
            try 
            {
                var entityAux = Context.Set<TEntity>().Find(entity.Handle);
                if (entityAux != null)
                {
                    entity.DataAlteracao = DateTime.Now;
                    entity.DataCadastro = entityAux.DataCadastro;

                    Context.Entry(entityAux).CurrentValues.SetValues(entity);
                }

                Context.Entry(entityAux).State = System.Data.Entity.EntityState.Modified;
                Context.IsValidateModel();                
                Context.SaveChanges();

                return true;                
            }
            catch (Exception erro)
            {
                throw new Exception(erro.GetException());
            }
        }

        public virtual bool DeletarByHandle(long handle)
        {
            try
            {
                ValidarDependencias(handle);

                var entityAux = Context.Set<TEntity>().Find(handle);
                if (entityAux != null)
                    Context.Entry(entityAux).State = System.Data.Entity.EntityState.Deleted;

                Context.SaveChanges();
                return true;
            }
            catch (Exception erro)
            {
                throw new Exception(erro.GetException());
            }
        }

        public virtual bool Deletar(TEntity entity)
        {
            try
            {
                ValidarDependencias(entity.Handle);

                var entityAux = Context.Set<TEntity>().Find(entity.Handle);
                if (entityAux != null)
                    Context.Entry(entityAux).State = System.Data.Entity.EntityState.Deleted;

                Context.SaveChanges();
                return true;                
            }
            catch (Exception erro)
            {
                throw new Exception(erro.GetException());
            }
        }

        public virtual IQueryable<TEntity> GetAll()
        {
            try
            {
                return Context.Set<TEntity>().AsNoTracking().AsQueryable();
            }
            catch (Exception erro)
            {
                throw new Exception(erro.GetException());
            }            
        }

        public virtual IQueryable<TEntity> Find(System.Linq.Expressions.Expression<Func<TEntity, bool>> where)
        {
            try
            {
                return Context.Set<TEntity>().AsNoTracking().Where(where).AsQueryable();
            }
            catch (Exception erro)
            {
                throw new Exception(erro.GetException());
            }            
        }

        public virtual TEntity GetByHandle(long handle)
        {
            try
            {
                return Context.Set<TEntity>().AsNoTracking().AsQueryable().FirstOrDefault(x => x.Handle == handle);
            }
            catch (Exception erro)
            {
                throw new Exception(erro.GetException());
            }            
        }

        public virtual IQueryable<TResult> FindSelect<TResult>(Expression<Func<TEntity, TResult>> select, Expression<Func<TEntity, bool>> where)
        {
            try
            {
                return Context.Set<TEntity>().AsNoTracking().Where(where).Select(select).AsQueryable<TResult>();
            }
            catch (Exception erro)
            {
                throw new Exception(erro.GetException());
            }
        }

        public void Dispose()
        {
            Context = null;
        }

        public abstract void ValidarDependencias(long handle);

        public abstract IQueryable<TEntity> GetAllWithDependences();
        public abstract IQueryable<TEntity> FindWithDependences(Expression<Func<TEntity, bool>> where);
        public abstract TEntity GetByHandleWithDependences(long handle);
    }
}

Paismapper class, where the method is.

namespace Projeto.ERP.Repositorio.Cadastros.Localidade
{
    public class PaisMapper : RepositorioMapperBase<Pais, PaisModel, PaisGrid>
    {
        public override void ConfigureAutoMapper()
        {
            var config = new AutoMapper.MapperConfiguration(cfg =>
            {
                cfg.CreateMap<Pais, PaisModel>()
                .ReverseMap();

                cfg.CreateMap<Pais, PaisGrid>()
                .ReverseMap();
            });

            this.Mapper = config.CreateMapper();
        }
    }

}

Base class of the Paismapper

namespace Projeto.ERP.Repositorio.Base
{
    public abstract class RepositorioMapperBase<TEntity, TEntityModel, TEntityGrid> : IRepositorioMapper<TEntity, TEntityModel, TEntityGrid>
        where TEntity : EntityBase
        where TEntityGrid : class
        where TEntityModel : class
    {
        public RepositorioMapperBase()
        {
            ConfigureAutoMapper();
        }

        private IMapper _mapper = null;

        public IMapper Mapper
        {
            get
            {
                return _mapper;
            }
            set
            {
                if (_mapper == null)
                    _mapper = value;
            }
        }

        public abstract void ConfigureAutoMapper();

        public virtual TEntityGrid ToEntityForToEntityGrid(TEntity entity)
        {
            VerificaSeIMapperFoiConfigurado();
            return AutoMapper.Mapper.Map<TEntity, TEntityGrid>(entity);
        }

        public virtual IEnumerable<TEntityGrid> ToEntityForToEntityGrid(IEnumerable<TEntity> entities)
        {
            VerificaSeIMapperFoiConfigurado();
            return AutoMapper.Mapper.Map<IEnumerable<TEntity>, IEnumerable<TEntityGrid>>(entities);
        }

        public virtual TEntityModel ToEntityForToEntityModel(TEntity entity)
        {
            VerificaSeIMapperFoiConfigurado();
            return AutoMapper.Mapper.Map<TEntity, TEntityModel>(entity);
        }

        public virtual IEnumerable<TEntityModel> ToEntityForToEntityModel(IEnumerable<TEntity> entities)
        {
            VerificaSeIMapperFoiConfigurado();
            return AutoMapper.Mapper.Map<IEnumerable<TEntity>, IEnumerable<TEntityModel>>(entities);
        }

        public virtual TEntity ToEntityGridForToEntity(TEntityGrid entityGrid)
        {
            VerificaSeIMapperFoiConfigurado();
            return AutoMapper.Mapper.Map<TEntityGrid, TEntity>(entityGrid);
        }

        public virtual IEnumerable<TEntity> ToEntityGridForToEntity(IEnumerable<TEntityGrid> entitiesGrid)
        {
            VerificaSeIMapperFoiConfigurado();
            return AutoMapper.Mapper.Map<IEnumerable<TEntityGrid>, IEnumerable<TEntity>>(entitiesGrid);
        }

        public virtual TEntity ToEntityModelForToEntity(TEntityModel entityModel)
        {
            VerificaSeIMapperFoiConfigurado();
            return AutoMapper.Mapper.Map<TEntityModel, TEntity>(entityModel);
        }

        public virtual IEnumerable<TEntity> ToEntityModelForToEntity(IEnumerable<TEntityModel> entitiesModel)
        {
            VerificaSeIMapperFoiConfigurado();
            return AutoMapper.Mapper.Map<IEnumerable<TEntityModel>, IEnumerable<TEntity>>(entitiesModel);
        }

        private void VerificaSeIMapperFoiConfigurado()
        {
            if (_mapper == null)
            {
                throw new Exception("Auto Mapper não configurado.");
            }
        }
    }
}
  • Where is the class RepositorioPais? Just look at this code, you don’t have to do anything but this.

  • @Maniero, I just edited the post, need actually instantiate another class, had put wrong.

  • The namespace is Projeto.ERP.Repositorio.Cadastros.Localidade, now you can use this name wherever you want in your code. I just don’t know if it will be useful. It’s that simple.

  • Disregard the namespace, I need to actually create an instance of Paismapper, but so Enerico, as I put in the example, see if you can understand

  • I came across the following error, with the above code: --------------------------- --------------------------- Error while performing research: It was not possible to load the Paismapper type from Assembly Project.ERP.Repositorio, Version=1.0.0.0, Culture=neutral, Publickeytoken=null. &#xA;---------------------------&#xA;OK &#xA;---------------------------

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.