SEFAZ - Nfedistribuicaodfe - c# - Console Application

Asked

Viewed 2,847 times

1

I already inform that I do not understand much of SOAP or XML and I’m only posting the question before studying a lot, because I’m on a very tight deadline.

I need to make an appointment at SEFAZ on webservice Nfedistribuicaodfe.

When opening the classes I found it very confusing so I added a ?WSDL at the end and the webservice I return only with class NFeDistribuicaoDFe.

Within that class I might notice that she hopes to receive one XmlNode. Code of webservice:

        /// <remarks/>
    public event nfeDistDFeInteresseCompletedEventHandler nfeDistDFeInteresseCompleted;

    /// <remarks/>
    [System.Web.Services.Protocols.SoapDocumentMethodAttribute("http://www.portalfiscal.inf.br/nfe/wsdl/NFeDistribuicaoDFe/nfeDistDFeInteresse", RequestNamespace="http://www.portalfiscal.inf.br/nfe/wsdl/NFeDistribuicaoDFe", ResponseNamespace="http://www.portalfiscal.inf.br/nfe/wsdl/NFeDistribuicaoDFe", Use=System.Web.Services.Description.SoapBindingUse.Literal, ParameterStyle=System.Web.Services.Protocols.SoapParameterStyle.Wrapped)]
    public System.Xml.XmlNode nfeDistDFeInteresse(System.Xml.XmlNode nfeDadosMsg) {
        object[] results = this.Invoke("nfeDistDFeInteresse", new object[] {
                    nfeDadosMsg});
        return ((System.Xml.XmlNode)(results[0]));
    }

From what I understand Xmlnode is an XML node which I found strange, because I expected to send the full XML and not only its node, follows the code I did trying to consume this webservice:

        try
        {
            string xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                         "<distDFeInt versao=\"1.00\" xmlns=\"http://www.portalfiscal.inf.br/nfe\">" +      
                         "<tpAmb>1</tpAmb>" +       
                         "<cUFAutor>35</cUFAutor>" +       
                         "<CNPJ>99999999999999</CNPJ>" +      
                         "<distNSU>" +      
                         "<ultNSU>0</ultNSU>" +
                         "</distNSU>" +
                         "</distDFeInt>";

            XmlNode xmlNodeRequest, xmlNodeResponse;
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(xml);

            xmlNodeRequest = doc.FirstChild;

            ServiceNFe.NFeDistribuicaoDFe nFeDistribuicao = new ServiceNFe.NFeDistribuicaoDFe();
            xmlNodeResponse = nFeDistribuicao.nfeDistDFeInteresse(xmlNodeRequest);

        }
        catch (Exception ex)
        {
            Console.WriteLine("Erro: " + ex.Message);
            Console.ReadLine();
        }

Observing:: Servicenfe was created here:

Serviço de Referência WEB

This is the error you make when trying to execute:

Catch

Information from my xmlNodeRequest (You’re just taking the first line, as I expected):

inserir a descrição da imagem aqui

To lost, how do I send the full XML? this code is right?

  • and what is the question ? access the [tour] to know how to ask

  • I forgot to put the error Rovann, I will insert, but in advance it does not work my Xmlnode takes only the first line of XML and when sending my ctch informs that it was not possible to create XML.

2 answers

2


Good people, I managed to make it work in the nail, I will leave my solution here in case someone else goes through this problem:

#region Certificado

            var objCertificadoX509 = new X509Certificate2([CAMINHODO CERTIFICADO], [SENHA]); //Pegando dados do Certificado

            #endregion

            #region XML

            //Instancia
            XmlNode Noderequest, Noderesponse;
            XmlDocument doc = new XmlDocument();
            NFeDistribuicaoDFe distribuicaoDFe = new NFeDistribuicaoDFe();
            string NSU, base64, xmlNota;

            //Criação da String XML
            string xml = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
                         "<distDFeInt versao=\"1.00\" xmlns=\"http://www.portalfiscal.inf.br/nfe\">" +
                         "<tpAmb>1</tpAmb>" +
                         "<cUFAutor>35</cUFAutor>" +
                         "<CNPJ>[CNPJ]</CNPJ>" +
                         "<distNSU>" +
                         "<ultNSU>000000000000000</ultNSU>" +
                         "</distNSU>" +
                         "</distDFeInt>";



            //Convertendo a string em xml
            doc.LoadXml(xml);

            //Transformando o XML em XmlNode (Requisito da API)
            Noderequest = doc.DocumentElement;

            #endregion

            #region Envio API

            //Setando os Atributos de Certificado e endereço de envio
            distribuicaoDFe.ClientCertificates.Add(objCertificadoX509);
            distribuicaoDFe.Url = "https://www1.nfe.fazenda.gov.br/NFeDistribuicaoDFe/NFeDistribuicaoDFe.asmx?wsdl";

            //Envio ao WebService
            Noderesponse = distribuicaoDFe.nfeDistDFeInteresse(Noderequest);

            #endregion

            #region Tratamento
            Noderesponse = Noderequest.FirstChild.LastChild;

            //Percorre todos os Nós do XML principal
            foreach (XmlNode loopNode in Noderesponse)
            {
                NSU = loopNode.Attributes["NSU"].Value;
                base64 = loopNode.InnerText;

                //Descompactar a nota
                byte[] buffer = Convert.FromBase64String(base64);
                xmlNota = Decompress(buffer);

                //Carregar xml descompactado
                doc.LoadXml(xmlNota);

                //Pegando os valores do XML compactado
                XmlNode globalNode = doc.SelectSingleNode("resNFe");
                XmlNode pathImpNode = globalNode.SelectSingleNode("chNFe");
                string chave = pathImpNode.InnerText;
            }

            #endregion

And this is the code that I found on the Internet to unzip the Doczip of the SEFAZ return xml, which is being used there inside FOREACH

 static string  Decompress(byte[] gzip)
    {
        using (GZipStream stream = new GZipStream(new
        MemoryStream(gzip), CompressionMode.Decompress))
        {
            const int size = 4096;
            byte[] buffer = new byte[size];
            using (MemoryStream memory = new MemoryStream())
            {
                int count = 0;
                do
                {
                    count = stream.Read(buffer, 0, size);
                    if (count > 0)
                    {
                        memory.Write(buffer, 0, count);
                    }
                }
                while (count > 0);
                return Encoding.UTF8.GetString(memory.ToArray());

            }
        }
    }

Just remembering also that this is a Consoleapplication, ie, I only assembled the basics of the basic, just to see work, who will use not forget to create the validations Try catch and etc... and there in certificate use methods to get information of certificates installed, it is not a good practice to leave the path and the password in HARDCODE...

0

For me, the code that worked to unzip gzip is:

    private static string GzipDecodeWW(string inputStr)
    {
        byte[] inputBytes = Convert.FromBase64String(inputStr);

        using (var inputStream = new MemoryStream(inputBytes))
        using (var gZipStream = new GZipStream(inputStream, CompressionMode.Decompress))
        using (var outputStream = new MemoryStream())
        {
            gZipStream.CopyTo(outputStream);
            var outputBytes = outputStream.ToArray();

            string decompressed = Encoding.UTF8.GetString(outputBytes);

            return decompressed;
        }
    }

Go for the hot one...

Wide Web - Easy Software

Browser other questions tagged

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