Ejemplo n.º 1
0
 public static NFe.ConvertTxt.Emit LoaderEmit(string xml)
 {
     NFe.ConvertTxt.nfeRead read = new NFe.ConvertTxt.nfeRead();
     read.ReadFromString(xml);
     return((NFe.ConvertTxt.Emit)read.nfe.emit);
 }
Ejemplo n.º 2
0
 public static NFe.ConvertTxt.NFe Loader(string xml)
 {
     NFe.ConvertTxt.nfeRead read = new NFe.ConvertTxt.nfeRead();
     read.ReadFromString(xml);
     return(read.nfe);
 }
Ejemplo n.º 3
0
        public static void ExecutaUniDanfe(string nomeArquivoRecebido, DateTime dataEmissaoNFe, NFe.Settings.Empresa emp, Dictionary<string, string> args = null)
        {
#if DEBUG
            Auxiliar.WriteLog("ExecutaUniDanfe: Preparando a execução do UniDANFe p/ o arquivo: \"" + nomeArquivoRecebido + "\"", false);
#endif
            const string erroMsg = "Arquivo {0} não encontrado para impressão do DANFE/DACTE/CCe/DAMDFe {1}";

            //Disparar a geração/impressão do UniDanfe. 03/02/2010 - Wandrey
            if (!string.IsNullOrEmpty(emp.PastaExeUniDanfe) &&
                File.Exists(Path.Combine(emp.PastaExeUniDanfe, "unidanfe.exe")))
            {
                Auxiliar.WriteLog("ExecutaUniDanfe: Preparando a execução do UniDANFe.", false);

                string nomePastaEnviado = string.Empty;
                string arqProcNFe = string.Empty;
                string fExtensao = string.Empty;
                string fEmail = "";
                string fProtocolo = "";
                string tipo = "";
                string tempFile = "";
                string fAuxiliar = "";
                string epecTipo = "";
                bool denegada = false;
                bool temCancelamento = false;
                bool isEPEC = false;

                if (!File.Exists(nomeArquivoRecebido))
                    throw new Exception(string.Format(erroMsg, nomeArquivoRecebido, ""));

                XmlDocument doc = new XmlDocument();
                doc.Load(nomeArquivoRecebido);

                switch (doc.DocumentElement.Name)
                {
                    case "nfeProc":
                        arqProcNFe = nomeArquivoRecebido;
                        break;

                    case "NFe":
                        foreach (var el3 in doc.GetElementsByTagName("ide"))
                        {
                            if (((XmlElement)el3).GetElementsByTagName(NFe.Components.TpcnResources.tpEmis.ToString())[0] != null)
                            {
                                NFe.Components.TipoEmissao tpe = NFe.Components.EnumHelper.StringToEnum<NFe.Components.TipoEmissao>(((XmlElement)el3).GetElementsByTagName(NFe.Components.TpcnResources.tpEmis.ToString())[0].InnerText);
                                if (tpe != (NFe.Components.TipoEmissao)emp.tpEmis)
                                {
                                    throw new Exception("Tipo de emissão do arquivo diferente do tipo de emissão definido na empresa");
                                }
                                tipo = ((XmlElement)el3).GetElementsByTagName(NFe.Components.TpcnResources.mod.ToString())[0].InnerText.Equals("55") ? "nfe" : "nfce";
                            }
                        }
                        arqProcNFe = nomeArquivoRecebido;
                        break;

                    case "cteProc":
                    case "CTe":
                        tipo = "cte";
                        arqProcNFe = nomeArquivoRecebido;
                        ///
                        /// le o protocolo de autorizacao
                        /// 
                        if (doc.DocumentElement.Name.Equals("cteProc"))
                        {
                            foreach (var el3 in doc.GetElementsByTagName("protCTe"))
                            {
                                if (((XmlElement)el3).GetElementsByTagName(NFe.Components.TpcnResources.cStat.ToString())[0] != null)
                                {
                                    string cStat = ((XmlElement)el3).GetElementsByTagName(NFe.Components.TpcnResources.cStat.ToString())[0].InnerText;
                                    switch (cStat)
                                    {
                                        //denegada
                                        case "110":
                                        case "301":
                                        case "302":
                                        case "303":
                                        case "304":
                                        case "305":
                                        case "306":
                                            denegada = true;
                                            break;
                                    }
                                    break;
                                }
                            }
                        }
                        break;

                    case "mdfeProc":
                    case "MDFe":
                        tipo = "mdfe";
                        arqProcNFe = nomeArquivoRecebido;
                        break;

                    case "procCancNFe": //cancelamento antigo
                        {
                            temCancelamento = true;
                            tipo = "nfe";
                            XmlElement cl = (XmlElement)doc.GetElementsByTagName(NFe.Components.TpcnResources.chNFe.ToString())[0];
                            if (cl != null)
                            {
                                tempFile = cl.InnerText;
                                arqProcNFe = cl.InnerText + Propriedade.ExtRetorno.ProcNFe;
                            }
                        }
                        break;

                    case "procEventoNFe":
                    case "procEventoCTe":
                    case "procEventoMDFe":
                        {
                            XmlElement cl = (XmlElement)doc.GetElementsByTagName(NFe.Components.TpcnResources.tpEvento.ToString())[0];
                            if (cl != null)
                            {
                                switch ((NFe.ConvertTxt.tpEventos)Convert.ToInt32(cl.InnerText))
                                {
                                    case ConvertTxt.tpEventos.tpEvCCe:
                                        switch (doc.DocumentElement.Name)
                                        {
                                            case "procEventoCTe":
                                                tipo = "ccte";
                                                cl = (XmlElement)doc.GetElementsByTagName(TpcnResources.chCTe.ToString())[0];
                                                break;
                                            case "procEventoMDFe":
                                                ///
                                                /// nao existe CCe de MDFe, mas fica aqui por enquanto
                                                tipo = "ccemdfe";
                                                cl = null;
                                                break;
                                            default:
                                                tipo = "cce";
                                                cl = (XmlElement)doc.GetElementsByTagName(NFe.Components.TpcnResources.chNFe.ToString())[0];
                                                break;
                                        }
                                        break;

                                    case ConvertTxt.tpEventos.tpEvCancelamentoNFe:
                                        temCancelamento = true;
                                        switch (doc.DocumentElement.Name)
                                        {
                                            case "procEventoCTe":
                                                tipo = "cte";
                                                cl = (XmlElement)doc.GetElementsByTagName(TpcnResources.chCTe.ToString())[0];
                                                break;
                                            case "procEventoMDFe":
                                                tipo = "canmdfe";
                                                cl = (XmlElement)doc.GetElementsByTagName(TpcnResources.chMDFe.ToString())[0];
                                                break;
                                            default:
                                                tipo = "nfe";
                                                cl = (XmlElement)doc.GetElementsByTagName(TpcnResources.chNFe.ToString())[0];
                                                break;
                                        }
                                        break;

                                    case ConvertTxt.tpEventos.tpEvEPEC:
                                        cl = null;
                                        isEPEC = true;
                                        epecTipo = doc.DocumentElement.Name;
                                        break;

                                    default:
                                        ///
                                        /// tipo de evento desconhecido
                                        /// 
                                        throw new Exception("Arquivo de evento " + nomeArquivoRecebido + " desconhecido para impressão do DANFE/DACTE/CCe/DAMDFe");
                                }

                                if (cl != null)
                                {
                                    ///
                                    /// le o nome do arquivo de distribuicao da NFe/CTe
                                    /// 
                                    switch (tipo)
                                    {
                                        case "nfe":
                                        case "cce":
                                            arqProcNFe = cl.InnerText + Propriedade.ExtRetorno.ProcNFe;
                                            break;
                                        case "cte":
                                        case "ccte":
                                            arqProcNFe = cl.InnerText + Propriedade.ExtRetorno.ProcCTe;
                                            break;
                                        case "canmdfe":
                                            arqProcNFe = cl.InnerText + Propriedade.ExtRetorno.ProcMDFe;
                                            break;
                                    }
                                }
                            }
                        }
                        break;

                    default:
                        if (!nomeArquivoRecebido.EndsWith(Propriedade.ExtRetorno.Den))
                        {
                            ///
                            /// tipo de arquivo desconhecido
                            /// 
                            throw new Exception("Arquivo " + nomeArquivoRecebido + " desconhecido para impressão do DANFE/DACTE/CCe/DAMDFe");
                        }
                        break;
                }

                if (isEPEC)
                {
                    switch (epecTipo)
                    {
                        case "procEventoCTe":
                            fExtensao = Propriedade.ExtEnvio.Cte;
                            break;
                        case "procEventoMDFe":
                            fExtensao = Propriedade.ExtEnvio.MDFe;
                            break;
                        default:    //pode ser NFe
                            fExtensao = Propriedade.ExtEnvio.Nfe;
                            break;
                    }
                    string xTemp = Path.GetFileName(Functions.ExtrairNomeArq(nomeArquivoRecebido, Propriedade.ExtRetorno.ProcEventoNFe)) + fExtensao;

                    xTemp = xTemp.Replace("_" + ((int)ConvertTxt.tpEventos.tpEvEPEC).ToString() + "_01", "");

                    ///
                    /// pesquisa pelo arquivo da NFe/NFCe/MDFe/CTe
                    /// 
                    if (File.Exists(Path.Combine(Path.GetDirectoryName(nomeArquivoRecebido), xTemp)))
                        arqProcNFe = Path.Combine(Path.GetDirectoryName(nomeArquivoRecebido), xTemp);
                    else
                    {
                        string[] fTemp = Directory.GetFiles(emp.PastaXmlEnvio, xTemp, SearchOption.AllDirectories);
                        if (fTemp.Length == 0)
                        {
                            fTemp = Directory.GetFiles(emp.PastaXmlEnviado, xTemp, SearchOption.AllDirectories);
                            if (fTemp.Length == 0)
                            {
                                if (emp.tpEmis != (int)NFe.Components.TipoEmissao.teNormal)
                                {
                                    fTemp = Directory.GetFiles(emp.PastaContingencia,
                                                                            Path.GetFileName(Functions.ExtrairNomeArq(nomeArquivoRecebido, Propriedade.ExtEnvio.PedEve) + fExtensao),
                                                                    SearchOption.AllDirectories);
                                    if (fTemp.Length == 0)
                                    {
                                        fTemp = Directory.GetFiles(emp.PastaValidado, xTemp, SearchOption.TopDirectoryOnly);
                                        if (fTemp.Length == 0)
                                            fTemp = Directory.GetFiles(emp.PastaContingencia, xTemp, SearchOption.TopDirectoryOnly);
                                    }
                                }
                                if (fTemp.Length == 0)
                                {
                                    ///
                                    /// OPS!!! EPEC <-> denegado?
                                    /// 
                                    xTemp = Functions.ExtrairNomeArq(xTemp, fExtensao) + Propriedade.ExtRetorno.Den;
                                    if (File.Exists(Path.Combine(Path.GetDirectoryName(nomeArquivoRecebido), xTemp)))
                                        arqProcNFe = Path.Combine(Path.GetDirectoryName(nomeArquivoRecebido), xTemp);
                                    else
                                        fTemp = Directory.GetFiles(emp.PastaXmlEnviado + "\\" + PastaEnviados.Denegados.ToString(), xTemp, SearchOption.AllDirectories);
                                }
                            }
                        }

                        if (fTemp.Length > 0)
                            arqProcNFe = fTemp[0];
                    }
                    if (string.IsNullOrEmpty(arqProcNFe) || !File.Exists(arqProcNFe))
                        throw new Exception(string.Format(erroMsg, xTemp, ""));
                }

                if (nomeArquivoRecebido.EndsWith(Propriedade.ExtRetorno.Den))
                {
                    nomePastaEnviado = Path.GetDirectoryName(nomeArquivoRecebido);
                    arqProcNFe = nomeArquivoRecebido;
                }
                else
                {
                    nomePastaEnviado = emp.PastaXmlEnviado + "\\" +
                        PastaEnviados.Autorizados.ToString() + "\\" +
                        emp.DiretorioSalvarComo.ToString(dataEmissaoNFe);
                }

                if (arqProcNFe != string.Empty)
                {
                    if (File.Exists(Path.Combine(Path.GetDirectoryName(nomeArquivoRecebido), Path.GetFileName(arqProcNFe))))
                        ///
                        /// em sistemas que o XML é gravado no DB, ele pode nao precisar deixar gravado o XML nas pastas de autorizados/denegados
                        /// então eles podem extrair os conteudos do DB e gravá-los em uma pasta qualquer
                        ///
                        arqProcNFe = Path.Combine(Path.GetDirectoryName(nomeArquivoRecebido), Path.GetFileName(arqProcNFe));
                    else

                        if (Path.GetDirectoryName(arqProcNFe) == "")
                            ///
                            /// o nome pode ter sido atribuido pela leitura do evento, então não tem 'path'
                            /// 
                            arqProcNFe = Path.Combine(nomePastaEnviado, arqProcNFe);

                    if (!File.Exists(arqProcNFe))
                    {
                        ///
                        /// arquivo da NFe/NFce não encontrada no 'path' especifico, então pesquisamos na arvore de enviados
                        /// 
                        int ndias = 0;
                        while (ndias < 60)
                        {
                            ///
                            /// usamos o 'DiretorioSalvarComo' para pesquisar pelo arquivo numa pasta baseando-se pela
                            /// dataEmissaoNFe.AddDays(-ndias)
                            /// 
                            string fTemp = Path.Combine(emp.PastaXmlEnviado +
                                                            "\\" + PastaEnviados.Autorizados.ToString() +
                                                            "\\" + getSubFolder(dataEmissaoNFe, ndias, emp.DiretorioSalvarComo), //.ToString(dataEmissaoNFe.AddDays(ndias * -1)),
                                                        Path.GetFileName(arqProcNFe));
                            if (!File.Exists(fTemp))
                                fTemp = Path.Combine(emp.PastaXmlEnviado +
                                                        "\\" + PastaEnviados.Denegados.ToString() +
                                                        "\\" + getSubFolder(dataEmissaoNFe, ndias, emp.DiretorioSalvarComo), //emp.DiretorioSalvarComo.ToString(dataEmissaoNFe.AddDays(ndias * -1)),
                                                     Path.GetFileName(arqProcNFe));
                            ++ndias;
                            if (File.Exists(fTemp))
                            {
                                arqProcNFe = fTemp;
                                break;
                            }
                            if (emp.DiretorioSalvarComo.ToString().Equals("Raiz") || emp.DiretorioSalvarComo.ToString().Equals(""))
                                ///
                                /// ops!
                                /// Se definido como 'Raiz' e nao encontrou, nao precisamos mais pesquisar pelo arquivo em 
                                /// pastas baseado na data de emissao da nota
                                /// 
                                break;
                        }
                    }

                    if (!File.Exists(arqProcNFe))
                        throw new Exception(string.Format(erroMsg, Path.GetFileName(arqProcNFe), ": (" + tipo + ")"));

                    if (tipo.Equals("nfe") || tipo.Equals("nfce") || tipo.Equals("cce") || tipo == "")
                    {
                        ///
                        /// le o xml da NFe/NFCe
                        /// 
                        var nfer = new NFe.ConvertTxt.nfeRead();
                        nfer.ReadFromXml(arqProcNFe);
                        fEmail = nfer.nfe.dest.email;

                        if (tipo == "")
                            tipo = (nfer.nfe.ide.mod == ConvertTxt.TpcnMod.modNFCe ? "nfce" : "nfe");
                        switch (nfer.nfe.protNFe.cStat)
                        {
                            case 110:
                            case 205:
                            case 301:
                            case 302:
                            case 303:
                                denegada = true;
                                break;

                            default:
                                if (arqProcNFe.Equals(nomeArquivoRecebido))
                                    tempFile = nfer.nfe.infNFe.ID.Replace("NFe", "").Replace("NFCe", "");
                                break;
                        }
                    }

                    if (!temCancelamento && !denegada && tempFile != "")
                    {
                        ///
                        /// mandou imprimir pelo -procNFe, -procMDFe ou -procCTe, verifica se tem o xml de cancelamento
                        /// 
                        switch (tipo)
                        {
                            case "nfe":
                            case "nfce":
                                fExtensao = Propriedade.ExtRetorno.ProcEventoNFe;
                                break;
                            case "cte":
                                fExtensao = Propriedade.ExtRetorno.ProcEventoCTe;
                                break;
                            case "mdfe":
                                fExtensao = Propriedade.ExtRetorno.ProcEventoMDFe;
                                break;
                            default:
                                fExtensao = "";
                                break;
                        }
                        if (!string.IsNullOrEmpty(fExtensao))
                        {
                            int ndias = 0;
                            while (ndias < 60)
                            {
                                string filenameCancelamento = tempFile +
                                                                string.Format("_{0}_01{1}",
                                                                    ((int)NFe.ConvertTxt.tpEventos.tpEvCancelamentoNFe).ToString(),
                                                                    fExtensao);

                                ///
                                /// usamos o 'DiretorioSalvarComo' para pesquisar pelo arquivo numa pasta baseando-se pela
                                /// dataEmissaoNFe.AddDays(-ndias)
                                /// 
                                string fTemp = Path.Combine(emp.PastaXmlEnviado +
                                                                "\\" + PastaEnviados.Autorizados.ToString() +
                                                                "\\" + getSubFolder(dataEmissaoNFe, ndias, emp.DiretorioSalvarComo), //emp.DiretorioSalvarComo.ToString(dataEmissaoNFe.AddDays(ndias * -1)),
                                                            Path.GetFileName(filenameCancelamento));
                                if (!File.Exists(fTemp) && tipo.Equals("nfe"))
                                {
                                    ///
                                    /// ops, por evento não foi encontrado, procuramos pelo cancelamento antigo
                                    /// só entramos aqui se o xml de cancelamento nao foi encontrado e se a nota for 'nfe' 
                                    /// já que para outros tipos não existia o cancelamento por '-procCancNFe.xml'.
                                    /// 
                                    filenameCancelamento = tempFile + "-procCancNFe.xml";
                                    fTemp = Path.Combine(emp.PastaXmlEnviado +
                                                            "\\" + PastaEnviados.Autorizados.ToString() +
                                                            "\\" + getSubFolder(dataEmissaoNFe, ndias, emp.DiretorioSalvarComo), //emp.DiretorioSalvarComo.ToString(dataEmissaoNFe.AddDays(ndias * -1)),
                                                         Path.GetFileName(filenameCancelamento));
                                }
                                if (!File.Exists(fTemp))
                                    ///
                                    /// em sistemas que o XML é gravado no DB, ele pode nao precisar deixar gravado o XML nas pastas de autorizados/denegados
                                    /// então eles podem extrair os conteudos do DB e gravá-los em uma pasta qualquer
                                    ///
                                    if (File.Exists(Path.Combine(Path.GetDirectoryName(nomeArquivoRecebido), Path.GetFileName(filenameCancelamento))))
                                        fTemp = Path.Combine(Path.GetDirectoryName(nomeArquivoRecebido), Path.GetFileName(filenameCancelamento));

                                ++ndias;
                                if (File.Exists(fTemp))
                                {
                                    doc.Load(nomeArquivoRecebido = fTemp);
                                    temCancelamento = true;
                                    break;
                                }
                                else
                                {
                                    if (!tipo.Equals("nfe") || emp.DiretorioSalvarComo.ToString().Equals("Raiz") || emp.DiretorioSalvarComo.ToString().Equals(""))
                                        ///
                                        /// ops!
                                        /// Se definido como 'Raiz' e nao encontrou, nao precisamos mais pesquisar pelo arquivo em 
                                        /// pastas baseado na data de emissao da nota e se o tipo de nota nao é 'nfe'
                                        /// 
                                        break;
                                }
                            }
                        }
                    }
                }
                ///
                /// EPEC, CCe e Cancelamento por evento
                /// 
                string ctemp = doc.OuterXml;// File.ReadAllText(nomeArqXMLNFe);
                string dhReg = RetornarConteudoEntre(ctemp, "<dhRegEvento>", "</dhRegEvento>");
                DateTime dhRegEvento = Functions.GetDateTime(dhReg);

                if (dhRegEvento.Year > 1)
                {
                    if ((fProtocolo = RetornarConteudoEntre(ctemp, "</dhRegEvento><nProt>", "</nProt>")) == "")
                        fProtocolo = RetornarConteudoEntre(ctemp, "<nProt>", "</nProt>");

                    fProtocolo += "  " + dhRegEvento.ToString("dd/MM/yyyy HH:mm:ss");
                    if (dhReg.EndsWith("-01:00") ||
                        dhReg.EndsWith("-02:00") ||
                        dhReg.EndsWith("-03:00") ||
                        dhReg.EndsWith("-04:00"))
                    {
                        fProtocolo += dhReg.Substring(dhReg.Length - 6);
                    }
                }

                if (File.Exists(arqProcNFe) || File.Exists(nomeArquivoRecebido))
                {
                    string Args = "";

                    if (tipo.Equals("cte"))
                    {
                        Args += " EE=1";    //EnviarEmail
                        if (!string.IsNullOrEmpty(emp.EmailDanfe) && !emp.AdicionaEmailDanfe)
                            Args += " E=\"" + emp.EmailDanfe + "\"";
                    }
                    else
                    {

                        if (string.IsNullOrEmpty(fEmail))
                        {
                            if (args != null)
                                args.TryGetValue("email", out fEmail);
                        }

                        ///
                        /// se tem um e-mail definido nos parametros da empresa
                        /// 

                        if (!string.IsNullOrEmpty(emp.EmailDanfe))
                        {
                            if (!emp.AdicionaEmailDanfe)
                                fEmail = emp.EmailDanfe;
                            else
                                fEmail += ";" + emp.EmailDanfe;
                        }

                        if (!string.IsNullOrEmpty(fEmail))
                        {
                            fEmail = fEmail.Replace(";", ",").TrimStart(new char[] { ',', ' ' }).TrimEnd(new char[] { ',' });

                            if (!string.IsNullOrEmpty(fEmail))
                            {
                                Args += " EE=1";    //EnviarEmail
                                Args += " E=\"" + fEmail + "\"";
                                Args += " IEX=1";   //IgnorarEmail principal
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(emp.PastaConfigUniDanfe))
                    {
                        Args += " PC=\"" + emp.PastaConfigUniDanfe + "\"";
                    }

                    if (isEPEC)
                        Args += " P=2"; //numero de cópias
                    else
                    {
                        if (args != null)
                        {
                            string copias = "";
                            if (args.TryGetValue("copias", out copias))
                                if (!copias.Equals("-1") && Convert.ToInt32("0" + copias) > 0)
                                    Args += " P=" + copias;
                        }
                    }

                    string configDanfe = "";
                    if (isEPEC)
                    {
                        ///
                        /// define como arquivo principal o XML da NFe/NFCe/MDFe/CTe
                        /// 
                        Args += " A=\"" + arqProcNFe + "\"";
                        ///
                        /// define como arquivo adicional o enviado a esta chamada
                        /// 
                        Args += " AD=\"" + nomeArquivoRecebido + "\"";
                        if (epecTipo.Equals("procEventoMDFe"))
                            Args += " T=damdfe";
                        else
                            if (epecTipo.Equals("procEventoCTe"))
                                Args += " T=dacte";
                            else
                                Args += " T=danfe";
                        configDanfe = emp.ConfiguracaoDanfe;
                    }
                    else
                    {
                        switch (tipo)
                        {
                            case "nfe":
                            case "nfce":
                                Args += " A=\"" + arqProcNFe + "\"";
                                Args += " T=danfe";
                                configDanfe = emp.ConfiguracaoDanfe;
                                break;

                            case "mdfe":
                                Args += " A=\"" + arqProcNFe + "\"";
                                Args += " T=damdfe";
                                configDanfe = emp.ConfiguracaoDanfe;
                                break;

                            case "cte":
                                Args += " A=\"" + arqProcNFe + "\"";
                                Args += " T=dacte";
                                configDanfe = emp.ConfiguracaoDanfe;
                                break;

                            default:
                                if (File.Exists(arqProcNFe))
                                {
                                    switch (tipo)
                                    {
                                        case "cce":
                                        case "ccte":
                                            Args += " A=\"" + nomeArquivoRecebido + "\"";
                                            Args += " N=\"" + arqProcNFe + "\"";
                                            configDanfe = emp.ConfiguracaoCCe;
                                            break;
                                        case "canmdfe":
                                            Args += " A=\"" + nomeArquivoRecebido + "\"";
                                            Args += " N=\"" + arqProcNFe + "\"";
                                            tipo = "";
                                            break;
                                        default:
                                            Args += " A=\"" + arqProcNFe + "\"";
                                            break;
                                    }
                                }
                                else
                                {
                                    Args += " A=\"" + nomeArquivoRecebido + "\"";
                                }
                                if (!string.IsNullOrEmpty(tipo))
                                    Args += " T=" + tipo;
                                break;
                        }
                    }
                    if (!string.IsNullOrEmpty(configDanfe))
                        Args += " C=\"" + configDanfe + "\"";


                    if (temCancelamento)
                        Args += " CC=1"; //Cancelamento

                    string temps = "";

                    if (args != null)
                    {
                        if (args.TryGetValue("impressora", out temps))
                            if (!string.IsNullOrEmpty(temps))
                                Args += " I=\"" + temps + "\"";

                        if (args.TryGetValue("anexos", out temps))
                            if (!string.IsNullOrEmpty(temps))
                            {
                                var an = 1;
                                foreach (var af in temps.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries))
                                {
                                    Args += " anexo" + an.ToString() + "=\"" + af.Replace("\"", "") + "\"";
                                    ++an;
                                    if (an > 6) break;
                                }
                            }

                        if (args.TryGetValue("opcoes", out temps))
                            if (!string.IsNullOrEmpty(temps))
                                Args += " " + temps + " ";   //opcoes do UniDANFE

                        if (args.TryGetValue("np", out temps))
                            if (!string.IsNullOrEmpty(temps))
                            {
                                Args += " NP=\"" + temps + "\"";   //NomePDF
                                Args += " M=0"; //NAO Imprimir
                                Args += " V=0"; //NAO Visualizar
                            }

                        if (args.TryGetValue("pp", out temps))
                            if (!string.IsNullOrEmpty(temps))
                                Args += " PP=\"" + temps + "\"";   //PastaPDF

                        if (args.TryGetValue("plq", out temps))
                            if (!string.IsNullOrEmpty(temps))
                                Args += " plq=\"" + temps + "\"";   //pasta local ou da rede para onde a imagem do QR

                        ///
                        /// define o arquivo de saida de erros
                        /// 
                        args.TryGetValue("auxiliar", out fAuxiliar);
                    }

                    temps = Path.GetFileName(nomeArquivoRecebido).Replace(".xml", "");

                    if (string.IsNullOrEmpty(fAuxiliar))
                    {
                        ///
                        /// formata o arquivo auxiliar com base no arquivo enviado para impressao
                        /// 
                        /// 999999-procNFe.xml -> aux-99999-procNFe-danfe-erros.txt
                        /// 999999-procCTe.xml -> aux-99999-procCTe-danfe-erros.txt
                        /// 999999-procMDFe.xml -> aux-99999-procMDFe-danfe-erros.txt
                        /// 999999-procEventoNFe.xml -> aux-99999-procEventoNFe-danfe-erros.txt
                        /// 
                        fAuxiliar = temps + "-danfe-erros.txt";
                    }

                    //saida erros para arquivo e nome do arquivo de erro
                    Args += " S=A AE=\"" + Path.Combine(emp.PastaXmlRetorno, Path.GetFileName(fAuxiliar)) + "\"";
                    fAuxiliar = "";

                    if (fProtocolo != "")
                    {
                        ///
                        /// formata o arquivo de saida de erros com base no arquivo enviado para impressao
                        /// 999999-procNFe.xml -> aux-99999-procNFe.xml
                        /// 999999-procCTe.xml -> aux-99999-procCTe.xml
                        /// 999999-procMDFe.xml -> aux-99999-procMDFe.xml
                        /// 999999-procEventoNFe.xml -> aux-99999-procEventoNFe.xml
                        /// 
                        fAuxiliar = Path.Combine(Path.GetTempPath(), "aux-" + Path.GetFileName(nomeArquivoRecebido));

                        StringBuilder xmlAux = new StringBuilder();
                        xmlAux.Append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>");
                        xmlAux.Append("<outrasInfDANFe>");
                        xmlAux.AppendFormat("<protocolonfe>{0}</protocolonfe>", fProtocolo);
                        xmlAux.Append("</outrasInfDANFe>");

                        File.WriteAllText(fAuxiliar, xmlAux.ToString());
                        Args += " AU=\"" + fAuxiliar + "\"";
                        ///
                        ///OBS: deveria existir um argumento para excluir o arquivo auxiliar, já que ele é temporario
                    }

                    Auxiliar.WriteLog("ExecutaUniDanfe: Iniciou a execução do UniDANFe.", false);
                    System.Diagnostics.Process.Start(Path.Combine(emp.PastaExeUniDanfe, "unidanfe.exe"), Args);
                    Auxiliar.WriteLog("ExecutaUniDanfe: Encerrou a execução do UniDANFe.", false);

                    if (args != null)
                    {
                        string fFileNameRetornoOk = temps + NFe.Components.Propriedade.ExtRetorno.RetImpressaoDanfe_XML;
                        ///
                        /// formata o arquivo de retorno ao ERP com base no arquivo enviado para impressao
                        /// 999999-procNFe.xml -> 99999-procNFe-ret-danfe.xml
                        /// 999999-procCTe.xml -> 99999-procCTe-ret-danfe.xml
                        /// 999999-procMDFe.xml -> 99999-procMDFe-ret-danfe.xml
                        /// 999999-procEventoNFe.xml -> 99999-procEventoNFe-ret-danfe.xml
                        tipo = "";
                        if (args.TryGetValue("xml", out tipo))
                            if (tipo == "0")    //é TXT?
                                fFileNameRetornoOk = NFe.Components.Functions.ExtrairNomeArq(fFileNameRetornoOk, NFe.Components.Propriedade.ExtRetorno.RetImpressaoDanfe_XML) + NFe.Components.Propriedade.ExtRetorno.RetImpressaoDanfe_TXT;

                        if (fFileNameRetornoOk.EndsWith(NFe.Components.Propriedade.ExtRetorno.RetImpressaoDanfe_XML))
                        {
                            var xml = new XDocument(new XDeclaration("1.0", "utf-8", null),
                                                    new XElement("DANFE",
                                                        new XElement(NFe.Components.TpcnResources.cStat.ToString(), "1"),
                                                        new XElement("Argumentos", Args)));
                            xml.Save(Path.Combine(emp.PastaXmlRetorno, fFileNameRetornoOk));
                        }
                        else
                        {
                            File.WriteAllText(Path.Combine(emp.PastaXmlRetorno, fFileNameRetornoOk), "cStat|1\n\rArgumentos|" + Args + "\n\r");
                        }
                    }

                    if (fAuxiliar != "")
                    {
                        System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
                        worker.WorkerSupportsCancellation = true;
                        worker.RunWorkerCompleted += ((sender, e) => ((System.ComponentModel.BackgroundWorker)sender).Dispose());
                        worker.DoWork += new System.ComponentModel.DoWorkEventHandler(ExcluirArqAuxiliar);
                        worker.RunWorkerAsync(fAuxiliar);
                    }
                }
            }
        }