XML serialization - NFC-e ide element

Asked

Viewed 1,594 times

5

I am trying to serialize an XML of the electronic invoice, but when I arrived at the ide element where is an Array object I unpacked, as I receive the error "Undefined object reference to an instance of an object." Based on an Nfe XML I generated the classes to be serialized, using the Visual Studio automatic option, special edit/paste/Paste XML as classes.

And to test I made the following code.

private void button1_Click_1(object sender, EventArgs e)
    {
        try
        {
            nfeProc nota = new nfeProc();
            nota.versao = 3.10M;
            nota.NFe = new nfeProcNFe();
            nota.NFe.infNFe = new nfeProcNFeInfNFe();
            nota.NFe.infNFe.Id = "NFe13130604501136000136650020000973882010222458";
            nota.NFe.infNFe.versao = 3.10M;

            nota.NFe.infNFe.ide = new nfeProcNFeInfNFeIde();
            nota.NFe.infNFe.ide.cUF = 11;
            nota.NFe.infNFe.ide.cNF = 01022245;
            nota.NFe.infNFe.ide.natOp = "VENDA DE MERCADORIA";
            nota.NFe.infNFe.ide.indPag = 0;
            nota.NFe.infNFe.ide.mod = 65;
            nota.NFe.infNFe.ide.serie = 1;
            nota.NFe.infNFe.ide.nNF = 23354;
            nota.NFe.infNFe.ide.dhEmi = DateTime.Now;
            nota.NFe.infNFe.ide.tpNF = 1;
            nota.NFe.infNFe.ide.idDest = 1;
            nota.NFe.infNFe.ide.cMunFG = 1100114;
            nota.NFe.infNFe.ide.tpImp = 4;
            nota.NFe.infNFe.ide.tpEmis = 1;
            nota.NFe.infNFe.ide.cDV = 8;
            nota.NFe.infNFe.ide.tpAmb = 2;
            nota.NFe.infNFe.ide.finNFe = 1;
            nota.NFe.infNFe.ide.indFinal = 1;
            nota.NFe.infNFe.ide.indPres = 1;
            nota.NFe.infNFe.ide.procEmi = 0;
            nota.NFe.infNFe.ide.verProc = "1.0";

            nota.NFe.infNFe.emit = new nfeProcNFeInfNFeEmit();
            nota.NFe.infNFe.emit.CNPJ = 55555555555555;
            nota.NFe.infNFe.emit.xNome = "LOJA FAKE CONFECCOES";

            nota.NFe.infNFe.emit.enderEmit = new nfeProcNFeInfNFeEmitEnderEmit();
            nota.NFe.infNFe.emit.enderEmit.xLgr = "AVENIDA TESTE I";
            nota.NFe.infNFe.emit.enderEmit.nro = 1257;
            nota.NFe.infNFe.emit.enderEmit.xCpl = "COMERCIO";
            nota.NFe.infNFe.emit.enderEmit.xBairro = "BAIRRO";
            nota.NFe.infNFe.emit.enderEmit.cMun = 1100114;
            nota.NFe.infNFe.emit.enderEmit.xMun = "JARULANDIA";
            nota.NFe.infNFe.emit.enderEmit.UF = "RO";
            nota.NFe.infNFe.emit.enderEmit.CEP = 76590000;
            nota.NFe.infNFe.emit.enderEmit.cPais = 1058;
            nota.NFe.infNFe.emit.enderEmit.xPais = "BRASIL";
            nota.NFe.infNFe.emit.enderEmit.fone = 333333333;
            nota.NFe.infNFe.emit.IE = 2222222;
            nota.NFe.infNFe.emit.CRT = 1;

            nota.NFe.infNFe.dest = new nfeProcNFeInfNFeDest();
            nota.NFe.infNFe.dest.CPF = 98765432198;
            nota.NFe.infNFe.dest.xNome = "";

            nota.NFe.infNFe.dest.enderDest = new nfeProcNFeInfNFeDestEnderDest();
            nota.NFe.infNFe.dest.enderDest.xLgr = "";
            nota.NFe.infNFe.dest.enderDest.nro = 0;
            nota.NFe.infNFe.dest.enderDest.xCpl = "";
            nota.NFe.infNFe.dest.enderDest.xBairro = "";
            nota.NFe.infNFe.dest.enderDest.cMun = 0;
            nota.NFe.infNFe.dest.enderDest.xMun = "";
            nota.NFe.infNFe.dest.enderDest.UF = "";
            nota.NFe.infNFe.dest.enderDest.CEP = 0;
            nota.NFe.infNFe.dest.enderDest.cPais = 0;
            nota.NFe.infNFe.dest.enderDest.xPais = "";
            nota.NFe.infNFe.dest.enderDest.fone = 0;
            nota.NFe.infNFe.dest.indIEDest = 0;

            /*Aqui o problema ao instanciar a classe ide, tentei fazer a instancia usando a linha que está comentada abaixo e deu o mesmo erro*/
            //nota.NFe.infNFe.det = new nfeProcNFeInfNFeDet[1];
            nota.NFe.infNFe.det[1]= new nfeProcNFeInfNFeDet();
            nota.NFe.infNFe.det[0].nItem = 1;

            /*fim do campo com problemas*/

            XmlSerializer ser = new XmlSerializer(typeof(nfeProc));
            FileStream arquivo = new FileStream("xmls/serializado.xml",FileMode.OpenOrCreate);

            ser.Serialize(arquivo,nota);
            MessageBox.Show("Xml Gerado");
        }
        catch (Exception erro)
        {
            MessageBox.Show(erro.Message,"Erro ao gerar NFe");
        }
    }

Example Nfe XML link View or Download XML

I only installed the class det and assigns a value to the attribute nItem.

  • 1

    This exception (Nullreferenceexception) is triggered when you try to access something "something" that has value null, or that you have never assigned any value to her. Go thrashing your code, put breakpoints and notice what is the "thing" (class, variable, property) that you try to access whose value is null. If you can, I recommend reading from here. In your case, from the little information I have, it may be that the nota is empty when you access it, can be the nota.NFe, as well as the nota.NFe.infNFE or the nota.NFe.infNFe.det[n].

  • Your note.NFe.infNFe.det, is an array of ? as it is being created in its class nfeProcNFeInfNFe?

  • Yes what is empty is the note.NFe.infNFe.det[n] but Exception occurs when you create the instance note.NFe.infNFe.det[n]=new note.NFe.infNFe.det(); if you passed this point, then I would just add the values to the attributes of this object.

  • @GOKU Ssjgod is an Array of nfeProcNFeInfNFe, follows the link of the https://drive.google.com/open?id=0B_S5T_wFQISqM2dQZ05ZNHh6dncproject

  • Try generating the nfe classes with XSD.EXE to test, or test the classes in the Zeusnfe library. One more thing, Procnfe is the distribution xml, it already has the authorization protocol. To create the note you must use the Nfe class.

  • Consider adding an answer to your question, if any is satisfactory.

  • @Ronyelias Consider marking the answer as aceita, I’m glad I helped you.

Show 2 more comments

2 answers

7

nota.NFe.infNFe.det expecting a array of nfeProcNFeInfNFeDet a solution would be:

var det = new TNFeInfNFeDet
{
    nItem = "1",
    prod = new TNFeInfNFeDetProd()
    {
        xProd = "Nome produto",
        cProd = "123"
    },
    imposto = new TNFeInfNFeDetImposto(),
    infAdProd = ""
};
var det2 = new TNFeInfNFeDet
{
    nItem = "2",
    prod = new TNFeInfNFeDetProd()
    {
        xProd = "Nome produto 2",
        cProd = "123456"
    },
    imposto = new TNFeInfNFeDetImposto(),
    infAdProd = "nonono"
};
nota.det = new[] { det, det2 };

Upshot:


inserir a descrição da imagem aqui

The class name is different but the principle is the same

6


Analyzing your code, I believe the problem is time to instantiate the infNFe.det

Because before adding elements to Arrya you must instantiate it by stating its size

What have you done

nota.NFe.infNFe.det[1]= new nfeProcNFeInfNFeDet();
nota.NFe.infNFe.det[0].nItem = 1;

As it should be

int tamanho = 1;
nota.NFe.infNFe.det = new TNFeInfNFeDet[tamanho];
int indice = 0;
nota.NFe.infNFe.det[indice]= new nfeProcNFeInfNFeDet();
nota.NFe.infNFe.det[indice].nItem = 1;

Here’s a full example of how I do using integration with a list of products

#region Produtos
var produtos = NotaFiscalEletronicaBusiness2.PesquisarEstoque(nfeEntity.NFeId).OrderBy(a => a.EstoqueProdutoId).ToList();
nfe.infNFe.det = new TNFeInfNFeDet[produtos.Count()];
foreach (var produto in produtos)
{
    decimal valorVenda = produto.ValorVenda;
    decimal valorAcrescimo = Math.Abs(produto.ValorAcrescimo);

    if (produto.AcrescimoDesconto == false)
    {
        valorVenda = produto.ValorVenda + Math.Abs(produto.ValorAcrescimo) - Math.Abs(produto.ValorDesconto);
    }

    TNFeInfNFeDet infNfeDet = new TNFeInfNFeDet();
    infNfeDet.nItem = i.ToString();
    infNfeDet.prod = new TNFeInfNFeDetProd();
    infNfeDet.prod.cProd = produto.ProdutoId.ToString();
    if (produto.CodBarras == null)
        produto.CodBarras = "";
    infNfeDet.prod.cEAN = produto.CodBarras;

    infNfeDet.prod.xProd = produto.Descricao;

    infNfeDet.prod.NCM = produto.CodigoNCM;
    if (produto.CFOPNFe.HasValue)
        infNfeDet.prod.CFOP = GetCFOP(produto.CFOPNFe.Value);
    if (produto.UnidadeComercial != null)
        infNfeDet.prod.uCom = produto.UnidadeComercial.Trim();
    else infNfeDet.prod.uCom = "UN";
    infNfeDet.prod.qCom = Math.Abs(produto.Quantidade).ToString("#0.0000", CultureInfo.InvariantCulture);
    infNfeDet.prod.vUnCom = valorVenda.ToString("#0.0000", CultureInfo.InvariantCulture);

    var vProd = valorVenda * Math.Abs(produto.Quantidade);
    infNfeDet.prod.vProd = vProd.ToString("#0.00", CultureInfo.InvariantCulture);

    decimal vOutros = 0;
    if (produto.AcrescimoDesconto == true)
    {
        vOutros = valorAcrescimo * produto.QuantidadeAbs;
        if (vOutros > 0)
            infNfeDet.prod.vOutro = vOutros.ToString("#0.00", CultureInfo.InvariantCulture);
    }

    infNfeDet.prod.cEANTrib = produto.CodBarras;
    infNfeDet.prod.vUnTrib = valorVenda.ToString("#0.0000", CultureInfo.InvariantCulture);

    infNfeDet.prod.uTrib = infNfeDet.prod.uCom;
    infNfeDet.prod.qTrib = Math.Abs(produto.Quantidade).ToString("#0.0000", CultureInfo.InvariantCulture);

    decimal valorDesconto = 0;
    if (produto.AcrescimoDesconto == true)
    {
        valorDesconto = Math.Abs(produto.ValorDesconto * Math.Abs(produto.Quantidade));
        if (valorDesconto > 0)
            infNfeDet.prod.vDesc = valorDesconto.ToString("#0.00", CultureInfo.InvariantCulture);
    }
    infNfeDet.prod.indTot = TNFeInfNFeDetProdIndTot.Item1;

    TNFeInfNFeDetImpostoICMS icms = SetaIcms(ref vBC, ref vICMS, ref vST, ref vBCST, produto);

    TNFeInfNFeDetImpostoPIS pis = SetaPis();

    var estoqueProdutoIpi = Context.EstoqueProdutoIpi.FirstOrDefault(a => a.EstoqueProdutoIpiId == produto.EstoqueProdutoId);

    TIpi ipi = null;
    if (estoqueProdutoIpi != null)
    {

        ipi = new TIpi();

        if (!String.IsNullOrWhiteSpace(estoqueProdutoIpi.clEnq))
            ipi.clEnq = estoqueProdutoIpi.clEnq;

        if (!String.IsNullOrWhiteSpace(estoqueProdutoIpi.CNPJProd))
            ipi.CNPJProd = estoqueProdutoIpi.CNPJProd;

        if (!String.IsNullOrWhiteSpace(estoqueProdutoIpi.cSelo))
            ipi.cSelo = estoqueProdutoIpi.cSelo;

        if (estoqueProdutoIpi.qSelo.HasValue)
            ipi.qSelo = estoqueProdutoIpi.qSelo.Value.ToString();

        if (!String.IsNullOrWhiteSpace(estoqueProdutoIpi.cEnq))
            ipi.cEnq = estoqueProdutoIpi.cEnq;

        if (estoqueProdutoIpi.CST.StartsWith("IPITRIB"))
        {
            TIpiIPITrib ipiTrib = new TIpiIPITrib();

            switch (estoqueProdutoIpi.CST)
            {
                case "IPITRIB00":
                    ipiTrib.CST = TIpiIPITribCST.Item00;
                    break;

                case "IPITRIB49":
                    ipiTrib.CST = TIpiIPITribCST.Item49;
                    break;

                case "IPITRIB50":
                    ipiTrib.CST = TIpiIPITribCST.Item50;
                    break;

                case "IPITRIB99":
                    ipiTrib.CST = TIpiIPITribCST.Item99;
                    break;
            };

            //Percentual
            if (estoqueProdutoIpi.TipoCalculo.HasValue && estoqueProdutoIpi.TipoCalculo.Value == 0)
            {
                ipiTrib.Items = new string[2];
                ipiTrib.ItemsElementName = new ItemsChoiceType[2];
                if (estoqueProdutoIpi.vBC.HasValue)
                {
                    ipiTrib.Items[0] = estoqueProdutoIpi.vBC.Value.ToString("#0.00", CultureInfo.InvariantCulture);
                    ipiTrib.ItemsElementName[0] = ItemsChoiceType.vBC;
                }


                if (estoqueProdutoIpi.pIPI.HasValue)
                {
                    ipiTrib.Items[1] = estoqueProdutoIpi.pIPI.Value.ToString("#0.00", CultureInfo.InvariantCulture);
                    ipiTrib.ItemsElementName[1] = ItemsChoiceType.pIPI;
                }
            }
            //Valor
            else if (estoqueProdutoIpi.TipoCalculo.HasValue && estoqueProdutoIpi.TipoCalculo.Value == 1)
            {
                ipiTrib.Items = new string[2];
                ipiTrib.ItemsElementName = new ItemsChoiceType[2];

                if (estoqueProdutoIpi.qUnid.HasValue)
                {
                    ipiTrib.Items[0] = estoqueProdutoIpi.qUnid.Value.ToString("#0.0000", CultureInfo.InvariantCulture);
                    ipiTrib.ItemsElementName[0] = ItemsChoiceType.qUnid;
                }

                if (estoqueProdutoIpi.vUnid.HasValue)
                {
                    ipiTrib.Items[1] = estoqueProdutoIpi.vUnid.Value.ToString("#0.0000", CultureInfo.InvariantCulture);
                    ipiTrib.ItemsElementName[1] = ItemsChoiceType.vUnid;
                }
            }

            if (estoqueProdutoIpi.vIPI.HasValue)
            {
                ipiTrib.vIPI = estoqueProdutoIpi.vIPI.Value.ToString("#0.00", CultureInfo.InvariantCulture);
                vIPI += estoqueProdutoIpi.vIPI.Value;
            }

            ipi.Item = ipiTrib;

        }
        else if (estoqueProdutoIpi.CST.StartsWith("IPINT"))
        {
            TIpiIPINT ipiInt = new TIpiIPINT();
            switch (estoqueProdutoIpi.CST)
            {
                case "IPINT01": ipiInt.CST = TIpiIPINTCST.Item01; break;
                case "IPINT02": ipiInt.CST = TIpiIPINTCST.Item02; break;
                case "IPINT03": ipiInt.CST = TIpiIPINTCST.Item03; break;
                case "IPINT04": ipiInt.CST = TIpiIPINTCST.Item04; break;
                case "IPINT05": ipiInt.CST = TIpiIPINTCST.Item05; break;
                case "IPINT51": ipiInt.CST = TIpiIPINTCST.Item51; break;
                case "IPINT52": ipiInt.CST = TIpiIPINTCST.Item52; break;
                case "IPINT53": ipiInt.CST = TIpiIPINTCST.Item53; break;
                case "IPINT54": ipiInt.CST = TIpiIPINTCST.Item54; break;
                case "IPINT55": ipiInt.CST = TIpiIPINTCST.Item55; break;
            };

            ipi.Item = ipiInt;
        }
    }

    infNfeDet.imposto = new TNFeInfNFeDetImposto();
    if (infNfeDet.imposto.Items == null)
    {
        if (ipi != null)
            infNfeDet.imposto.Items = new object[2];
        else infNfeDet.imposto.Items = new object[1];
    }
    infNfeDet.imposto.Items[0] = icms;
    if (ipi != null)
        infNfeDet.imposto.Items[1] = ipi;

    infNfeDet.imposto.PIS = pis;
    infNfeDet.imposto.COFINS = new TNFeInfNFeDetImpostoCOFINS();
    infNfeDet.imposto.COFINS.Item = new TNFeInfNFeDetImpostoCOFINSCOFINSNT();
    (infNfeDet.imposto.COFINS.Item as TNFeInfNFeDetImpostoCOFINSCOFINSNT).CST = TNFeInfNFeDetImpostoCOFINSCOFINSNTCST.Item07;

    nfe.infNFe.det[j] = infNfeDet;
    j++;
    i++;

    valorTotal += (valorVenda * produto.QuantidadeAbs);
    nfeValorDesconto += valorDesconto;
    nfeVoutros += vOutros;
}
#endregion
  • So if I do as in your tip gives the same error, you can see that in the code I posted has the line commented note.NFe.infNFe.det = new nfeProcNFeInfNFeDet[1]; is with size 1 plus I had tried various sizes, then with the answer of rubStackOverflow I realized that my note.NFe.infNFe.det was empty and when trying to instantiate it gave the error. Then I added the data to a list of type Nfeinfnfedet and then added this list to note.NFe.infNFe.det ,getting note.NFe.infNFe.det=listDet.Toarray(); thus all the data in the list are serialized.

  • And I do the validations before I add them to the list. I also did tests after the note line.NFe.infNFe.det=listDet.Toarray(); make a note.infNFe.det[n] = new Nfeinfnfedet(); and fill in the values.

  • So in your example, you don’t instantiate your array and also you instantiate an element at position 1 and then try to assign the nItem in the 0 element, I made an edit in my example, where I declare an Indice = 0 to try to illustrate that you should use the same Index for all items of the same position.

  • If you look at the snippet of code I posted, I work all of it with just the infNfeDet and only at the end I assign to the array nfe.infNFe.det[j] = infNfeDet; and the j is my input. And the size of the array I determine by the amount of products nfe.infNFe.det = new TNFeInfNFeDet[produtos.Count()];

  • Now I understand what you meant in your comment and you really are correct. But it was good that I learned more of a way to make this serialization.

Browser other questions tagged

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