Classe de validação dos XML´s
Exemple #1
0
        /// <summary>
        /// Metodo responsável por invocar o serviço do WebService do SEFAZ
        /// </summary>
        /// <param name="wsProxy">Objeto da classe construida do WSDL</param>
        /// <param name="servicoWS">Objeto da classe de envio do XML</param>
        /// <param name="metodo">Método da classe de envio do XML que faz o envio</param>
        /// <param name="cabecMsg">Objeto da classe de cabecalho do serviço</param>
        /// <param name="servicoNFe">Objeto do Serviço de envio da NFE do UniNFe</param>
        /// <param name="finalArqEnvio">string do final do arquivo a ser enviado. Sem a extensão ".xml"</param>
        /// <param name="finalArqRetorno">string do final do arquivo a ser gravado com o conteúdo do retorno. Sem a extensão ".xml"</param>
        /// <remarks>
        /// Autor: Wandrey Mundin Ferreira
        /// Data: 17/03/2010
        /// </remarks>
        public void Invocar(WebServiceProxy wsProxy,
                            object servicoWS,
                            string metodo,
                            object cabecMsg,
                            object servicoNFe,
                            string finalArqEnvio,
                            string finalArqRetorno)
        {
            int emp = Empresas.FindEmpresaByThread();

            XmlDocument docXML = new XmlDocument();

            // Definir o tipo de serviço da NFe
            Type typeServicoNFe = servicoNFe.GetType();

            Servicos servico = (Servicos)wsProxy.GetProp(servicoNFe, NFe.Components.NFeStrConstants.Servico);

            // Resgatar o nome do arquivo XML a ser enviado para o webservice
            string XmlNfeDadosMsg = (string)(typeServicoNFe.InvokeMember("NomeArquivoXML", System.Reflection.BindingFlags.GetProperty, null, servicoNFe, null));

            // Exclui o Arquivo de Erro
            Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlRetorno + "\\" + Functions.ExtrairNomeArq(XmlNfeDadosMsg, finalArqEnvio + ".xml") + finalArqRetorno + ".err");

            // Validar o Arquivo XML
            ValidarXML validar = new ValidarXML(XmlNfeDadosMsg, Empresas.Configuracoes[emp].UnidadeFederativaCodigo);

            string cResultadoValidacao = validar.ValidarArqXML(XmlNfeDadosMsg);
            if (cResultadoValidacao != "")
            {
                throw new Exception(cResultadoValidacao);
            }

            // Montar o XML de Lote de envio de Notas fiscais
            docXML.Load(XmlNfeDadosMsg);

            // Definir Proxy
            if (ConfiguracaoApp.Proxy)
            {
                wsProxy.SetProp(servicoWS, "Proxy", Proxy.DefinirProxy(ConfiguracaoApp.ProxyServidor, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyPorta, ConfiguracaoApp.DetectarConfiguracaoProxyAuto));
            }

            // Limpa a variável de retorno
            XmlNode XmlRetorno = null;
            string strRetorno = string.Empty;

            //Vou mudar o timeout para evitar que demore a resposta e o uninfe aborte antes de recebe-la. Wandrey 17/09/2009
            //Isso talvez evite de não conseguir o número do recibo se o serviço do SEFAZ estiver lento.
            wsProxy.SetProp(servicoWS, "Timeout", 60000);

            //Verificar antes se tem conexão com a internet, se não tiver já gera uma exceção no padrão já esperado pelo ERP
            if (ConfiguracaoApp.ChecarConexaoInternet)
                if (!Functions.IsConnectedToInternet())
                {
                    //Registrar o erro da validação para o sistema ERP
                    throw new ExceptionSemInternet(ErroPadrao.FalhaInternet, "\r\nArquivo: " + XmlNfeDadosMsg);
                }

            //Atribuir conteúdo para uma propriedade da classe NfeStatusServico2
            switch (servico)
            {
                case Servicos.MDFePedidoConsultaSituacao:
                case Servicos.MDFePedidoSituacaoLote:
                case Servicos.MDFeEnviarLote:
                case Servicos.MDFeConsultaStatusServico:
                case Servicos.MDFeRecepcaoEvento:
                case Servicos.MDFeConsultaNaoEncerrado:
                    wsProxy.SetProp(servicoWS, "mdfeCabecMsgValue", cabecMsg);
                    break;

                case Servicos.CTeInutilizarNumeros:
                case Servicos.CTePedidoConsultaSituacao:
                case Servicos.CTePedidoSituacaoLote:
                case Servicos.CTeEnviarLote:
                case Servicos.CTeRecepcaoEvento:
                case Servicos.CTeConsultaStatusServico:
                    if (wsProxy.GetProp(cabecMsg, NFe.Components.TpcnResources.cUF.ToString()).ToString() == "50") //Mato Grosso do Sul fugiu o padrão nacional
                    {
                        try
                        {
                            wsProxy.SetProp(servicoWS, "cteCabecMsg", cabecMsg);
                        }
                        catch //Se der erro é pq não está no ambiente normal então tem que ser o nome padrão pois Mato Grosso do Sul fugiu o padrão nacional.
                        {
                            wsProxy.SetProp(servicoWS, "cteCabecMsgValue", cabecMsg);
                        }
                    }
                    else
                    {
                        wsProxy.SetProp(servicoWS, "cteCabecMsgValue", cabecMsg);
                    }
                    break;

                case Servicos.DFeEnviar:
                    break;

                case Servicos.LMCAutorizacao:
                    break;

                default:
                    wsProxy.SetProp(servicoWS, "nfeCabecMsgValue", cabecMsg);
                    break;
            }

            // Envio da NFe Compactada - Renan
            if (servico == Servicos.NFeEnviarLoteZip2)
            {
                XmlNfeDadosMsg = XmlNfeDadosMsg + ".gz";
                FileInfo XMLNfeZip = new FileInfo(XmlNfeDadosMsg);
                string encodedData = StreamExtensions.ToBase64(XMLNfeZip);
                XmlRetorno = wsProxy.InvokeXML(servicoWS, metodo, new object[] { encodedData });
            }
            else
                XmlRetorno = wsProxy.InvokeXML(servicoWS, metodo, new object[] { docXML });

            if (XmlRetorno == null)
                throw new Exception("Erro de envio da solicitação do serviço: " + servico.ToString());

            typeServicoNFe.InvokeMember("vStrXmlRetorno", System.Reflection.BindingFlags.SetProperty, null, servicoNFe, new object[] { XmlRetorno.OuterXml });

            // Registra o retorno de acordo com o status obtido
            if (finalArqEnvio != string.Empty && finalArqRetorno != string.Empty)
            {
                typeServicoNFe.InvokeMember("XmlRetorno", System.Reflection.BindingFlags.InvokeMethod, null, servicoNFe, new Object[] { finalArqEnvio + ".xml", finalArqRetorno + ".xml" });
            }
        }
Exemple #2
0
        /// <summary>
        /// Assinar e validar o XML da Nota Fiscal Eletrônica e move para a pasta de assinados
        /// </summary>
        /// <param name="pasta">Nome da pasta onde está o XML a ser validado e assinado</param>
        /// <returns>true = Conseguiu assinar e validar</returns>
        /// <remarks>
        /// Autor: Wandrey Mundin Ferreira
        /// Data: 03/04/2009
        /// </remarks>
        public void AssinarValidarXMLNFe(string pasta)
        {
            int emp = Empresas.FindEmpresaByThread();


            //Criar Pasta dos XML´s a ser enviado em Lote já assinados
            string pastaLoteAssinado = pasta + Propriedade.NomePastaXMLAssinado;

            //Se o arquivo XML já existir na pasta de assinados, vou avisar o ERP que já tem um em andamento
            string arqDestino = pastaLoteAssinado + "\\" + Functions.ExtrairNomeArq(NomeArquivoXML, ".xml") + ".xml";

            try
            {
                //Fazer uma leitura de algumas tags do XML
                DadosNFeClass dadosNFe = this.LerXMLNFe(NomeArquivoXML);
                string ChaveNfe = dadosNFe.chavenfe;
                string TpEmis = dadosNFe.tpEmis;

                //Inserir NFe no XML de controle do fluxo
                FluxoNfe oFluxoNfe = new FluxoNfe();
                if (oFluxoNfe.NfeExiste(ChaveNfe))
                {
                    //Mover o arquivo da pasta em processamento para a pasta de XML´s com erro
                    oAux.MoveArqErro(Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" + PastaEnviados.EmProcessamento.ToString() + "\\" + Functions.ExtrairNomeArq(NomeArquivoXML, ".xml") + ".xml");

                    //Deletar a NFE do arquivo de controle de fluxo
                    oFluxoNfe.ExcluirNfeFluxo(ChaveNfe);

                    //Vou forçar uma exceção, e o ERP através do inicio da mensagem de erro pode tratar e já gerar uma consulta
                    //situação para finalizar o processo. Assim envito perder os XML´s que estão na pasta EmProcessamento
                    //tendo assim a possibilidade de gerar o -procNfe.XML através da consulta situação.
                    //Wandrey 08/10/2009
                    //throw new Exception("NFE NO FLUXO: Esta nota fiscal já está na pasta de Notas Fiscais em processo de envio, desta forma não é possível envia-la novamente. Se a nota fiscal estiver presa no fluxo de envio sem conseguir finalizar o processo, gere um consulta situação da NFe para forçar a finalização.\r\n" + NomeArquivoXML);
                }
                else
                {
                    //Deletar o arquivo XML da pasta de temporários de XML´s com erros se o mesmo existir
                    Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlErro + "\\" + Functions.ExtrairNomeArq(NomeArquivoXML, ".xml") + ".xml");
                }

                //Validações gerais
                ValidacoesGeraisXMLNFe(NomeArquivoXML, dadosNFe);

                //Assinar o arquivo XML
                AssinaturaDigital assDig = new AssinaturaDigital();
                assDig.Assinar(NomeArquivoXML, emp, Convert.ToInt32(dadosNFe.cUF));

                //Adicionar a tag do QRCode
                if (!String.IsNullOrEmpty(Empresas.Configuracoes[emp].IndentificadorCSC) && dadosNFe.mod == "65")
                {
                    QRCode qrCode = new QRCode(Empresas.Configuracoes[emp].IndentificadorCSC, Empresas.Configuracoes[emp].TokenCSC, NomeArquivoXML);

                    if (qrCode.CalcularLink())
                    {
                        string url = Empresas.Configuracoes[emp].AmbienteCodigo == (int)NFe.Components.TipoAmbiente.taHomologacao ? Empresas.Configuracoes[emp].URLConsultaDFe.UrlNFCeH : Empresas.Configuracoes[emp].URLConsultaDFe.UrlNFCe;
                        qrCode.GerarLinkConsulta(url);
                        qrCode.AddLinkQRCode();
                    }
                }

                // Validar o Arquivo XML da NFe com os Schemas se estiver assinado
                ValidarXML validar = new ValidarXML(NomeArquivoXML, Convert.ToInt32(dadosNFe.cUF));
                string cResultadoValidacao = validar.ValidarArqXML(NomeArquivoXML);
                if (cResultadoValidacao != "")
                {
                    //Registrar o erro da validação do schema para o sistema ERP
                    throw new Exception(cResultadoValidacao);
                }

                //Mover o arquivo XML da pasta de lote para a pasta de XML´s assinados
                //Se a pasta de assinados não existir, vamos criar
                if (!Directory.Exists(pastaLoteAssinado))
                {
                    Directory.CreateDirectory(pastaLoteAssinado);
                }

                FileInfo fiDestino = new FileInfo(arqDestino);

                if (!File.Exists(arqDestino) || (long)DateTime.Now.Subtract(fiDestino.LastWriteTime).TotalMilliseconds >= 60000) //60.000 ms que corresponde á 60 segundos que corresponde a 1 minuto
                {
                    //Mover o arquivo para a pasta de XML´s assinados
                    Functions.Move(NomeArquivoXML, arqDestino);

                    oFluxoNfe.InserirNfeFluxo(ChaveNfe, dadosNFe.mod, arqDestino);
                }

                else
                {
                    oFluxoNfe.InserirNfeFluxo(ChaveNfe, dadosNFe.mod, arqDestino);

                    throw new IOException("Esta nota fiscal já está na pasta de Notas Fiscais assinadas e em processo de envio, desta forma não é possível enviar a mesma novamente.\r\n" +
                        NomeArquivoXML);
                }
            }
            catch (Exception ex)
            {
                try
                {
                    string extFinal = Propriedade.ExtEnvio.Nfe;
                    string extErro = Propriedade.ExtRetorno.Nfe_ERR;
                    switch (Servico)
                    {
                        case Servicos.MDFeAssinarValidarEnvioEmLote:
                        case Servicos.MDFeMontarLoteUm:
                            extFinal = Propriedade.ExtEnvio.MDFe;
                            extErro = Propriedade.ExtRetorno.MDFe_ERR;
                            break;

                        case Servicos.CTeAssinarValidarEnvioEmLote:
                        case Servicos.CTeMontarLoteUm:
                            extFinal = Propriedade.ExtEnvio.Cte;
                            extErro = Propriedade.ExtRetorno.Cte_ERR;
                            break;
                    }

                    TFunctions.GravarArqErroServico(NomeArquivoXML, extFinal, extErro, ex);

                    //Se já foi movido o XML da Nota Fiscal para a pasta em Processamento, vou ter que 
                    //forçar mover para a pasta de XML com erro neste ponto.
                    oAux.MoveArqErro(arqDestino);
                }
                catch (Exception exx)
                {
                    Auxiliar.WriteLog(exx.Message, true);
                    //Se ocorrer algum erro na hora de tentar gravar o XML de erro para o ERP ou mover o arquivo XML para a pasta de XML com erro, não 
                    //vou poder fazer nada, pq foi algum erro de rede, permissão de acesso a pasta ou arquivo, etc.
                    //Wandey 13/03/2010
                }
                throw;
            }
        }
Exemple #3
0
        /// <summary>
        /// Metodo responsável por invocar o serviço do WebService do SEFAZ
        /// </summary>
        /// <param name="wsProxy">Objeto da classe construida do WSDL</param>
        /// <param name="servicoWS">Objeto da classe de envio do XML</param>
        /// <param name="metodo">Método da classe de envio do XML que faz o envio</param>
        /// <param name="cabecMsg">Objeto da classe de cabecalho do serviço</param>
        /// <param name="servicoNFe">Objeto do Serviço de envio da NFE do UniNFe</param>
        /// <param name="finalArqEnvio">string do final do arquivo a ser enviado. Sem a extensão ".xml"</param>
        /// <param name="finalArqRetorno">string do final do arquivo a ser gravado com o conteúdo do retorno. Sem a extensão ".xml"</param>
        /// <remarks>
        /// Autor: Wandrey Mundin Ferreira
        /// Data: 17/03/2010
        /// </remarks>
        public void InvocarNFSe(WebServiceProxy wsProxy,
                            object servicoWS,
                            string metodo,
                            string cabecMsg,
                            object servicoNFe,
                            string finalArqEnvio,
                            string finalArqRetorno,
                            PadroesNFSe padraoNFSe,
                            Servicos servicoNFSe)
        {
            int emp = Empresas.FindEmpresaByThread();

            XmlDocument docXML = new XmlDocument();

            // Definir o tipo de serviço da NFe
            Type typeServicoNFe = servicoNFe.GetType();

            // Resgatar o nome do arquivo XML a ser enviado para o webservice
            string XmlNfeDadosMsg = (string)(typeServicoNFe.InvokeMember("NomeArquivoXML", System.Reflection.BindingFlags.GetProperty, null, servicoNFe, null));

            // Exclui o Arquivo de Erro
            Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlRetorno + "\\" + Functions.ExtrairNomeArq(XmlNfeDadosMsg, finalArqEnvio + ".xml") + finalArqRetorno + ".err");

            // Validar o Arquivo XML
            ValidarXML validar = new ValidarXML(XmlNfeDadosMsg, Empresas.Configuracoes[emp].UnidadeFederativaCodigo);
            string cResultadoValidacao = validar.ValidarArqXML(XmlNfeDadosMsg);
            if (cResultadoValidacao != "")
            {
                switch (padraoNFSe)
                {
                    case PadroesNFSe.ISSONLINE4R:
                        break;
                    case PadroesNFSe.SMARAPD:
                        break;
                    default:
                        throw new Exception(cResultadoValidacao);
                }

            }

            // Montar o XML de Lote de envio de Notas fiscais
            docXML.Load(XmlNfeDadosMsg);

            // Definir Proxy
            if (ConfiguracaoApp.Proxy)
                if (padraoNFSe != PadroesNFSe.BETHA)
                {
                    wsProxy.SetProp(servicoWS, "Proxy", Proxy.DefinirProxy(ConfiguracaoApp.ProxyServidor, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyPorta, ConfiguracaoApp.DetectarConfiguracaoProxyAuto));
                }
                else
                {
                    wsProxy.Betha.Proxy = Proxy.DefinirProxy(ConfiguracaoApp.ProxyServidor, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyPorta, ConfiguracaoApp.DetectarConfiguracaoProxyAuto);
                }

            // Limpa a variável de retorno
            string strRetorno = string.Empty;

            //Vou mudar o timeout para evitar que demore a resposta e o uninfe aborte antes de recebe-la. Wandrey 17/09/2009
            //Isso talvez evite de não conseguir o número do recibo se o serviço do SEFAZ estiver lento.
            if (padraoNFSe != PadroesNFSe.BETHA)
                wsProxy.SetProp(servicoWS, "Timeout", 120000);

            //Verificar antes se tem conexão com a internet, se não tiver já gera uma exceção no padrão já esperado pelo ERP
            if (ConfiguracaoApp.ChecarConexaoInternet)  //danasa: 12/2013
                if (!Functions.IsConnectedToInternet())
                {
                    //Registrar o erro da validação para o sistema ERP
                    throw new ExceptionSemInternet(ErroPadrao.FalhaInternet, "\r\nArquivo: " + XmlNfeDadosMsg);
                }

            //Invocar o membro
            switch (padraoNFSe)
            {
                #region Padrão BETHA
                case PadroesNFSe.BETHA:
                    switch (metodo)
                    {
                        case "ConsultarSituacaoLoteRps":
                            strRetorno = wsProxy.Betha.ConsultarSituacaoLoteRps(docXML, Empresas.Configuracoes[emp].AmbienteCodigo);
                            break;

                        case "ConsultarLoteRps":
                            strRetorno = wsProxy.Betha.ConsultarLoteRps(docXML, Empresas.Configuracoes[emp].AmbienteCodigo);
                            break;

                        case "CancelarNfse":
                            strRetorno = wsProxy.Betha.CancelarNfse(docXML, Empresas.Configuracoes[emp].AmbienteCodigo);
                            break;

                        case "ConsultarNfse":
                            strRetorno = wsProxy.Betha.ConsultarNfse(docXML, Empresas.Configuracoes[emp].AmbienteCodigo);
                            break;

                        case "ConsultarNfsePorRps":
                            strRetorno = wsProxy.Betha.ConsultarNfsePorRps(docXML, Empresas.Configuracoes[emp].AmbienteCodigo);
                            break;

                        case "RecepcionarLoteRps":
                            strRetorno = wsProxy.Betha.RecepcionarLoteRps(docXML, Empresas.Configuracoes[emp].AmbienteCodigo);
                            break;
                    }
                    break;
                #endregion

                #region Padrão ISSONLINE
                case PadroesNFSe.ISSONLINE:
                    int operacao;
                    string senhaWs = Functions.GetMD5Hash(Empresas.Configuracoes[emp].SenhaWS);

                    switch (servicoNFSe)
                    {
                        case Servicos.NFSeRecepcionarLoteRps:
                            operacao = 1;
                            break;
                        case Servicos.NFSeCancelar:
                            operacao = 2;
                            break;
                        default:
                            operacao = 3;
                            break;
                    }

                    strRetorno = wsProxy.InvokeStr(servicoWS, metodo, new object[] { Convert.ToSByte(operacao), Empresas.Configuracoes[emp].UsuarioWS, senhaWs, docXML.OuterXml });
                    break;
                #endregion

                #region Padrão Blumenau-SC
                case PadroesNFSe.BLUMENAU_SC:
                    strRetorno = wsProxy.InvokeStr(servicoWS, metodo, new object[] { 1, docXML.OuterXml });
                    break;
                #endregion

                #region Padrão Paulistana
                case PadroesNFSe.PAULISTANA:
                    strRetorno = wsProxy.InvokeStr(servicoWS, metodo, new object[] { 1, docXML.OuterXml });
                    break;
                #endregion

                #region Demais padrões
                case PadroesNFSe.TECNOSISTEMAS:
                    strRetorno = wsProxy.InvokeStr(servicoWS, metodo, new object[] { docXML.OuterXml, cabecMsg.ToString() });
                    break;

                case PadroesNFSe.SMARAPD:
                    if (metodo == "nfdEntradaCancelar")
                        strRetorno = wsProxy.InvokeStr(servicoWS, metodo, new object[] { Empresas.Configuracoes[emp].UsuarioWS,
                        TFunctions.EncryptSHA1(Empresas.Configuracoes[emp].SenhaWS),
                        docXML.OuterXml });
                    else
                        strRetorno = wsProxy.InvokeStr(servicoWS, metodo, new object[] { Empresas.Configuracoes[emp].UsuarioWS,
                        TFunctions.EncryptSHA1(Empresas.Configuracoes[emp].SenhaWS),
                        Empresas.Configuracoes[emp].UnidadeFederativaCodigo, 
                        docXML.OuterXml });
                    break;

                case PadroesNFSe.ISSWEB:
                    string versao = docXML.DocumentElement.GetElementsByTagName("Versao")[0].InnerText;
                    string cnpj = docXML.DocumentElement.GetElementsByTagName("CNPJCPFPrestador")[0].InnerText;
                    strRetorno = wsProxy.InvokeStr(servicoWS, metodo, new object[] { cnpj, docXML.OuterXml, versao });
                    break;

                case PadroesNFSe.GINFES:
                case PadroesNFSe.THEMA:
                case PadroesNFSe.SALVADOR_BA:
                case PadroesNFSe.CANOAS_RS:
                case PadroesNFSe.ISSNET:
                default:
                    if (string.IsNullOrEmpty(cabecMsg))
                        strRetorno = wsProxy.InvokeStr(servicoWS, metodo, new object[] { docXML.OuterXml });
                    else
                        strRetorno = wsProxy.InvokeStr(servicoWS, metodo, new object[] { cabecMsg.ToString(), docXML.OuterXml });
                    break;
                #endregion
            }
            #region gerar arquivos assinados(somente debug)
#if DEBUG
            string path = Application.StartupPath + "\\teste_assintura\\";

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            StreamWriter sw = new StreamWriter(path + "nfseMsg_assinado.xml", true);
            sw.Write(docXML.OuterXml);
            sw.Close();

            StreamWriter sw2 = new StreamWriter(path + "cabecMsg_assinado.xml", true);
            sw2.Write(cabecMsg.ToString());
            sw2.Close();
#endif
            #endregion

            //Atualizar o atributo do serviço da Nfe com o conteúdo retornado do webservice do sefaz                  
            typeServicoNFe.InvokeMember("vStrXmlRetorno", System.Reflection.BindingFlags.SetProperty, null, servicoNFe, new object[] { strRetorno });

            // Registra o retorno de acordo com o status obtido
            if (finalArqEnvio != string.Empty && finalArqRetorno != string.Empty)
            {
                typeServicoNFe.InvokeMember("XmlRetorno", System.Reflection.BindingFlags.InvokeMethod, null, servicoNFe, new Object[] { finalArqEnvio + ".xml", finalArqRetorno + ".xml" });
            }
        }
Exemple #4
0
        /// <summary>
        /// Executa as tarefas pertinentes ao processo de somente assinar e validar os arquivos
        /// </summary>
        /// <param name="arquivo">Arquivo a ser assinado e validado</param>
        protected void AssinarValidar(string arquivo)
        {
            try
            {
                int emp = Empresas.FindEmpresaByThread();

                Functions.DeletarArquivo(Path.Combine(Empresas.Configuracoes[emp].PastaValidado, Path.GetFileName(Path.ChangeExtension(arquivo, ".xml"))));
                Functions.DeletarArquivo(Path.Combine(Empresas.Configuracoes[emp].PastaXmlErro, Path.GetFileName(Path.ChangeExtension(arquivo, ".xml"))));
                Functions.DeletarArquivo(Path.Combine(Empresas.Configuracoes[emp].PastaXmlErro, Path.GetFileName(arquivo)));

                if (arquivo.EndsWith(".txt", StringComparison.InvariantCultureIgnoreCase))
                {
                    if (arquivo.EndsWith(Propriedade.ExtEnvio.EnvDFe_TXT, StringComparison.InvariantCultureIgnoreCase))
                    {
                        #region DFe
                        Functions.DeletarArquivo(Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Functions.ExtrairNomeArq(arquivo, Propriedade.ExtEnvio.EnvDFe_TXT) + Propriedade.ExtRetorno.retEnvDFe_ERR));
                        Functions.DeletarArquivo(Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Functions.ExtrairNomeArq(arquivo, Propriedade.ExtEnvio.EnvDFe_TXT) + Propriedade.ExtRetorno.retEnvDFe_XML));
                        DirecionarArquivo(emp, false, false, arquivo, new TaskDFeRecepcao());
                        #endregion
                    }

                    if (arquivo.EndsWith(Propriedade.ExtEnvio.ConsCad_TXT, StringComparison.InvariantCultureIgnoreCase))
                    {
                        #region Consulta ao cadastro de contribuinte
                        Functions.DeletarArquivo(Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Functions.ExtrairNomeArq(arquivo, Propriedade.ExtEnvio.ConsCad_TXT) + Propriedade.ExtRetorno.ConsCad_ERR));
                        Functions.DeletarArquivo(Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Functions.ExtrairNomeArq(arquivo, Propriedade.ExtEnvio.ConsCad_TXT) + Propriedade.ExtRetorno.ConsCad_XML));
                        DirecionarArquivo(emp, false, false, arquivo, new TaskCadastroContribuinte());
                        #endregion
                    }

                    if (arquivo.EndsWith(Propriedade.ExtEnvio.Nfe_TXT, StringComparison.InvariantCultureIgnoreCase))
                    {
                        new ConverterTXT(arquivo);
                    }

                    if (arquivo.EndsWith(Propriedade.ExtEnvio.EnvCCe_TXT, StringComparison.InvariantCultureIgnoreCase) ||
                        arquivo.EndsWith(Propriedade.ExtEnvio.EnvCancelamento_TXT, StringComparison.InvariantCultureIgnoreCase) ||
                        arquivo.EndsWith(Propriedade.ExtEnvio.EnvManifestacao_TXT, StringComparison.InvariantCultureIgnoreCase) ||
                        arquivo.EndsWith(Propriedade.ExtEnvio.PedEve_TXT, StringComparison.InvariantCultureIgnoreCase))
                    {
                        #region Eventos
                        Functions.DeletarArquivo(Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Functions.ExtrairNomeArq(arquivo, Propriedade.ExtEnvio.EnvCCe_TXT) + Propriedade.ExtRetorno.retEnvCCe_ERR));
                        Functions.DeletarArquivo(Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Functions.ExtrairNomeArq(arquivo, Propriedade.ExtEnvio.EnvCancelamento_TXT) + Propriedade.ExtRetorno.retCancelamento_ERR));
                        Functions.DeletarArquivo(Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Functions.ExtrairNomeArq(arquivo, Propriedade.ExtEnvio.EnvManifestacao_TXT) + Propriedade.ExtRetorno.retManifestacao_ERR));
                        Functions.DeletarArquivo(Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Functions.ExtrairNomeArq(arquivo, Propriedade.ExtEnvio.PedEve_TXT) + Propriedade.ExtRetorno.Eve_ERR));
                        DirecionarArquivo(emp, false, false, arquivo, new TaskNFeEventos());
                        #endregion
                    }

                    if (arquivo.EndsWith(Propriedade.ExtEnvio.PedInu_TXT, StringComparison.InvariantCultureIgnoreCase))
                    {
                        #region Inutilizacao
                        Functions.DeletarArquivo(Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Functions.ExtrairNomeArq(arquivo, Propriedade.ExtEnvio.PedInu_TXT) + Propriedade.ExtRetorno.Inu_ERR));
                        Functions.DeletarArquivo(Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Functions.ExtrairNomeArq(arquivo, Propriedade.ExtEnvio.PedInu_TXT) + "-ped-inu-ret.xml"));
                        DirecionarArquivo(emp, false, false, arquivo, new TaskNFeInutilizacao());
                        #endregion
                    }

                    if (arquivo.EndsWith(Propriedade.ExtEnvio.PedSta_TXT, StringComparison.InvariantCultureIgnoreCase))
                    {
                        Functions.DeletarArquivo(Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Functions.ExtrairNomeArq(arquivo, Propriedade.ExtEnvio.PedSta_TXT) + Propriedade.ExtRetorno.Sta_ERR));
                        DirecionarArquivo(emp, false, false, arquivo, new TaskNFeConsultaStatus());
                    }

                    if (arquivo.IndexOf(Propriedade.ExtEnvio.ConsNFeDest_TXT) >= 0)
                    {
                        Functions.DeletarArquivo(Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Functions.ExtrairNomeArq(arquivo, Propriedade.ExtEnvio.ConsNFeDest_TXT) + Propriedade.ExtRetorno.retConsNFeDest_ERR));
                        DirecionarArquivo(emp, false, false, arquivo, new TaskNFeConsultaNFDest());
                    }

                    if (arquivo.IndexOf(Propriedade.ExtEnvio.PedSit_TXT) >= 0)
                    {
                        Functions.DeletarArquivo(Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Functions.ExtrairNomeArq(arquivo, Propriedade.ExtEnvio.PedSit_TXT) + Propriedade.ExtRetorno.Sit_ERR));
                        DirecionarArquivo(emp, false, false, arquivo, new TaskNFeConsultaSituacao());
                    }
                }
                else
                {
                    if (arquivo.EndsWith(Propriedade.ExtEnvio.EnvCCe_XML, StringComparison.InvariantCultureIgnoreCase) ||
                        arquivo.EndsWith(Propriedade.ExtEnvio.EnvCancelamento_XML, StringComparison.InvariantCultureIgnoreCase) ||
                        arquivo.EndsWith(Propriedade.ExtEnvio.EnvManifestacao_XML, StringComparison.InvariantCultureIgnoreCase) ||
                        arquivo.EndsWith(Propriedade.ExtEnvio.PedEve, StringComparison.InvariantCultureIgnoreCase) ||
                        arquivo.EndsWith(Propriedade.ExtEnvio.PedSit_XML, StringComparison.InvariantCultureIgnoreCase) ||
                        arquivo.EndsWith(Propriedade.ExtEnvio.PedSta_XML, StringComparison.InvariantCultureIgnoreCase))
                    {
                        DirecionarArquivo(arquivo);
                    }

                    ValidarXML validar = new ValidarXML(arquivo, Empresas.Configuracoes[emp].UnidadeFederativaCodigo);
                    validar.ValidarAssinarXML(arquivo);
                }
            }
            catch
            {
            }
        }