Change property value depending on your type

Asked

Viewed 16 times

0

In my Rest application I receive values via json that are converted to a class

My endpoit

[HttpPost]
[Route("Pessoa/Adicionar")]
public JsonResult AdicionarPessoa([FromBody] PessoaCommand body)
{
     try
     {
     _svcAutentication.Autenticar(Request.Headers["Autentication"].ToString(), Request.Headers["DataBase"].ToString());

     body.TratarValoresRecebidos();

     _svcPessoa.Adicionar(body);

     return new JsonResult(body.TipoPessoa == "F" ? _svcPessoa.BuscarPorCpf(body.Cpf) : _svcPessoa.BuscarPorCnpj(body.Cnpj));
     }
     catch (Exception ex)
     {
          Response.StatusCode = 400;
          return new JsonResult(ex.Message);
     }
}

When sending the request, in case any json field is not filled in, it will arrive in my application with its default value, in case booleans will come as false, numeric types will be converted to 0, strings to null and dates to 0001/01/01

The parse value function serves to convert the string types q will come null to empty string "", and convert the dates that came 0001/01/01 to 1900/01/01 and turns some string fields q came filled in uppercase

As I do a repetitive job, I wonder if there is any way to read all properties of my class and depending on the type of it I do some manipulation, in case the conversion of the null strings to "", string filled with some value do a Toupper (in the case of Tipopessoa and Tipoadvogado) and standard dates (0001/01/01) for 1900/01/01

public class PessoaCommand
{
    public decimal CodigoCliente { get; set; }
    public string TipoPessoa { get; set; }
    public bool Advogado { get; set; }
    public bool Captador { get; set; }
    public bool Cobrador { get; set; }
    public bool Cliente { get; set; }
    public bool Fornecedor { get; set; }
    public bool Devedor { get; set; }
    public string Nome { get; set; }
    public string InscricaoEstadual { get; set; }
    public string InscricaoMunicipal { get; set; }
    public string Rg { get; set; }
    public string Login { get; set; }
    public string TipoAdvogado { get; set; }
    public string Observacao { get; set; }
    public decimal GrupoSeguranca { get; set; }
    public decimal Atividade { get; set; }
    public decimal Contato { get; set; } 
    public decimal Oficial { get; set; } 
    public decimal Segurado { get; set; } 
    public decimal GrupoCliente { get; set; }
    public decimal Autor { get; set; } 
    public decimal Reu { get; set; }
    public string CodigoAlteracao { get; set; }
    public DateTime DataAlteracao { get; set; }
    public string CodigoCriacao { get; set; } 
    public DateTime DataCriacao { get; set; }
    public decimal Filial { get; set; }
    public decimal Inativo { get; set; } 
    public int Localizador { get; set; } 
    public int Usuario { get; set; } 
    public decimal Filiais { get; set; }
    public DateTime Nascimento { get; set; }
    public int Setor { get; set; }
    public decimal Amigavel { get; set; } 
    public decimal Juridico { get; set; }
    public decimal Horario { get; set; }
    public DateTime Admissao { get; set; }
    public DateTime Rescisao { get; set; }
    public decimal Banco { get; set; }
    public string Agencia { get; set; }
    public string Conta { get; set; }
    public int Cartorio { get; set; }
    public DateTime Admissao2 { get; set; }
    public DateTime Rescisao2 { get; set; }
    public decimal GrupoCobranca { get; set; }
    public string DigitoConta { get; set; }
    public decimal Cpf { get; set; }
    public decimal Cnpj { get; set; }
    public string ArquivoMorto { get; set; }
    public decimal Cargo { get; set; }
    public decimal Ramal { get; set; }
    public decimal Empresa { get; set; }
    public string Email { get; set; }
    public decimal ValidaHorario { get; set; } 
    public decimal PosJuridico { get; set; } 
    public string Oab { get; set; }
    public decimal CarteiraFoco { get; set; }
    public string DigitoAgencia { get; set; }
    public string OpVar { get; set; }
    public decimal Pis { get; set; }
    public decimal UtilizaSoftPhone { get; set; }
    public decimal CarteiraWo { get; set; }
    public string Senha { get; set; }
    public decimal TipoCentral { get; set; }
    public decimal DiscagemManual { get; set; }
    public decimal CentralAlternativa { get; set; } 
    public decimal Receptivo { get; set; } 
    public decimal MetaDiscador { get; set; }
    public string SapClienteNcNds { get; set; }
    public string SapClienteNrp { get; set; }
    public string SapFornecedorNds { get; set; }
    public int EmailFuncional { get; set; }
    public int TipoUsuario { get; set; }
    public decimal Fiador { get; set; }
    public decimal SegurancaGrupoCobranca { get; set; }

    public void TratarValoresRecebidos()
    {
        TipoPessoa = TipoPessoa?.ToUpper();

        if (InscricaoEstadual == null) InscricaoEstadual = "";

        if (InscricaoMunicipal == null) InscricaoMunicipal = "";

        if (Rg == null) Rg = "";

        if (Login == null) Login = "";

        TipoAdvogado = TipoAdvogado == null ? "" : TipoAdvogado?.ToUpper();

        if (Observacao == null) Observacao = "";

        if (CodigoAlteracao == null) CodigoAlteracao = "";

        if (DataAlteracao == new DateTime(0001, 01, 01)) DataAlteracao = new DateTime(1900, 01, 01);

        if (CodigoCriacao == null) CodigoCriacao = "";

        if (DataCriacao == new DateTime(0001, 01, 01)) DataCriacao = new DateTime(1900, 01, 01);

        if (Nascimento == null) Nascimento = new DateTime(1900, 01, 01);

        if (Admissao == null) Admissao = new DateTime(1900, 01, 01);

        if (Rescisao == null) Admissao = new DateTime(1900, 01, 01);

        if (Agencia == null) Agencia = "";

        if (Conta == null) Conta = "";

        if (Admissao2 == null) Admissao2 = new DateTime(1900, 01, 01);

        if (Rescisao2 == null) Rescisao2 = new DateTime(1900, 01, 01);

        if (DigitoConta == null) DigitoConta = "";

        if (ArquivoMorto == null) ArquivoMorto = "";

        if (Email == null) Email = "";

        if (Oab == null) Oab = "";

        if (DigitoAgencia == null) DigitoAgencia = "";

        if (OpVar == null) OpVar = "";

        if (Senha == null) Senha = "";

        if (SapClienteNcNds == null) SapClienteNcNds = "";

        if (SapClienteNrp == null) SapClienteNrp = "";

        if (SapFornecedorNds == null) SapFornecedorNds = "";
    }
}

1 answer

0

You can use Reflection for that reason.

With Reflection it is possible to treat an object instance in a generic way, without knowing its type and analyzing its members (properties, methods, etc).

Based on the example of this link: system.reflection.propertyinfo.getvalue? view=net-5.0, the code below takes a class and inspects each property. It is a short example, showing how to change the value of a property DateTime and String, just do the same for the other types and with the values you want:

PessoaCommand teste = new PessoaCommand();
teste.Agencia = "123";

ValidarValores(teste);

private static void ValidarValores(Object obj)
{
    Type t = obj.GetType();
    PropertyInfo[] props = t.GetProperties();

    foreach (var prop in props)
    {
        // Se for data, seta a data atual 
        if (prop.PropertyType == typeof(DateTime))
        {
            prop.SetValue(obj, DateTime.Now);
        }

        // se for string e estiver com o valor default, seta um valor
        if (prop.PropertyType == typeof(String))
        {
            if (prop.GetValue(obj) == default(String)) prop.SetValue(obj, "valor default");
        }
    }
}

You can see an example working here: https://dotnetfiddle.net/oWaIOL

Browser other questions tagged

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