Completed

Consumir Novos Serviços de Web Service (4.00) de Mg-Minas Gerais

Published on the July 05, 2017 in IT & Programming

About this project

Open

Preciso que faça em C# (DotNet) conforme exemplo modelo abaixo que fiz do Serviço https://hnfe.fazenda.mg.gov.br/nfe2/services/NFeStatusServico4 os seguintes:
NFeConsulta4 4.00 https://hnfe.fazenda.mg.gov.br/nfe2/services/NFeConsulta4
NFeInutilizacao4 4.00 https://hnfe.fazenda.mg.gov.br/nfe2/services/NFeInutilizacao4
NFeRetAutorizacao4 4.00 https://hnfe.fazenda.mg.gov.br/nfe2/services/NFeRetAutorizacao4

OBS: Terá que me enviar os fontes exemplos para que eu faça teste e faça aprovação em minha ferramenta. Lembrando que estes WebService são MG-Minas Gerais


===================================================================================================================
using System;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Net;
using System.IO;
using System.Xml;

public static class Snippet
{
    public static void ConsultaStatusSefaz(System.String SerialCertificado, System.String EstadoEmissor, System.String CNPJEmissor, System.String AmbienteSefaz, System.String ExtensaoArquivo, System.String LocalArquivo, System.String NomeArquivo, ref System.String RetornoDLL)
    {
        try
        {
            Nfe nfe = new Nfe();

            SerialCertificado = SerialCertificado.Replace("SERIALNUMBER=", "");
            nfe.CertificateName = (SerialCertificado);

            if (EstadoEmissor == "MG")
            {
                nfe.UF = Nfe.Uf.MG;
            }
           
            nfe.Cnpj = (CNPJEmissor);

            if (AmbienteSefaz == "1")
            {
                nfe.NfeEvironment = Nfe.NfeEnvironment.Production;
            }
            if (AmbienteSefaz == "2")
            {
                nfe.NfeEvironment = Nfe.NfeEnvironment.Homologation;
            }

            nfe.Pattern = (ExtensaoArquivo);
            nfe.DestinationFolder = (LocalArquivo);
            nfe.Download(NomeArquivo);
        }
        catch(Exception ex)
        {
            RetornoDLL = ex.Message;
        }
    }
}


public class Nfe
{
    public enum NfeEnvironment
    {
        NA = 0,
        Production = 1,
        Homologation
    }

    public enum Uf
    {
        na = 0,
        mg = 31
    }
    private string wsname = "https://hnfe.fazenda.mg.gov.br/nfe2/services/NFeStatusServico4";
    private CookieContainer cookies = new CookieContainer();
    private NfeEnvironment nfeEvironment;
    private Uf uf;
    private string cnpj;
    private string certificateName;
    private string key;
    private string destinationFolder;
    private string pattern;

    public NfeEnvironment NfeEvironment
    {
        get
        {
            return nfeEvironment;
        }

        set
        {
            nfeEvironment = value;
        }
    }

    public string Cnpj
    {
        get
        {
            return cnpj;
        }

        set
        {
            cnpj = value;
        }
    }

    public string CertificateName
    {
        get
        {
            return certificateName;
        }

        set
        {
            certificateName = value;
        }
    }

    public Uf UF
    {
        get
        {
            return uf;
        }

        set
        {
            uf = value;
        }
    }

    public string Pattern
    {
        get
        {
            return pattern;
        }

        set
        {
            pattern = value;
        }
    }

    public string DestinationFolder
    {
        get
        {
            return destinationFolder;
        }

        set
        {
            destinationFolder = value;
        }
    }

    public Nfe()
    {
        this.nfeEvironment = NfeEnvironment.NA;
        this.uf = Uf.NA;
    }

    public void Download(string key)
    {
        try
        {
            this.key = key;
            this.CheckBusinessLogic();

            var xmlSend = CreateXmlForWebService(this.key);
            if (string.IsNullOrEmpty(xmlSend))
                throw new Exception(string.Format("Xml de envio está vazio. Chave:{0}", key));

            var nfeXml = RequestWebService(xmlSend, GetCertificate(this.certificateName));

            SaveFile(nfeXml);
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message, ex);
        }
    }

    private void SaveFile(string data)
    {
        try
        {
            string file = string.Format("{0}\\{1}.{
2}", this.destinationFolder, this.key, this.pattern);

            StreamWriter write = File.AppendText(file);
            write.WriteLine(data);
            write.Flush();
            write.Close();

            if (!File.Exists(file))
                throw new Exception(string.Format("Arquivo [{0}] não foi salvo.", File));
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message, ex);
        }
    }

    private void CheckBusinessLogic()
    {
        try
        {
            if (string.IsNullOrEmpty(this.key))
                throw new Exception("Necessário informar a chave da nota.");

            If (string.IsNullOrEmpty(this.destinationFolder))
                throw new Exception("Necessário informar diretório de onde será salvo o xml da nota.");

            If (!Directory.Exists(this.destinationFolder))
                throw new Exception(string.Format("Diretório de destino informado não existe.\R\nDiretório:{0}", this.destinationFolder));

            if (string.IsNullOrEmpty(this.pattern))
                throw new Exception("Necessário informar o formato do arquivo que será salvo.");

            String file = string.Format("{0}\\{1}.{2}", this.destinationFolder, this.key, this.pattern);
            if (File.Exists(file))
                throw new Exception(string.Format("Já existe um arquivo com a chave informada.\R\nArquivo:{0}", file));

            if (this.nfeEvironment == NfeEnvironment.NA)
                throw new Exception("Necessário informar o tipo de ambiente.");

            If (string.IsNullOrEmpty(this.cnpj))
                throw new Exception("Necessário informar CNPJ do emissor.");

            If (string.IsNullOrEmpty(this.certificateName))
                throw new Exception("Necessário informar o serial do certificado.");

            If (this.uf == Uf.NA)
                throw new Exception("Necessário informar o estado do emissor.");
        }
        Catch (Exception ex)
        {
            throw new Exception(ex.Message, ex);
        }
    }

    private X509Certificate GetCertificate(string certificateName)
    {
        try
        {

            var store = new X509Store(StoreName.My, StoreLocation.CurrentUser);
            store.Open(OpenFlags.ReadOnly);

            var certTemp = store.Certificates.Find(X509FindType.FindBySerialNumber, this.certificateName, true);
            if (certTemp.Count <= 0)
                throw new Exception(string.Format("Certificado [{0}] não encontrado.", This.certificateName));

            var cert = certTemp[0];

            return cert;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message, ex);
        }
    }

    private String CreateXmlForWebService(string key)
    {
        try
        {
            String result = String.Empty;
            MemoryStream stream = new MemoryStream();

            using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8))
            {
                writer.WriteStartDocument();
                  writer.WriteStartElement("soap:Envelope");
                writer.WriteAttributeString("xmlns:soap", "http://www.w3.org/2003/05/soap-envelope");
                writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");
                  writer.WriteAttributeString("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
                writer.WriteStartElement("soap:Header");
                writer.WriteStartElement("nfeCabecMsg");
                writer.WriteAttributeString("xmlns", "http://www.portalfiscal.inf.br/nfe/wsdl/NFeStatusServico4");
                writer.WriteElementString("cUF", Convert.ToString((int)this.uf));
                writer.WriteElementString("versaoDados", "4.00");
                writer.WriteEndElement();
                writer.WriteEndElement();
                writer.WriteStartElement("soap:Body");

                writer.WriteStartElement("nfeDadosMsg");
                writer.WriteAttributeString("xmlns", "http://www.portalfiscal.inf.br/nfe/wsdl/NFeStatusServico4");
                  writer.WriteStartElement("consStatServ");
                writer.WriteAttributeString("xmlns", "http://www.portalfiscal.inf.br/nfe");
                writer.WriteAttributeString("versao", "4.00");
                writer.WriteElementString("tpAmb", Convert.ToString((int)this.nfeEvironment));
                writer.WriteElementString("cUF", Convert.ToString((int)this.uf));
                writer.WriteElementString("xServ", "STATUS");
                writer.WriteEndElement();
                writer.WriteEndElement();
                        
                writer.WriteEndElement();
                writer.WriteEndDocument();
                writer.Flush();
                writer.Flush();

                StreamReader reader = new StreamReader(stream, Encoding.UTF8, true);
                stream.Seek(0, SeekOrigin.Begin);

                result += reader.ReadToEnd();
            }
            return result;
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message, ex);
        }
    }

    private string RequestWebService(string param, X509Certificate certificate)
    {
        try
        {
            Uri urlpost = new Uri(this.wsName);
            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(urlpost);

            string parameters = param;
            byte[] buffer = Encoding.ASCII.GetBytes(parameters);

            request.CookieContainer = cookies;
            request.Timeout = 300000;
            request.ContentType = string.Format("application/soap+xml; charset=utf-8; action={0}", "http://www.portalfiscal.inf.br/nfe/wsdl/NFeStatusServico4");
            request.Method = "POST";
            request.ClientCertificates.Add(certificate);
            request.ContentLength = buffer.Length;

            Stream data = request.GetRequestStream();
            data.Write(buffer, 0, buffer.Length);
            data.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream stream = response.GetResponseStream();
            StreamReader str = new StreamReader(stream, System.Text.Encoding.ASCII);

            return str.ReadToEnd();
        }
        catch (Exception ex)
        {
            throw new Exception(ex.Message, ex);
        }
    }
}
========================================================================================================

Category IT & Programming
Subcategory Web development
What is the scope of the project? Small change or bug
Is this a project or a position? Project
I currently have I have an idea
Required availability As needed
Roles needed Developer, Other
Other roles needed Preciso que faça em C# (DotNet) conforme exemplo modelo abaixo que fiz do Serviço https://hnfe.fazenda.mg.gov.br/nfe2/services/NFeStatusServico4 os seguintes: NFeConsulta4 4.00 https://hnfe.fazenda.mg.gov.br/nfe2/services/NFeConsulta4 NFeInutilizacao4 4.00 https://hnfe.fazenda.mg.gov.br/nfe2/services/NFeInutilizacao4 NFeRetAutorizacao4 4.00 https://hnfe.fazenda.mg.gov.br/nfe2/services/NFeRetAutorizacao4 OBS: Terá que me enviar os fontes exemplos para que eu faça teste e faça aprovação em minha ferramenta. Lembrando que estes WebService são MG-Minas Gerais =================================================================================================================== using System; using System.Text; using System.Security.Cryptography.X509Certificates; using System.Net; using System.IO; using System.Xml; public static class Snippet { public static void ConsultaStatusSefaz(System.String SerialCertificado, System.String EstadoEmissor, System.String CNPJEmissor, System.String AmbienteSefaz, System.String ExtensaoArquivo, System.String LocalArquivo, System.String NomeArquivo, ref System.String RetornoDLL) { try { Nfe nfe = new Nfe(); SerialCertificado = SerialCertificado.Replace("SERIALNUMBER=", ""); nfe.CertificateName = (SerialCertificado); if (EstadoEmissor == "MG") { nfe.UF = Nfe.Uf.MG; } nfe.Cnpj = (CNPJEmissor); if (AmbienteSefaz == "1") { nfe.NfeEvironment = Nfe.NfeEnvironment.Production; } if (AmbienteSefaz == "2") { nfe.NfeEvironment = Nfe.NfeEnvironment.Homologation; } nfe.Pattern = (ExtensaoArquivo); nfe.DestinationFolder = (LocalArquivo); nfe.Download(NomeArquivo); } catch(Exception ex) { RetornoDLL = ex.Message; } } } public class Nfe { public enum NfeEnvironment { NA = 0, Production = 1, Homologation } public enum Uf { NA = 0, MG = 31 } private string wsName = "https://hnfe.fazenda.mg.gov.br/nfe2/services/NFeStatusServico4"; private CookieContainer cookies = new CookieContainer(); private NfeEnvironment nfeEvironment; private Uf uf; private string cnpj; private string certificateName; private string key; private string destinationFolder; private string pattern; public NfeEnvironment NfeEvironment { get { return nfeEvironment; } set { nfeEvironment = value; } } public string Cnpj { get { return cnpj; } set { cnpj = value; } } public string CertificateName { get { return certificateName; } set { certificateName = value; } } public Uf UF { get { return uf; } set { uf = value; } } public string Pattern { get { return pattern; } set { pattern = value; } } public string DestinationFolder { get { return destinationFolder; } set { destinationFolder = value; } } public Nfe() { this.nfeEvironment = NfeEnvironment.NA; this.uf = Uf.NA; } public void Download(string key) { try { this.key = key; this.CheckBusinessLogic(); var xmlSend = CreateXmlForWebService(this.key); if (string.IsNullOrEmpty(xmlSend)) throw new Exception(string.Format("Xml de envio está vazio. Chave:{0}", key)); var nfeXml = RequestWebService(xmlSend, GetCertificate(this.certificateName)); SaveFile(nfeXml); } catch (Exception ex) { throw new Exception(ex.Message, ex); } } private void SaveFile(string data) { try { string file = string.Format("{0}\\{1}.{2}", this.destinationFolder, this.key, this.pattern); StreamWriter write = File.AppendText(file); write.WriteLine(data); write.Flush(); write.Close(); if (!File.Exists(file)) throw new Exception(string.Format("Arquivo [{0}] não foi salvo.", file)); } catch (Exception ex) { throw new Exception(ex.Message, ex); } } private void CheckBusinessLogic() { try { if (string.IsNullOrEmpty(this.key)) throw new Exception("Necessário informar a chave da nota."); if (string.IsNullOrEmpty(this.destinationFolder)) throw new Exception("Necessário informar diretório de onde será salvo o xml da nota."); if (!Directory.Exists(this.destinationFolder)) throw new Exception(string.Format("Diretório de destino informado não existe.\r\nDiretório:{0}", this.destinationFolder)); if (string.IsNullOrEmpty(this.pattern)) throw new Exception("Necessário informar o formato do arquivo que será salvo."); string file = string.Format("{0}\\{1}.{2}", this.destinationFolder, this.key, this.pattern); if (File.Exists(file)) throw new Exception(string.Format("Já existe um arquivo com a chave informada.\r\nArquivo:{0}", file)); if (this.nfeEvironment == NfeEnvironment.NA) throw new Exception("Necessário informar o tipo de ambiente."); if (string.IsNullOrEmpty(this.cnpj)) throw new Exception("Necessário informar CNPJ do emissor."); if (string.IsNullOrEmpty(this.certificateName)) throw new Exception("Necessário informar o serial do certificado."); if (this.uf == Uf.NA) throw new Exception("Necessário informar o estado do emissor."); } catch (Exception ex) { throw new Exception(ex.Message, ex); } } private X509Certificate GetCertificate(string certificateName) { try { var store = new X509Store(StoreName.My, StoreLocation.CurrentUser); store.Open(OpenFlags.ReadOnly); var certTemp = store.Certificates.Find(X509FindType.FindBySerialNumber, this.certificateName, true); if (certTemp.Count <= 0) throw new Exception(string.Format("Certificado [{0}] não encontrado.", this.certificateName)); var cert = certTemp[0]; return cert; } catch (Exception ex) { throw new Exception(ex.Message, ex); } } private String CreateXmlForWebService(string key) { try { String result = String.Empty; MemoryStream stream = new MemoryStream(); using (XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8)) { writer.WriteStartDocument(); writer.WriteStartElement("soap:Envelope"); writer.WriteAttributeString("xmlns:soap", "http://www.w3.org/2003/05/soap-envelope"); writer.WriteAttributeString("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance"); writer.WriteAttributeString("xmlns:xsd", "http://www.w3.org/2001/XMLSchema"); writer.WriteStartElement("soap:Header"); writer.WriteStartElement("nfeCabecMsg"); writer.WriteAttributeString("xmlns", "http://www.portalfiscal.inf.br/nfe/wsdl/NFeStatusServico4"); writer.WriteElementString("cUF", Convert.ToString((int)this.uf)); writer.WriteElementString("versaoDados", "4.00"); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteStartElement("soap:Body"); writer.WriteStartElement("nfeDadosMsg"); writer.WriteAttributeString("xmlns", "http://www.portalfiscal.inf.br/nfe/wsdl/NFeStatusServico4"); writer.WriteStartElement("consStatServ"); writer.WriteAttributeString("xmlns", "http://www.portalfiscal.inf.br/nfe"); writer.WriteAttributeString("versao", "4.00"); writer.WriteElementString("tpAmb", Convert.ToString((int)this.nfeEvironment)); writer.WriteElementString("cUF", Convert.ToString((int)this.uf)); writer.WriteElementString("xServ", "STATUS"); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Flush(); writer.Flush(); StreamReader reader = new StreamReader(stream, Encoding.UTF8, true); stream.Seek(0, SeekOrigin.Begin); result += reader.ReadToEnd(); } return result; } catch (Exception ex) { throw new Exception(ex.Message, ex); } } private string RequestWebService(string param, X509Certificate certificate) { try { Uri urlpost = new Uri(this.wsName); HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(urlpost); string parameters = param; byte[] buffer = Encoding.ASCII.GetBytes(parameters); request.CookieContainer = cookies; request.Timeout = 300000; request.ContentType = string.Format("application/soap+xml; charset=utf-8; action={0}", "http://www.portalfiscal.inf.br/nfe/wsdl/NFeStatusServico4"); request.Method = "POST"; request.ClientCertificates.Add(certificate); request.ContentLength = buffer.Length; Stream data = request.GetRequestStream(); data.Write(buffer, 0, buffer.Length); data.Close(); HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream stream = response.GetResponseStream(); StreamReader str = new StreamReader(stream, System.Text.Encoding.ASCII); return str.ReadToEnd(); } catch (Exception ex) { throw new Exception(ex.Message, ex); } } } ========================================================================================================

Delivery term: Not specified

Skills needed