public override void Execute() { int emp = Empresas.FindEmpresaByThread(); try { Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlRetorno + "\\" + Functions.ExtrairNomeArq(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSeTom).EnvioXML) + Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSeTom).RetornoERR); Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlErro + "\\" + NomeArquivoXML); dadosXML = new DadosPedSitNfse(emp); //Criar objetos das classes dos serviços dos webservices do SEFAZ PadroesNFSe padraoNFSe = Functions.PadraoNFSe(dadosXML.cMunicipio); //Este serviço, quando padrão BETHA, só tem para a versão do XML 2.02 if (padraoNFSe == PadroesNFSe.BETHA) { padraoNFSe = PadroesNFSe.BETHA202; } WebServiceProxy wsProxy = null; object pedConsNfseTomados = null; if (IsUtilizaCompilacaoWs(padraoNFSe)) { wsProxy = ConfiguracaoApp.DefinirWS(Servico, emp, dadosXML.cMunicipio, dadosXML.tpAmb, dadosXML.tpEmis, padraoNFSe, dadosXML.cMunicipio); pedConsNfseTomados = wsProxy.CriarObjeto(wsProxy.NomeClasseWS); } string cabecMsg = ""; switch (padraoNFSe) { case PadroesNFSe.INDAIATUBA_SP: cabecMsg = "<cabecalho versao=\"2.03\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\"><versaoDados>2.03</versaoDados></cabecalho>"; break; case PadroesNFSe.BETHA202: ConteudoXML.PreserveWhitespace = false; ConteudoXML.Load(NomeArquivoXML); Betha betha = new Betha((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, dadosXML.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor); betha.ConsultarNfseServicoTomado(NomeArquivoXML); break; case PadroesNFSe.SIGCORP_SIGISS_203: cabecMsg = "<cabecalho versao=\"2.03\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\"><versaoDados>2.03</versaoDados></cabecalho>"; break; case PadroesNFSe.SMARAPD_204: cabecMsg = "<cabecalho versao=\"2.04\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\"><versaoDados>2.04</versaoDados></cabecalho>"; break; case PadroesNFSe.IIBRASIL: cabecMsg = "<cabecalho xmlns=\"http://www.abrasf.org.br/nfse.xsd\" versao=\"2.04\"><versaoDados>2.04</versaoDados></cabecalho>"; break; } System.Net.SecurityProtocolType securityProtocolType = WebServiceProxy.DefinirProtocoloSeguranca(dadosXML.cMunicipio, dadosXML.tpAmb, dadosXML.tpEmis, padraoNFSe, Servico); if (IsInvocar(padraoNFSe, Servico, dadosXML.cMunicipio)) { //Assinar o XML AssinaturaDigital ad = new AssinaturaDigital(); ad.Assinar(NomeArquivoXML, emp, dadosXML.cMunicipio); //Invocar o método que envia o XML para o SEFAZ oInvocarObj.InvocarNFSe(wsProxy, pedConsNfseTomados, NomeMetodoWS(Servico, dadosXML.cMunicipio), cabecMsg, this, Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSeTom).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSeTom).RetornoXML, padraoNFSe, Servico, securityProtocolType); /// grava o arquivo no FTP string filenameFTP = Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Functions.ExtrairNomeArq(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSeTom).EnvioXML) + Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSeTom).RetornoXML); if (File.Exists(filenameFTP)) { new GerarXML(emp).XmlParaFTP(emp, filenameFTP); } } } catch (Exception ex) { var strErro = ex.HResult.ToString(); var strMesagemErro = ex.Message; try { //Gravar o arquivo de erro de retorno para o ERP, caso ocorra TFunctions.GravarArqErroServico(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSeTom).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSeTom).RetornoERR, ex); } catch { //Se falhou algo na hora de gravar o retorno .ERR (de erro) para o ERP, infelizmente não posso fazer mais nada. //Wandrey 31/08/2011 RetornoErroERP.GeraArquivoErroERP(NomeArquivoXML, strErro, strMesagemErro, Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSeTom).RetornoERR); } } finally { try { Functions.DeletarArquivo(NomeArquivoXML); } catch { //Se falhou algo na hora de deletar o XML de cancelamento de NFe, infelizmente //não posso fazer mais nada, o UniNFe vai tentar mandar o arquivo novamente para o webservice, pois ainda não foi excluido. //Wandrey 31/08/2011 } } }
public override void Execute() { int emp = Empresas.FindEmpresaByThread(); try { dadosRec = new DadosRecClass(); FluxoNfe fluxoNfe = new FluxoNfe(); LerXML lerXml = new LerXML(); //Ler o XML de Lote para pegar o número do lote que está sendo enviado lerXml.Cte(ConteudoXML); var idLote = lerXml.oDadosNfe.idLote; //Definir o objeto do WebService WebServiceProxy wsProxy = ConfiguracaoApp.DefinirWS( Servico, emp, Convert.ToInt32(lerXml.oDadosNfe.cUF), Convert.ToInt32(lerXml.oDadosNfe.tpAmb), Convert.ToInt32(lerXml.oDadosNfe.tpEmis), 0); System.Net.SecurityProtocolType securityProtocolType = WebServiceProxy.DefinirProtocoloSeguranca(Convert.ToInt32(lerXml.oDadosNfe.cUF), Convert.ToInt32(lerXml.oDadosNfe.tpAmb), Convert.ToInt32(lerXml.oDadosNfe.tpEmis), Servico); //Criar objetos das classes dos serviços dos webservices do SEFAZ object oRecepcao = wsProxy.CriarObjeto(wsProxy.NomeClasseWS); var oCabecMsg = wsProxy.CriarObjeto(NomeClasseCabecWS(Convert.ToInt32(lerXml.oDadosNfe.cUF), Servico)); //Atribuir conteúdo para duas propriedades da classe nfeCabecMsg wsProxy.SetProp(oCabecMsg, TpcnResources.cUF.ToString(), lerXml.oDadosNfe.cUF); wsProxy.SetProp(oCabecMsg, TpcnResources.versaoDados.ToString(), lerXml.oDadosNfe.versao); // //XML neste ponto o CTe já está assinado, pois foi assinado, validado e montado o lote para envio por outro serviço. //Fica aqui somente este lembrete. Wandrey 16/03/2010 // //Invocar o método que envia o XML para o SEFAZ oInvocarObj.Invocar(wsProxy, oRecepcao, wsProxy.NomeMetodoWS[0], oCabecMsg, this, Propriedade.Extensao(Propriedade.TipoEnvio.EnvLot).EnvioXML, Propriedade.ExtRetorno.Rec, true, securityProtocolType); #region Parte que trata o retorno do lote, ou seja, o número do recibo Recibo(vStrXmlRetorno, emp); if (dadosRec.cStat == "103") //Lote recebido com sucesso { if (dadosRec.tMed > 0) { Thread.Sleep(dadosRec.tMed * 1000); } //Atualizar o número do recibo no XML de controle do fluxo de notas enviadas fluxoNfe.AtualizarTag(lerXml.oDadosNfe.chavenfe, FluxoNfe.ElementoEditavel.tMed, (dadosRec.tMed + 2).ToString()); fluxoNfe.AtualizarTagRec(idLote, dadosRec.nRec); XmlDocument xmlPedRec = oGerarXML.XmlPedRecCTe(dadosRec.nRec, dadosRec.versao, emp); TaskCTeRetRecepcao cteRetRecepcao = new TaskCTeRetRecepcao(xmlPedRec); cteRetRecepcao.Execute(); } else if (Convert.ToInt32(dadosRec.cStat) > 200 || Convert.ToInt32(dadosRec.cStat) == 108 || //Verifica se o servidor de processamento está paralisado momentaneamente. Wandrey 13/04/2012 Convert.ToInt32(dadosRec.cStat) == 109) //Verifica se o servidor de processamento está paralisado sem previsão. Wandrey 13/04/2012 { //Se o status do retorno do lote for maior que 200 ou for igual a 108 ou 109, //vamos ter que excluir a nota do fluxo, porque ela foi rejeitada pelo SEFAZ //Primeiro vamos mover o xml da nota da pasta EmProcessamento para pasta de XML´s com erro e depois tira ela do fluxo //Wandrey 30/04/2009 oAux.MoveArqErro(Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" + PastaEnviados.EmProcessamento.ToString() + "\\" + fluxoNfe.LerTag(lerXml.oDadosNfe.chavenfe, FluxoNfe.ElementoFixo.ArqNFe)); fluxoNfe.ExcluirNfeFluxo(lerXml.oDadosNfe.chavenfe); } //Deleta o arquivo de lote Functions.DeletarArquivo(NomeArquivoXML); #endregion Parte que trata o retorno do lote, ou seja, o número do recibo } catch (ExceptionEnvioXML ex) { //Ocorreu algum erro no exato momento em que tentou enviar o XML para o SEFAZ, vou ter que tratar //para ver se o XML chegou lá ou não, se eu consegui pegar o número do recibo de volta ou não, etc. //E ver se vamos tirar o XML do Fluxo ou finalizar ele com a consulta situação da NFe try { //Gravar o arquivo de erro de retorno para o ERP, caso ocorra TFunctions.GravarArqErroServico(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.EnvLot).EnvioXML, Propriedade.ExtRetorno.Rec_ERR, ex); } catch { //Se falhou algo na hora de gravar o retorno .ERR (de erro) para o ERP, infelizmente não posso fazer mais nada. //Wandrey 16/03/2010 } } catch (ExceptionSemInternet ex) { try { //Gravar o arquivo de erro de retorno para o ERP, caso ocorra TFunctions.GravarArqErroServico(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.EnvLot).EnvioXML, Propriedade.ExtRetorno.Rec_ERR, ex, false); } catch { //Se falhou algo na hora de gravar o retorno .ERR (de erro) para o ERP, infelizmente não posso fazer mais nada. //Wandrey 16/03/2010 } } catch (Exception ex) { try { //Gravar o arquivo de erro de retorno para o ERP, caso ocorra TFunctions.GravarArqErroServico(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.EnvLot).EnvioXML, Propriedade.ExtRetorno.Rec_ERR, ex); } catch { //Se falhou algo na hora de gravar o retorno .ERR (de erro) para o ERP, infelizmente não posso fazer mais nada. //Wandrey 16/03/2010 } } }
/// <summary> /// Alguns estados nao tem o servico de consulta ao cadastro de contribuinte, por exemplo. /// Então, antes da aplicacao chamar um servico, ela pode consultar para saber ser um servico está disponivel para um estado /// </summary> public override void Execute() { int emp = Empresas.FindEmpresaByThread(); pedidoWSExiste odados = new pedidoWSExiste(); odados.cUF = Empresas.Configuracoes[emp].UnidadeFederativaCodigo; odados.tpEmis = Empresas.Configuracoes[emp].tpEmis; odados.tpAmb = Empresas.Configuracoes[emp].AmbienteCodigo; odados.servicos = ""; //Definir o serviço que será executado para a classe Servico = Servicos.WSExiste; try { int intValue; if (this.vXmlNfeDadosMsgEhXML) //danasa 12-9-2009 { #if modelo_xml <?xml version = "1.0" encoding = "utf-8"?> < dados > < cUF > 31 < / cUF > opcional ou se informada a UF por sigla, convertemos para UF->inteiro < tpAmb > 2 < / tpAmb > opcional < tpEmis > 1 < / tpEmis > opcional <servicos> NFeConsultaCadastro, NFeStatusServico, ...< / servicos > < / dados > #endif Functions.DeletarArquivo(Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Path.GetFileName(NomeArquivoXML.Replace(Propriedade.Extensao(Propriedade.TipoEnvio.EnvWSExiste).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.EnvWSExiste).RetornoXML).Replace(".xml", ".err")))); XmlDocument doc = new XmlDocument(); doc.Load(NomeArquivoXML); foreach (XmlNode node in doc.GetElementsByTagName("dados")) { XmlElement elementConfig = (XmlElement)node; odados.tpEmis = Convert.ToInt32(Functions.LerTag(elementConfig, TpcnResources.tpEmis.ToString(), odados.tpEmis.ToString())); odados.tpAmb = Convert.ToInt32(Functions.LerTag(elementConfig, TpcnResources.tpAmb.ToString(), odados.tpAmb.ToString())); string temp = Functions.LerTag(elementConfig, TpcnResources.cUF.ToString(), odados.cUF.ToString()); if (int.TryParse(temp, out intValue)) { odados.cUF = intValue; } else { odados.cUF = Functions.UFParaCodigo(temp); } odados.servicos = Functions.LerTag(elementConfig, "servicos", false); } }
public override void Execute() { int emp = Empresas.FindEmpresaByThread(); //Definir o serviço que será executado para a classe Servico = Servicos.CTeConsultaStatusServico; try { dadosPedSta = new DadosPedSta(); //Ler o XML para pegar parâmetros de envio PedSta(emp, dadosPedSta);//NomeArquivoXML); //Definir o objeto do WebService WebServiceProxy wsProxy = ConfiguracaoApp.DefinirWS(Servico, emp, dadosPedSta.cUF, dadosPedSta.tpAmb, dadosPedSta.tpEmis); System.Net.SecurityProtocolType securityProtocolType = WebServiceProxy.DefinirProtocoloSeguranca(dadosPedSta.cUF, dadosPedSta.tpAmb, dadosPedSta.tpEmis, PadroesNFSe.NaoIdentificado, Servico); //Criar objetos das classes dos serviços dos webservices do SEFAZ var oStatusServico = wsProxy.CriarObjeto(wsProxy.NomeClasseWS); var oCabecMsg = wsProxy.CriarObjeto(NomeClasseCabecWS(dadosPedSta.cUF, Servico, dadosPedSta.tpEmis)); //Atribuir conteúdo para duas propriedades da classe nfeCabecMsg wsProxy.SetProp(oCabecMsg, TpcnResources.cUF.ToString(), dadosPedSta.cUF.ToString()); wsProxy.SetProp(oCabecMsg, NFe.Components.TpcnResources.versaoDados.ToString(), NFe.ConvertTxt.versoes.VersaoXMLCTeStatusServico); //Invocar o método que envia o XML para o SEFAZ oInvocarObj.Invocar(wsProxy, oStatusServico, wsProxy.NomeMetodoWS[0], oCabecMsg, this, Propriedade.Extensao(Propriedade.TipoEnvio.PedSta).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedSta).RetornoXML, true, securityProtocolType); } catch (Exception ex) { try { //Gravar o arquivo de erro de retorno para o ERP, caso ocorra TFunctions.GravarArqErroServico(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedSta).EnvioXML, Propriedade.ExtRetorno.Sta_ERR, ex); } catch { //Se falhou algo na hora de gravar o retorno .ERR (de erro) para o ERP, infelizmente não posso fazer mais nada. //Wandrey 09/03/2010 } } finally { try { //Deletar o arquivo de solicitação do serviço Functions.DeletarArquivo(NomeArquivoXML); } catch { //Se falhou algo na hora de deletar o XML de solicitação do serviço, //infelizmente não posso fazer mais nada, o UniNFe vai tentar mandar //o arquivo novamente para o webservice //Wandrey 09/03/2010 } } }
private DadosenvDownload oDadosenvDownload;// = new DadosenvDownload(); #endregion #region Execute public override void Execute() { int emp = Empresas.FindEmpresaByThread(); Servico = Servicos.NFeDownload; try { oDadosenvDownload = new DadosenvDownload(); //Ler o XML para pegar parâmetros de envio EnvDownloadNFe(emp, NomeArquivoXML); if (vXmlNfeDadosMsgEhXML) { //Definir o objeto do WebService WebServiceProxy wsProxy = ConfiguracaoApp.DefinirWS(Servico, emp, Convert.ToInt32(oDadosenvDownload.chNFe.Substring(0, 2)), oDadosenvDownload.tpAmb); System.Net.SecurityProtocolType securityProtocolType = WebServiceProxy.DefinirProtocoloSeguranca(Convert.ToInt32(oDadosenvDownload.chNFe.Substring(0, 2)), oDadosenvDownload.tpAmb, (int)TipoEmissao.teNormal, PadroesNFSe.NaoIdentificado, Servico); //Criar objetos das classes dos serviços dos webservices do SEFAZ object oDownloadEvento = wsProxy.CriarObjeto(wsProxy.NomeClasseWS); object oCabecMsg = wsProxy.CriarObjeto(NomeClasseCabecWS(Convert.ToInt32(oDadosenvDownload.chNFe.Substring(0, 2)), Servico)); //Atribuir conteúdo para duas propriedades da classe nfeCabecMsg wsProxy.SetProp(oCabecMsg, NFe.Components.TpcnResources.cUF.ToString(), oDadosenvDownload.chNFe.Substring(0, 2)); wsProxy.SetProp(oCabecMsg, NFe.Components.TpcnResources.versaoDados.ToString(), NFe.ConvertTxt.versoes.VersaoXMLEnvDownload); //Invocar o método que envia o XML para o SEFAZ oInvocarObj.Invocar(wsProxy, oDownloadEvento, wsProxy.NomeMetodoWS[0], oCabecMsg, this, Propriedade.Extensao(Propriedade.TipoEnvio.EnvDownload).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.EnvDownload).RetornoXML, false, securityProtocolType); //Ler o retorno LerRetornoDownloadNFe(emp); //Gravar o xml de retorno para o ERP. Não pode gravar antes de extrair os downloads, para que o ERP saiba quando realmente terminou. Wandrey 03/04/2013 oGerarXML.XmlRetorno(Propriedade.Extensao(Propriedade.TipoEnvio.EnvDownload).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.EnvDownload).RetornoXML, this.vStrXmlRetorno); } else { // Gerar o XML de eventos a partir do TXT gerado pelo ERP oGerarXML.EnvioDownloadNFe(Functions.ExtrairNomeArq(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.EnvDownload).EnvioTXT) + Propriedade.Extensao(Propriedade.TipoEnvio.EnvDownload).EnvioXML, oDadosenvDownload); } } catch (Exception ex) { try { var ExtRet = vXmlNfeDadosMsgEhXML ? Propriedade.Extensao(Propriedade.TipoEnvio.EnvDownload).EnvioXML : Propriedade.Extensao(Propriedade.TipoEnvio.EnvDownload).EnvioTXT; //Gravar o arquivo de erro de retorno para o ERP, caso ocorra TFunctions.GravarArqErroServico(NomeArquivoXML, ExtRet, Propriedade.ExtRetorno.retDownload_ERR, ex); } catch { //Se falhou algo na hora de gravar o retorno .ERR (de erro) para o ERP, infelizmente não posso fazer mais nada. //Wandrey 09/03/2010 } } finally { try { Functions.DeletarArquivo(NomeArquivoXML); } catch { //Se falhou algo na hora de deletar o XML de evento, infelizmente //não posso fazer mais nada, o UniNFe vai tentar mandar o arquivo novamente para o webservice, pois ainda não foi excluido. //Wandrey 09/03/2010 } } }
public override void Execute() { int emp = Empresas.FindEmpresaByThread(); /// /// extensao permitida: PedSitNfseRps = "-ped-sitnfserps.xml"; /// /// Definir o serviço que será executado para a classe Servico = Servicos.NFSeConsultarPorRps; try { Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlRetorno + "\\" + Functions.ExtrairNomeArq(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSeRps).EnvioXML) + Propriedade.ExtRetorno.SitNfseRps_ERR); Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlErro + "\\" + NomeArquivoXML); //Ler o XML para pegar parâmetros de envio LerXML ler = new LerXML(); ler.PedSitNfseRps(NomeArquivoXML); //Criar objetos das classes dos serviços dos webservices do SEFAZ PadroesNFSe padraoNFSe = Functions.PadraoNFSe(ler.oDadosPedSitNfseRps.cMunicipio); WebServiceProxy wsProxy = null; object pedLoteRps = null; if (IsUtilizaCompilacaoWs(padraoNFSe, Servico, ler.oDadosPedSitNfseRps.cMunicipio)) { wsProxy = ConfiguracaoApp.DefinirWS(Servico, emp, ler.oDadosPedSitNfseRps.cMunicipio, ler.oDadosPedSitNfseRps.tpAmb, ler.oDadosPedSitNfseRps.tpEmis, padraoNFSe, ler.oDadosPedSitNfseRps.cMunicipio); if (wsProxy != null) { pedLoteRps = wsProxy.CriarObjeto(wsProxy.NomeClasseWS); } } System.Net.SecurityProtocolType securityProtocolType = WebServiceProxy.DefinirProtocoloSeguranca(ler.oDadosPedSitNfseRps.cMunicipio, ler.oDadosPedSitNfseRps.tpAmb, ler.oDadosPedSitNfseRps.tpEmis, padraoNFSe, Servico); string cabecMsg = ""; switch (padraoNFSe) { case PadroesNFSe.GINFES: switch (ler.oDadosPedSitNfseRps.cMunicipio) { case 2304400: //Fortaleza - CE cabecMsg = "<ns2:cabecalho versao=\"3\" xmlns:ns2=\"http://www.ginfes.com.br/cabecalho_v03.xsd\"><versaoDados>3</versaoDados></ns2:cabecalho>"; break; case 4125506: //São José dos Pinhais - PR cabecMsg = "<ns2:cabecalho versao=\"3\" xmlns:ns2=\"http://nfe.sjp.pr.gov.br/cabecalho_v03.xsd\"><versaoDados>3</versaoDados></ns2:cabecalho>"; break; default: cabecMsg = "<ns2:cabecalho versao=\"3\" xmlns:ns2=\"http://www.ginfes.com.br/cabecalho_v03.xsd\"><versaoDados>3</versaoDados></ns2:cabecalho>"; break; } break; case PadroesNFSe.ABASE: cabecMsg = "<cabecalho xmlns=\"http://nfse.abase.com.br/nfse.xsd\" versao =\"1.00\"><versaoDados>1.00</versaoDados></cabecalho>"; break; case PadroesNFSe.BETHA: #region Betha ConteudoXML.PreserveWhitespace = false; ConteudoXML.Load(NomeArquivoXML); if (!ConteudoXML.DocumentElement.Name.Contains("e:")) { padraoNFSe = PadroesNFSe.BETHA202; Components.Betha.NewVersion.Betha betha = new Components.Betha.NewVersion.Betha((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, ler.oDadosPedSitNfseRps.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor); betha.ConsultarNfsePorRps(NomeArquivoXML); } else { wsProxy = new WebServiceProxy(Empresas.Configuracoes[emp].X509Certificado); wsProxy.Betha = new Betha(); } break; #endregion Betha case PadroesNFSe.ABACO: case PadroesNFSe.CANOAS_RS: cabecMsg = "<cabecalho versao=\"201001\"><versaoDados>V2010</versaoDados></cabecalho>"; break; case PadroesNFSe.BHISS: cabecMsg = "<cabecalho xmlns=\"http://www.abrasf.org.br/nfse.xsd\" versao=\"1.00\"><versaoDados >1.00</versaoDados ></cabecalho>"; break; case PadroesNFSe.WEBISS: cabecMsg = "<cabecalho xmlns=\"http://www.abrasf.org.br/nfse.xsd\" versao=\"1.00\"><versaoDados >1.00</versaoDados ></cabecalho>"; break; case PadroesNFSe.WEBISS_202: cabecMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><cabecalho xmlns=\"http://www.abrasf.org.br/nfse.xsd\" versao=\"2.02\"><versaoDados>2.02</versaoDados></cabecalho>"; break; case PadroesNFSe.PORTOVELHENSE: cabecMsg = "<cabecalho versao=\"2.00\" xmlns:ns2=\"http://www.w3.org/2000/09/xmldsig#\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\"><versaoDados>2.00</versaoDados></cabecalho>"; break; case PadroesNFSe.TECNOSISTEMAS: cabecMsg = "<?xml version=\"1.0\" encoding=\"utf-8\"?><cabecalho xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" versao=\"20.01\" xmlns=\"http://www.nfse-tecnos.com.br/nfse.xsd\"><versaoDados>20.01</versaoDados></cabecalho>"; break; case PadroesNFSe.FINTEL: cabecMsg = "<cabecalho versao=\"2.02\" xmlns=\"http://iss.irati.pr.gov.br/Arquivos/nfseV202.xsd\"><versaoDados>2.02</versaoDados></cabecalho>"; break; case PadroesNFSe.IIBRASIL: cabecMsg = "<cabecalho xmlns=\"http://www.abrasf.org.br/nfse.xsd\" versao=\"2.04\"><versaoDados>2.04</versaoDados></cabecalho>"; break; case PadroesNFSe.FIORILLI: Fiorilli fiorilli = new Fiorilli((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, ler.oDadosPedSitNfseRps.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor, Empresas.Configuracoes[emp].X509Certificado); fiorilli.ConsultarNfsePorRps(NomeArquivoXML); break; case PadroesNFSe.SIMPLISS: SimplISS simpliss = new SimplISS((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, ler.oDadosPedSitNfseRps.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor); simpliss.ConsultarNfsePorRps(NomeArquivoXML); break; case PadroesNFSe.EGOVERNE: #region E-Governe EGoverne egoverne = new EGoverne((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, ler.oDadosPedSitNfseRps.cMunicipio, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor, Empresas.Configuracoes[emp].X509Certificado); AssinaturaDigital assegov = new AssinaturaDigital(); assegov.Assinar(NomeArquivoXML, emp, ler.oDadosPedSitNfseRps.cMunicipio); egoverne.ConsultarNfsePorRps(NomeArquivoXML); #endregion E-Governe break; case PadroesNFSe.EL: #region E&L EL el = new EL((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, ler.oDadosPedSitNfseRps.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS, (ConfiguracaoApp.Proxy ? ConfiguracaoApp.ProxyUsuario : ""), (ConfiguracaoApp.Proxy ? ConfiguracaoApp.ProxySenha : ""), (ConfiguracaoApp.Proxy ? ConfiguracaoApp.ProxyServidor : "")); el.ConsultarNfsePorRps(NomeArquivoXML); #endregion E&L break; case PadroesNFSe.GOVDIGITAL: GovDigital govdig = new GovDigital((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, Empresas.Configuracoes[emp].X509Certificado, ler.oDadosPedSitNfseRps.cMunicipio, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor); AssinaturaDigital adgovdig = new AssinaturaDigital(); adgovdig.Assinar(NomeArquivoXML, emp, ler.oDadosPedSitNfseRps.cMunicipio); govdig.ConsultarNfsePorRps(NomeArquivoXML); break; case PadroesNFSe.EQUIPLANO: cabecMsg = "1"; break; case PadroesNFSe.PORTALFACIL_ACTCON_202: cabecMsg = "<cabecalho><versaoDados>2.02</versaoDados></cabecalho>"; break; case PadroesNFSe.PORTALFACIL_ACTCON: case PadroesNFSe.PRODATA: cabecMsg = "<cabecalho versao=\"2.01\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"<versaoDados>2.01</versaoDados></cabecalho>"; break; case PadroesNFSe.FISSLEX: FISSLEX fisslex = new FISSLEX((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, ler.oDadosPedSitNfseRps.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor); fisslex.ConsultarNfsePorRps(NomeArquivoXML); break; case PadroesNFSe.NATALENSE: cabecMsg = "<cabecalho xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" versao=\"1\" xmlns=\"http://www.abrasf.org.br/ABRASF/arquivos/nfse.xsd\"><versaoDados>1</versaoDados></cabecalho>"; break; case PadroesNFSe.CONAM: throw new NFe.Components.Exceptions.ServicoInexistenteException(); case PadroesNFSe.PAULISTANA: wsProxy = new WebServiceProxy(Empresas.Configuracoes[emp].X509Certificado); if (ler.oDadosPedSitNfseRps.tpAmb == 1) { pedLoteRps = new NFe.Components.PSaoPauloSP.LoteNFe(); } else { throw new Exception("Município de São Paulo-SP não dispõe de ambiente de homologação para envio de NFS-e em teste."); } break; case PadroesNFSe.METROPOLIS: #region METROPOLIS Metropolis metropolis = new Metropolis((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, ler.oDadosPedSitNfseRps.cMunicipio, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor, Empresas.Configuracoes[emp].X509Certificado); AssinaturaDigital metropolisdig = new AssinaturaDigital(); metropolisdig.Assinar(NomeArquivoXML, emp, ler.oDadosPedSitNfseRps.cMunicipio); metropolis.ConsultarNfsePorRps(NomeArquivoXML); break; #endregion METROPOLIS case PadroesNFSe.MEMORY: #region Memory Memory memory = new Memory((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, ler.oDadosPedSitNfseRps.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor); memory.ConsultarNfsePorRps(NomeArquivoXML); break; #endregion Memory case PadroesNFSe.CAMACARI_BA: cabecMsg = "<cabecalho><versaoDados>2.01</versaoDados><versao>2.01</versao></cabecalho>"; break; case PadroesNFSe.NA_INFORMATICA: wsProxy = new WebServiceProxy(Empresas.Configuracoes[emp].X509Certificado); //if (ler.oDadosPedSitNfseRps.tpAmb == 1) // pedLoteRps = new Components.PCorumbaMS.NfseWSService(); //else // pedLoteRps = new Components.HCorumbaMS.NfseWSService(); break; case PadroesNFSe.BSITBR: wsProxy = new WebServiceProxy(Empresas.Configuracoes[emp].X509Certificado); if (ler.oDadosPedSitNfseRps.tpAmb == 1) { switch (ler.oDadosPedSitNfseRps.cMunicipio) { case 5211800: pedLoteRps = new Components.PJaraguaGO.nfseWS(); break; case 5220454: pedLoteRps = new Components.PSenadorCanedoGO.nfseWS(); break; } } else { throw new Exception("Este município não dispõe de ambiente de homologação para envio de NFS-e em teste."); } break; case PadroesNFSe.PRONIN: if (ler.oDadosPedSitNfseRps.cMunicipio == 4109401 || ler.oDadosPedSitNfseRps.cMunicipio == 3131703 || ler.oDadosPedSitNfseRps.cMunicipio == 4303004 || ler.oDadosPedSitNfseRps.cMunicipio == 4322509 || ler.oDadosPedSitNfseRps.cMunicipio == 3556602 || ler.oDadosPedSitNfseRps.cMunicipio == 3512803 || ler.oDadosPedSitNfseRps.cMunicipio == 4323002 || ler.oDadosPedSitNfseRps.cMunicipio == 3505807 || ler.oDadosPedSitNfseRps.cMunicipio == 3530300 || ler.oDadosPedSitNfseRps.cMunicipio == 4308904 || ler.oDadosPedSitNfseRps.cMunicipio == 4118501 || ler.oDadosPedSitNfseRps.cMunicipio == 3554300 || ler.oDadosPedSitNfseRps.cMunicipio == 3542404 || ler.oDadosPedSitNfseRps.cMunicipio == 5005707 || ler.oDadosPedSitNfseRps.cMunicipio == 4314423 || ler.oDadosPedSitNfseRps.cMunicipio == 3511102 || ler.oDadosPedSitNfseRps.cMunicipio == 3535804 || ler.oDadosPedSitNfseRps.cMunicipio == 4306932) { Pronin pronin = new Pronin((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, ler.oDadosPedSitNfseRps.cMunicipio, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor, Empresas.Configuracoes[emp].X509Certificado); AssinaturaDigital assPronin = new AssinaturaDigital(); assPronin.Assinar(NomeArquivoXML, emp, ler.oDadosPedSitNfseRps.cMunicipio); pronin.ConsultarNfsePorRps(NomeArquivoXML); } break; case PadroesNFSe.COPLAN: Coplan coplan = new Coplan((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, ler.oDadosPedSitNfseRps.cMunicipio, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor, Empresas.Configuracoes[emp].X509Certificado); AssinaturaDigital assCoplan = new AssinaturaDigital(); assCoplan.Assinar(NomeArquivoXML, emp, ler.oDadosPedSitNfseRps.cMunicipio); coplan.ConsultarNfsePorRps(NomeArquivoXML); break; case PadroesNFSe.TINUS: Tinus tinus = new Tinus((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, ler.oDadosPedSitNfseRps.cMunicipio, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor, Empresas.Configuracoes[emp].X509Certificado); tinus.ConsultarNfsePorRps(NomeArquivoXML); break; case PadroesNFSe.INTERSOL: cabecMsg = "<?xml version=\"1.0\" encoding=\"utf-8\"?><p:cabecalho versao=\"1\" xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\" xmlns:p=\"http://ws.speedgov.com.br/cabecalho_v1.xsd\" xmlns:p1=\"http://ws.speedgov.com.br/tipos_v1.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://ws.speedgov.com.br/cabecalho_v1.xsd cabecalho_v1.xsd \"><versaoDados>1</versaoDados></p:cabecalho>"; break; case PadroesNFSe.MANAUS_AM: cabecMsg = "<cabecalho versao=\"201001\"><versaoDados>V2010</versaoDados></cabecalho>"; break; case PadroesNFSe.JOINVILLE_SC: wsProxy = new WebServiceProxy(Empresas.Configuracoes[emp].X509Certificado); if (ler.oDadosPedSitNfseRps.tpAmb == 2) { pedLoteRps = new Components.HJoinvilleSC.Servicos(); } else { pedLoteRps = new Components.PJoinvilleSC.Servicos(); } break; case PadroesNFSe.AVMB_ASTEN: cabecMsg = "<cabecalho versao=\"2.02\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\"><versaoDados>2.02</versaoDados></cabecalho>"; wsProxy = new WebServiceProxy(Empresas.Configuracoes[emp].X509Certificado); if (ler.oDadosPedSitNfseRps.tpAmb == 2) { pedLoteRps = new Components.HPelotasRS.INfseservice(); } else { pedLoteRps = new Components.PPelotasRS.INfseservice(); } break; case PadroesNFSe.EMBRAS: cabecMsg = "<cabecalho versao=\"2.02\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\"><versaoDados>2.02</versaoDados></cabecalho>"; break; case PadroesNFSe.MODERNIZACAO_PUBLICA: cabecMsg = "<cabecalho xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\" versao=\"2.02\"><versaoDados>2.02</versaoDados></cabecalho>"; break; case PadroesNFSe.E_RECEITA: cabecMsg = "<cabecalho xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\" versao=\"2.02\"><versaoDados>2.02</versaoDados></cabecalho>"; break; case PadroesNFSe.TIPLAN_203: case PadroesNFSe.INDAIATUBA_SP: cabecMsg = "<cabecalho versao=\"2.03\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\"><versaoDados>2.03</versaoDados></cabecalho>"; break; #if _fw46 case PadroesNFSe.ADM_SISTEMAS: cabecMsg = "<cabecalho versao=\"2.01\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\"><versaoDados>2.01</versaoDados></cabecalho>"; wsProxy = new WebServiceProxy(Empresas.Configuracoes[emp].X509Certificado); pedLoteRps = ler.oDadosPedSitNfseRps.tpAmb == 1 ? new Components.PAmargosaBA.InfseClient(GetBinding(), new EndpointAddress("https://demo.saatri.com.br/servicos/nfse.svc")) : new Components.HAmargosaBA.InfseClient(GetBinding(), new EndpointAddress("https://homologa-demo.saatri.com.br/servicos/nfse.svc")) as object; SignUsingCredentials(emp, pedLoteRps); break; #endif case PadroesNFSe.PUBLIC_SOFT: if (ler.oDadosPedSitNfseRps.cMunicipio.Equals(2610707)) { cabecMsg = "N9M="; } break; case PadroesNFSe.MEGASOFT: cabecMsg = "<cabecalho versao=\"1.00\" xmlns=\"http://megasoftarrecadanet.com.br/xsd/nfse_v01.xsd\"><versaoDados>1.00</versaoDados></cabecalho>"; break; case PadroesNFSe.SIMPLE: Simple simple = new Simple((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, ler.oDadosPedSitNfseRps.cMunicipio, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor, Empresas.Configuracoes[emp].X509Certificado); simple.ConsultarNfsePorRps(NomeArquivoXML); break; case PadroesNFSe.SISPMJP: cabecMsg = "<cabecalho versao=\"2.02\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\" ><versaoDados>2.02</versaoDados></cabecalho>"; break; case PadroesNFSe.SIGCORP_SIGISS_203: cabecMsg = "<cabecalho versao=\"2.03\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\"><versaoDados>2.03</versaoDados></cabecalho>"; break; case PadroesNFSe.SMARAPD_204: cabecMsg = "<cabecalho versao=\"2.04\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\"><versaoDados>2.04</versaoDados></cabecalho>"; break; case PadroesNFSe.DSF: if (ler.oDadosPedSitNfseRps.cMunicipio == 3549904) { cabecMsg = "<cabecalho versao=\"3\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\"><versaoDados>3</versaoDados></cabecalho>"; } break; } if (IsInvocar(padraoNFSe, Servico, ler.oDadosPedSitNfseRps.cMunicipio)) { //Assinar o XML AssinaturaDigital ad = new AssinaturaDigital(); ad.Assinar(NomeArquivoXML, emp, ler.oDadosPedSitNfseRps.cMunicipio); //Invocar o método que envia o XML para o SEFAZ oInvocarObj.InvocarNFSe(wsProxy, pedLoteRps, NomeMetodoWS(Servico, ler.oDadosPedSitNfseRps.cMunicipio), cabecMsg, this, Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSeRps).EnvioXML, //"-ped-sitnfserps", Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSeRps).RetornoXML, //"-sitnfserps", padraoNFSe, Servico, securityProtocolType); /// /// grava o arquivo no FTP string filenameFTP = Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Functions.ExtrairNomeArq(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSeRps).EnvioXML) + Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSeRps).RetornoXML); if (File.Exists(filenameFTP)) { new GerarXML(emp).XmlParaFTP(emp, filenameFTP); } } } catch (Exception ex) { try { //Gravar o arquivo de erro de retorno para o ERP, caso ocorra TFunctions.GravarArqErroServico(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSeRps).EnvioXML, Propriedade.ExtRetorno.SitNfseRps_ERR, ex); } catch { //Se falhou algo na hora de gravar o retorno .ERR (de erro) para o ERP, infelizmente não posso fazer mais nada. //Wandrey 31/08/2011 } } finally { try { Functions.DeletarArquivo(NomeArquivoXML); } catch { //Se falhou algo na hora de deletar o XML de cancelamento de NFe, infelizmente //não posso fazer mais nada, o UniNFe vai tentar mandar o arquivo novamente para o webservice, pois ainda não foi excluido. //Wandrey 31/08/2011 } } }
private void RaiseFileChanged(FileInfo fi, int emp) { string msgError = null; if (File.Exists(fi.FullName)) { /// /// TODO!!! /// entre este processo e o RaiseEvent está tendo uma demora considerável /// if (fi.Length > 0 || (fi.Name.ToLower().EndsWith(Propriedade.Extensao(Propriedade.TipoEnvio.sair_XML).EnvioTXT) || fi.Name.ToLower().EndsWith(Propriedade.Extensao(Propriedade.TipoEnvio.pedUpdatewsdl).EnvioTXT) || fi.Name.ToLower().EndsWith(Propriedade.Extensao(Propriedade.TipoEnvio.pedLayouts).EnvioTXT) || fi.Name.ToLower().EndsWith(Propriedade.Extensao(Propriedade.TipoEnvio.pedRestart).EnvioTXT))) { Thread tworker = new Thread( new ThreadStart( delegate { if (OnFileChanged != null) { try { OnFileChanged(fi); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.ToString()); } } } )); tworker.IsBackground = true; tworker.Start(); if (emp >= 0) { if (fi.Name.ToLower().IndexOf(Propriedade.Extensao(Propriedade.TipoEnvio.AltCon).EnvioXML) >= 0 || fi.Name.ToLower().IndexOf(Propriedade.Extensao(Propriedade.TipoEnvio.AltCon).EnvioTXT) >= 0) { Empresas.Configuracoes[emp].CriarFilaProcesamento = true; } if (Empresas.Configuracoes[emp].X509Certificado.IsA3() || Empresas.Configuracoes[emp].CriarFilaProcesamento) { tworker.Join(); } } else { tworker.Join(); } } else { msgError = fi.FullName + " - Arquivo com tamanho zerado."; } } else { msgError = fi.FullName + " - Arquivo não existe."; } if (msgError != null) { if (fi.Directory.Name.ToLower().EndsWith("geral\\temp")) { Functions.WriteLog(msgError, false, true, ""); } else { Auxiliar.WriteLog(msgError, true); } } }
/// <summary> /// Faz a leitura do XML de pedido de consulta da situação da NFe /// </summary> /// <param name="arquivoXML">Nome do XML a ser lido</param> /// <param name="emp">Código da empresa</param> /*private void PedSit(int emp, string arquivoXML) * { * this.dadosPedSit.tpAmb = Empresas.Configuracoes[emp].AmbienteCodigo; * this.dadosPedSit.chNFe = string.Empty; * * XmlDocument doc = new XmlDocument(); * doc.Load(arquivoXML); * * XmlNodeList consSitNFeList = doc.GetElementsByTagName("consSitCTe"); * * foreach (XmlNode consSitNFeNode in consSitNFeList) * { * XmlElement consSitNFeElemento = (XmlElement)consSitNFeNode; * * dadosPedSit.tpAmb = Convert.ToInt32("0" + consSitNFeElemento.GetElementsByTagName(TpcnResources.tpAmb.ToString())[0].InnerText); * dadosPedSit.chNFe = consSitNFeElemento.GetElementsByTagName(TpcnResources.chCTe.ToString())[0].InnerText; * * if (consSitNFeElemento.GetElementsByTagName(TpcnResources.tpEmis.ToString()).Count != 0) * { * this.dadosPedSit.tpEmis = Convert.ToInt16(consSitNFeElemento.GetElementsByTagName(TpcnResources.tpEmis.ToString())[0].InnerText); * /// para que o validador não rejeite, excluo a tag <tpEmis> * doc.DocumentElement.RemoveChild(consSitNFeElemento.GetElementsByTagName(TpcnResources.tpEmis.ToString())[0]); * /// salvo o arquivo modificado * doc.Save(arquivoXML); * } * } * }*/ #endregion #region LerRetornoSitCTe() /// <summary> /// Ler o retorno da consulta situação da nota fiscal e de acordo com o status ele trata as notas enviadas se ainda não foram tratadas /// </summary> /// <param name="ChaveCTe">Chave da NFe que está sendo consultada</param> /// <remarks> /// Autor: Wandrey Mundin Ferreira /// Data: 16/06/2010 /// </remarks> private void LerRetornoSitCTe(string ChaveCTe) { int emp = Empresas.FindEmpresaByThread(); oGerarXML.XmlDistEventoCTe(emp, this.vStrXmlRetorno); //<<<danasa 6-2011 LerXML oLerXml = new LerXML(); MemoryStream msXml = Functions.StringXmlToStream(vStrXmlRetorno); FluxoNfe oFluxoNfe = new FluxoNfe(); XmlDocument doc = new XmlDocument(); doc.Load(msXml); XmlNodeList retConsSitList = doc.GetElementsByTagName("retConsSitCTe"); foreach (XmlNode retConsSitNode in retConsSitList) { XmlElement retConsSitElemento = (XmlElement)retConsSitNode; //Definir a chave da NFe a ser pesquisada string strChaveCTe = "CTe" + ChaveCTe; //Definir o nome do arquivo da NFe e seu caminho string strNomeArqCTe = oFluxoNfe.LerTag(strChaveCTe, FluxoNfe.ElementoFixo.ArqNFe); if (string.IsNullOrEmpty(strNomeArqCTe)) { strNomeArqCTe = strChaveCTe.Substring(3) + Propriedade.Extensao(Propriedade.TipoEnvio.CTe).EnvioXML; } string strArquivoCTe = Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" + PastaEnviados.EmProcessamento.ToString() + "\\" + strNomeArqCTe; #region CNPJ da chave não é de uma empresa Uninfe bool notDaEmpresa = (ChaveCTe.Substring(6, 14) != Empresas.Configuracoes[emp].CNPJ || ChaveCTe.Substring(0, 2) != Empresas.Configuracoes[emp].UnidadeFederativaCodigo.ToString()); if (!File.Exists(strArquivoCTe) && notDaEmpresa) { return; } #endregion //Pegar o status de retorno da NFe que está sendo consultada a situação var cStatCons = string.Empty; if (retConsSitElemento.GetElementsByTagName(TpcnResources.cStat.ToString())[0] != null) { cStatCons = retConsSitElemento.GetElementsByTagName(TpcnResources.cStat.ToString())[0].InnerText; } switch (cStatCons) { #region Rejeições do XML de consulta do recibo (Não é o lote que foi rejeitado e sim o XML de consulta do recibo) case "280": //A-Certificado transmissor inválido case "281": //A-Validade do certificado case "283": //A-Verifica a cadeia de Certificação case "286": //A-LCR do certificado de Transmissor case "284": //A-Certificado do Transmissor revogado case "285": //A-Certificado Raiz difere da "IPC-Brasil" case "282": //A-Falta a extensão de CNPJ no Certificado case "214": //B-Tamanho do XML de dados superior a 500 Kbytes case "243": //B-XML de dados mal formatado case "108": //B-Verifica se o Serviço está paralisado momentaneamente case "109": //B-Verifica se o serviço está paralisado sem previsão case "242": //C-Elemento nfeCabecMsg inexistente no SOAP Header case "409": //C-Campo cUF inexistente no elemento nfeCabecMsg do SOAP Header case "410": //C-Campo versaoDados inexistente no elemento nfeCabecMsg do SOAP case "411": //C-Campo versaoDados inexistente no elemento nfeCabecMsg do SOAP case "238": //C-Versão dos Dados informada é superior à versão vigente case "239": //C-Versão dos Dados não suportada case "215": //D-Verifica schema XML da área de dados case "404": //D-Verifica o uso de prefixo no namespace case "402": //D-XML utiliza codificação diferente de UTF-8 case "252": //E-Tipo do ambiente da NF-e difere do ambiente do web service case "226": //E-UF da Chave de Acesso difere da UF do Web Service case "236": //E-Valida DV da Chave de Acesso case "216": //E-Verificar se campo "Codigo Numerico" break; #endregion #region Nota fiscal rejeitada case "217": //J-NFe não existe na base de dados do SEFAZ goto case "TirarFluxo"; #endregion #region Nota fiscal autorizada case "100": //Autorizado o uso da NFe case "150": XmlNodeList infConsSitList = retConsSitElemento.GetElementsByTagName("infProt"); if (infConsSitList != null) { foreach (XmlNode infConsSitNode in infConsSitList) { XmlElement infConsSitElemento = (XmlElement)infConsSitNode; //Pegar o Status do Retorno da consulta situação string strStat = Functions.LerTag(infConsSitElemento, TpcnResources.cStat.ToString()).Replace(";", ""); switch (strStat) { case "100": case "150": var strProtNfe = retConsSitElemento.GetElementsByTagName("protCTe")[0].OuterXml; //Definir o nome do arquivo -procNfe.xml string strArquivoNFeProc = Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" + PastaEnviados.EmProcessamento.ToString() + "\\" + Functions.ExtrairNomeArq(strArquivoCTe, Propriedade.Extensao(Propriedade.TipoEnvio.CTe).EnvioXML) + Propriedade.ExtRetorno.ProcCTe; //Se existir o strArquivoNfe, tem como eu fazer alguma coisa, se ele não existir //Não tenho como fazer mais nada. Wandrey 08/10/2009 if (File.Exists(strArquivoCTe)) { //Ler o XML para pegar a data de emissão para criar a pasta dos XML´s autorizados oLerXml.Cte(strArquivoCTe); //Verificar se a -nfe.xml existe na pasta de autorizados bool NFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoCTe, oLerXml.oDadosNfe.dEmi, Propriedade.Extensao(Propriedade.TipoEnvio.CTe).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.CTe).EnvioXML); //Verificar se o -procNfe.xml existe na past de autorizados bool procNFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoCTe, oLerXml.oDadosNfe.dEmi, Propriedade.Extensao(Propriedade.TipoEnvio.CTe).EnvioXML, Propriedade.ExtRetorno.ProcCTe); //Se o XML de distribuição não estiver na pasta em processamento if (!procNFeJaNaAutorizada && !File.Exists(strArquivoNFeProc)) { oGerarXML.XmlDistCTe(strArquivoCTe, strProtNfe); } //Se o XML de distribuição não estiver ainda na pasta de autorizados if (!(procNFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoCTe, oLerXml.oDadosNfe.dEmi, Propriedade.Extensao(Propriedade.TipoEnvio.CTe).EnvioXML, Propriedade.ExtRetorno.ProcCTe))) { //Move a nfeProc da pasta de NFE em processamento para a NFe Autorizada TFunctions.MoverArquivo(strArquivoNFeProc, PastaEnviados.Autorizados, oLerXml.oDadosNfe.dEmi); } //Se a NFe não existir ainda na pasta de autorizados if (!(NFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoCTe, oLerXml.oDadosNfe.dEmi, Propriedade.Extensao(Propriedade.TipoEnvio.CTe).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.CTe).EnvioXML))) { //Mover a NFE da pasta de NFE em processamento para NFe Autorizada TFunctions.MoverArquivo(strArquivoCTe, PastaEnviados.Autorizados, oLerXml.oDadosNfe.dEmi); } else { //Se já estiver na pasta de autorizados, vou somente excluir ela da pasta de XML´s em processamento Functions.DeletarArquivo(strArquivoCTe); } //Disparar a geração/impressao do UniDanfe. 03/02/2010 - Wandrey if (procNFeJaNaAutorizada) { try { var strArquivoDist = Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" + PastaEnviados.Autorizados.ToString() + "\\" + Empresas.Configuracoes[emp].DiretorioSalvarComo.ToString(oLerXml.oDadosNfe.dEmi) + Path.GetFileName(strArquivoNFeProc); TFunctions.ExecutaUniDanfe(strArquivoDist, oLerXml.oDadosNfe.dEmi, Empresas.Configuracoes[emp]); } catch (Exception ex) { Auxiliar.WriteLog("TaskCTeConsultaSituacao: " + ex.Message, false); } } } if (File.Exists(strArquivoNFeProc)) { //Se já estiver na pasta de autorizados, vou somente excluir ela da pasta de XML´s em processamento Functions.DeletarArquivo(strArquivoNFeProc); } break; case "301": //Ler o XML para pegar a data de emissão para criar a psta dos XML´s Denegados if (File.Exists(strArquivoCTe)) { oLerXml.Cte(strArquivoCTe); //Move a NFE da pasta de NFE em processamento para NFe Denegadas if (!oAux.EstaDenegada(strArquivoCTe, oLerXml.oDadosNfe.dEmi, Propriedade.Extensao(Propriedade.TipoEnvio.CTe).EnvioXML, Propriedade.ExtRetorno.Den)) { TFunctions.MoverArquivo(strArquivoCTe, PastaEnviados.Denegados, oLerXml.oDadosNfe.dEmi); /// /// existe DACTE de CTe denegado??? /// try { var strArquivoDist = Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" + PastaEnviados.Denegados.ToString() + "\\" + Empresas.Configuracoes[emp].DiretorioSalvarComo.ToString(oLerXml.oDadosNfe.dEmi) + Functions.ExtrairNomeArq(strArquivoCTe, Propriedade.Extensao(Propriedade.TipoEnvio.CTe).EnvioXML) + Propriedade.ExtRetorno.Den; TFunctions.ExecutaUniDanfe(strArquivoDist, oLerXml.oDadosNfe.dEmi, Empresas.Configuracoes[emp]); } catch (Exception ex) { Auxiliar.WriteLog("TaskCTeConsultaSituacao: " + ex.Message, false); } } } break; case "302": goto case "301"; case "303": goto case "301"; case "304": goto case "301"; case "305": goto case "301"; case "306": goto case "301"; case "110": //Uso Denegado goto case "301"; default: //Mover o XML da NFE a pasta de XML´s com erro oAux.MoveArqErro(strArquivoCTe); break; } //Deletar a NFE do arquivo de controle de fluxo oFluxoNfe.ExcluirNfeFluxo(strChaveCTe); } } break; #endregion #region Nota fiscal cancelada case "101": //Cancelamento Homologado ou Nfe Cancelada goto case "100"; #endregion #region Nota fiscal Denegada case "110": //NFe Denegada goto case "100"; case "301": //NFe Denegada goto case "100"; case "302": //NFe Denegada goto case "100"; case "303": //NFe Denegada goto case "100"; case "304": //NFe Denegada goto case "100"; case "305": //NFe Denegada goto case "100"; case "306": //NFe Denegada goto case "100"; #endregion #region Conteúdo para retirar a nota fiscal do fluxo case "TirarFluxo": //Mover o XML da NFE a pasta de XML´s com erro oAux.MoveArqErro(strArquivoCTe); //Deletar a NFE do arquivo de controle de fluxo oFluxoNfe.ExcluirNfeFluxo(strChaveCTe); break; #endregion default: break; } } }
public override void Execute() { int emp = Empresas.FindEmpresaByThread(); try { dadosPedSit = new DadosPedSit(); //Ler o XML para pegar parâmetros de envio PedSit(emp, dadosPedSit);// NomeArquivoXML); //Definir o objeto do WebService WebServiceProxy wsProxy = ConfiguracaoApp.DefinirWS(Servico, emp, dadosPedSit.cUF, dadosPedSit.tpAmb, dadosPedSit.tpEmis); System.Net.SecurityProtocolType securityProtocolType = WebServiceProxy.DefinirProtocoloSeguranca(dadosPedSit.cUF, dadosPedSit.tpAmb, dadosPedSit.tpEmis, PadroesNFSe.NaoIdentificado, Servico); //Criar objetos das classes dos serviços dos webservices do SEFAZ object oConsulta = wsProxy.CriarObjeto(wsProxy.NomeClasseWS);//NomeClasseWS(Servico, dadosPedSit.cUF)); object oCabecMsg = wsProxy.CriarObjeto(NomeClasseCabecWS(dadosPedSit.cUF, Servico)); //Atribuir conteúdo para duas propriedades da classe nfeCabecMsg wsProxy.SetProp(oCabecMsg, TpcnResources.cUF.ToString(), dadosPedSit.cUF.ToString()); wsProxy.SetProp(oCabecMsg, TpcnResources.versaoDados.ToString(), NFe.ConvertTxt.versoes.VersaoXMLCTePedSit); //Invocar o método que envia o XML para o SEFAZ oInvocarObj.Invocar(wsProxy, oConsulta, wsProxy.NomeMetodoWS[0],//NomeMetodoWS(Servico, dadosPedSit.cUF), oCabecMsg, this, Propriedade.Extensao(Propriedade.TipoEnvio.PedSit).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedSit).RetornoXML, false, securityProtocolType); //Efetuar a leitura do retorno da situação para ver se foi autorizada ou não //Na versão 1 não posso gerar o -procNfe, ou vou ter que tratar a estrutura do XML de acordo com a versão, a consulta na versão 1 é somente para obter o resultado mesmo. LerRetornoSitCTe(dadosPedSit.chNFe); //Gerar o retorno para o ERP oGerarXML.XmlRetorno(Propriedade.Extensao(Propriedade.TipoEnvio.PedSit).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedSit).RetornoXML, this.vStrXmlRetorno); } catch (Exception ex) { try { TFunctions.GravarArqErroServico(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedSit).EnvioXML, Propriedade.ExtRetorno.Sit_ERR, ex); } catch { //Se falhou algo na hora de gravar o retorno .ERR (de erro) para o ERP, infelizmente não posso fazer mais nada. //Wandrey 09/03/2010 } } finally { try { Functions.DeletarArquivo(NomeArquivoXML); } catch { //Se falhou algo na hora de deletar o XML de pedido da consulta da situação da NFe, infelizmente //não posso fazser mais nada, o UniNFe vai tentar mantar o arquivo novamente para o webservice, pois ainda não foi excluido. //Wandrey 22/03/2010 } } }
public override void Execute() { int emp = Empresas.FindEmpresaByThread(); try { Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlRetorno + "\\" + Functions.ExtrairNomeArq(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedCanCFSe).EnvioXML) + Propriedade.Extensao(Propriedade.TipoEnvio.PedCanCFSe).RetornoERR); Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlErro + "\\" + NomeArquivoXML); oDadosPedCanNfse = new DadosPedCanNfse(emp); PadroesNFSe padraoNFSe = Functions.PadraoNFSe(oDadosPedCanNfse.cMunicipio); WebServiceProxy wsProxy = null; object pedCanNfse = null; //Criar objetos das classes dos serviços dos webservices do SEFAZ if (IsUtilizaCompilacaoWs(padraoNFSe)) { wsProxy = ConfiguracaoApp.DefinirWS(Servico, emp, oDadosPedCanNfse.cMunicipio, oDadosPedCanNfse.tpAmb, oDadosPedCanNfse.tpEmis, padraoNFSe, oDadosPedCanNfse.cMunicipio); if (wsProxy != null) { pedCanNfse = wsProxy.CriarObjeto(wsProxy.NomeClasseWS); } } System.Net.SecurityProtocolType securityProtocolType = WebServiceProxy.DefinirProtocoloSeguranca(oDadosPedCanNfse.cMunicipio, oDadosPedCanNfse.tpAmb, oDadosPedCanNfse.tpEmis, padraoNFSe, Servico); string cabecMsg = ""; switch (padraoNFSe) { case PadroesNFSe.FINTEL: cabecMsg = "<cabecalho versao=\"2.02\" xmlns=\"http://iss.irati.pr.gov.br/Arquivos/nfseV202.xsd\"><versaoDados>2.02</versaoDados></cabecalho>"; break; } if (IsInvocar(padraoNFSe)) { //Assinar o XML AssinaturaDigital ad = new AssinaturaDigital(); ad.Assinar(NomeArquivoXML, emp, oDadosPedCanNfse.cMunicipio); //Invocar o método que envia o XML para o SEFAZ oInvocarObj.InvocarNFSe(wsProxy, pedCanNfse, NomeMetodoWS(Servico, oDadosPedCanNfse.cMunicipio), cabecMsg, this, Propriedade.Extensao(Propriedade.TipoEnvio.PedCanCFSe).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedCanCFSe).RetornoXML, padraoNFSe, Servico, securityProtocolType); /// /// grava o arquivo no FTP string filenameFTP = Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Functions.ExtrairNomeArq(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedCanCFSe).EnvioXML) + Propriedade.Extensao(Propriedade.TipoEnvio.PedCanCFSe).RetornoXML); if (File.Exists(filenameFTP)) { new GerarXML(emp).XmlParaFTP(emp, filenameFTP); } } } catch (Exception ex) { try { //Gravar o arquivo de erro de retorno para o ERP, caso ocorra TFunctions.GravarArqErroServico(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedCanCFSe).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedCanCFSe).RetornoERR, ex); } catch { //Se falhou algo na hora de gravar o retorno .ERR (de erro) para o ERP, infelizmente não posso fazer mais nada. //Wandrey 31/08/2011 } } finally { try { Functions.DeletarArquivo(NomeArquivoXML); } catch { //Se falhou algo na hora de deletar o XML de cancelamento de NFe, infelizmente //não posso fazer mais nada, o UniNFe vai tentar mandar o arquivo novamente para o webservice, pois ainda não foi excluido. //Wandrey 31/08/2011 } } }
public override void Execute() { int emp = Empresas.FindEmpresaByThread(); //Definir o serviço que será executado para a classe Servico = Servicos.NFSeRecepcionarLoteRps; try { Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlRetorno + "\\" + Functions.ExtrairNomeArq(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.EnvLoteRps).EnvioXML) + Propriedade.ExtRetorno.RetEnvLoteRps_ERR); Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlErro + "\\" + NomeArquivoXML); oDadosEnvLoteRps = new DadosEnvLoteRps(emp); EnvLoteRps(emp, NomeArquivoXML); //Criar objetos das classes dos serviços dos webservices do SEFAZ PadroesNFSe padraoNFSe = Functions.PadraoNFSe(oDadosEnvLoteRps.cMunicipio); WebServiceProxy wsProxy = null; object envLoteRps = null; if (IsUtilizaCompilacaoWs(padraoNFSe, Servico, oDadosEnvLoteRps.cMunicipio)) { wsProxy = ConfiguracaoApp.DefinirWS(Servico, emp, oDadosEnvLoteRps.cMunicipio, oDadosEnvLoteRps.tpAmb, oDadosEnvLoteRps.tpEmis, padraoNFSe, oDadosEnvLoteRps.cMunicipio); if (wsProxy != null) { envLoteRps = wsProxy.CriarObjeto(wsProxy.NomeClasseWS); } } System.Net.SecurityProtocolType securityProtocolType = WebServiceProxy.DefinirProtocoloSeguranca(oDadosEnvLoteRps.cMunicipio, oDadosEnvLoteRps.tpAmb, oDadosEnvLoteRps.tpEmis, padraoNFSe, Servico); string cabecMsg = ""; switch (padraoNFSe) { case PadroesNFSe.IPM: //código da cidade da receita federal, este arquivo pode ser encontrado em ~\uninfe\doc\Codigos_Cidades_Receita_Federal.xls</para> //O código da cidade está hardcoded pois ainda está sendo usado apenas para campo mourão IPM ipm = new IPM((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS, oDadosEnvLoteRps.cMunicipio); if (ConfiguracaoApp.Proxy) { ipm.Proxy = Proxy.DefinirProxy(ConfiguracaoApp.ProxyServidor, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyPorta); } ipm.EmiteNF(NomeArquivoXML); break; case PadroesNFSe.GINFES: switch (oDadosEnvLoteRps.cMunicipio) { case 2304400: //Fortaleza - CE cabecMsg = "<ns2:cabecalho versao=\"3\" xmlns:ns2=\"http://www.ginfes.com.br/cabecalho_v03.xsd\"><versaoDados>3</versaoDados></ns2:cabecalho>"; break; case 4125506: //São José dos Pinhais - PR cabecMsg = "<ns2:cabecalho versao=\"3\" xmlns:ns2=\"http://nfe.sjp.pr.gov.br/cabecalho_v03.xsd\"><versaoDados>3</versaoDados></ns2:cabecalho>"; break; default: cabecMsg = "<ns2:cabecalho versao=\"3\" xmlns:ns2=\"http://www.ginfes.com.br/cabecalho_v03.xsd\"><versaoDados>3</versaoDados></ns2:cabecalho>"; break; } break; case PadroesNFSe.ABASE: cabecMsg = "<cabecalho xmlns=\"http://nfse.abase.com.br/nfse.xsd\" versao =\"1.00\"><versaoDados>1.00</versaoDados></cabecalho>"; break; case PadroesNFSe.BETHA: #region Betha string versao = Functions.GetAttributeXML("LoteRps", "versao", NomeArquivoXML); if (versao.Equals("2.02")) { padraoNFSe = PadroesNFSe.BETHA202; Components.Betha.NewVersion.Betha betha = new Components.Betha.NewVersion.Betha((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, oDadosEnvLoteRps.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor); AssinaturaDigital signbetha = new AssinaturaDigital(); signbetha.Assinar(NomeArquivoXML, emp, 202); if (GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.BETHA202) == Servicos.NFSeRecepcionarLoteRpsSincrono) { betha.EmiteNFSincrono(NomeArquivoXML); } else { betha.EmiteNF(NomeArquivoXML); } } else { wsProxy = new WebServiceProxy(Empresas.Configuracoes[emp].X509Certificado); wsProxy.Betha = new Betha(); } break; #endregion Betha case PadroesNFSe.ABACO: case PadroesNFSe.CANOAS_RS: cabecMsg = "<cabecalho versao=\"201001\"><versaoDados>V2010</versaoDados></cabecalho>"; break; case PadroesNFSe.BHISS: cabecMsg = "<cabecalho xmlns=\"http://www.abrasf.org.br/nfse.xsd\" versao=\"1.00\"><versaoDados >1.00</versaoDados ></cabecalho>"; Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.BHISS); break; case PadroesNFSe.SH3: cabecMsg = "<cabecalho xmlns=\"http://www.abrasf.org.br/nfse.xsd\" versao=\"1.00\"><versaoDados >1.00</versaoDados ></cabecalho>"; Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.SH3); break; case PadroesNFSe.WEBISS: cabecMsg = "<cabecalho xmlns=\"http://www.abrasf.org.br/nfse.xsd\" versao=\"1.00\"><versaoDados >1.00</versaoDados ></cabecalho>"; break; case PadroesNFSe.WEBISS_202: Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.WEBISS_202); cabecMsg = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><cabecalho xmlns=\"http://www.abrasf.org.br/nfse.xsd\" versao=\"2.02\"><versaoDados>2.02</versaoDados></cabecalho>"; break; case PadroesNFSe.PAULISTANA: wsProxy = new WebServiceProxy(Empresas.Configuracoes[emp].X509Certificado); //if (oDadosEnvLoteRps.tpAmb == 1) envLoteRps = new Components.PSaoPauloSP.LoteNFe(); //else // throw new Exception("Município de São Paulo-SP não dispõe de ambiente de homologação para envio de NFS-e em teste."); EncryptAssinatura(); break; case PadroesNFSe.NA_INFORMATICA: Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.VVISS); wsProxy = new WebServiceProxy(Empresas.Configuracoes[emp].X509Certificado); //if (oDadosEnvLoteRps.tpAmb == 1) // envLoteRps = new Components.PCorumbaMS.NfseWSService(); //else // envLoteRps = new Components.HCorumbaMS.NfseWSService(); break; case PadroesNFSe.BSITBR: Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.BSITBR); wsProxy = new WebServiceProxy(Empresas.Configuracoes[emp].X509Certificado); if (oDadosEnvLoteRps.tpAmb == 1) { switch (oDadosEnvLoteRps.cMunicipio) { case 5211800: envLoteRps = new Components.PJaraguaGO.nfseWS(); break; case 5220454: envLoteRps = new Components.PSenadorCanedoGO.nfseWS(); break; } } else { throw new Exception("Este município não dispõe de ambiente de homologação para envio de NFS-e em teste."); } break; case PadroesNFSe.PORTOVELHENSE: cabecMsg = "<cabecalho versao=\"2.00\" xmlns:ns2=\"http://www.w3.org/2000/09/xmldsig#\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\"><versaoDados>2.00</versaoDados></cabecalho>"; break; case PadroesNFSe.DSF: if (oDadosEnvLoteRps.cMunicipio == 3549904) { cabecMsg = "<cabecalho versao=\"3\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\"><versaoDados>3</versaoDados></cabecalho>"; } else { EncryptAssinatura(); } break; case PadroesNFSe.TECNOSISTEMAS: cabecMsg = "<?xml version=\"1.0\" encoding=\"utf-8\"?><cabecalho xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" versao=\"20.01\" xmlns=\"http://www.nfse-tecnos.com.br/nfse.xsd\"><versaoDados>20.01</versaoDados></cabecalho>"; break; case PadroesNFSe.FINTEL: cabecMsg = "<cabecalho versao=\"2.02\" xmlns=\"http://iss.irati.pr.gov.br/Arquivos/nfseV202.xsd\"><versaoDados>2.02</versaoDados></cabecalho>"; Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.FINTEL); break; case PadroesNFSe.PORTALFACIL_ACTCON: cabecMsg = "<cabecalho><versaoDados>2.01</versaoDados></cabecalho>"; Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.PORTALFACIL_ACTCON); break; case PadroesNFSe.PORTALFACIL_ACTCON_202: cabecMsg = "<cabecalho><versaoDados>2.02</versaoDados></cabecalho>"; Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.PORTALFACIL_ACTCON_202); break; case PadroesNFSe.SYSTEMPRO: #region SystemPro SystemPro syspro = new SystemPro((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, Empresas.Configuracoes[emp].X509Certificado, oDadosEnvLoteRps.cMunicipio); AssinaturaDigital ad = new AssinaturaDigital(); ad.Assinar(NomeArquivoXML, emp, oDadosEnvLoteRps.cMunicipio); syspro.EmiteNF(NomeArquivoXML); break; #endregion SystemPro case PadroesNFSe.SIGCORP_SIGISS: SigCorp sigcorp = new SigCorp((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, oDadosEnvLoteRps.cMunicipio); sigcorp.EmiteNF(NomeArquivoXML); break; case PadroesNFSe.SIGCORP_SIGISS_203: Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.SIGCORP_SIGISS_203); cabecMsg = "<cabecalho versao=\"2.03\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\"><versaoDados>2.03</versaoDados></cabecalho>"; break; case PadroesNFSe.FIORILLI: #region Fiorilli Fiorilli fiorilli = new Fiorilli((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, oDadosEnvLoteRps.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor, Empresas.Configuracoes[emp].X509Certificado); AssinaturaDigital ass = new AssinaturaDigital(); ass.Assinar(NomeArquivoXML, emp, oDadosEnvLoteRps.cMunicipio); // Validar o Arquivo XML ValidarXML validar = new ValidarXML(NomeArquivoXML, Empresas.Configuracoes[emp].UnidadeFederativaCodigo, false); string resValidacao = validar.ValidarArqXML(NomeArquivoXML); if (resValidacao != "") { throw new Exception(resValidacao); } fiorilli.EmiteNF(NomeArquivoXML); break; #endregion Fiorilli case PadroesNFSe.SIMPLISS: #region Simpliss SimplISS simpliss = new SimplISS((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, oDadosEnvLoteRps.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor); AssinaturaDigital sign = new AssinaturaDigital(); sign.Assinar(NomeArquivoXML, emp, oDadosEnvLoteRps.cMunicipio); simpliss.EmiteNF(NomeArquivoXML); break; #endregion Simpliss case PadroesNFSe.CONAM: #region Conam Conam conam = new Conam((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, oDadosEnvLoteRps.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS); conam.EmiteNF(NomeArquivoXML); break; #endregion Conam case PadroesNFSe.RLZ_INFORMATICA: #region RLZ Rlz_Informatica rlz = new Rlz_Informatica((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, oDadosEnvLoteRps.cMunicipio); rlz.EmiteNF(NomeArquivoXML); break; #endregion RLZ case PadroesNFSe.EGOVERNE: #region E-Governe EGoverne egoverne = new EGoverne((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, oDadosEnvLoteRps.cMunicipio, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor, Empresas.Configuracoes[emp].X509Certificado); AssinaturaDigital assEGovoverne = new AssinaturaDigital(); assEGovoverne.Assinar(NomeArquivoXML, emp, oDadosEnvLoteRps.cMunicipio); egoverne.EmiteNF(NomeArquivoXML); break; #endregion E-Governe case PadroesNFSe.EL: #region E&L EL el = new EL((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, oDadosEnvLoteRps.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS, (ConfiguracaoApp.Proxy ? ConfiguracaoApp.ProxyUsuario : ""), (ConfiguracaoApp.Proxy ? ConfiguracaoApp.ProxySenha : ""), (ConfiguracaoApp.Proxy ? ConfiguracaoApp.ProxyServidor : "")); el.EmiteNF(NomeArquivoXML); break; #endregion E&L case PadroesNFSe.GOVDIGITAL: #region GOV-Digital GovDigital govdig = new GovDigital((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, Empresas.Configuracoes[emp].X509Certificado, oDadosEnvLoteRps.cMunicipio, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor); AssinaturaDigital adgovdig = new AssinaturaDigital(); adgovdig.Assinar(NomeArquivoXML, emp, oDadosEnvLoteRps.cMunicipio); govdig.EmiteNF(NomeArquivoXML); break; #endregion GOV-Digital case PadroesNFSe.EQUIPLANO: cabecMsg = "1"; break; case PadroesNFSe.NATALENSE: cabecMsg = "<cabecalho xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" versao=\"1\" xmlns=\"http://www.abrasf.org.br/ABRASF/arquivos/nfse.xsd\"><versaoDados>1</versaoDados></cabecalho>"; break; case PadroesNFSe.PRODATA: Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.PRODATA); cabecMsg = "<cabecalho><versaoDados>2.01</versaoDados></cabecalho>"; break; case PadroesNFSe.VVISS: Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.VVISS); break; case PadroesNFSe.METROPOLIS: #region METROPOLIS Metropolis metropolis = new Metropolis((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, oDadosEnvLoteRps.cMunicipio, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor, Empresas.Configuracoes[emp].X509Certificado); AssinaturaDigital metropolisdig = new AssinaturaDigital(); metropolisdig.Assinar(NomeArquivoXML, emp, oDadosEnvLoteRps.cMunicipio); metropolis.EmiteNF(NomeArquivoXML); break; #endregion METROPOLIS case PadroesNFSe.MGM: #region MGM MGM mgm = new MGM((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, oDadosEnvLoteRps.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS); mgm.EmiteNF(NomeArquivoXML); break; #endregion MGM case PadroesNFSe.CONSIST: #region Consist Consist consist = new Consist((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, oDadosEnvLoteRps.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor); consist.EmiteNF(NomeArquivoXML); break; #endregion Consist case PadroesNFSe.NOTAINTELIGENTE: #region Nota Inteligente wsProxy = new WebServiceProxy(Empresas.Configuracoes[emp].X509Certificado); if (oDadosEnvLoteRps.tpAmb == 1) { //envLoteRps = new NFe.Components.PClaudioMG.api_portClient(); } else { throw new Exception("Município de São Paulo-SP não dispõe de ambiente de homologação para envio de NFS-e em teste."); } #endregion Nota Inteligente break; case PadroesNFSe.COPLAN: #region Coplan Coplan coplan = new Coplan((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, oDadosEnvLoteRps.cMunicipio, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor, Empresas.Configuracoes[emp].X509Certificado); AssinaturaDigital assCoplan = new AssinaturaDigital(); assCoplan.Assinar(NomeArquivoXML, emp, oDadosEnvLoteRps.cMunicipio); coplan.EmiteNF(NomeArquivoXML); break; #endregion Coplan case PadroesNFSe.MEMORY: #region Memory Memory memory = new Memory((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, oDadosEnvLoteRps.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor); AssinaturaDigital sigMem = new AssinaturaDigital(); sigMem.Assinar(NomeArquivoXML, emp, oDadosEnvLoteRps.cMunicipio); memory.EmiteNF(NomeArquivoXML); break; #endregion Memory case PadroesNFSe.CAMACARI_BA: Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.CAMACARI_BA); cabecMsg = "<cabecalho><versaoDados>2.01</versaoDados><versao>2.01</versao></cabecalho>"; break; case PadroesNFSe.CARIOCA: Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.CARIOCA); break; case PadroesNFSe.PRONIN: if (oDadosEnvLoteRps.cMunicipio == 4109401 || oDadosEnvLoteRps.cMunicipio == 3131703 || oDadosEnvLoteRps.cMunicipio == 4303004 || oDadosEnvLoteRps.cMunicipio == 3556602 || oDadosEnvLoteRps.cMunicipio == 3512803 || oDadosEnvLoteRps.cMunicipio == 4323002 || oDadosEnvLoteRps.cMunicipio == 3505807 || oDadosEnvLoteRps.cMunicipio == 3530300 || oDadosEnvLoteRps.cMunicipio == 4308904 || oDadosEnvLoteRps.cMunicipio == 4118501 || oDadosEnvLoteRps.cMunicipio == 3554300 || oDadosEnvLoteRps.cMunicipio == 3542404 || oDadosEnvLoteRps.cMunicipio == 5005707 || oDadosEnvLoteRps.cMunicipio == 4314423 || oDadosEnvLoteRps.cMunicipio == 3511102 || oDadosEnvLoteRps.cMunicipio == 3535804 || oDadosEnvLoteRps.cMunicipio == 4306932) { Pronin pronin = new Pronin((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, oDadosEnvLoteRps.cMunicipio, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor, Empresas.Configuracoes[emp].X509Certificado); AssinaturaDigital assPronin = new AssinaturaDigital(); assPronin.Assinar(NomeArquivoXML, emp, oDadosEnvLoteRps.cMunicipio); pronin.EmiteNF(NomeArquivoXML); } break; case PadroesNFSe.EGOVERNEISS: #region EGoverne ISS EGoverneISS egoverneiss = new EGoverneISS((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, oDadosEnvLoteRps.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor); egoverneiss.EmiteNF(NomeArquivoXML); break; #endregion EGoverne ISS case PadroesNFSe.SUPERNOVA: Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.SUPERNOVA); break; case PadroesNFSe.MARINGA_PR: Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.MARINGA_PR); break; case PadroesNFSe.BAURU_SP: #region BAURU_SP Bauru_SP bauru_SP = new Bauru_SP((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, oDadosEnvLoteRps.cMunicipio); bauru_SP.EmiteNF(NomeArquivoXML); break; #endregion BAURU_SP #region Tinus case PadroesNFSe.TINUS: Tinus tinus = new Tinus((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, oDadosEnvLoteRps.cMunicipio, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor, Empresas.Configuracoes[emp].X509Certificado); AssinaturaDigital tinusAss = new AssinaturaDigital(); tinusAss.Assinar(NomeArquivoXML, emp, oDadosEnvLoteRps.cMunicipio); tinus.EmiteNF(NomeArquivoXML); break; #endregion Tinus #if _fw46 #region SOFTPLAN case PadroesNFSe.SOFTPLAN: Components.SOFTPLAN.SOFTPLAN softplan = new Components.SOFTPLAN.SOFTPLAN((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, Empresas.Configuracoes[emp].TokenNFse, Empresas.Configuracoes[emp].TokenNFSeExpire, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS, Empresas.Configuracoes[emp].ClientID, Empresas.Configuracoes[emp].ClientSecret); AssinaturaDigital softplanAssinatura = new AssinaturaDigital(); softplanAssinatura.Assinar(NomeArquivoXML, emp, oDadosEnvLoteRps.cMunicipio); // Validar o Arquivo XML ValidarXML softplanValidar = new ValidarXML(NomeArquivoXML, Empresas.Configuracoes[emp].UnidadeFederativaCodigo, false); string validacao = softplanValidar.ValidarArqXML(NomeArquivoXML); if (validacao != "") { throw new Exception(validacao); } if (ConfiguracaoApp.Proxy) { softplan.Proxy = Proxy.DefinirProxy(ConfiguracaoApp.ProxyServidor, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyPorta); } AssinaturaDigital softplanAss = new AssinaturaDigital(); softplanAss.Assinar(NomeArquivoXML, emp, oDadosEnvLoteRps.cMunicipio, AlgorithmType.Sha256); softplan.EmiteNF(NomeArquivoXML); if (Empresas.Configuracoes[emp].TokenNFse != softplan.Token) { Empresas.Configuracoes[emp].SalvarConfiguracoesNFSeSoftplan(softplan.Usuario, softplan.Senha, softplan.ClientID, softplan.ClientSecret, softplan.Token, softplan.TokenExpire, Empresas.Configuracoes[emp].CNPJ); } break; #endregion SOFTPLAN #endif case PadroesNFSe.INTERSOL: cabecMsg = "<?xml version=\"1.0\" encoding=\"utf-8\"?><p:cabecalho versao=\"1\" xmlns:ds=\"http://www.w3.org/2000/09/xmldsig#\" xmlns:p=\"http://ws.speedgov.com.br/cabecalho_v1.xsd\" xmlns:p1=\"http://ws.speedgov.com.br/tipos_v1.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://ws.speedgov.com.br/cabecalho_v1.xsd cabecalho_v1.xsd \"><versaoDados>1</versaoDados></p:cabecalho>"; break; case PadroesNFSe.MANAUS_AM: cabecMsg = "<cabecalho versao=\"201001\"><versaoDados>V2010</versaoDados></cabecalho>"; break; case PadroesNFSe.JOINVILLE_SC: wsProxy = new WebServiceProxy(Empresas.Configuracoes[emp].X509Certificado); if (oDadosEnvLoteRps.tpAmb == 2) { envLoteRps = new Components.HJoinvilleSC.Servicos(); } else { envLoteRps = new Components.PJoinvilleSC.Servicos(); } break; case PadroesNFSe.AVMB_ASTEN: Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.AVMB_ASTEN); cabecMsg = "<cabecalho versao=\"2.02\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\"><versaoDados>2.02</versaoDados></cabecalho>"; wsProxy = new WebServiceProxy(Empresas.Configuracoes[emp].X509Certificado); if (oDadosEnvLoteRps.tpAmb == 2) { envLoteRps = new Components.HPelotasRS.INfseservice(); } else { envLoteRps = new Components.PPelotasRS.INfseservice(); } break; case PadroesNFSe.EMBRAS: Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.EMBRAS); cabecMsg = "<cabecalho versao=\"2.02\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\"><versaoDados>2.02</versaoDados></cabecalho>"; break; case PadroesNFSe.DESENVOLVECIDADE: Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.EMBRAS); break; case PadroesNFSe.MODERNIZACAO_PUBLICA: Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.MODERNIZACAO_PUBLICA); cabecMsg = "<cabecalho xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\" versao=\"2.02\"><versaoDados>2.02</versaoDados></cabecalho>"; break; case PadroesNFSe.E_RECEITA: Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.E_RECEITA); cabecMsg = "<cabecalho xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\" versao=\"2.02\"><versaoDados>2.02</versaoDados></cabecalho>"; break; case PadroesNFSe.TIPLAN_203: Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.TIPLAN_203); cabecMsg = "<cabecalho versao=\"2.03\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\"><versaoDados>2.03</versaoDados></cabecalho>"; break; #if _fw46 case PadroesNFSe.ADM_SISTEMAS: cabecMsg = "<cabecalho versao=\"2.01\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\"><versaoDados>2.01</versaoDados></cabecalho>"; wsProxy = new WebServiceProxy(Empresas.Configuracoes[emp].X509Certificado); envLoteRps = oDadosEnvLoteRps.tpAmb == 1 ? new Components.PAmargosaBA.InfseClient(GetBinding(), new EndpointAddress("https://demo.saatri.com.br/servicos/nfse.svc")) : new Components.HAmargosaBA.InfseClient(GetBinding(), new EndpointAddress("https://homologa-demo.saatri.com.br/servicos/nfse.svc")) as object; SignUsingCredentials(emp, envLoteRps); break; #endif case PadroesNFSe.PUBLIC_SOFT: if (oDadosEnvLoteRps.cMunicipio.Equals(2610707)) { Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.PUBLIC_SOFT); cabecMsg = "N9M="; } break; case PadroesNFSe.MEGASOFT: Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.MEGASOFT); cabecMsg = "<cabecalho versao=\"1.00\" xmlns=\"http://megasoftarrecadanet.com.br/xsd/nfse_v01.xsd\"><versaoDados>1.00</versaoDados></cabecalho>"; break; case PadroesNFSe.SIMPLE: Simple simple = new Simple((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, oDadosEnvLoteRps.cMunicipio, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor, Empresas.Configuracoes[emp].X509Certificado); simple.EmiteNF(NomeArquivoXML); break; case PadroesNFSe.INDAIATUBA_SP: Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.INDAIATUBA_SP); cabecMsg = "<cabecalho versao=\"2.03\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\"><versaoDados>2.03</versaoDados></cabecalho>"; break; case PadroesNFSe.SISPMJP: Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.SISPMJP); cabecMsg = "<cabecalho versao=\"2.02\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\" ><versaoDados>2.02</versaoDados></cabecalho>"; break; case PadroesNFSe.SMARAPD_204: Servico = GetTipoServicoSincrono(Servico, NomeArquivoXML, PadroesNFSe.SMARAPD_204); cabecMsg = "<cabecalho versao=\"2.04\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\"><versaoDados>2.04</versaoDados></cabecalho>"; break; case PadroesNFSe.D2TI: cabecMsg = "<cabecalhoNfseLote xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://www.ctaconsult.com/nfse\"><versao>1.00</versao><ambiente>2</ambiente></cabecalhoNfseLote>"; break; case PadroesNFSe.IIBRASIL: Servico = Servicos.NFSeGerarNfse; cabecMsg = "<cabecalho xmlns=\"http://www.abrasf.org.br/nfse.xsd\" versao=\"2.04\"><versaoDados>2.04</versaoDados></cabecalho>"; break; case PadroesNFSe.WEBFISCO_TECNOLOGIA: WEBFISCO_TECNOLOGIA webTecnologia = new WEBFISCO_TECNOLOGIA((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, oDadosEnvLoteRps.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS); webTecnologia.EmiteNF(NomeArquivoXML); break; } if (IsInvocar(padraoNFSe, Servico, oDadosEnvLoteRps.cMunicipio)) { //Assinar o XML AssinaturaDigital ad = new AssinaturaDigital(); ad.Assinar(NomeArquivoXML, emp, oDadosEnvLoteRps.cMunicipio); //Invocar o método que envia o XML para o SEFAZ oInvocarObj.InvocarNFSe(wsProxy, envLoteRps, NomeMetodoWS(Servico, oDadosEnvLoteRps.cMunicipio), cabecMsg, this, Propriedade.Extensao(Propriedade.TipoEnvio.EnvLoteRps).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.EnvLoteRps).RetornoXML, padraoNFSe, Servico, securityProtocolType); /// /// grava o arquivo no FTP string filenameFTP = Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Functions.ExtrairNomeArq(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.EnvLoteRps).EnvioXML) + "\\" + Propriedade.Extensao(Propriedade.TipoEnvio.EnvLoteRps).RetornoXML); if (File.Exists(filenameFTP)) { new GerarXML(emp).XmlParaFTP(emp, filenameFTP); } } } catch (Exception ex) { try { //Gravar o arquivo de erro de retorno para o ERP, caso ocorra TFunctions.GravarArqErroServico(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.EnvLoteRps).EnvioXML, Propriedade.ExtRetorno.RetEnvLoteRps_ERR, ex); } catch { //Se falhou algo na hora de gravar o retorno .ERR (de erro) para o ERP, infelizmente não posso fazer mais nada. //Wandrey 31/08/2011 } } finally { try { Functions.DeletarArquivo(NomeArquivoXML); } catch { //Se falhou algo na hora de deletar o XML de cancelamento de NFe, infelizmente //não posso fazer mais nada, o UniNFe vai tentar mandar o arquivo novamente para o webservice, pois ainda não foi excluido. //Wandrey 31/08/2011 } } }
public override void Execute() { int emp = Empresas.FindEmpresaByThread(); try { dadosRec = new DadosRecClass(); FluxoNfe fluxoNfe = new FluxoNfe(); LerXML lerXml = new LerXML(); //Ler o XML de Lote para pegar o número do lote que está sendo enviado lerXml.Cte(ConteudoXML); var idLote = lerXml.oDadosNfe.idLote; //Definir o objeto do WebService WebServiceProxy wsProxy = ConfiguracaoApp.DefinirWS( Servico, emp, Convert.ToInt32(lerXml.oDadosNfe.cUF), Convert.ToInt32(lerXml.oDadosNfe.tpAmb), Convert.ToInt32(lerXml.oDadosNfe.tpEmis), 0); System.Net.SecurityProtocolType securityProtocolType = WebServiceProxy.DefinirProtocoloSeguranca(Convert.ToInt32(lerXml.oDadosNfe.cUF), Convert.ToInt32(lerXml.oDadosNfe.tpAmb), Convert.ToInt32(lerXml.oDadosNfe.tpEmis), Servico); //Criar objetos das classes dos serviços dos webservices do SEFAZ object oRecepcao = wsProxy.CriarObjeto(wsProxy.NomeClasseWS); var oCabecMsg = wsProxy.CriarObjeto(NomeClasseCabecWS(Convert.ToInt32(lerXml.oDadosNfe.cUF), Servico)); //Atribuir conteúdo para duas propriedades da classe nfeCabecMsg wsProxy.SetProp(oCabecMsg, TpcnResources.cUF.ToString(), lerXml.oDadosNfe.cUF); wsProxy.SetProp(oCabecMsg, TpcnResources.versaoDados.ToString(), lerXml.oDadosNfe.versao); //Criar objeto da classe de assinatura digita AssinaturaDigital oAD = new AssinaturaDigital(); //Assinar o XML oAD.Assinar(ConteudoXML, emp, Convert.ToInt32(lerXml.oDadosNfe.cUF)); //Mover o arquivo para a pasta em processamento Empresas.Configuracoes[emp].CriarSubPastaEnviado(); string arqEmProcessamento = Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" + PastaEnviados.EmProcessamento.ToString() + "\\" + Path.GetFileName(NomeArquivoXML); StreamWriter sw = File.CreateText(arqEmProcessamento); sw.Write(ConteudoXML.OuterXml); sw.Close(); if (File.Exists(arqEmProcessamento)) { File.Delete(NomeArquivoXML); NomeArquivoXML = arqEmProcessamento; } NumeroLote = oGerarXML.GerarLoteCTeOS(NomeArquivoXML); //Invocar o método que envia o XML para o SEFAZ oInvocarObj.Invocar(wsProxy, oRecepcao, wsProxy.NomeMetodoWS[0], oCabecMsg, this, Propriedade.Extensao(Propriedade.TipoEnvio.CTeOS).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedRec).RetornoXML, false, securityProtocolType); #region Parte que trata o retorno do lote, ou seja, o número do recibo LerRetorno(emp); //Gravar o XML retornado pelo WebService do SEFAZ na pasta de retorno para o ERP //Tem que ser feito neste ponto, pois somente aqui terminamos todo o processo oGerarXML.XmlRetorno(Propriedade.Extensao(Propriedade.TipoEnvio.CTeOS).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedRec).RetornoXML, vStrXmlRetorno, Empresas.Configuracoes[emp].PastaXmlRetorno, NumeroLote.ToString("000000000000000") + Propriedade.Extensao(Propriedade.TipoEnvio.CTeOS).EnvioXML); #endregion Parte que trata o retorno do lote, ou seja, o número do recibo } catch (ExceptionEnvioXML ex) { //Ocorreu algum erro no exato momento em que tentou enviar o XML para o SEFAZ, vou ter que tratar //para ver se o XML chegou lá ou não, se eu consegui pegar o número do recibo de volta ou não, etc. //E ver se vamos tirar o XML do Fluxo ou finalizar ele com a consulta situação da NFe try { //Gravar o arquivo de erro de retorno para o ERP, caso ocorra TFunctions.GravarArqErroServico(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.CTeOS).EnvioXML, Propriedade.ExtRetorno.ProRec_ERR, ex, NumeroLote.ToString("000000000000000") + Propriedade.Extensao(Propriedade.TipoEnvio.CTeOS).EnvioXML); } catch { //Se falhou algo na hora de gravar o retorno .ERR (de erro) para o ERP, infelizmente não posso fazer mais nada. //Wandrey 16/03/2010 } } catch (ExceptionSemInternet ex) { try { //Gravar o arquivo de erro de retorno para o ERP, caso ocorra TFunctions.GravarArqErroServico(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.CTeOS).EnvioXML, Propriedade.ExtRetorno.ProRec_ERR, ex, NumeroLote.ToString("000000000000000") + Propriedade.Extensao(Propriedade.TipoEnvio.CTeOS).EnvioXML); } catch { //Se falhou algo na hora de gravar o retorno .ERR (de erro) para o ERP, infelizmente não posso fazer mais nada. //Wandrey 16/03/2010 } } catch (Exception ex) { try { //Gravar o arquivo de erro de retorno para o ERP, caso ocorra TFunctions.GravarArqErroServico(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.CTeOS).EnvioXML, Propriedade.ExtRetorno.ProRec_ERR, ex, NumeroLote.ToString("000000000000000") + Propriedade.Extensao(Propriedade.TipoEnvio.CTeOS).EnvioXML); } catch { //Se falhou algo na hora de gravar o retorno .ERR (de erro) para o ERP, infelizmente não posso fazer mais nada. //Wandrey 16/03/2010 } } }
private void LerRetorno(int emp) { /* * vStrXmlRetorno = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" + * "<retCTeOS versao=\"3.00\" xmlns=\"http://www.portalfiscal.inf.br/cte\"><tpAmb>2</tpAmb><cUF>35</cUF><verAplic>SP-CTe-23-06-2017</verAplic><cStat>100</cStat><xMotivo>Autorizado o uso do CT-e</xMotivo><protCTe versao=\"3.00\"><infProt><tpAmb>2</tpAmb><verAplic>SP-CTe-23-06-2017</verAplic><chCTe>35170746014122000138670000000000061860795141</chCTe><dhRecbto>2017-07-21T09:52:19-03:00</dhRecbto><nProt>135170008578938</nProt><digVal>iYpkun2Ovm+sp+eMkzDtX6gtkzI=</digVal><cStat>100</cStat><xMotivo>Autorizado o uso do CT-e</xMotivo></infProt></protCTe></retCTeOS>"; */ /* * vStrXmlRetorno = "<retCTeOS versao=\"3.00\" xmlns=\"http://www.portalfiscal.inf.br/cte\"><tpAmb>2</tpAmb><cUF>35</cUF><verAplic>SP-CTe-23-06-2017</verAplic><cStat>100</cStat><xMotivo>Autorizado o uso do CT-e</xMotivo><protCTe versao=\"3.00\"><infProt><tpAmb>2</tpAmb><verAplic>SP-CTe-23-06-2017</verAplic><chCTe>35170746014122000138670000000000261309301440</chCTe><dhRecbto>2017-07-26T11:47:48-03:00</dhRecbto><nProt>135170008595733</nProt><digVal>XTkEEwjNnoYasDYz/VJ7HuZVUEo=</digVal><cStat>100</cStat><xMotivo>Autorizado o uso do CT-e</xMotivo></infProt></protCTe></retCTeOS>"; */ var oLerXml = new LerXML(); var doc = new XmlDocument(); doc.Load(Functions.StringXmlToStreamUTF8(vStrXmlRetorno)); var retConsReciNFeList = doc.GetElementsByTagName("retCTeOS"); foreach (XmlNode retConsReciNFeNode in retConsReciNFeList) { var retConsReciNFeElemento = (XmlElement)retConsReciNFeNode; //Pegar o número do recibo do lote enviado var nRec = string.Empty; if (retConsReciNFeElemento.GetElementsByTagName(TpcnResources.nRec.ToString())[0] != null) { nRec = retConsReciNFeElemento.GetElementsByTagName(TpcnResources.nRec.ToString())[0].InnerText; } //Pegar o status de retorno do lote enviado var cStatLote = string.Empty; if (retConsReciNFeElemento.GetElementsByTagName(TpcnResources.cStat.ToString())[0] != null) { cStatLote = retConsReciNFeElemento.GetElementsByTagName(TpcnResources.cStat.ToString())[0].InnerText; } switch (cStatLote) { #region Rejeições do XML de consulta do recibo (Não é o lote que foi rejeitado e sim o XML de consulta do recibo) case "280": //A-Certificado transmissor inválido case "281": //A-Validade do certificado case "283": //A-Verifica a cadeia de Certificação case "286": //A-LCR do certificado de Transmissor case "284": //A-Certificado do Transmissor revogado case "285": //A-Certificado Raiz difere da "IPC-Brasil" case "282": //A-Falta a extensão de CNPJ no Certificado case "214": //B-Tamanho do XML de dados superior a 500 Kbytes case "243": //B-XML de dados mal formatado case "108": //B-Verifica se o Serviço está paralisado momentaneamente case "109": //B-Verifica se o serviço está paralisado sem previsão case "242": //C-Elemento nfeCabecMsg inexistente no SOAP Header case "409": //C-Campo cUF inexistente no elemento nfeCabecMsg do SOAP Header case "410": //C-Campo versaoDados inexistente no elemento nfeCabecMsg do SOAP case "411": //C-Campo versaoDados inexistente no elemento nfeCabecMsg do SOAP case "238": //C-Versão dos Dados informada é superior à versão vigente case "239": //C-Versão dos Dados não suportada case "215": //D-Verifica schema XML da área de dados case "404": //D-Verifica o uso de prefixo no namespace case "402": //D-XML utiliza codificação diferente de UTF-8 case "252": //E-Tipo do ambiente da NF-e difere do ambiente do web service case "226": //E-UF da Chave de Acesso difere da UF do Web Service case "236": //E-Valida DV da Chave de Acesso case "217": //E-Acesso BD CTE case "216": //E-Verificar se campo "Codigo Numerico" break; #endregion Rejeições do XML de consulta do recibo (Não é o lote que foi rejeitado e sim o XML de consulta do recibo) #region Lote ainda está sendo processado case "105": //E-Verifica se o lote não está na fila de resposta, mas está na fila de entrada (Lote em processamento) //Ok vou aguardar o ERP gerar uma nova consulta para encerrar o fluxo da nota break; #endregion Lote ainda está sendo processado #region Lote foi processado, agora tenho que tratar as notas fiscais dele case "104": //Lote processado case "100": //Processo sincrono já retorna como 100 var protNFeList = retConsReciNFeElemento.GetElementsByTagName("protCTe"); foreach (XmlNode protNFeNode in protNFeList) { var protNFeElemento = (XmlElement)protNFeNode; var strProtNfe = protNFeElemento.OuterXml; var infProtList = protNFeElemento.GetElementsByTagName("infProt"); foreach (XmlNode infProtNode in infProtList) { var infProtElemento = (XmlElement)infProtNode; var strStat = string.Empty; if (infProtElemento.GetElementsByTagName(TpcnResources.cStat.ToString())[0] != null) { strStat = infProtElemento.GetElementsByTagName(TpcnResources.cStat.ToString())[0].InnerText; } //Definir o nome do arquivo da NFe e seu caminho var strArquivoNFe = NomeArquivoXML; switch (strStat) { case "100": //NFe Autorizada if (File.Exists(strArquivoNFe)) { //Ler o XML para pegar a data de emissão para criar a pasta dos XML´s autorizados XmlDocument conteudoXMLCTe = new XmlDocument(); conteudoXMLCTe.Load(strArquivoNFe); oLerXml.Cte(conteudoXMLCTe); //Juntar o protocolo com a NFE já copiando para a pasta em processamento var strArquivoNFeProc = oGerarXML.XmlDistCTeOS(strArquivoNFe, strProtNfe, oLerXml.oDadosNfe.versao); //Mover a cteProc da pasta de CTe em processamento para a NFe Autorizada //Para envitar falhar, tenho que mover primeiro o XML de distribuição (-procCTe.xml) para //depois mover o da nfe (-cte.xml), pois se ocorrer algum erro, tenho como reconstruir o senário, //assim sendo não inverta as posições. Wandrey 08/10/2009 TFunctions.MoverArquivo(strArquivoNFeProc, PastaEnviados.Autorizados, oLerXml.oDadosNfe.dEmi); //Mover a CTe da pasta de CTe em processamento para CTe Autorizada //Para envitar falhar, tenho que mover primeiro o XML de distribuição (-procCTe.xml) para //depois mover o da nfe (-cte.xml), pois se ocorrer algum erro, tenho como reconstruir o cenário. //assim sendo não inverta as posições. Wandrey 08/10/2009 TFunctions.MoverArquivo(strArquivoNFe, PastaEnviados.Autorizados, oLerXml.oDadosNfe.dEmi); //Disparar a geração/impressao do UniDanfe. 03/02/2010 - Wandrey try { var strArquivoDist = Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" + PastaEnviados.Autorizados.ToString() + "\\" + Empresas.Configuracoes[emp].DiretorioSalvarComo.ToString(oLerXml.oDadosNfe.dEmi) + Path.GetFileName(strArquivoNFeProc); TFunctions.ExecutaUniDanfe(strArquivoDist, oLerXml.oDadosNfe.dEmi, Empresas.Configuracoes[emp]); } catch (Exception ex) { Auxiliar.WriteLog("TaskCTeRetRecepcao: " + ex.Message, false); } } break; case "301": //NFe Denegada - Irregularidade fiscal do emitente if (File.Exists(strArquivoNFe)) { //Ler o XML para pegar a data de emissão para criar a pasta dos XML´s Denegados XmlDocument conteudoXMLCTe = new XmlDocument(); conteudoXMLCTe.Load(strArquivoNFe); oLerXml.Cte(conteudoXMLCTe); //Mover a NFE da pasta de NFE em processamento para NFe Denegadas TFunctions.MoverArquivo(strArquivoNFe, PastaEnviados.Denegados, oLerXml.oDadosNfe.dEmi); /// /// existe DACTE de CTe denegado??? /// try { var strArquivoDist = Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" + PastaEnviados.Denegados.ToString() + "\\" + Empresas.Configuracoes[emp].DiretorioSalvarComo.ToString(oLerXml.oDadosNfe.dEmi) + Functions.ExtrairNomeArq(strArquivoNFe, Propriedade.Extensao(Propriedade.TipoEnvio.CTe).EnvioXML) + Propriedade.ExtRetorno.Den; TFunctions.ExecutaUniDanfe(strArquivoDist, oLerXml.oDadosNfe.dEmi, Empresas.Configuracoes[emp]); } catch (Exception ex) { Auxiliar.WriteLog("TaskCTeRecepcaoOS: " + ex.Message, false); } } break; case "302": //NFe Denegada - Irregularidade fiscal do remetente goto case "301"; case "303": //NFe Denegada - Irregularidade fiscal do destinatário goto case "301"; case "304": //NFe Denegada - Irregularidade fiscal do expedidor goto case "301"; case "305": //NFe Denegada - Irregularidade fiscal do recebedor goto case "301"; case "306": //NFe Denegada - Irregularidade fiscal do tomador goto case "301"; case "110": //NFe Denegada - Não sei quando ocorre este, mas descobrir ele no manual então estou incluindo. Wandrey 20/10/2009 goto case "301"; default: //NFe foi rejeitada //Mover o XML da NFE a pasta de XML´s com erro oAux.MoveArqErro(strArquivoNFe); break; } break; } } break; #endregion Lote foi processado, agora tenho que tratar as notas fiscais dele #region Qualquer outro tipo de status que não for os acima relacionados, vai tirar a nota fiscal do fluxo. default: //Qualquer outro tipo de rejeião vou tirar todas as notas do lote do fluxo, pois se o lote foi rejeitado, todas as notas fiscais também foram //De acordo com o manual de integração se o status do lote não for 104, tudo foi rejeitado. Wandrey 20/07/2010 TFunctions.MoveArqErro(NomeArquivoXML); break; #endregion Qualquer outro tipo de status que não for os acima relacionados, vai tirar a nota fiscal do fluxo. } } }
/// <summary> /// Faz a leitura do XML de pedido de consulta da situação da NFe /// </summary> /// <param name="arquivoXML">Nome do XML a ser lido</param> /// <param name="emp">Código da empresa</param> /* * private void PedSit(int emp, string arquivoXML) * { * this.dadosPedSit.tpAmb = Empresas.Configuracoes[emp].AmbienteCodigo; * this.dadosPedSit.chNFe = string.Empty; * * XmlDocument doc = new XmlDocument(); * doc.Load(arquivoXML); * * XmlNodeList consSitNFeList = doc.GetElementsByTagName("consSitMDFe"); * * foreach (XmlNode consSitNFeNode in consSitNFeList) * { * XmlElement consSitNFeElemento = (XmlElement)consSitNFeNode; * * dadosPedSit.tpAmb = Convert.ToInt32("0" + consSitNFeElemento.GetElementsByTagName(NFe.Components.TpcnResources.tpAmb.ToString())[0].InnerText); * dadosPedSit.chNFe = consSitNFeElemento.GetElementsByTagName(TpcnResources.chMDFe.ToString())[0].InnerText; * * if (consSitNFeElemento.GetElementsByTagName(NFe.Components.TpcnResources.tpEmis.ToString()).Count != 0) * { * this.dadosPedSit.tpEmis = Convert.ToInt16(consSitNFeElemento.GetElementsByTagName(NFe.Components.TpcnResources.tpEmis.ToString())[0].InnerText); * /// para que o validador não rejeite, excluo a tag <tpEmis> * doc.DocumentElement.RemoveChild(consSitNFeElemento.GetElementsByTagName(NFe.Components.TpcnResources.tpEmis.ToString())[0]); * /// salvo o arquivo modificado * doc.Save(arquivoXML); * } * } * }*/ #endregion #region LerRetornoSitMDFe() /// <summary> /// Ler o retorno da consulta situação da nota fiscal e de acordo com o status ele trata as notas enviadas se ainda não foram tratadas /// </summary> /// <param name="ChaveMDFe">Chave da NFe que está sendo consultada</param> /// <remarks> /// Autor: Wandrey Mundin Ferreira /// Data: 16/06/2010 /// </remarks> private void LerRetornoSitMDFe(string ChaveMDFe) { int emp = Empresas.FindEmpresaByThread(); oGerarXML.XmlDistEventoMDFe(emp, this.vStrXmlRetorno); LerXML oLerXml = new LerXML(); MemoryStream msXml = Functions.StringXmlToStreamUTF8(this.vStrXmlRetorno); FluxoNfe oFluxoNfe = new FluxoNfe(); XmlDocument doc = new XmlDocument(); doc.Load(msXml); XmlNodeList retConsSitList = doc.GetElementsByTagName("retConsSitMDFe"); foreach (XmlNode retConsSitNode in retConsSitList) { XmlElement retConsSitElemento = (XmlElement)retConsSitNode; //Definir a chave da NFe a ser pesquisada string strChaveNFe = "MDFe" + ChaveMDFe; //Definir o nome do arquivo da NFe e seu caminho string strNomeArqNfe = oFluxoNfe.LerTag(strChaveNFe, FluxoNfe.ElementoFixo.ArqNFe); if (string.IsNullOrEmpty(strNomeArqNfe)) { strNomeArqNfe = strChaveNFe.Substring(4) + Propriedade.Extensao(Propriedade.TipoEnvio.MDFe).EnvioXML; } string strArquivoNFe = Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" + PastaEnviados.EmProcessamento.ToString() + "\\" + strNomeArqNfe; #region CNPJ da chave não é de uma empresa Uninfe bool notDaEmpresa = (ChaveMDFe.Substring(6, 14) != Empresas.Configuracoes[emp].CNPJ || ChaveMDFe.Substring(0, 2) != Empresas.Configuracoes[emp].UnidadeFederativaCodigo.ToString()); if (!File.Exists(strArquivoNFe) && notDaEmpresa) { return; } #endregion //Pegar o status de retorno da NFe que está sendo consultada a situação var cStatCons = string.Empty; if (retConsSitElemento.GetElementsByTagName(TpcnResources.cStat.ToString())[0] != null) { cStatCons = retConsSitElemento.GetElementsByTagName(TpcnResources.cStat.ToString())[0].InnerText; } switch (cStatCons) { #region Rejeições do XML de consulta da situação da NFe (Não é a nfe que foi rejeitada e sim o XML de consulta da situação da nfe) #region Validação do Certificado de Transmissão case "280": case "281": case "283": case "286": case "284": case "285": case "282": #endregion #region Validação Inicial da Mensagem no WebService case "214": case "243": case "108": case "109": #endregion #region Validação das informações de controle da chamada ao WebService case "242": case "409": case "410": case "411": case "238": case "239": #endregion #region Validação da forma da área de dados case "215": case "598": case "599": case "404": case "402": #endregion #region Validação das regras de negócios da consulta a NF-e case "252": case "226": case "494": case "227": case "253": break; #endregion #region Nota fiscal rejeitada case "217": //J-NFe não existe na base de dados do SEFAZ goto case "TirarFluxo"; #endregion #endregion #region Nota fiscal autorizada case "100": //Autorizado o uso da NFe XmlNodeList infConsSitList = retConsSitElemento.GetElementsByTagName("infProt"); if (infConsSitList != null) { foreach (XmlNode infConsSitNode in infConsSitList) { XmlElement infConsSitElemento = (XmlElement)infConsSitNode; //Pegar o Status do Retorno da consulta situação string strStat = Functions.LerTag(infConsSitElemento, NFe.Components.TpcnResources.cStat.ToString()).Replace(";", ""); switch (strStat) { case "100": var strProtNfe = retConsSitElemento.GetElementsByTagName("protMDFe")[0].OuterXml; //Definir o nome do arquivo -procNfe.xml string strArquivoNFeProc = Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" + PastaEnviados.EmProcessamento.ToString() + "\\" + Functions.ExtrairNomeArq(strArquivoNFe, Propriedade.Extensao(Propriedade.TipoEnvio.MDFe).EnvioXML) + Propriedade.ExtRetorno.ProcMDFe; //Se existir o strArquivoNfe, tem como eu fazer alguma coisa, se ele não existir //Não tenho como fazer mais nada. Wandrey 08/10/2009 if (File.Exists(strArquivoNFe)) { //Ler o XML para pegar a data de emissão para criar a pasta dos XML´s autorizados oLerXml.Mdfe(strArquivoNFe); //Verificar se a -nfe.xml existe na pasta de autorizados bool NFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoNFe, oLerXml.oDadosNfe.dEmi, Propriedade.Extensao(Propriedade.TipoEnvio.MDFe).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.MDFe).EnvioXML); //Verificar se o -procNfe.xml existe na past de autorizados bool procNFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoNFe, oLerXml.oDadosNfe.dEmi, Propriedade.Extensao(Propriedade.TipoEnvio.MDFe).EnvioXML, Propriedade.ExtRetorno.ProcMDFe); //Se o XML de distribuição não estiver na pasta de autorizados if (!procNFeJaNaAutorizada) { if (!File.Exists(strArquivoNFeProc)) { oGerarXML.XmlDistMDFe(strArquivoNFe, strProtNfe, Propriedade.ExtRetorno.ProcMDFe); } } //Se o XML de distribuição não estiver ainda na pasta de autorizados if (!(procNFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoNFe, oLerXml.oDadosNfe.dEmi, Propriedade.Extensao(Propriedade.TipoEnvio.MDFe).EnvioXML, Propriedade.ExtRetorno.ProcMDFe))) { //Move a nfeProc da pasta de NFE em processamento para a NFe Autorizada TFunctions.MoverArquivo(strArquivoNFeProc, PastaEnviados.Autorizados, oLerXml.oDadosNfe.dEmi); //Atualizar a situação para que eu só mova o arquivo com final -NFe.xml para a pasta autorizado se //a procnfe já estiver lá, ou vai ficar na pasta emProcessamento para tentar gerar novamente. //Isso vai dar uma maior segurança para não deixar sem gerar o -procnfe.xml. Wandrey 13/12/2012 procNFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoNFe, oLerXml.oDadosNfe.dEmi, Propriedade.Extensao(Propriedade.TipoEnvio.MDFe).EnvioXML, Propriedade.ExtRetorno.ProcMDFe); } //Se a NFe não existir ainda na pasta de autorizados if (!(NFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoNFe, oLerXml.oDadosNfe.dEmi, Propriedade.Extensao(Propriedade.TipoEnvio.MDFe).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.MDFe).EnvioXML))) { //1-Mover a NFE da pasta de NFE em processamento para NFe Autorizada //2-Só vou mover o -nfe.xml para a pasta autorizados se já existir a -procnfe.xml, caso contrário vou manter na pasta EmProcessamento // para tentar gerar novamente o -procnfe.xml // Isso vai dar uma maior segurança para não deixar sem gerar o -procnfe.xml. Wandrey 13/12/2012 if (procNFeJaNaAutorizada) { TFunctions.MoverArquivo(strArquivoNFe, PastaEnviados.Autorizados, oLerXml.oDadosNfe.dEmi); } } else { //1-Se já estiver na pasta de autorizados, vou somente mover ela da pasta de XML´s em processamento //2-Só vou mover o -nfe.xml da pasta EmProcessamento se também existir a -procnfe.xml na pasta autorizados, caso contrário vou manter na pasta EmProcessamento // para tentar gerar novamente o -procnfe.xml // Isso vai dar uma maior segurança para não deixar sem gerar o -procnfe.xml. Wandrey 13/12/2012 if (procNFeJaNaAutorizada) { oAux.MoveArqErro(strArquivoNFe); } //oAux.DeletarArquivo(strArquivoNFe); } //Disparar a geração/impressão do UniDanfe. 03/02/2010 - Wandrey if (procNFeJaNaAutorizada) { string strArquivoDist = Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" + PastaEnviados.Autorizados.ToString() + "\\" + Empresas.Configuracoes[emp].DiretorioSalvarComo.ToString(oLerXml.oDadosNfe.dEmi) + Functions.ExtrairNomeArq(strArquivoNFe, Propriedade.Extensao(Propriedade.TipoEnvio.MDFe).EnvioXML) + Propriedade.ExtRetorno.ProcMDFe; try { TFunctions.ExecutaUniDanfe(strArquivoDist, oLerXml.oDadosNfe.dEmi, Empresas.Configuracoes[emp]); } catch (Exception ex) { Auxiliar.WriteLog("TaskMDFeConsultaSituacao: " + ex.Message, false); } } } if (File.Exists(strArquivoNFeProc)) { //Se já estiver na pasta de autorizados, vou somente excluir ela da pasta de XML´s em processamento Functions.DeletarArquivo(strArquivoNFeProc); } break; default: //Mover o XML da NFE a pasta de XML´s com erro oAux.MoveArqErro(strArquivoNFe); break; } //Deletar a NFE do arquivo de controle de fluxo oFluxoNfe.ExcluirNfeFluxo(strChaveNFe); } } break; #endregion #region Nota fiscal cancelada case "101": //Cancelamento Homologado ou Nfe Cancelada goto case "100"; #endregion #region Conteúdo para retirar a nota fiscal do fluxo case "TirarFluxo": //Mover o XML da NFE a pasta de XML´s com erro oAux.MoveArqErro(strArquivoNFe); //Deletar a NFE do arquivo de controle de fluxo oFluxoNfe.ExcluirNfeFluxo(strChaveNFe); break; #endregion default: break; } } }
public override void Execute() { int emp = Empresas.FindEmpresaByThread(); try { dadosEnvEvento = new DadosenvEvento(); //Ler o XML para pegar parâmetros de envio EnvEvento(emp, dadosEnvEvento); ValidaEvento(emp, dadosEnvEvento); //vai pegar o ambiente da Chave da Nfe autorizada p/ corrigir tpEmis int tpEmis = dadosEnvEvento.eventos[0].tpEmis; //Pegar o estado da chave, pois na cOrgao pode vir o estado 91 - Wandreuy 22/08/2012 int cOrgao = dadosEnvEvento.eventos[0].cOrgao; int ufParaWS = cOrgao; //Se o cOrgao for igual a 91 tenho que mudar a ufParaWS para que na hora de buscar o WSDL para conectar ao serviço, ele consiga encontrar. Wandrey 23/01/2013 if (cOrgao == 91) { ufParaWS = Convert.ToInt32(dadosEnvEvento.eventos[0].chNFe.Substring(0, 2)); } //Definir o objeto do WebService WebServiceProxy wsProxy = ConfiguracaoApp.DefinirWS(Servico, emp, ufParaWS, dadosEnvEvento.eventos[0].tpAmb, tpEmis, 0); System.Net.SecurityProtocolType securityProtocolType = WebServiceProxy.DefinirProtocoloSeguranca(ufParaWS, dadosEnvEvento.eventos[0].tpAmb, tpEmis, Servico); object oRecepcaoEvento = wsProxy.CriarObjeto(wsProxy.NomeClasseWS); object oCabecMsg = wsProxy.CriarObjeto(NomeClasseCabecWS(cOrgao, Servico)); wsProxy.SetProp(oCabecMsg, TpcnResources.cUF.ToString(), cOrgao.ToString()); wsProxy.SetProp(oCabecMsg, TpcnResources.versaoDados.ToString(), dadosEnvEvento.versao); //Criar objeto da classe de assinatura digital AssinaturaDigital oAD = new AssinaturaDigital(); //Assinar o XML oAD.Assinar(ConteudoXML, emp, cOrgao); oInvocarObj.Invocar(wsProxy, oRecepcaoEvento, wsProxy.NomeMetodoWS[0], oCabecMsg, this, Propriedade.Extensao(Propriedade.TipoEnvio.PedEve).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedEve).RetornoXML, true, securityProtocolType); //Ler o retorno LerRetornoEvento(emp); } catch (Exception ex) { try { //Gravar o arquivo de erro de retorno para o ERP, caso ocorra TFunctions.GravarArqErroServico(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedEve).EnvioXML, Propriedade.ExtRetorno.Eve_ERR, ex); } catch { //Se falhou algo na hora de gravar o retorno .ERR (de erro) para o ERP, infelizmente não posso fazer mais nada. //Wandrey 09/03/2010 } } finally { try { Functions.DeletarArquivo(NomeArquivoXML); } catch { //Se falhou algo na hora de deletar o XML de evento, infelizmente //não posso fazer mais nada, o UniNFe vai tentar mandar o arquivo novamente para o webservice, pois ainda não foi excluido. //Wandrey 09/03/2010 } } }
/// <summary> /// Efetua a leitura do XML de retorno do processamento da Inutilização /// </summary> /// <by>Wandrey Mundin Ferreira</by> /// <date>21/04/2009</date> private void LerRetornoInut() { int emp = Empresas.FindEmpresaByThread(); //vStrXmlRetorno = "<retInutNFe versao=\"3.10\" xmlns=\"http://www.portalfiscal.inf.br/nfe\"><infInut><tpAmb>1</tpAmb><verAplic>SP_NFE_PL_008i2</verAplic><cStat>102</cStat><xMotivo>Inutilização de número homologado</xMotivo><cUF>35</cUF><ano>17</ano><CNPJ>48221139000191</CNPJ><mod>55</mod><serie>1</serie><nNFIni>46066</nNFIni><nNFFin>46066</nNFFin><dhRecbto>2017-03-27T09:58:07-03:00</dhRecbto><nProt>135170189046750</nProt></infInut></retInutNFe>"; XmlDocument doc = new XmlDocument(); doc.Load(Functions.StringXmlToStream(vStrXmlRetorno)); XmlNodeList retInutNFeList = doc.GetElementsByTagName("retInutNFe"); foreach (XmlNode retInutNFeNode in retInutNFeList) { XmlElement retInutNFeElemento = (XmlElement)retInutNFeNode; XmlNodeList infInutList = retInutNFeElemento.GetElementsByTagName("infInut"); foreach (XmlNode infInutNode in infInutList) { XmlElement infInutElemento = (XmlElement)infInutNode; if (infInutElemento.GetElementsByTagName(TpcnResources.cStat.ToString())[0].InnerText == "102") //Inutilização de Número Homologado { string strRetInutNFe = retInutNFeNode.OuterXml; oGerarXML.XmlDistInut(ConteudoXML, strRetInutNFe, NomeArquivoXML); //Move o arquivo de solicitação do serviço para a pasta de enviados autorizados StreamWriter sw = File.CreateText(NomeArquivoXML); sw.Write(ConteudoXML.OuterXml); sw.Close(); TFunctions.MoverArquivo(NomeArquivoXML, PastaEnviados.Autorizados, DateTime.Now); //Move o arquivo de Distribuição para a pasta de enviados autorizados string strNomeArqProcInutNFe = Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" + PastaEnviados.EmProcessamento.ToString() + "\\" + Functions.ExtrairNomeArq(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedInu).EnvioXML) + Propriedade.ExtRetorno.ProcInutNFe; TFunctions.MoverArquivo(strNomeArqProcInutNFe, PastaEnviados.Autorizados, DateTime.Now); } else { //Deletar o arquivo de solicitação do serviço da pasta de envio Functions.DeletarArquivo(NomeArquivoXML); } } } }
public override void Execute() { int emp = Empresas.FindEmpresaByThread(); List <string> arquivosNFe = new List <string>(); //Aguardar a assinatura de todos os arquivos da pasta de lotes arquivosNFe = oAux.ArquivosPasta(Empresas.Configuracoes[emp].PastaXmlEmLote, "*" + Propriedade.Extensao(Propriedade.TipoEnvio.MDFe).EnvioXML); if (arquivosNFe.Count == 0) { List <ArquivoXMLDFe> notas = new List <ArquivoXMLDFe>(); FileStream fsArquivo = null; FluxoNfe fluxoNfe = new FluxoNfe(); try { try { XmlDocument doc = new XmlDocument(); //Criar instância do XmlDocument Class fsArquivo = new FileStream(NomeArquivoXML, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //Abrir um arquivo XML usando FileStream doc.Load(fsArquivo); //Carregar o arquivo aberto no XmlDocument string versaoXml = string.Empty; XmlNodeList documentoList = doc.GetElementsByTagName("MontarLoteMDFe"); //Pesquisar o elemento Documento no arquivo XML foreach (XmlNode documentoNode in documentoList) { XmlElement documentoElemento = (XmlElement)documentoNode; int QtdeArquivo = documentoElemento.GetElementsByTagName("ArquivoMDFe").Count; for (int d = 0; d < QtdeArquivo; d++) { string arquivoNFe = Empresas.Configuracoes[emp].PastaXmlEmLote + "\\temp\\" + documentoElemento.GetElementsByTagName("ArquivoMDFe")[d].InnerText; if (File.Exists(arquivoNFe)) { XmlDocument conteudoXMLMDFe = new XmlDocument(); conteudoXMLMDFe.Load(arquivoNFe); DadosNFeClass oDadosNfe = LerXMLNFe(conteudoXMLMDFe); if (string.IsNullOrEmpty(versaoXml)) { versaoXml = oDadosNfe.versao; } if (!fluxoNfe.NFeComLote(oDadosNfe.chavenfe)) { notas.Add(new ArquivoXMLDFe() { NomeArquivoXML = arquivoNFe, ConteudoXML = conteudoXMLMDFe }); } else { throw new Exception("Arquivo: " + arquivoNFe + " já está no fluxo de envio e não será incluido em novo lote."); } } else { throw new Exception("Arquivo: " + arquivoNFe + " não existe e não será incluido no lote!"); } } } fsArquivo.Close(); XmlDocument xmlLote = LoteNfe(notas, versaoXml); TaskMDFeRecepcao mdfeRecepcao = new TaskMDFeRecepcao(xmlLote); mdfeRecepcao.Execute(); } catch { if (fsArquivo != null) { fsArquivo.Close(); } } //Deletar o arquivo de solicitão de montagem do lote de NFe FileInfo oArquivo = new FileInfo(NomeArquivoXML); oArquivo.Delete(); } catch (Exception ex) { try { TFunctions.GravarArqErroServico(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.MontarLote).EnvioXML, Propriedade.ExtRetorno.MontarLote_ERR, ex); } catch { //Se deu algum erro na hora de gravar o arquivo de erro de retorno para o ERP, infelizmente não poderemos fazer nada //pois deve estar ocorrendo alguma falha de rede, hd, permissão de acesso a pasta ou arquivos, etc. Wandrey 22/03/2010 //TODO: Não poderia gravar algum LOG para análise? Erro de rede normalmente é erro de IO } } } }
public override void Execute() { int emp = Empresas.FindEmpresaByThread(); try { dadosPedInut = new DadosPedInut(emp); PedInut(emp); if (vXmlNfeDadosMsgEhXML) //danasa 12-9-2009 { //Definir o objeto do WebService WebServiceProxy wsProxy = ConfiguracaoApp.DefinirWS(Servico, emp, dadosPedInut.cUF, dadosPedInut.tpAmb, dadosPedInut.tpEmis, dadosPedInut.versao, dadosPedInut.mod.ToString(), 0); System.Net.SecurityProtocolType securityProtocolType = WebServiceProxy.DefinirProtocoloSeguranca(dadosPedInut.cUF, dadosPedInut.tpAmb, dadosPedInut.tpEmis, Servico); //Criar objetos das classes dos serviços dos webservices do SEFAZ object oInutilizacao = wsProxy.CriarObjeto(wsProxy.NomeClasseWS); object oCabecMsg = null; if (dadosPedInut.versao != "4.00") { oCabecMsg = wsProxy.CriarObjeto(NomeClasseCabecWS(dadosPedInut.cUF, Servico)); wsProxy.SetProp(oCabecMsg, TpcnResources.cUF.ToString(), dadosPedInut.cUF.ToString()); wsProxy.SetProp(oCabecMsg, TpcnResources.versaoDados.ToString(), dadosPedInut.versao); } //Assinar o XML AssinaturaDigital oAD = new AssinaturaDigital(); oAD.Assinar(ConteudoXML, emp, Convert.ToInt32(dadosPedInut.cUF)); //Invocar o método que envia o XML para o SEFAZ oInvocarObj.Invocar(wsProxy, oInutilizacao, wsProxy.NomeMetodoWS[0], oCabecMsg, this, Propriedade.Extensao(Propriedade.TipoEnvio.PedInu).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedInu).RetornoXML, true, securityProtocolType); //Ler o retorno do webservice LerRetornoInut(); } else { string f = Path.GetFileNameWithoutExtension(NomeArquivoXML) + ".xml"; if (NomeArquivoXML.IndexOf(Empresas.Configuracoes[emp].PastaValidar, StringComparison.InvariantCultureIgnoreCase) >= 0) { f = Path.Combine(Empresas.Configuracoes[emp].PastaValidar, f); } oGerarXML.Inutilizacao(f, dadosPedInut.tpAmb, dadosPedInut.tpEmis, dadosPedInut.cUF, dadosPedInut.ano, dadosPedInut.CNPJ, dadosPedInut.mod, dadosPedInut.serie, dadosPedInut.nNFIni, dadosPedInut.nNFFin, dadosPedInut.xJust, dadosPedInut.versao); } } catch (Exception ex) { string ExtRet = string.Empty; if (vXmlNfeDadosMsgEhXML) //Se for XML { ExtRet = Propriedade.Extensao(Propriedade.TipoEnvio.PedInu).EnvioXML; } else //Se for TXT { ExtRet = Propriedade.Extensao(Propriedade.TipoEnvio.PedInu).EnvioTXT; } try { //Gravar o arquivo de erro de retorno para o ERP, caso ocorra TFunctions.GravarArqErroServico(NomeArquivoXML, ExtRet, Propriedade.ExtRetorno.Inu_ERR, ex); } catch { //Se falhou algo na hora de gravar o retorno .ERR (de erro) para o ERP, infelizmente não posso fazer mais nada. //Wandrey 09/03/2010 } } finally { try { if (!vXmlNfeDadosMsgEhXML) //Se for o TXT para ser transformado em XML, vamos excluir o TXT depois de gerado o XML { Functions.DeletarArquivo(NomeArquivoXML); } } catch { //Se falhou algo na hora de deletar o XML de inutilização, infelizmente não posso //fazer mais nada. Com certeza o uninfe sendo restabelecido novamente vai tentar enviar o mesmo //xml de inutilização para o SEFAZ. Este erro pode ocorrer por falha no HD, rede, Permissão de pastas, etc. Wandrey 23/03/2010 } } }
public override void Execute() { int emp = Empresas.FindEmpresaByThread(); try { Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlRetorno + "\\" + Functions.ExtrairNomeArq(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.eSocial_downevt).EnvioXML) + Propriedade.Extensao(Propriedade.TipoEnvio.eSocial_downevt).RetornoERR); Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlErro + "\\" + NomeArquivoXML); WebServiceProxy wsProxy = null; object eSocial = null; wsProxy = ConfiguracaoApp.DefinirWS(Servico, emp, 991, Empresas.Configuracoes[emp].AmbienteCodigo, 0); if (wsProxy != null) { eSocial = wsProxy.CriarObjeto(wsProxy.NomeClasseWS); } System.Net.SecurityProtocolType securityProtocolType = WebServiceProxy.DefinirProtocoloSeguranca(991, 1, 0, Servico); var nomeMetodo = NomeMetodo(); new AssinaturaDigital().Assinar(ConteudoXML, emp, 991, AlgorithmType.Sha256); oInvocarObj.Invocar(wsProxy, eSocial, nomeMetodo, null, this, Propriedade.Extensao(Propriedade.TipoEnvio.eSocial_downevt).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.eSocial_downevt).RetornoXML, true, securityProtocolType); /// /// grava o arquivo no FTP string filenameFTP = Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Functions.ExtrairNomeArq(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.eSocial_downevt).EnvioXML) + "\\" + Propriedade.Extensao(Propriedade.TipoEnvio.eSocial_downevt).RetornoXML); if (File.Exists(filenameFTP)) { new GerarXML(emp).XmlParaFTP(emp, filenameFTP); } } catch (Exception ex) { try { //Gravar o arquivo de erro de retorno para o ERP, caso ocorra TFunctions.GravarArqErroServico(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.eSocial_downevt).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.eSocial_downevt).RetornoERR, ex); } catch { //Se falhou algo na hora de gravar o retorno .ERR (de erro) para o ERP, infelizmente não posso fazer mais nada. //Wandrey 31/08/2011 } } finally { try { Functions.DeletarArquivo(NomeArquivoXML); } catch { //Se falhou algo na hora de deletar o XML de cancelamento de NFe, infelizmente //não posso fazer mais nada, o UniNFe vai tentar mandar o arquivo novamente para o webservice, pois ainda não foi excluido. //Wandrey 31/08/2011 } } }
public override void Execute() { int emp = Empresas.FindEmpresaByThread(); FluxoNfe oFluxoNfe = new FluxoNfe(); LerXML oLer = new LerXML(); try { dadosRec = new DadosRecClass(); //Ler o XML de Lote para pegar o número do lote que está sendo enviado oLer.Nfe(ConteudoXML); var idLote = oLer.oDadosNfe.idLote; //Definir o objeto do WebService WebServiceProxy wsProxy = ConfiguracaoApp.DefinirWS(Servico, emp, Convert.ToInt32(oLer.oDadosNfe.cUF), Convert.ToInt32(oLer.oDadosNfe.tpAmb), Convert.ToInt32(oLer.oDadosNfe.tpEmis), oLer.oDadosNfe.versao, oLer.oDadosNfe.mod, 0); System.Net.SecurityProtocolType securityProtocolType = WebServiceProxy.DefinirProtocoloSeguranca(Convert.ToInt32(oLer.oDadosNfe.cUF), Convert.ToInt32(oLer.oDadosNfe.tpAmb), Convert.ToInt32(oLer.oDadosNfe.tpEmis), Servico); //Criar objetos das classes dos serviços dos webservices do SEFAZ object oRecepcao = wsProxy.CriarObjeto(wsProxy.NomeClasseWS); object oCabecMsg = null; if (oLer.oDadosNfe.versao != "4.00") { oCabecMsg = wsProxy.CriarObjeto(NomeClasseCabecWS(Convert.ToInt32(oLer.oDadosNfe.cUF), Servico)); wsProxy.SetProp(oCabecMsg, TpcnResources.cUF.ToString(), oLer.oDadosNfe.cUF); wsProxy.SetProp(oCabecMsg, TpcnResources.versaoDados.ToString(), oLer.oDadosNfe.versao); } //Invocar o método que envia o XML para o SEFAZ if (Empresas.Configuracoes[emp].IndSinc && oLer.oDadosNfe.indSinc) { //Não posso gerar o arquivo na pasta de retorno através do método Invocar, por isso não estou colocando os dois ultimos parâmetros com a definição dos prefixos dos arquivos. O arquivo de retorno no processo síncrono deve acontecer somente depois de finalizado o processo da nota, ou gera problemas. Wandrey 11/06/2015 oInvocarObj.Invocar(wsProxy, oRecepcao, wsProxy.NomeMetodoWS[0], oCabecMsg, this, Propriedade.Extensao(Propriedade.TipoEnvio.EnvLot).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedRec).RetornoXML, false, securityProtocolType); Protocolo(vStrXmlRetorno); } else { oInvocarObj.Invocar(wsProxy, oRecepcao, wsProxy.NomeMetodoWS[0], oCabecMsg, this, Propriedade.Extensao(Propriedade.TipoEnvio.EnvLot).EnvioXML, Propriedade.ExtRetorno.Rec, true, securityProtocolType); Recibo(vStrXmlRetorno, emp); } if (dadosRec.cStat == "104") //Lote processado - Processo da NFe Síncrono - Wandrey 13/03/2014 { FinalizarNFeSincrono(vStrXmlRetorno, emp, oLer.oDadosNfe.chavenfe); oGerarXML.XmlRetorno(Propriedade.Extensao(Propriedade.TipoEnvio.EnvLot).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedRec).RetornoXML, vStrXmlRetorno); } else if (dadosRec.cStat == "103") //Lote recebido com sucesso - Processo da NFe Assíncrono { if (dadosRec.tMed > 0) { Thread.Sleep(dadosRec.tMed * 1000); } //Atualizar o número do recibo no XML de controle do fluxo de notas enviadas oFluxoNfe.AtualizarTag(oLer.oDadosNfe.chavenfe, FluxoNfe.ElementoEditavel.tMed, dadosRec.tMed.ToString()); oFluxoNfe.AtualizarTagRec(idLote, dadosRec.nRec); XmlDocument xmlPedRec = oGerarXML.XmlPedRecNFe(dadosRec.nRec, oLer.oDadosNfe.versao, oLer.oDadosNfe.mod, emp); TaskNFeRetRecepcao nfeRetRecepcao = new TaskNFeRetRecepcao(xmlPedRec); nfeRetRecepcao.chNFe = oLer.oDadosNfe.chavenfe; nfeRetRecepcao.Execute(); } else if (Convert.ToInt32(dadosRec.cStat) > 200 || Convert.ToInt32(dadosRec.cStat) == 108 || //Verifica se o servidor de processamento está paralisado momentaneamente. Wandrey 13/04/2012 Convert.ToInt32(dadosRec.cStat) == 109) //Verifica se o servidor de processamento está paralisado sem previsão. Wandrey 13/04/2012 { if (Empresas.Configuracoes[emp].IndSinc && oLer.oDadosNfe.indSinc) { // OPS!!! Processo sincrono rejeição da SEFAZ, temos que gravar o XML para o ERP, pois no processo síncrono isso não pode ser feito dentro do método Invocar oGerarXML.XmlRetorno(Propriedade.Extensao(Propriedade.TipoEnvio.EnvLot).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedRec).RetornoXML /*.ExtRetorno.ProRec_XML*/, vStrXmlRetorno); } //Se o status do retorno do lote for maior que 200 ou for igual a 108 ou 109, //vamos ter que excluir a nota do fluxo, porque ela foi rejeitada pelo SEFAZ //Primeiro vamos mover o xml da nota da pasta EmProcessamento para pasta de XML´s com erro e depois a tira do fluxo //Wandrey 30/04/2009 oAux.MoveArqErro(Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" + PastaEnviados.EmProcessamento.ToString() + "\\" + oFluxoNfe.LerTag(oLer.oDadosNfe.chavenfe, FluxoNfe.ElementoFixo.ArqNFe)); oFluxoNfe.ExcluirNfeFluxo(oLer.oDadosNfe.chavenfe); } //Deleta o arquivo de lote Functions.DeletarArquivo(NomeArquivoXML); } catch (ExceptionEnvioXML ex) { TrataException(emp, ex, oLer.oDadosNfe.chavenfe); } catch (ExceptionSemInternet ex) { TrataException(emp, ex, oLer.oDadosNfe.chavenfe); } catch (Exception ex) { TrataException(emp, ex, oLer.oDadosNfe.chavenfe); } }
public override void Execute() { int emp = Empresas.FindEmpresaByThread(); //Definir o serviço que será executado para a classe Servico = Servicos.NFSeConsultarNFSePNG; try { Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlRetorno + "\\" + Functions.ExtrairNomeArq(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedNFSePNG).EnvioXML) + Propriedade.ExtRetorno.NFSePNG_ERR); Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlErro + "\\" + NomeArquivoXML); oDadosPedNfsePNG = new DadosPedSitNfse(emp); //Criar objetos das classes dos serviços dos webservices do SEFAZ PadroesNFSe padraoNFSe = Functions.PadraoNFSe(oDadosPedNfsePNG.cMunicipio); WebServiceProxy wsProxy = ConfiguracaoApp.DefinirWS(Servico, emp, oDadosPedNfsePNG.cMunicipio, oDadosPedNfsePNG.tpAmb, oDadosPedNfsePNG.tpEmis, padraoNFSe, oDadosPedNfsePNG.cMunicipio); object pedNfsePNG = wsProxy.CriarObjeto(wsProxy.NomeClasseWS); string cabecMsg = ""; System.Net.SecurityProtocolType securityProtocolType = WebServiceProxy.DefinirProtocoloSeguranca(oDadosPedNfsePNG.cMunicipio, oDadosPedNfsePNG.tpAmb, oDadosPedNfsePNG.tpEmis, padraoNFSe, Servico); //Assinar o XML AssinaturaDigital ad = new AssinaturaDigital(); ad.Assinar(NomeArquivoXML, emp, Convert.ToInt32(oDadosPedNfsePNG.cMunicipio)); //Invocar o método que envia o XML para o SEFAZ oInvocarObj.InvocarNFSe(wsProxy, pedNfsePNG, NomeMetodoWS(Servico, oDadosPedNfsePNG.cMunicipio), cabecMsg, this, Propriedade.Extensao(Propriedade.TipoEnvio.PedNFSePNG).EnvioXML, //"-ped-nfsepng", Propriedade.Extensao(Propriedade.TipoEnvio.PedNFSePNG).RetornoXML, //"-nfsepng", padraoNFSe, Servico, securityProtocolType); /// /// grava o arquivo no FTP string filenameFTP = Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Functions.ExtrairNomeArq(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedNFSePNG).EnvioXML) + Propriedade.Extensao(Propriedade.TipoEnvio.PedNFSePNG).RetornoXML); if (File.Exists(filenameFTP)) { new GerarXML(emp).XmlParaFTP(emp, filenameFTP); } } catch (Exception ex) { try { //Gravar o arquivo de erro de retorno para o ERP, caso ocorra TFunctions.GravarArqErroServico(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedNFSePNG).EnvioXML, Propriedade.ExtRetorno.NFSePNG_ERR, ex); } catch { //Se falhou algo na hora de gravar o retorno .ERR (de erro) para o ERP, infelizmente não posso fazer mais nada. //Wandrey 31/08/2011 } } finally { try { Functions.DeletarArquivo(NomeArquivoXML); } catch { //Se falhou algo na hora de deletar o XML de cancelamento de NFe, infelizmente //não posso fazer mais nada, o UniNFe vai tentar mandar o arquivo novamente para o webservice, pois ainda não foi excluido. //Wandrey 31/08/2011 } } }
public override void Execute() { int emp = Empresas.FindEmpresaByThread(); try { Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlRetorno + "\\" + Functions.ExtrairNomeArq(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedSeqLoteNotaRPS).EnvioXML) + Propriedade.ExtRetorno.SeqLoteNotaRPS_ERR); Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlErro + "\\" + NomeArquivoXML); dadosPedSeqLoteNotaRPS = new DadosPedSeqLoteNotaRPS(emp); //Ler o XML para pegar parâmetros de envio PedSeqLoteNotaRPS(NomeArquivoXML); //Criar objetos das classes dos serviços dos webservices do SEFAZ PadroesNFSe padraoNFSe = Functions.PadraoNFSe(dadosPedSeqLoteNotaRPS.cMunicipio); WebServiceProxy wsProxy = null; object pedSeqLoteNotaRPS = null; if (IsUtilizaCompilacaoWs(padraoNFSe, Servico, dadosPedSeqLoteNotaRPS.cMunicipio)) { wsProxy = ConfiguracaoApp.DefinirWS(Servico, emp, dadosPedSeqLoteNotaRPS.cMunicipio, dadosPedSeqLoteNotaRPS.tpAmb, dadosPedSeqLoteNotaRPS.tpEmis, padraoNFSe, dadosPedSeqLoteNotaRPS.cMunicipio); if (wsProxy != null) { pedSeqLoteNotaRPS = wsProxy.CriarObjeto(wsProxy.NomeClasseWS); } } System.Net.SecurityProtocolType securityProtocolType = WebServiceProxy.DefinirProtocoloSeguranca(dadosPedSeqLoteNotaRPS.cMunicipio, dadosPedSeqLoteNotaRPS.tpAmb, dadosPedSeqLoteNotaRPS.tpEmis, padraoNFSe, Servico); string cabecMsg = ""; switch (padraoNFSe) { case PadroesNFSe.TECNOSISTEMAS: cabecMsg = "<?xml version=\"1.0\" encoding=\"utf-8\"?><cabecalho xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" versao=\"20.01\" xmlns=\"http://www.nfse-tecnos.com.br/nfse.xsd\"><versaoDados>20.01</versaoDados></cabecalho>"; break; } if (IsInvocar(padraoNFSe, Servico, dadosPedSeqLoteNotaRPS.cMunicipio)) { //Assinar o XML AssinaturaDigital ad = new AssinaturaDigital(); ad.Assinar(NomeArquivoXML, emp, dadosPedSeqLoteNotaRPS.cMunicipio); //Invocar o método que envia o XML para o SEFAZ oInvocarObj.InvocarNFSe(wsProxy, pedSeqLoteNotaRPS, NomeMetodoWS(Servico, dadosPedSeqLoteNotaRPS.cMunicipio), cabecMsg, this, Propriedade.Extensao(Propriedade.TipoEnvio.PedSeqLoteNotaRPS).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedSeqLoteNotaRPS).RetornoXML, padraoNFSe, Servico, securityProtocolType); /// /// grava o arquivo no FTP string filenameFTP = Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Functions.ExtrairNomeArq(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedSeqLoteNotaRPS).EnvioXML) + Propriedade.Extensao(Propriedade.TipoEnvio.PedSeqLoteNotaRPS).RetornoXML); if (File.Exists(filenameFTP)) { new GerarXML(emp).XmlParaFTP(emp, filenameFTP); } } } catch (Exception ex) { try { //Gravar o arquivo de erro de retorno para o ERP, caso ocorra TFunctions.GravarArqErroServico(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedSeqLoteNotaRPS).EnvioXML, Propriedade.ExtRetorno.SeqLoteNotaRPS_ERR, ex); } catch { //Se falhou algo na hora de gravar o retorno .ERR (de erro) para o ERP, infelizmente não posso fazer mais nada. //Wandrey 31/08/2011 } } finally { try { Functions.DeletarArquivo(NomeArquivoXML); } catch { //Se falhou algo na hora de deletar o XML de cancelamento de NFe, infelizmente //não posso fazer mais nada, o UniNFe vai tentar mandar o arquivo novamente para o webservice, pois ainda não foi excluido. //Wandrey 31/08/2011 } } }
public override void Execute() { int emp = Empresas.FindEmpresaByThread(); /// /// extensao permitida: PedSitNfseRps = "-ped-sitnfserps.xml"; /// /// Definir o serviço que será executado para a classe Servico = Servicos.NFSeConsultarPorRps; try { Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlRetorno + "\\" + Functions.ExtrairNomeArq(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSeRps).EnvioXML) + Propriedade.ExtRetorno.SitNfseRps_ERR); Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlErro + "\\" + NomeArquivoXML); //Ler o XML para pegar parâmetros de envio LerXML ler = new LerXML(); ler.PedSitNfseRps(NomeArquivoXML); //Criar objetos das classes dos serviços dos webservices do SEFAZ PadroesNFSe padraoNFSe = Functions.PadraoNFSe(ler.oDadosPedSitNfseRps.cMunicipio); WebServiceProxy wsProxy = null; object pedLoteRps = null; if (IsUtilizaCompilacaoWs(padraoNFSe)) { wsProxy = ConfiguracaoApp.DefinirWS(Servico, emp, ler.oDadosPedSitNfseRps.cMunicipio, ler.oDadosPedSitNfseRps.tpAmb, ler.oDadosPedSitNfseRps.tpEmis, padraoNFSe); if (wsProxy != null) { pedLoteRps = wsProxy.CriarObjeto(wsProxy.NomeClasseWS); } } System.Net.SecurityProtocolType securityProtocolType = WebServiceProxy.DefinirProtocoloSeguranca(ler.oDadosPedSitNfseRps.cMunicipio, ler.oDadosPedSitNfseRps.tpAmb, ler.oDadosPedSitNfseRps.tpEmis, padraoNFSe, Servico); string cabecMsg = ""; switch (padraoNFSe) { case PadroesNFSe.GINFES: if (ler.oDadosPedSitNfseRps.cMunicipio == 4125506) //São José dos Pinhais - PR { cabecMsg = "<ns2:cabecalho versao=\"3\" xmlns:ns2=\"http://nfe.sjp.pr.gov.br/cabecalho_v03.xsd\"><versaoDados>3</versaoDados></ns2:cabecalho>"; } else { cabecMsg = "<ns2:cabecalho versao=\"3\" xmlns:ns2=\"http://www.ginfes.com.br/cabecalho_v03.xsd\"><versaoDados>3</versaoDados></ns2:cabecalho>"; } break; case PadroesNFSe.BETHA: wsProxy = new WebServiceProxy(Empresas.Configuracoes[emp].X509Certificado); wsProxy.Betha = new Betha(); break; case PadroesNFSe.CANOAS_RS: cabecMsg = "<cabecalho versao=\"201001\"><versaoDados>V2010</versaoDados></cabecalho>"; break; case PadroesNFSe.BHISS: cabecMsg = "<cabecalho xmlns=\"http://www.abrasf.org.br/nfse.xsd\" versao=\"1.00\"><versaoDados >1.00</versaoDados ></cabecalho>"; break; case PadroesNFSe.WEBISS: cabecMsg = "<cabecalho xmlns=\"http://www.abrasf.org.br/nfse.xsd\" versao=\"1.00\"><versaoDados >1.00</versaoDados ></cabecalho>"; break; case PadroesNFSe.PORTOVELHENSE: cabecMsg = "<cabecalho versao=\"2.00\" xmlns:ns2=\"http://www.w3.org/2000/09/xmldsig#\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\"><versaoDados>2.00</versaoDados></cabecalho>"; break; case PadroesNFSe.TECNOSISTEMAS: cabecMsg = "<?xml version=\"1.0\" encoding=\"utf-8\"?><cabecalho xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" versao=\"20.01\" xmlns=\"http://www.nfse-tecnos.com.br/nfse.xsd\"><versaoDados>20.01</versaoDados></cabecalho>"; break; case PadroesNFSe.FINTEL: cabecMsg = "<cabecalho xmlns=\"http://iss.pontagrossa.pr.gov.br/Arquivos/nfse.xsd\" versao=\"1.00\"><versaoDados >1.00</versaoDados ></cabecalho>"; break; case PadroesNFSe.FIORILLI: Fiorilli fiorilli = new Fiorilli((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, ler.oDadosPedSitNfseRps.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor); fiorilli.ConsultarNfsePorRps(NomeArquivoXML); break; case PadroesNFSe.SIMPLISS: SimplISS simpliss = new SimplISS((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, ler.oDadosPedSitNfseRps.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor); simpliss.ConsultarNfsePorRps(NomeArquivoXML); break; case PadroesNFSe.EGOVERNE: #region E-Governe EGoverne egoverne = new EGoverne((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, ler.oDadosPedSitNfseRps.cMunicipio, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor, Empresas.Configuracoes[emp].X509Certificado); AssinaturaDigital assegov = new AssinaturaDigital(); assegov.Assinar(NomeArquivoXML, emp, ler.oDadosPedSitNfseRps.cMunicipio); egoverne.ConsultarNfsePorRps(NomeArquivoXML); #endregion break; case PadroesNFSe.EL: #region E&L EL el = new EL((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, ler.oDadosPedSitNfseRps.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS, (ConfiguracaoApp.Proxy ? ConfiguracaoApp.ProxyUsuario : ""), (ConfiguracaoApp.Proxy ? ConfiguracaoApp.ProxySenha : ""), (ConfiguracaoApp.Proxy ? ConfiguracaoApp.ProxyServidor : "")); el.ConsultarNfsePorRps(NomeArquivoXML); #endregion break; case PadroesNFSe.GOVDIGITAL: GovDigital govdig = new GovDigital((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, Empresas.Configuracoes[emp].X509Certificado, ler.oDadosPedSitNfseRps.cMunicipio, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor); AssinaturaDigital adgovdig = new AssinaturaDigital(); adgovdig.Assinar(NomeArquivoXML, emp, ler.oDadosPedSitNfseRps.cMunicipio); govdig.ConsultarNfsePorRps(NomeArquivoXML); break; case PadroesNFSe.EQUIPLANO: cabecMsg = "1"; break; case PadroesNFSe.ACTCON: case PadroesNFSe.PRODATA: cabecMsg = "<cabecalho versao=\"2.01\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"<versaoDados>2.01</versaoDados></cabecalho>"; break; case PadroesNFSe.FISSLEX: FISSLEX fisslex = new FISSLEX((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, ler.oDadosPedSitNfseRps.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor); fisslex.ConsultarNfsePorRps(NomeArquivoXML); break; case PadroesNFSe.NATALENSE: cabecMsg = "<cabecalho xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" versao=\"1\" xmlns=\"http://www.abrasf.org.br/ABRASF/arquivos/nfse.xsd\"><versaoDados>1</versaoDados></cabecalho>"; break; case PadroesNFSe.CONAM: throw new NFe.Components.Exceptions.ServicoInexistenteException(); case PadroesNFSe.PAULISTANA: wsProxy = new WebServiceProxy(Empresas.Configuracoes[emp].X509Certificado); if (ler.oDadosPedSitNfseRps.tpAmb == 1) { pedLoteRps = new NFe.Components.PSaoPauloSP.LoteNFe(); } else { throw new Exception("Município de São Paulo-SP não dispõe de ambiente de homologação para envio de NFS-e em teste."); } break; case PadroesNFSe.METROPOLIS: #region METROPOLIS Metropolis metropolis = new Metropolis((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, ler.oDadosPedSitNfseRps.cMunicipio, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor, Empresas.Configuracoes[emp].X509Certificado); AssinaturaDigital metropolisdig = new AssinaturaDigital(); metropolisdig.Assinar(NomeArquivoXML, emp, ler.oDadosPedSitNfseRps.cMunicipio); metropolis.ConsultarNfsePorRps(NomeArquivoXML); break; #endregion case PadroesNFSe.FREIRE_INFORMATICA: cabecMsg = "<cabecalho xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"http://www.abrasf.org.br/nfse.xsd\" versao=\"2.02\"><versaoDados>2.02</versaoDados></cabecalho>"; break; case PadroesNFSe.MEMORY: #region Memory Memory memory = new Memory((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, ler.oDadosPedSitNfseRps.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS, ConfiguracaoApp.ProxyUsuario, ConfiguracaoApp.ProxySenha, ConfiguracaoApp.ProxyServidor); memory.CancelarNfse(NomeArquivoXML); break; #endregion case PadroesNFSe.CAMACARI_BA: cabecMsg = "<cabecalho><versaoDados>2.01</versaoDados><versao>2.01</versao></cabecalho>"; break; case PadroesNFSe.NA_INFORMATICA: wsProxy = new WebServiceProxy(Empresas.Configuracoes[emp].X509Certificado); if (ler.oDadosPedSitNfseRps.tpAmb == 1) { pedLoteRps = new Components.PCorumbaMS.NfseWSService(); } else { pedLoteRps = new Components.HCorumbaMS.NfseWSService(); } break; } if (IsInvocar(padraoNFSe, Servico)) { //Assinar o XML AssinaturaDigital ad = new AssinaturaDigital(); ad.Assinar(NomeArquivoXML, emp, ler.oDadosPedSitNfseRps.cMunicipio); //Invocar o método que envia o XML para o SEFAZ oInvocarObj.InvocarNFSe(wsProxy, pedLoteRps, NomeMetodoWS(Servico, ler.oDadosPedSitNfseRps.cMunicipio), cabecMsg, this, Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSeRps).EnvioXML, //"-ped-sitnfserps", Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSeRps).RetornoXML, //"-sitnfserps", padraoNFSe, Servico, securityProtocolType); /// /// grava o arquivo no FTP string filenameFTP = Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Functions.ExtrairNomeArq(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSeRps).EnvioXML) + Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSeRps).RetornoXML); if (File.Exists(filenameFTP)) { new GerarXML(emp).XmlParaFTP(emp, filenameFTP); } } } catch (Exception ex) { try { //Gravar o arquivo de erro de retorno para o ERP, caso ocorra TFunctions.GravarArqErroServico(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSeRps).EnvioXML, Propriedade.ExtRetorno.SitNfseRps_ERR, ex); } catch { //Se falhou algo na hora de gravar o retorno .ERR (de erro) para o ERP, infelizmente não posso fazer mais nada. //Wandrey 31/08/2011 } } finally { try { Functions.DeletarArquivo(NomeArquivoXML); } catch { //Se falhou algo na hora de deletar o XML de cancelamento de NFe, infelizmente //não posso fazer mais nada, o UniNFe vai tentar mandar o arquivo novamente para o webservice, pois ainda não foi excluido. //Wandrey 31/08/2011 } } }
public override void Execute() { var emp = Empresas.FindEmpresaByThread(); //Definir o serviço que será executado para a classe Servico = Servicos.NFSeObterNotaFiscal; try { Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlRetorno + "\\" + Functions.ExtrairNomeArq(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedNFSeXML).EnvioXML) + Propriedade.ExtRetorno.NFSeXML_ERR); Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlErro + "\\" + NomeArquivoXML); oObterNotaFiscal = new DadosPedSitNfse(emp); //Criar objetos das classes dos serviços dos webservices do municipio var padraoNFSe = Functions.PadraoNFSe(oObterNotaFiscal.cMunicipio); WebServiceProxy wsProxy = null; object pedNfseXML = null; if (IsUtilizaCompilacaoWs(padraoNFSe, Servico, oObterNotaFiscal.cMunicipio)) { wsProxy = ConfiguracaoApp.DefinirWS(Servico, emp, oObterNotaFiscal.cMunicipio, oObterNotaFiscal.tpAmb, oObterNotaFiscal.tpEmis, padraoNFSe, oObterNotaFiscal.cMunicipio); if (wsProxy != null) { pedNfseXML = wsProxy.CriarObjeto(wsProxy.NomeClasseWS); } } var securityProtocolType = WebServiceProxy.DefinirProtocoloSeguranca(oObterNotaFiscal.cMunicipio, oObterNotaFiscal.tpAmb, oObterNotaFiscal.tpEmis, padraoNFSe, Servico); var cabecMsg = ""; switch (padraoNFSe) { case PadroesNFSe.WEBFISCO_TECNOLOGIA: var webTecnologia = new WEBFISCO_TECNOLOGIA((TipoAmbiente)Empresas.Configuracoes[emp].AmbienteCodigo, Empresas.Configuracoes[emp].PastaXmlRetorno, oObterNotaFiscal.cMunicipio, Empresas.Configuracoes[emp].UsuarioWS, Empresas.Configuracoes[emp].SenhaWS); webTecnologia.ConsultarXml(NomeArquivoXML); break; } if (IsInvocar(padraoNFSe, Servico, oObterNotaFiscal.cMunicipio)) { //Assinar o XML var ad = new AssinaturaDigital(); ad.Assinar(NomeArquivoXML, emp, Convert.ToInt32(oObterNotaFiscal.cMunicipio)); //Invocar o método que envia o XML para o municipio oInvocarObj.InvocarNFSe(wsProxy, pedNfseXML, NomeMetodoWS(Servico, oObterNotaFiscal.cMunicipio), cabecMsg, this, Propriedade.Extensao(Propriedade.TipoEnvio.PedNFSeXML).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedNFSeXML).RetornoXML, padraoNFSe, Servico, securityProtocolType); /// grava o arquivo no FTP var filenameFTP = Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, Functions.ExtrairNomeArq(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedNFSeXML).EnvioXML) + Propriedade.Extensao(Propriedade.TipoEnvio.PedNFSeXML).RetornoXML); if (File.Exists(filenameFTP)) { new GerarXML(emp).XmlParaFTP(emp, filenameFTP); } } } catch (Exception ex) { try { //Gravar o arquivo de erro de retorno para o ERP, caso ocorra TFunctions.GravarArqErroServico(NomeArquivoXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedNFSeXML).EnvioXML, Propriedade.ExtRetorno.NFSeXML_ERR, ex); } catch { //Se falhou algo na hora de gravar o retorno .ERR (de erro) para o ERP, infelizmente não posso fazer mais nada. //Wandrey 31/08/2011 } } finally { try { Functions.DeletarArquivo(NomeArquivoXML); } catch { //Se falhou algo na hora de deletar o XML de cancelamento de NFe, infelizmente //não posso fazer mais nada, o UniNFe vai tentar mandar o arquivo novamente para o webservice, pois ainda não foi excluido. //Wandrey 31/08/2011 } } }
public TaskCTeRecepcao(XmlDocument conteudoXML) { Servico = Servicos.CTeEnviarLote; ConteudoXML = conteudoXML; ConteudoXML.PreserveWhitespace = false; NomeArquivoXML = Empresas.Configuracoes[Empresas.FindEmpresaByThread()].PastaXmlEnvio + "\\temp\\" + conteudoXML.GetElementsByTagName(TpcnResources.idLote.ToString())[0].InnerText + Propriedade.Extensao(Propriedade.TipoEnvio.EnvLot).EnvioXML; }
protected override void EnvEvento(int emp, DadosenvEvento dadosEnvEvento) { novaNomenclatura = NomeArquivoXML.ToLower().EndsWith(Propriedade.Extensao(Propriedade.TipoEnvio.PedEve).EnvioXML) || NomeArquivoXML.ToLower().EndsWith(Propriedade.Extensao(Propriedade.TipoEnvio.PedEve).EnvioTXT); /// /// danasa 6/2011 /// if (Path.GetExtension(NomeArquivoXML).ToLower() == ".txt") { #region --txt ///<<<<EVENTO DE CARTA DE CORRECAO>>>> ///idLote|000000000015255 ///evento|1 ///Id|ID1101103511031029073900013955001000000001105112804101 <<opcional ///cOrgao|35 ///tpAmb|2 ///CNPJ|10290739000139 /// ou ///CPF|12345678901 ///chNFe|35110310290739000139550010000000011051128041 ///dhEvento|2011-03-03T08:06:00 ///tpEvento|110110 ///nSeqEvento|1 ///verEvento|1.00 ///descEvento|Carta de Correção <<opcional ///xCorrecao|Texto de teste para Carta de Correção. Conteúdo do campo xCorrecao. ///xCondUso|A Carta de Correção é disciplinada pelo § 1º-A do art. .......... <<opcional ///evento|2 ///Id|ID1101103511031029073900013955001000000001105112804102 ///... ///evento|20 <<MAXIMO ///Id|ID1101103511031029073900013955001000000001105112804103 ///... ///<<<<EVENTO DE CANCELAMENTO>>>> /// idLote|000000000015255 /// evento|1 /// Id|ID1101113511031029073900013955001000000001105112804102 /// cOrgao|35 /// tpAmb|2 /// CNPJ|10290739000139 /// ou /// CPF|12345678901 /// chNFe|35110310290739000139550010000000011051128041 /// dhEvento|2011-03-03T08:06:00-03:00 /// tpEvento|110111 /// nSeqEvento|1 /// verEvento|1.00 /// descEvento|Cancelamento <<opcional /// xJust|Justificativa do cancelamento /// nProt|010101010101010 ///<<<<EVENTO DE CONFIRMACAO DA OPERACAO>>>> ///idLote|000000000015255 ///evento|1 ///Id|ID2102003511031029073900013955001000000001105112804102 ///cOrgao|35 ///tpAmb|2 ///CNPJ|10290739000139 /// ou ///CPF|12345678901 ///chNFe|35110310290739000139550010000000011051128041 ///dhEvento|2011-03-03T08:06:00-03:00 ///tpEvento|210200 ///nSeqEvento|1 ///verEvento|1.00 ///descEvento|Confirmacao da Operacao <<opcional ///xJust|Justificativa..... /// ------------------------------------ ///<<<<EVENTO DE CIENCIA DA OPERACAO>>>> ///idLote|000000000015255 ///evento|1 ///Id|ID2102103511031029073900013955001000000001105112804102 ///cOrgao|35 ///tpAmb|2 ///CNPJ|10290739000139 /// ou ///CPF|12345678901 ///chNFe|35110310290739000139550010000000011051128041 ///dhEvento|2011-03-03T08:06:00-03:00 ///tpEvento|210210 ///nSeqEvento|1 ///verEvento|1.00 ///descEvento|Ciencia da Operacao <<opcional /// -------------------------------------------- ///<<<<EVENTO DE DESCONHECIMENTO DA OPERACAO>>>> ///idLote|000000000015255 ///evento|1 ///Id|ID2102203511031029073900013955001000000001105112804102 ///cOrgao|35 ///tpAmb|2 ///CNPJ|10290739000139 /// ou ///CPF|12345678901 ///chNFe|35110310290739000139550010000000011051128041 ///dhEvento|2011-03-03T08:06:00-03:00 ///tpEvento|210220 ///nSeqEvento|1 ///verEvento|1.00 ///descEvento|Desconhecimento da Operacao <<opcional ///xJust|Justificativa..... /// -------------------------------------------- ///<<<<EVENTO DE OPERACAO NAO REALIZADA>>>> ///idLote|000000000015255 ///evento|1 ///Id|ID2102403511031029073900013955001000000001105112804102 ///cOrgao|35 ///tpAmb|2 ///CNPJ|10290739000139 /// ou ///CPF|12345678901 ///chNFe|35110310290739000139550010000000011051128041 ///dhEvento|2011-03-03T08:06:00-03:00 ///tpEvento|210240 ///nSeqEvento|1 ///verEvento|1.00 ///descEvento|Operacao nao realizada <<opcional /// -------------------------------------------- ///<<<<EVENTO EPEC>>>> ///idLote|000000000015255 ///evento|1 ///Id|ID2102403511031029073900013955001000000001105112804102 ///cOrgao|35 ///tpAmb|2 ///CNPJ|10290739000139 /// ou ///CPF|12345678901 ///chNFe|35110310290739000139550010000000011051128041 ///dhEvento|2011-03-03T08:06:00-03:00 ///tpEvento|110140 ///nSeqEvento|1 ///verEvento|1.00 ///descEvento|EPEC <<opcional ///epec.cOrgaoAutor|35 ///epec.tpAutor|1 ///epec.verAplic|1.1.1.0 ///epec.dhEmi|2011-03-03T08:06:00-03:00 ///epec.tpNF|1 ///epec.IE|ISENTO ///epec.dest.UF|SP ///epec.dest.CNPJ|10290739000139 /// ou ///epec.dest.CPF|12345678901 /// ou ///epec.dest.idEstrangeiro|9999999 ///epec.dest.IE|nao pode conter o texto 'ISENTO' ///epec.dest.vNF|1234.00 ///epec.dest.vICMS|1.00 ///epec.dest.vST|2.00 /// -------------------------------------------- ///<<<<Evento pedido de prorrogação de ICMS | Evento cancelamento de pedido de prorrogação de ICMS>>>> ///idLote|000000000015255 ///evento|1 ///Id|ID2102403511031029073900013955001000000001105112804102 ///cOrgao|35 ///tpAmb|2 ///CNPJ|10290739000139 ///chNFe|35110310290739000139550010000000011051128041 ///dhEvento|2011-03-03T08:06:00-03:00 ///tpEvento|111500 ou 111501 ou 111502 ou 111503 ///nSeqEvento|1 ///verEvento|1.00 ///descEvento|Pedido de Prorrogacao <<opcional ///nProt|0000000000001 ///itemPedido.numItem|1 ///itemPedido.qtdeItem|1 /// ///descEvento|Cancelamento de Pedido de Prorrogacao <<opcional ///nProt|0000000000001 ///idPedidoCancelado|ID999999CHAVE-NFE-9 /// -------------------------------------------- ///<<<<Evento Fisco Resposta ao Pedido de Prorrogação>>>> ///idLote|000000000015255 ///evento|1 ///Id|ID2102403511031029073900013955001000000001105112804102 ///cOrgao|35 ///tpAmb|2 ///CNPJ|10290739000139 ///chNFe|35110310290739000139550010000000011051128041 ///dhEvento|2011-03-03T08:06:00-03:00 ///tpEvento|411500 ou 411501 ou 411502 ou 411503 ///nSeqEvento|1 ///verEvento|1.00 ///descEvento|Fisco – Prorrogação ICMS remessa para industrialização <<opcional ///idPedido| ///respPedido.statPrazo| ///respPedido.itemPedido.numItem| ///respPedido.itemPedido.statPedido| ///respPedido.itemPedido.justStatus| ///respPedido.itemPedido.justStaOutra| ///respCancPedido.statCancPedido| ///respCancPedido.justStatus| ///respCancPedido.justStaOutra| List <string> cLinhas = Functions.LerArquivo(NomeArquivoXML); ProrrogacaoICMS lpcICMS = null; ItemPedido itemPedido = null; const string err0 = "Informe a linha \"respPedido.itemPedido.numItem\""; foreach (string cTexto in cLinhas) { string[] dados = cTexto.Split(new char[] { '|' }); if (dados.Length == 1) { continue; } switch (dados[0].ToLower()) { case "idlote": this.dadosEnvEvento.idLote = dados[1].Trim(); break; case "evento": this.dadosEnvEvento.eventos.Add(new Evento()); break; case "id": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].Id = dados[1].Trim(); break; case "corgao": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].cOrgao = Convert.ToInt32("0" + dados[1].Trim()); break; case "tpamb": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].tpAmb = Convert.ToInt32("0" + dados[1].Trim()); break; case "tpemis": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].tpEmis = Convert.ToInt32("0" + dados[1].Trim()); break; case "cnpj": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].CNPJ = dados[1].Trim(); break; case "cpf": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].CPF = dados[1].Trim(); break; case "chnfe": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].chNFe = dados[1].Trim(); break; case "dhevento": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].dhEvento = dados[1].Trim(); break; case "tpevento": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].tpEvento = dados[1].Trim(); break; case "nseqevento": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].nSeqEvento = Convert.ToInt32("0" + dados[1].Trim()); break; case "verevento": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].verEvento = dados[1].Trim(); break; case "descevento": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].descEvento = dados[1].Trim(); break; case "xcorrecao": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].xCorrecao = dados[1].Trim(); break; case "xconduso": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].xCondUso = dados[1].Trim(); break; case "xjust": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].xJust = dados[1].Trim(); break; case "nprot": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].nProt = dados[1].Trim(); break; /// /// Prorrogacao/Cancelamento de ICMS /// case "itempedido.numitem": lpcICMS = new ProrrogacaoICMS() { numItem = dados[1].Trim() }; this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].prorrogacaoICMS.Add(lpcICMS); break; case "itempedido.qtdeitem": if (lpcICMS == null) { throw new Exception("Informe a linha \"itemPedido.numItem\""); } lpcICMS.qtdeItem = dados[1].Trim(); lpcICMS = null; break; case "idpedidocancelado": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].idPedidoCancelado = dados[1].Trim(); break; /// /// Fisco – Prorrogação ICMS remessa para industrialização /// case "idpedido": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].idPedido = dados[1].Trim(); break; case "resppedido.statprazo": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].respPedido.statPrazo = dados[1].Trim(); break; case "resppedido.itempedido.numitem": itemPedido = new ItemPedido() { numItem = Convert.ToInt32("0" + dados[1].Trim()) }; this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].respPedido.itemPedido.Add(itemPedido); break; case "resppedido.itempedido.statpedido": if (itemPedido == null) { throw new Exception(err0); } itemPedido.statPedido = Convert.ToInt32("0" + dados[1].Trim()); break; case "resppedido.itempedido.juststatus": if (itemPedido == null) { throw new Exception(err0); } itemPedido.justStatus = Convert.ToInt32("0" + dados[1].Trim()); break; case "resppedido.itempedido.juststaoutra": if (!string.IsNullOrEmpty(dados[1].Trim())) { if (itemPedido == null) { throw new Exception(err0); } itemPedido.justStaOutra = dados[1].Trim(); } break; case "respcancpedido.statcancpedido": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].respCancPedido.statCancPedido = Convert.ToInt32("0" + dados[1].Trim()); break; case "respcancpedido.juststatus": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].respCancPedido.justStatus = Convert.ToInt32("0" + dados[1].Trim()); break; case "respcancpedido.juststaoutra": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].respCancPedido.justStaOutra = dados[1].Trim(); break; /// /// EPEC /// case "epec.corgaoautor": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].epec.cOrgaoAutor = Convert.ToInt32("0" + dados[1].Trim()); break; case "epec.dhemi": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].epec.dhEmi = dados[1].Trim(); break; case "epec.ie": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].epec.IE = dados[1].Trim(); break; case "epec.veraplic": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].epec.verAplic = dados[1].Trim(); break; case "epec.tpautor": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].epec.tpAutor = NFe.Components.EnumHelper.StringToEnum <NFe.ConvertTxt.TpcnTipoAutor>(dados[1].Trim()); break; case "epec.tpnf": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].epec.tpNF = NFe.Components.EnumHelper.StringToEnum <NFe.ConvertTxt.TpcnTipoNFe>(dados[1].Trim()); break; case "epec.dest.idestrangeiro": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].epec.dest.idEstrangeiro = dados[1].Trim(); break; case "epec.dest.cnpj": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].epec.dest.CNPJ = dados[1].Trim(); break; case "epec.dest.cpf": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].epec.dest.CPF = dados[1].Trim(); break; case "epec.dest.ie": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].epec.dest.IE = dados[1].Trim(); break; case "epec.dest.uf": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].epec.dest.UF = dados[1].Trim(); break; case "epec.dest.vnf": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].epec.dest.vNF = Convert.ToDouble("0" + dados[1].Trim().Replace(".", System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator)); break; case "epec.dest.vicms": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].epec.dest.vICMS = Convert.ToDouble("0" + dados[1].Trim().Replace(".", System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator)); break; case "epec.dest.vst": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].epec.dest.vST = Convert.ToDouble("0" + dados[1].Trim().Replace(".", System.Globalization.NumberFormatInfo.CurrentInfo.NumberDecimalSeparator)); break; ///Cancelamento por substituição da NFCe case "cancelamentosubstituicao.corgaoautor": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].cancelamentoSubstituicao.cOrgaoAutor = Convert.ToInt32("0" + dados[1].Trim()); break; case "cancelamentosubstituicao.chnferef": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].cancelamentoSubstituicao.chNFeRef = dados[1].Trim(); break; case "cancelamentosubstituicao.veraplic": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].cancelamentoSubstituicao.verAplic = dados[1].Trim(); break; case "cancelamentosubstituicao.tpautor": this.dadosEnvEvento.eventos[this.dadosEnvEvento.eventos.Count - 1].cancelamentoSubstituicao.tpAutor = NFe.Components.EnumHelper.StringToEnum <NFe.ConvertTxt.TpcnTipoAutor>(dados[1].Trim()); break; } } foreach (Evento evento in this.dadosEnvEvento.eventos) { ConvertTxt.tpEventos tpe = EnumHelper.StringToEnum <ConvertTxt.tpEventos>(evento.tpEvento); switch (tpe) { case ConvertTxt.tpEventos.tpEvEPEC: case ConvertTxt.tpEventos.tpEvCancelamentoNFe: case ConvertTxt.tpEventos.tpEvCancelamentoSubstituicaoNFCe: case ConvertTxt.tpEventos.tpEvCienciaOperacao: case ConvertTxt.tpEventos.tpEvConfirmacaoOperacao: case ConvertTxt.tpEventos.tpEvDesconhecimentoOperacao: case ConvertTxt.tpEventos.tpEvOperacaoNaoRealizada: evento.nSeqEvento = 1; break; case ConvertTxt.tpEventos.tpEvEncerramentoMDFe: case ConvertTxt.tpEventos.tpEvInclusaoCondutor: case ConvertTxt.tpEventos.tpEvRegistroPassagem: case ConvertTxt.tpEventos.tpEvRegistroPassagemBRid: break; case ConvertTxt.tpEventos.tpEvPedProrrogacao_ICMS_1: //pedido de prorrogacao 1 case ConvertTxt.tpEventos.tpEvPedProrrogacao_ICMS_2: //pedido de prorrogacao 2 if (string.IsNullOrEmpty(evento.descEvento)) { evento.descEvento = "Pedido de Prorrogacao"; } break; case ConvertTxt.tpEventos.tpEvCancPedProrrogacao_ICMS_1: //pedido de cancelamento 1 case ConvertTxt.tpEventos.tpEvCancPedProrrogacao_ICMS_2: //pedido de cancelamento 2 if (string.IsNullOrEmpty(evento.descEvento)) { evento.descEvento = "Cancelamento de Pedido de Prorrogacao"; } break; case ConvertTxt.tpEventos.tpEvFiscoRespPedProrrogacao_ICMS_1: case ConvertTxt.tpEventos.tpEvFiscoRespPedProrrogacao_ICMS_2: case ConvertTxt.tpEventos.tpEvFiscoRespCancPedProrrogacao_ICMS_1: case ConvertTxt.tpEventos.tpEvFiscoRespCancPedProrrogacao_ICMS_2: if (string.IsNullOrEmpty(evento.descEvento)) { evento.descEvento = "Fisco – Prorrogacao ICMS remessa para industrializacao"; } break; } if (string.IsNullOrEmpty(evento.descEvento)) { evento.descEvento = EnumHelper.GetDescription(tpe); } if (string.IsNullOrEmpty(evento.verEvento)) { evento.verEvento = "1.00"; } if (evento.nSeqEvento == 0) { evento.nSeqEvento = 1; } if (evento.tpAmb == 0) { evento.tpAmb = Empresas.Configuracoes[emp].AmbienteCodigo; } if (evento.cOrgao == 0) { evento.cOrgao = Convert.ToInt32(evento.chNFe.Substring(0, 2)); } if (evento.tpEmis == 0) { evento.tpEmis = Convert.ToInt32(evento.chNFe.Substring(34, 1)); } if (string.IsNullOrEmpty(evento.Id)) { evento.Id = TpcnResources.ID.ToString() + evento.tpEvento + evento.chNFe + evento.nSeqEvento.ToString("00"); } if (string.IsNullOrEmpty(evento.xCondUso)) { evento.xCondUso = "A Carta de Correcao e disciplinada pelo paragrafo 1o-A do art. 7o do Convenio S/N, " + "de 15 de dezembro de 1970 e pode ser utilizada para regularizacao de erro ocorrido na emissao de " + "documento fiscal, desde que o erro nao esteja relacionado com: I - as variaveis que determinam o " + "valor do imposto tais como: base de calculo, aliquota, diferenca de preco, quantidade, valor da " + "operacao ou da prestacao; II - a correcao de dados cadastrais que implique mudanca do remetente " + "ou do destinatario; III - a data de emissao ou de saida."; } } #endregion --txt } else { //<?xml version="1.0" encoding="UTF-8"?> //<envEvento versao="1.00" xmlns="http://www.portalfiscal.inf.br/nfe"> // <idLote>000000000015255</idLote> // <evento versao="1.00" xmlns="http://www.portalfiscal.inf.br/nfe"> // <infEvento Id="ID1101103511031029073900013955001000000001105112804108"> // <cOrgao>35</cOrgao> // <tpAmb>2</tpAmb> // <CNPJ>10290739000139</CNPJ> // <chNFe>35110310290739000139550010000000011051128041</chNFe> // <dhEvento>2011-03-03T08:06:00-03:00</dhEvento> // <tpEvento>110110</tpEvento> // <nSeqEvento>8</nSeqEvento> // <verEvento>1.00</verEvento> // <detEvento versao="1.00"> // <descEvento>Carta de Correção</descEvento> // <xCorrecao>Texto de teste para Carta de Correção. Conteúdo do campo xCorrecao.</xCorrecao> // <xCondUso>A Carta de Correção é disciplinada pelo § 1º-A do art. 7º do Convênio S/N, de 15 de dezembro de 1970 e pode ser utilizada para regularização de erro ocorrido na emissão de documento fiscal, desde que o erro não esteja relacionado com: I - as variáveis que determinam o valor do imposto tais como: base de cálculo, alíquota, diferença de preço, quantidade, valor da operação ou da prestação; II - a correção de dados cadastrais que implique mudança do remetente ou do destinatário; III - a data de emissão ou de saída.</xCondUso> // </detEvento> // </infEvento> // </evento> //</envEvento> base.EnvEvento(emp, dadosEnvEvento); } }
public override void Execute() { Exception exx = null; var uext = NFe.Components.Propriedade.Extensao(Components.Propriedade.TipoEnvio.pedLayouts); string ExtRetorno = (this.NomeArquivoXML.ToLower().EndsWith(".xml") ? uext.EnvioXML : uext.EnvioTXT); string finalArqErro = uext.EnvioXML.Replace(".xml", ".err"); string pastaRetorno = Propriedade.PastaGeralRetorno; string arqRetorno = pastaRetorno + "\\" + Functions.ExtrairNomeArq(this.NomeArquivoXML, null) + Propriedade.Extensao(Propriedade.TipoEnvio.pedLayouts).RetornoXML; Functions.DeletarArquivo(arqRetorno); Functions.DeletarArquivo(Propriedade.PastaGeralRetorno + "\\" + Functions.ExtrairNomeArq(this.NomeArquivoXML, null) + finalArqErro); //Document document = new Document(); try { using (Document document = new Document(PageSize.A4, 20f, 20f, 80f, 10f)) { var pdfWriter = PdfWriter.GetInstance(document, new FileStream(arqRetorno, FileMode.Create)); pdfWriter.PageEvent = new ITextEvents(); document.AddTitle("Layout UniNFe"); document.AddSubject("Layout de arquivos texto"); document.AddCreator(Propriedade.DescricaoAplicacao); document.AddAuthor(ConfiguracaoApp.NomeEmpresa); //HeaderFooter header = new HeaderFooter(new Phrase("This is a header"), false); //document.Header = header; // landscape document.SetPageSize(PageSize.A4.Rotate()); document.Open(); PdfPTable table = null;// new PdfPTable(3); //document.Add(new Phrase("Extensões permitidas", new Font(Font.FontFamily.HELVETICA, 18))); //Paragraph epara = new Paragraph("Extensões permitidas", new Font(Font.FontFamily.HELVETICA, 22)); //epara.Alignment = Element.ALIGN_CENTER; //document.Add(epara); //document.Add(new Phrase()); int n = 0; foreach (Propriedade.TipoEnvio item in Enum.GetValues(typeof(Propriedade.TipoEnvio))) { if ((n % 20) == 0 || table == null) { if (table != null) { document.Add(table); document.NewPage(); } document.Add(new Phrase("Extensões permitidas" + (n > 0 ? "..." : ""), new Font(Font.FontFamily.HELVETICA, 18))); table = new PdfPTable(3); table.HorizontalAlignment = 0; table.TotalWidth = document.PageSize.GetRight(41); table.LockedWidth = true; table.PaddingTop = 2; table.SetWidths(new float[] { 40f, 40f, 100f }); table.AddCell(this.titulo("Envios")); table.AddCell(this.titulo("Retornos")); table.AddCell(this.titulo("Descrição")); } ++n; var EXT = Propriedade.Extensao(item); table.AddCell(this.texto(this.fmtname(EXT.EnvioXML) + this.fmtname(EXT.EnvioTXT, " ou "))); table.AddCell(this.texto(this.fmtname(EXT.RetornoXML) + this.fmtname(EXT.RetornoTXT, " ou "))); table.AddCell(this.texto(EXT.descricao)); } if (table != null) { document.Add(table); document.NewPage(); } /// /// Layout NFe/NFCe /// n = 0; table = null; //document.Add(new Phrase("Layout de notas NF-e/NFc-e", new Font(Font.FontFamily.HELVETICA, 18))); foreach (KeyValuePair <string, string> key in new NFe.ConvertTxt.ConversaoTXT().LayoutTXT) { if (key.Key.Contains("_")) { /// /// só considera o layout da versao >= 3.1 if (key.Key.Contains("_200")) { continue; } } if ((n % 24) == 0 || table == null) { if (table != null) { document.Add(table); document.NewPage(); } document.Add(new Phrase("Layout de notas NF-e/NFc-e" + (n > 0 ? "...":""), new Font(Font.FontFamily.HELVETICA, 18))); table = new PdfPTable(2); table.AddCell(this.titulo("Segmento")); table.AddCell(this.titulo("Formato")); table.HorizontalAlignment = 0; table.TotalWidth = document.PageSize.GetRight(41); table.LockedWidth = true; table.PaddingTop = 2; table.SetWidths(new float[] { 8f, 100f }); } ++n; if (key.Key.Contains("_")) { table.AddCell(this.texto(key.Key.Substring(0, key.Key.IndexOf("_")))); } else { table.AddCell(this.texto(key.Key)); } table.AddCell(this.texto(key.Value.ToString().Substring(1))); } if (table != null) { document.Add(table); document.NewPage(); } //for (int i = 0; i < 2; i++) //{ // Paragraph para = new Paragraph("Hello world. Checking Header Footer", new Font(Font.FontFamily.HELVETICA, 22)); // para.Alignment = Element.ALIGN_CENTER; // document.Add(para); // document.NewPage(); //} //document.NewPage(); //// step 4: we Add a paragraph to the document //for (int i = 0; i < 2000; i++) //{ // if (( i % 36) == 0) // document.NewPage(); // document.Add(new Paragraph("Hello World " + i.ToString(), new Font(Font.FontFamily.COURIER, 8))); //} //document.NewPage(); //document.Add(new Phrase("Phrase: Hello World, Hello Sun, Hello Moon, Hello Stars, Hello Sea, Hello Land, Hello People. ")); //Paragraph paragraph = new Paragraph(); //paragraph.Alignment = Element.ALIGN_JUSTIFIED; //for (int i = 0; i < 2000; i++) //{ // //paragraph.Add("Hello World, Hello Sun, Hello Moon, Hello Stars, Hello Sea, Hello Land, Hello People. "); //} //document.Add(paragraph); document.Close(); } } catch (DocumentException de) { exx = de; } catch (IOException ioe) { exx = ioe; } catch (Exception ex) { exx = ex; } finally { Functions.DeletarArquivo(this.NomeArquivoXML); if (exx != null) { Functions.DeletarArquivo(arqRetorno); try { NFe.Service.TFunctions.GravarArqErroServico(this.NomeArquivoXML, ExtRetorno, finalArqErro, exx); } catch { } } } }
public override void Execute() { int emp = Empresas.FindEmpresaByThread(); try { //Ler o XML para pegar parâmetros de envio EnvEvento(emp, dadosEnvEvento); string currentEvento = dadosEnvEvento.eventos[0].tpEvento; // mudei para aqui caso haja erro e qdo for gravar o arquivo de erro precisamos saber qual o servico switch (EnumHelper.StringToEnum <ConvertTxt.tpEventos>(currentEvento)) { case ConvertTxt.tpEventos.tpEvCancelamentoNFe: case ConvertTxt.tpEventos.tpEvCancelamentoSubstituicaoNFCe: Servico = Servicos.EventoCancelamento; break; case ConvertTxt.tpEventos.tpEvCCe: Servico = Servicos.EventoCCe; break; case ConvertTxt.tpEventos.tpEvEPEC: Servico = Servicos.EventoEPEC; break; case ConvertTxt.tpEventos.tpEvPedProrrogacao_ICMS_1: case ConvertTxt.tpEventos.tpEvPedProrrogacao_ICMS_2: case ConvertTxt.tpEventos.tpEvCancPedProrrogacao_ICMS_1: case ConvertTxt.tpEventos.tpEvCancPedProrrogacao_ICMS_2: case ConvertTxt.tpEventos.tpEvFiscoRespCancPedProrrogacao_ICMS_1: case ConvertTxt.tpEventos.tpEvFiscoRespCancPedProrrogacao_ICMS_2: case ConvertTxt.tpEventos.tpEvFiscoRespPedProrrogacao_ICMS_1: case ConvertTxt.tpEventos.tpEvFiscoRespPedProrrogacao_ICMS_2: Servico = Servicos.EventoRecepcao; break; default: Servico = Servicos.EventoManifestacaoDest; break; } ValidaEvento(emp, dadosEnvEvento); //Pegar o estado da chave, pois na cOrgao pode vir o estado 91 - Wandreuy 22/08/2012 int cOrgao = dadosEnvEvento.eventos[0].cOrgao; //vai pegar o ambiente da Chave da Nfe autorizada p/ corrigir tpEmis int tpEmis = this.dadosEnvEvento.eventos[0].tpEmis; //Convert.ToInt32(this.dadosEnvEvento.eventos[0].chNFe.Substring(34, 1)); int ufParaWS = cOrgao; //Se o cOrgao for igual a 91 tenho que mudar a ufParaWS para que na hora de buscar o WSDL para conectar ao serviço, ele consiga encontrar. Wandrey 23/01/2013 if (cOrgao == 91) { ufParaWS = Convert.ToInt32(dadosEnvEvento.eventos[0].chNFe.Substring(0, 2)); } switch (Servico) { case Servicos.EventoCancelamento: switch ((TipoEmissao)tpEmis) { case TipoEmissao.teSVCAN: case TipoEmissao.teSVCRS: case TipoEmissao.teSVCSP: case TipoEmissao.teNormal: //Se a nota fiscal foi emitida em ambiente NORMAL, o cancelamento tem que ir para o ambiente normal ou gera uma rejeição. Wandrey 15/02/2013 break; default: //Os demais tipos de emissão tem que sempre ir para o ambiente NORMAL. Wandrey 22/02/2013 tpEmis = (int)TipoEmissao.teNormal; break; } break; case Servicos.EventoCCe: //CCe só existe no ambiente Normal. Wandrey 22/04/2013 tpEmis = (int)TipoEmissao.teNormal; break; } if (vXmlNfeDadosMsgEhXML) { //Definir o objeto do WebService WebServiceProxy wsProxy = ConfiguracaoApp.DefinirWS( Servico, emp, ufParaWS, dadosEnvEvento.eventos[0].tpAmb, tpEmis, string.Empty, dadosEnvEvento.eventos[0].mod, 0); System.Net.SecurityProtocolType securityProtocolType = WebServiceProxy.DefinirProtocoloSeguranca(ufParaWS, dadosEnvEvento.eventos[0].tpAmb, tpEmis, Servico); //Criar objetos das classes dos serviços dos webservices do SEFAZ object oRecepcaoEvento = wsProxy.CriarObjeto(wsProxy.NomeClasseWS); string xmlExtEnvio = string.Empty; string xmlExtRetorno = string.Empty; object oCabecMsg = null; //Criei o try para deixar compativel a versão 3.10 com a 4.0 try { oCabecMsg = wsProxy.CriarObjeto(NomeClasseCabecWS(cOrgao, Servico)); wsProxy.SetProp(oCabecMsg, TpcnResources.cUF.ToString(), cOrgao.ToString()); wsProxy.SetProp(oCabecMsg, TpcnResources.versaoDados.ToString(), NFe.ConvertTxt.versoes.VersaoXMLEvento); } catch { } if (novaNomenclatura) { xmlExtEnvio = Propriedade.Extensao(Propriedade.TipoEnvio.PedEve).EnvioXML.Replace(".xml", ""); xmlExtRetorno = Propriedade.Extensao(Propriedade.TipoEnvio.PedEve).RetornoXML.Replace(".xml", ""); } else { switch (Servico) { case Servicos.EventoCCe: xmlExtEnvio = Propriedade.Extensao(Propriedade.TipoEnvio.EnvCCe).EnvioXML.Replace(".xml", ""); xmlExtRetorno = Propriedade.Extensao(Propriedade.TipoEnvio.EnvCCe).RetornoXML.Replace(".xml", ""); break; case Servicos.EventoCancelamento: xmlExtEnvio = Propriedade.Extensao(Propriedade.TipoEnvio.EnvCancelamento).EnvioXML.Replace(".xml", ""); xmlExtRetorno = Propriedade.Extensao(Propriedade.TipoEnvio.EnvCancelamento).RetornoXML.Replace(".xml", ""); break; default: xmlExtEnvio = Propriedade.Extensao(Propriedade.TipoEnvio.EnvManifestacao).EnvioXML.Replace(".xml", ""); xmlExtRetorno = Propriedade.Extensao(Propriedade.TipoEnvio.EnvManifestacao).RetornoXML.Replace(".xml", ""); break; } } //Criar objeto da classe de assinatura digital AssinaturaDigital oAD = new AssinaturaDigital(); //Assinar o XML oAD.Assinar(ConteudoXML, emp, cOrgao); oInvocarObj.Invocar(wsProxy, oRecepcaoEvento, wsProxy.NomeMetodoWS[0], oCabecMsg, this, xmlExtEnvio, xmlExtRetorno, true, securityProtocolType); //Ler o retorno LerRetornoEvento(emp); } else { // Gerar o XML de eventos a partir do TXT gerado pelo ERP string xmlFileExt = string.Empty; string xmlFileExtTXT = string.Empty; if (novaNomenclatura) { xmlFileExt = Propriedade.Extensao(Propriedade.TipoEnvio.PedEve).EnvioXML; xmlFileExtTXT = Propriedade.Extensao(Propriedade.TipoEnvio.PedEve).EnvioTXT; } else { switch (Servico) { case Servicos.EventoCCe: xmlFileExt = Propriedade.Extensao(Propriedade.TipoEnvio.EnvCCe).EnvioXML; xmlFileExtTXT = Propriedade.Extensao(Propriedade.TipoEnvio.EnvCCe).EnvioTXT; break; case Servicos.EventoCancelamento: xmlFileExt = Propriedade.Extensao(Propriedade.TipoEnvio.EnvCancelamento).EnvioXML; xmlFileExtTXT = Propriedade.Extensao(Propriedade.TipoEnvio.EnvCancelamento).EnvioTXT; break; default: xmlFileExt = Propriedade.Extensao(Propriedade.TipoEnvio.EnvManifestacao).EnvioXML; xmlFileExtTXT = Propriedade.Extensao(Propriedade.TipoEnvio.EnvManifestacao).EnvioTXT; break; } } string f = Functions.ExtrairNomeArq(NomeArquivoXML, xmlFileExtTXT) + xmlFileExt; if (NomeArquivoXML.IndexOf(Empresas.Configuracoes[emp].PastaValidar, StringComparison.InvariantCultureIgnoreCase) >= 0) { f = Path.Combine(Empresas.Configuracoes[emp].PastaValidar, f); } oGerarXML.EnvioEvento(f, dadosEnvEvento); } } catch (Exception ex) { try { //Gravar o arquivo de erro de retorno para o ERP, caso ocorra string ExtRet = string.Empty; string ExtRetorno = string.Empty; if (novaNomenclatura) { ExtRet = vXmlNfeDadosMsgEhXML ? Propriedade.Extensao(Propriedade.TipoEnvio.PedEve).EnvioXML : Propriedade.Extensao(Propriedade.TipoEnvio.PedEve).EnvioTXT; ExtRetorno = Propriedade.ExtRetorno.Eve_ERR; } else { if (Servico == Servicos.Nulo) { // pode ter vindo de um txt e houve erro if (NomeArquivoXML.ToLower().EndsWith(Propriedade.Extensao(Propriedade.TipoEnvio.EnvCCe).EnvioXML) || NomeArquivoXML.ToLower().EndsWith(Propriedade.Extensao(Propriedade.TipoEnvio.EnvCCe).EnvioTXT)) { Servico = Servicos.EventoCCe; } else if (NomeArquivoXML.ToLower().EndsWith(Propriedade.Extensao(Propriedade.TipoEnvio.EnvManifestacao).EnvioXML) || NomeArquivoXML.ToLower().EndsWith(Propriedade.Extensao(Propriedade.TipoEnvio.EnvManifestacao).EnvioTXT)) { Servico = Servicos.EventoManifestacaoDest; } else if (NomeArquivoXML.ToLower().EndsWith(Propriedade.Extensao(Propriedade.TipoEnvio.EnvCancelamento).EnvioXML) || NomeArquivoXML.ToLower().EndsWith(Propriedade.Extensao(Propriedade.TipoEnvio.EnvCancelamento).EnvioTXT)) { Servico = Servicos.EventoCancelamento; } } switch (Servico) { case Servicos.EventoCCe: ExtRet = vXmlNfeDadosMsgEhXML ? Propriedade.Extensao(Propriedade.TipoEnvio.EnvCCe).EnvioXML : Propriedade.Extensao(Propriedade.TipoEnvio.EnvCCe).EnvioTXT; ExtRetorno = Propriedade.ExtRetorno.retEnvCCe_ERR; break; case Servicos.EventoCancelamento: ExtRet = vXmlNfeDadosMsgEhXML ? Propriedade.Extensao(Propriedade.TipoEnvio.EnvCancelamento).EnvioXML : Propriedade.Extensao(Propriedade.TipoEnvio.EnvCancelamento).EnvioTXT; ExtRetorno = Propriedade.ExtRetorno.retCancelamento_ERR; break; case Servicos.EventoManifestacaoDest: ExtRet = vXmlNfeDadosMsgEhXML ? Propriedade.Extensao(Propriedade.TipoEnvio.EnvManifestacao).EnvioXML : Propriedade.Extensao(Propriedade.TipoEnvio.EnvManifestacao).EnvioTXT; ExtRetorno = Propriedade.ExtRetorno.retManifestacao_ERR; break; default: throw new Exception("Nao pode identificar o tipo de serviço para o arquivo: " + NomeArquivoXML); } } if (ExtRetorno != string.Empty) { TFunctions.GravarArqErroServico(NomeArquivoXML, ExtRet, ExtRetorno, ex); } } catch { //Se falhou algo na hora de gravar o retorno .ERR (de erro) para o ERP, infelizmente não posso fazer mais nada. //Wandrey 09/03/2010 } } finally { try { Functions.DeletarArquivo(NomeArquivoXML); } catch { //Se falhou algo na hora de deletar o XML de evento, infelizmente //não posso fazer mais nada, o UniNFe vai tentar mandar o arquivo novamente para o webservice, pois ainda não foi excluido. //Wandrey 09/03/2010 } } }
/// <summary> /// Efetua a validação de qualquer XML, NFE, Cancelamento, Inutilização, etc..., e retorna se está ok ou não /// </summary> /// <param name="Arquivo">Nome do arquivo XML a ser validado e assinado</param> /// <param name="PastaValidar">Nome da pasta onde fica os arquivos a serem validados</param> /// <param name="PastaXMLErro">Nome da pasta onde é para gravar os XML´s validados que apresentaram erro.</param> /// <param name="PastaXMLRetorno">Nome da pasta de retorno onde será gravado o XML com o status da validação</param> /// <param name="Certificado">Certificado digital a ser utilizado na validação</param> /// <by>Wandrey Mundin Ferreira</by> /// <date>28/05/2009</date> public void ValidarAssinarXML(string Arquivo) { int emp = Empresas.FindEmpresaByThread(); Boolean Assinou = true; //Assinar o XML se tiver tag para assinar AssinaturaDigital oAD = new AssinaturaDigital(); try { if (TipoArqXml.nRetornoTipoArq >= 1 && TipoArqXml.nRetornoTipoArq <= SchemaXML.MaxID) { this.EncryptAssinatura(Arquivo); //danasa: 12/2013 oAD.Assinar(Arquivo, emp, Empresas.Configuracoes[emp].UnidadeFederativaCodigo); Assinou = true; } } catch (Exception ex) { Assinou = false; try { GravarXMLRetornoValidacao(Arquivo, "2", "Ocorreu um erro ao assinar o XML: " + ex.Message); new Auxiliar().MoveArqErro(Arquivo); } catch { //Se deu algum erro na hora de gravar o retorno do erro para o ERP, infelizmente não posso fazer nada. //Isso pode acontecer se falhar rede, hd, problema de permissão de pastas, etc... Wandrey 23/03/2010 } } if (Assinou) { #region Adicionar a tag do qrCode na NFCe if (Arquivo.EndsWith(Propriedade.Extensao(Propriedade.TipoEnvio.NFe).EnvioXML, StringComparison.InvariantCultureIgnoreCase)) { if (!String.IsNullOrEmpty(Empresas.Configuracoes[emp].IdentificadorCSC)) { QRCode qrCode = new QRCode(Empresas.Configuracoes[emp].IdentificadorCSC, Empresas.Configuracoes[emp].TokenCSC, Arquivo); 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(); } } } #endregion // Validar o Arquivo XML if (TipoArqXml.nRetornoTipoArq >= 1 && TipoArqXml.nRetornoTipoArq <= SchemaXML.MaxID) { try { Validar(Arquivo); if (Retorno != 0) { this.GravarXMLRetornoValidacao(Arquivo, "3", "Ocorreu um erro ao validar o XML: " + RetornoString); new Auxiliar().MoveArqErro(Arquivo); } else { if (!Directory.Exists(Empresas.Configuracoes[emp].PastaValidado)) { Directory.CreateDirectory(Empresas.Configuracoes[emp].PastaValidado); } string ArquivoNovo = Empresas.Configuracoes[emp].PastaValidado + "\\" + Path.GetFileName(Arquivo);// Functions.ExtrairNomeArq(Arquivo, ".xml") + ".xml"; Functions.Move(Arquivo, ArquivoNovo); this.GravarXMLRetornoValidacao(Arquivo, "1", "XML assinado e validado com sucesso."); } } catch (Exception ex) { try { this.GravarXMLRetornoValidacao(Arquivo, "4", "Ocorreu um erro ao validar o XML: " + ex.Message); new Auxiliar().MoveArqErro(Arquivo); } catch { //Se deu algum erro na hora de gravar o retorno do erro para o ERP, infelizmente não posso fazer nada. //Isso pode acontecer se falhar rede, hd, problema de permissão de pastas, etc... Wandrey 23/03/2010 } } } else { if (TipoArqXml.nRetornoTipoArq == -1) { /// /// OPS!!! Arquivo de NFS-e enviado p/ a pasta de validação, mas não existe definicao de schemas p/ sua validacao /// this.GravarXMLRetornoValidacao(Arquivo, "1", "XML não validado contra o schema da prefeitura. XML: " + TipoArqXml.cRetornoTipoArq); new Auxiliar().MoveArqErro(Arquivo); } else { try { this.GravarXMLRetornoValidacao(Arquivo, "5", "Ocorreu um erro ao validar o XML: " + TipoArqXml.cRetornoTipoArq); new Auxiliar().MoveArqErro(Arquivo); } catch { //Se deu algum erro na hora de gravar o retorno do erro para o ERP, infelizmente não posso fazer nada. //Isso pode acontecer se falhar rede, hd, problema de permissão de pastas, etc... Wandrey 23/03/2010 } } } } }
private void edtFilename_MouseDown(object sender, MouseEventArgs e) { if (e.Button == System.Windows.Forms.MouseButtons.Left) { MetroFramework.Controls.MetroTextBox control = (MetroFramework.Controls.MetroTextBox)sender; int x = control.ClientRectangle.Width - control.Icon.Size.Width; if (e.Location.X >= x) { string path = uninfeDummy.xmlParams.ReadValue(this.GetType().Name, "path", ""); using (OpenFileDialog dlg = new OpenFileDialog()) { dlg.RestoreDirectory = true; dlg.Filter = ""; if (Empresas.Configuracoes[this.Emp].Servico == TipoAplicativo.Nfse) { dlg.Filter += "Arquivos de NFSe|*" + Propriedade.Extensao(Propriedade.TipoEnvio.EnvLoteRps).EnvioXML + ";*" + Propriedade.Extensao(Propriedade.TipoEnvio.PedCanNFSe).EnvioXML + ";*" + Propriedade.Extensao(Propriedade.TipoEnvio.PedLoteRps).EnvioXML + ";*" + Propriedade.Extensao(Propriedade.TipoEnvio.PedSitLoteRps).EnvioXML + ";*" + Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSe).EnvioXML + ";*" + Propriedade.Extensao(Propriedade.TipoEnvio.PedSitNFSeRps).EnvioXML + ";*" + Propriedade.Extensao(Propriedade.TipoEnvio.PedInuNFSe).EnvioXML + ";*" + Propriedade.Extensao(Propriedade.TipoEnvio.PedNFSePNG).EnvioXML + ";*" + Propriedade.Extensao(Propriedade.TipoEnvio.PedNFSePDF).EnvioXML + ";*" + Propriedade.Extensao(Propriedade.TipoEnvio.PedNFSeXML).EnvioXML; } else { dlg.Filter = "Todos os arquivos|*" + Propriedade.Extensao(Propriedade.TipoEnvio.NFe).EnvioXML + ";*" + Propriedade.Extensao(Propriedade.TipoEnvio.CTe).EnvioXML + ";*" + Propriedade.Extensao(Propriedade.TipoEnvio.EnvCancelamento).EnvioXML + ";*" + Propriedade.Extensao(Propriedade.TipoEnvio.EnvCCe).EnvioXML + ";*" + Propriedade.Extensao(Propriedade.TipoEnvio.EnvManifestacao).EnvioXML + ";*" + Propriedade.Extensao(Propriedade.TipoEnvio.EnvDFe).EnvioXML + ";*" + Propriedade.Extensao(Propriedade.TipoEnvio.PedEve).EnvioXML + ";*" + Propriedade.Extensao(Propriedade.TipoEnvio.PedInu).EnvioXML + ";*" + Propriedade.Extensao(Propriedade.TipoEnvio.PedSit).EnvioXML; dlg.Filter += string.Format("|Arquivos da NFe/NFCe (*.*{0})|*{0}", Propriedade.Extensao(Propriedade.TipoEnvio.NFe).EnvioXML); dlg.Filter += string.Format("|Arquivos de CTe (*.*{0})|*{0}", Propriedade.Extensao(Propriedade.TipoEnvio.CTe).EnvioXML); dlg.Filter += string.Format("|Arquivos de DFe (*.*{0})|*{0}", Propriedade.Extensao(Propriedade.TipoEnvio.EnvDFe).EnvioXML); dlg.Filter += string.Format("|Arquivos de MDFe (*.*{0})|*{0}", Propriedade.Extensao(Propriedade.TipoEnvio.MDFe).EnvioXML); dlg.Filter += string.Format("|Arquivos de eventos (*.*{0},*.*{1},*.*{2},*.*{3},*.*{4})|*{0};*{1};*{2};*{3};*{4}", Propriedade.Extensao(Propriedade.TipoEnvio.EnvCCe).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.PedEve).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.EnvCancelamento).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.EnvDownload).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.EnvManifestacao).EnvioXML); } if (!string.IsNullOrEmpty(path)) { dlg.InitialDirectory = path; } if (dlg.ShowDialog() == DialogResult.OK) { if (!string.IsNullOrEmpty(dlg.FileName)) { uninfeDummy.xmlParams.WriteValue(this.GetType().Name, "path", Path.GetDirectoryName(dlg.FileName)); uninfeDummy.xmlParams.Save(); this.edtFilename.Text = dlg.FileName; btn_Validar_Click(null, null); } } } } } }