Exemplo n.º 1
0
 public NFeBuilder(EmissorServicoConfig emissorServicoConfig)
 {
     NFe = new NFe();
     NFe.infNFe.total = new Dominio.NotaFiscalEletronica.Informacoes.Total.total();
     NFe.infNFe       = new infNFe();
     NFe.infNFe.emit  = emissorServicoConfig.Emitente;
 }
Exemplo n.º 2
0
        private bool RetornoConsultaRecibo(NFe nfe, RetConsReciNFe retConsReciNFe, string caminhoNF, out bool tentarNovamente)
        {
            retConsReciNFe.Salvar(ObterCaminhoArquivo($"{NumRecibo}{SufixoProRec}.xml"));

            if (retConsReciNFe.CStat == "103" || retConsReciNFe.CStat == "105")
            {
                tentarNovamente = true;
                Mensagem        = $"{retConsReciNFe.CStat}-{retConsReciNFe.XMotivo}";
                return(false);
            }

            tentarNovamente = false;

            if (retConsReciNFe.CStat == "104")
            {
                if (retConsReciNFe.ProtNFe.InfProt.CStat == "100")
                {
                    GerarProcNFe(nfe, retConsReciNFe, caminhoNF);
                    Mensagem = $"{retConsReciNFe.ProtNFe.InfProt.CStat}-{retConsReciNFe.ProtNFe.InfProt.XMotivo}";
                    return(true);
                }
                else
                {
                    Erro = $"{retConsReciNFe.ProtNFe.InfProt.CStat}-{retConsReciNFe.ProtNFe.InfProt.XMotivo}";
                    return(false);
                }
            }
            else
            {
                Erro = $"{retConsReciNFe.CStat}-{retConsReciNFe.XMotivo}";
                return(false);
            }
        }
Exemplo n.º 3
0
        internal static DanfeViewModel CreateFromXmlFile(String path)
        {
            if (String.IsNullOrWhiteSpace(path))
            {
                throw new ArgumentException("O arquivo Xml precisa ser especificado.");
            }

            if (!File.Exists(path))
            {
                throw new FileNotFoundException("O arquivo Xml não foi encontrado.", path);
            }

            bool xml_processado = false;

            // validar se é um xml processado ou não
            if (File.ReadAllText(path).ToLower().Contains("<nfeproc"))
            {
                xml_processado = true;
            }

            ProcNFe       procNfe            = null;
            XmlSerializer serializer_procNFe = new XmlSerializer(typeof(ProcNFe));

            NFe           nfe            = null;
            XmlSerializer serializer_nfe = new XmlSerializer(typeof(NFe));

            try
            {
                using (StreamReader reader = new StreamReader(path, true))
                {
                    if (xml_processado)
                    {
                        procNfe = (ProcNFe)serializer_procNFe.Deserialize(reader);
                    }
                    else
                    {
                        nfe = (NFe)serializer_nfe.Deserialize(reader);
                    }
                }

                if (xml_processado)
                {
                    return(CreateFromXml(procNfe));
                }
                else
                {
                    return(CreateFromXMLNFe(nfe));
                }
            }
            catch (System.InvalidOperationException e)
            {
                if (e.InnerException is XmlException)
                {
                    XmlException ex = (XmlException)e.InnerException;
                    throw new Exception(String.Format("Não foi possível interpretar o Xml. Linha {0} Posição {1}.", ex.LineNumber, ex.LinePosition));
                }

                throw new XmlException("O Xml não parece ser uma NF-e processada.", e);
            }
        }
Exemplo n.º 4
0
        private XmlDocument CriarLoteEAssinar(NFe nf, string idLote, bool NFCe = false)
        {
            XmlDocument lote, xmlNFe;
            EnviNFe     enviNFe = new EnviNFe();

            enviNFe.Versao  = nf.InfNFe.Versao;
            enviNFe.IndSinc = "0";

            enviNFe.IdLote = idLote;

            lote = enviNFe.ToXmlDocument();
            if (!AssinaturaDigital.Assinar(nf.ToXmlString(), "infNFe", Certificado.X509Certificado))
            {
                throw new Exception(AssinaturaDigital.Erro);
            }

            xmlNFe = AssinaturaDigital.XMLDoc;

            if (NFCe)
            {
                AdicionarQRCode(GerarQRCode(xmlNFe), WebServiceNFCe.EnderecoQRCode, xmlNFe);
            }

            XmlNode node = lote.ImportNode(xmlNFe.DocumentElement, true);

            lote.DocumentElement.AppendChild(node);
            lote.PreserveWhitespace   = true;
            xmlNFe.PreserveWhitespace = true;

            lote.Save(ObterCaminhoArquivo($"{enviNFe.IdLote}{SufixoLote}.xml"));
            xmlNFe.Save(ObterCaminhoArquivo($"{nf.InfNFe.Id.Substring(3)}{SufixoNFe}.xml"));

            return(lote);
        }
Exemplo n.º 5
0
        public static NFe Assinar(this NFe nfe, X509Certificate2 certificadoDigital)
        {
            var assinatura = Assinador.ObterAssinatura <NFe>(nfe, nfe.infNFe.Id, certificadoDigital);

            nfe.Signature = assinatura.Parse();
            return(nfe);
        }
Exemplo n.º 6
0
 public void Populate(NFe.Service.infCad infCad)
 {
     uninfeDummy.ClearControls(this, true, false);
     if (!string.IsNullOrEmpty(infCad.CNPJ))
     {
         this.label1.Text = NFe.Components.TpcnResources.CNPJ.ToString();
         this.txtCNPJ_CPF.Text = uninfeDummy.FmtCnpjCpf(infCad.CNPJ, true);
     }
     else
     {
         this.label1.Text = "CPF";
         this.txtCNPJ_CPF.Text = uninfeDummy.FmtCnpjCpf(infCad.CPF, false);
     }
     this.txtxIE.Text = infCad.IE;
     this.txtxNome.Text = infCad.xNome;
     this.txtxFant.Text = infCad.xFant;
     this.txtxEnder.Text = infCad.ender.xLgr;
     this.txtxBairro.Text = infCad.ender.xBairro;
     this.txtnro.Text = infCad.ender.nro;
     this.txtxCpl.Text = infCad.ender.xCpl;
     this.txtUF.Text = infCad.UF;
     this.txtxMun.Text = infCad.ender.xMun;
     this.txtCEP.Text = infCad.ender.CEP.ToString("00000000");
     this.txtdBaixa.Text = infCad.dBaixa.ToShortDateString();
     this.txtdUltSit.Text = infCad.dUltSit.ToShortDateString();
     this.txtdIniAtiv.Text = infCad.dIniAtiv.ToShortDateString();
     this.txtxRegApur.Text = infCad.xRegApur;
     this.txtCNAE.Text = infCad.CNAE.ToString();
     this.txtIEAtual.Text = infCad.IEAtual;
     this.txtIEUnica.Text = infCad.IEUnica;
     this.txtcSit.Text = infCad.cSit;
 }
Exemplo n.º 7
0
        /// <summary>
        ///     Obter url de contingência
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        private string ObterUrlContingencia(NFe entity)
        {
            //Tratar para ambiente de produção
            if (entity == null)
            {
                throw new ArgumentNullException(nameof(entity));
            }
            _contingencia = true;

            //Sendo o modelo 65, entao continuar com o mesmo endereço
            var modelo = entity.infNFe.ide.mod;

            if (modelo == ModeloDocumento.NfCe)
            {
                return(ObterUrlServicoNormal(entity));
            }
            //Sendo modelo 55, entao verificar o tipo de emissão escolhida
            var tpEmissao = entity.infNFe.ide.tpEmis;

            switch (tpEmissao)
            {
            case TipoEmissao.ContingenciaDpec:
                return(_emisorEmissorServicoConfig.ConfigServ.UrlsNFe.Producao.ContingenciaDpec);

            case TipoEmissao.ContingenciaSvcAn:
                return(_emisorEmissorServicoConfig.ConfigServ.UrlsNFe.Producao.ContingenciaSvcan);

            case TipoEmissao.ContingenciaSvcRs:
                return(_emisorEmissorServicoConfig.ConfigServ.UrlsNFe.Producao.ContingenciaSvcrs);

            default:
                throw new ArgumentOutOfRangeException(
                          $"Não foram encontrados os tipo de emissão em contigência SVC-AN, DPEC ou SVC-RS ");
            }
        }
Exemplo n.º 8
0
        private string ObtemUrlQrCode(NFe nfce, string idToken, string csc)
        {
            var url = _configDanfe.NFCeUrlConsultaQrCodeSefaz;

            const string pipe = "|";

            //Chave de Acesso da NFC-e
            var chave = _nfe.infNFe.Id.Substring(3);

            //Identificação do Ambiente (1 – Produção, 2 – Homologação)
            var ambiente = (int)_nfe.infNFe.ide.tpAmb;

            //Identificador do CSC (Código de Segurança do Contribuinte no Banco de Dados da SEFAZ). Informar sem os zeros não significativos
            var idCsc = Convert.ToInt16(csc);

            string dadosBase;

            if (_nfe.infNFe.ide.tpEmis == DFeBR.EmissorNFe.Utilidade.Tipos.TipoEmissao.ContingenciaOffLineNfce)
            {
                var diaEmi    = _nfe.infNFe.ide.dhEmi.Day.ToString("D2");
                var valorNfce = _nfe.infNFe.total.ICMSTot.vNF.ToString("0.00").Replace(',', '.');
                var digVal    = Nativo.Conversor.ObterHexDeString(_nfe.Signature.SignedInfo.Reference.DigestValue);
                dadosBase = string.Concat(chave, pipe, 2, pipe, ambiente, pipe, diaEmi, pipe, valorNfce, pipe, digVal, pipe, idCsc);
            }
            else
            {
                dadosBase = string.Concat(chave, pipe, 2, pipe, ambiente, pipe, idCsc);
            }

            var dadosSha1 = string.Concat(dadosBase, csc);
            var sh1       = Nativo.Conversor.ObterHexSha1DeString(dadosSha1);

            return(string.Concat(url, dadosBase, pipe, sh1));
        }
Exemplo n.º 9
0
        /// <summary>
        ///     Validar schema
        /// </summary>
        /// <param name="entity"></param>
        private void ValidarSchema(NFe entity)
        {
            var caminhoSchema = _emisorEmissorServicoConfig.DiretorioSchemaXsd;

            if (!Directory.Exists(caminhoSchema))
            {
                throw new Exception("Diretório de Schemas não encontrado: \n" + caminhoSchema);
            }
            // Define o tipo de validação
            var cfg = new XmlReaderSettings {
                ValidationType = ValidationType.Schema
            };
            //Listar arquivos XSD e inclui-las na validação
            var list = ObterListaNomeSchemas().ToList();

            list.ForEach(n => { cfg.Schemas.Add(null, Path.Combine(caminhoSchema, n)); });
            cfg.ValidationEventHandler += ValidationEventHandler;
            var xml      = Utils.ObterStringXML(entity);
            var reader   = XmlReader.Create(new StringReader(xml), cfg);
            var document = new XmlDocument();

            document.Load(reader);

            //Valida xml
            document.Validate(ValidationEventHandler);
        }
Exemplo n.º 10
0
        /// <summary>
        ///     Solicita autorização de uma NFe
        /// </summary>
        /// <param name="xmlNFe">Uma string Xml</param>
        /// <param name="compactarMensagem">Define se a mensagem será enviada para a SEFAZ compactada</param>
        /// <returns></returns>
        public IRetAutorz Autorizar(NFe nfe, bool compactarMensagem = false)
        {
            string xmlNFe = nfe.ObterStringXML();
            var    n2     = new ServAutorzNfe4(EmissorConfig, X509Certificate2,
                                               xmlNFe, VersaoServico.Ve400, compactarMensagem);

            return(n2.Executar());
        }
Exemplo n.º 11
0
        public ActionResult Post([FromBody] NFe nfe)
        {
            _context.NFes.Add(nfe);
            _context.SaveChanges();

            return(new CreatedAtRouteResult("ObterNFe",
                                            new { id = nfe.DocumentId }, nfe));
        }
Exemplo n.º 12
0
        public async Task <IRetornoAutorizacao> Autorizar(NFe nfe, int idLote = 0)
        {
            var lista = new List <NFe> {
                nfe
            };

            return(await Autorizar(lista, idLote));
        }
Exemplo n.º 13
0
        /// <summary>
        ///     Obtém a URL para uso no QR-Code, versão 2.0 - leiaute 4.00
        /// </summary>
        /// <param name="nfe">Nota Fiscal</param>
        /// <param name="cIdToken">Código ID 000001</param>
        /// <param name="csc">Código CSC</param>
        /// <param name="urlQrCode">Endereco Urldo QRCode</param>
        /// <returns></returns>
        public static string ObterUrlQrCode2(NFe nfe, string cIdToken, string csc, string urlQrCode)
        {
            if (nfe == null)
            {
                throw new ArgumentNullException(nameof(nfe));
            }
            if (cIdToken == null)
            {
                throw new ArgumentNullException(nameof(cIdToken));
            }
            if (csc == null)
            {
                throw new ArgumentNullException(nameof(csc));
            }
            if (urlQrCode == null)
            {
                throw new ArgumentNullException(nameof(urlQrCode));
            }

            #region 1ª parte

            var url = ObterUrlQrCode2ComParametro(urlQrCode);

            #endregion

            #region 2ª parte

            const string pipe = "|";

            //Chave de Acesso da NFC-e
            var chave = nfe.infNFe.Id.Substring(3);

            //Identificação do Ambiente (1 – Produção, 2 – Homologação)
            var ambiente = (int)nfe.infNFe.ide.tpAmb;

            //Identificador do CSC (Código de Segurança do Contribuinte no Banco de Dados da SEFAZ). Informar sem os zeros não significativos
            var    idCsc = Convert.ToInt32(cIdToken);
            string dadosBase;
            if (nfe.infNFe.ide.tpEmis == TipoEmissao.ContingenciaOffLineNfce)
            {
                var diaEmi    = nfe.infNFe.ide.dhEmi.Day.ToString("D2");
                var valorNfce = nfe.infNFe.total.ICMSTot.vNF.ToString("0.00").Replace(',', '.');
                var digVal    = Utils.ObterHexDeString(nfe.Signature.SignedInfo.Reference.DigestValue);
                dadosBase = string.Concat(chave, pipe, 2, pipe, ambiente, pipe, diaEmi, pipe, valorNfce, pipe, digVal, pipe, idCsc);
            }
            else
            {
                dadosBase = string.Concat(chave, pipe, 2, pipe, ambiente, pipe, idCsc);
            }

            var dadosSha1 = string.Concat(dadosBase, csc);
            var sh1       = Utils.ObterHexSha1DeString(dadosSha1);
            return(string.Concat(url, dadosBase, pipe, sh1));

            #endregion
        }
Exemplo n.º 14
0
 public ActionResult Put(string id, [FromBody] NFe nfe)
 {
     if (id != nfe.DocumentId)
     {
         return(BadRequest());
     }
     _context.Entry(nfe).State = EntityState.Modified;
     _context.SaveChanges();
     return(Ok());
 }
Exemplo n.º 15
0
        public static void Ler()
        {
            XmlSerializer ser        = new XmlSerializer(typeof(NFe));
            TextReader    textReader = (TextReader) new StreamReader("c:\\temp\\nfe.xml");
            XmlTextReader reader     = new XmlTextReader(textReader);

            reader.Read();

            NFe nota = (NFe)ser.Deserialize(reader);
        }
Exemplo n.º 16
0
        public bool ConsultaSituacaoAtualNFCe(string caminhoNFCe, string numRec, string serialCertificado = null)
        {
            Mensagem = "";

            try
            {
                NFe nfce = ManipularXML.Load <NFe>(caminhoNFCe);

                if (!SetarWebService("NFCe", Estados.ObterEstado(nfce.InfNFe.Ide.CUF), EnderecoWS.ObterAmbiemte(nfce.InfNFe.Ide.TpAmb), "NFeRetAutorizacao"))
                {
                    Erro = "Web Service não foi encontrado";
                    return(false);
                }

                if (!Certificado.BuscarCertificado(nroSerie: serialCertificado))
                {
                    Erro = Certificado.Erros;
                    return(false);
                }

                XmlDocument recNfe = ConsReciboNF(nfce, numRec).ToXmlDocument();

                using (Wsdl.NFCe.Autorizacao.NFeRetAutorizacao4 ws = new Wsdl.NFCe.Autorizacao.NFeRetAutorizacao4(WebServiceNFCe.WebService, Certificado.X509Certificado, TimeOut))
                {
                    bool tentarNovamente;
                    bool resultado;
                    do
                    {
                        tentarNovamente = false;
                        XmlNode n = ws.Execute(recNfe);
                        if (n == null)
                        {
                            throw new Exception($"Falha no envio do arquivo de retorno (404 - Serviço não encontrado).\n\nWeb Service {WebServiceNFCe.WebService}");
                        }
                        else
                        {
                            resultado = RetornoConsultaRecibo(nfce, n.OuterXml.ToXmlClass <RetConsReciNFe>(), caminhoNFCe, out tentarNovamente);

                            if (!tentarNovamente)
                            {
                                return(resultado);
                            }
                        }
                    } while (tentarNovamente);

                    return(resultado);
                }
            }
            catch (Exception ex)
            {
                Erro = $"ERRO NO PROCESSO DE CONSULTA ATUAL\n\n{ex.Message}";
                return(false);
            }
        }
Exemplo n.º 17
0
        public void btn_Click(object sender, EventArgs e)
        {
            XmlSerializer ser        = new XmlSerializer(typeof(NFe));
            TextReader    textReader = (TextReader) new StreamReader("D:\\downloads\\nfe exemplo.xml");
            XmlTextReader reader     = new XmlTextReader(textReader);

            reader.Read();

            //Desserializar o arquivo xml
            NFe nota = (NFe)ser.Deserialize(reader);
        }
Exemplo n.º 18
0
 public bool ValidaNull(NFe nfe)
 {
     if (string.IsNullOrEmpty(nfe.infNFe.ide.cNF.ToString()))
     {
         return(false);
     }
     else
     {
         return(true);
     }
 }
Exemplo n.º 19
0
        public void TestMethod1()
        {
            NFe _NFe = new NFe();

            _NFe.Id        = "";
            _NFe.infNFe.Id = _NFe.Id;
            emit emit = new emit();

            emit.Id          = 0;
            emit.enderEmitId = 0;
            Tendereco endereco = new Tendereco();
        }
Exemplo n.º 20
0
        private ConsReciNFe ConsReciboNF(NFe nf, string numRec)
        {
            ConsReciNFe consReciNFe = new ConsReciNFe()
            {
                Versao = nf.InfNFe.Versao,
                NRec   = numRec,
                TpAmb  = nf.InfNFe.Ide.TpAmb
            };

            consReciNFe.Salvar(ObterCaminhoArquivo($"{nf.InfNFe.Id.Substring(3)}{SufixoPedRec}.xml"));

            return(consReciNFe);
        }
Exemplo n.º 21
0
        public HttpResponseMessage GetNFe(int numeroNFe)
        {
            try
            {
                NFe nf = nfeNegocio.BuscaNFePorNumero(numeroNFe);

                return(Request.CreateResponse(HttpStatusCode.OK, nf));
            }
            catch (Exception e)
            {
                return(Request.CreateResponse(HttpStatusCode.InternalServerError, new { erro = "Ocorreu um erro ao efetuar sua solicitação. Ex: " + e.ToString() }));
            }
        }
Exemplo n.º 22
0
 /// <summary>
 ///     Assinar
 /// </summary>
 /// <param name="entity"></param>
 /// <returns></returns>
 private void Assinar(NFe entity)
 {
     try
     {
         var assinatura = AssinaturaDigital.AssinarNFe(entity, entity.infNFe.Id, _certificadoDigital);
         entity.Signature = assinatura;
     }
     catch (Exception ex)
     {
         Utils.TraceException(ex, "Erro ao assinar arquivo Xml");
         throw new FalhaAssinaturaException("Erro ao assinar arquivo Xml", ex);
     }
 }
Exemplo n.º 23
0
        public HttpResponseMessage GetNFe(int CHNFE)
        {
            NFe nfes = nfeRepositorio.Get(CHNFE);

            if (CHNFE == null)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.NotFound, "Estudante não localizado para o Id informado"));
            }
            else
            {
                return(Request.CreateResponse <NFe>(HttpStatusCode.OK, nfes));
            }
        }
Exemplo n.º 24
0
        public NFe CalculateWithhold(decimal invoiceValue, decimal IR, decimal PIS, decimal COFINS, decimal CSLL)
        {
            var csll   = new CSLLService(CSLL);
            var cofins = new COFINSService(COFINS);
            var ir     = new IRService(IR);
            var pis    = new PISService(PIS);

            NFe nfe = new NFe(cofins, csll, ir, pis);

            nfe.invoiceValue = invoiceValue;

            return(InternalCalculate(nfe));
        }
Exemplo n.º 25
0
        public bool EnviarNFe(NFe nfe, string idLote, string serialCertificado = "")
        {
            NumRecibo = "";

            try
            {
                if (!SetarWebService("NFe", Estados.ObterEstado(nfe.InfNFe.Ide.CUF), Wsdl.EnderecoWS.EnderecoWS.Ambientes.Homologacao, "NFeAutorizacao"))
                {
                    Erro = "Web Service não foi encontrado";
                    return(false);
                }

                if (!GerarChaveNF(nfe))
                {
                    return(false);
                }

                if (!Certificado.BuscarCertificado(nroSerie: serialCertificado))
                {
                    Erro = Certificado.Erros;
                    return(false);
                }

                if (!Certificado.BuscarCertificado(nroSerie: serialCertificado))
                {
                    Erro = Certificado.Erros;
                    return(false);
                }

                XmlDocument lote = CriarLoteEAssinar(nfe, idLote);

                using (Wsdl.NFe.Autorizacao.NFeAutorizacao4 ws = new Wsdl.NFe.Autorizacao.NFeAutorizacao4(WebServiceNFe.WebService, Certificado.X509Certificado, TimeOut))
                {
                    XmlNode n = ws.Execute(lote);

                    if (n == null)
                    {
                        throw new Exception($"Falha na obtenção do arquivo de retorno (404 - Serviço não encontrado).\n\nWeb Service {WebServiceNFe.WebService}");
                    }
                    else
                    {
                        return(RetornoRecibo(n.OuterXml.ToXmlClass <RetEnviNFe>()));
                    }
                }
            }
            catch (Exception ex)
            {
                Erro = $"ERRO NO PROCESSO DE ENVIO\n\n{ex.Message}";
                return(false);
            }
        }
Exemplo n.º 26
0
        public bool EnviarNFCe(NFe nfce, string idLote, string serialCertificado = "")
        {
            NumRecibo = "";
            Mensagem  = "";

            try
            {
                if (!SetarWebService("NFCe", Estados.ObterEstado(nfce.InfNFe.Ide.CUF), EnderecoWS.ObterAmbiemte(nfce.InfNFe.Ide.TpAmb), "NFeAutorizacao"))
                {
                    Erro = "Web Service não foi encontrado";
                    return(false);
                }

                if (!GerarChaveNF(nfce))
                {
                    return(false);
                }

                if (!Certificado.BuscarCertificado(nroSerie: serialCertificado))
                {
                    Erro = Certificado.Erros;
                    return(false);
                }

                XmlDocument lote = CriarLoteEAssinar(nfce, idLote, true);

                if (!ValidarDocumentoFiscal(ObterCaminhoArquivo($"{nfce.InfNFe.Id.Substring(3)}{SufixoNFe}.xml")))
                {
                    return(false);
                }

                using (Wsdl.NFCe.Autorizacao.NFeAutorizacao4 ws = new Wsdl.NFCe.Autorizacao.NFeAutorizacao4(WebServiceNFCe.WebService, Certificado.X509Certificado, TimeOut))
                {
                    XmlNode n = ws.Execute(lote);

                    if (n == null)
                    {
                        throw new Exception($"Falha no envio do arquivo de retorno (404 - Serviço não encontrado).\n\nWeb Service {WebServiceNFCe.WebService}");
                    }
                    else
                    {
                        return(RetornoRecibo(n.OuterXml.ToXmlClass <RetEnviNFe>()));
                    }
                }
            }
            catch (Exception ex)
            {
                Erro = $"ERRO NO PROCESSO DE ENVIO\n\n{ex.Message}";
                return(false);
            }
        }
Exemplo n.º 27
0
        /// <summary>
        ///     Gerar string QRcode
        /// </summary>
        /// <param name="entity"></param>
        private void GerarUrlQrCode(NFe entity)
        {
            //QRCode somente para modelo de documento NFCe
            if (entity.infNFe.ide.mod != ModeloDocumento.NfCe)
            {
                return;
            }
            entity.infNFeSupl = new infNFeSupl();
            var urlQrCodeConsulta = ObterUrlQrCodeConsulta();
            var urlQrCodeChave    = ObterUrlQrCodeChave();

            entity.infNFeSupl.urlChave = urlQrCodeConsulta;
            entity.infNFeSupl.qrCode   = QrCodeNfCe.ObterUrlQrCode2(entity, _emisorEmissorServicoConfig.Token.CscID,
                                                                    _emisorEmissorServicoConfig.Token.CscToken, urlQrCodeChave);
        }
Exemplo n.º 28
0
        //public static async Task<string> SalvarArquivoAsync(this NFe nfe)
        //{
        //    var caminho = Path.GetTempFileName();
        //    var nome = Path.GetFileName(caminho);
        //    var diretorio = Path.GetDirectoryName(caminho);

        //    return await nfe.SalvarArquivoAsync(nome, diretorio);
        //}

        public static async Task <string> SalvarArquivoAsync(this NFe nfe, string nomeArquivo, string diretorio)
        {
            if (nomeArquivo is null)
            {
                throw new ArgumentNullException(nameof(nomeArquivo));
            }

            if (string.IsNullOrEmpty(diretorio))
            {
                diretorio = Path.GetTempPath();
            }

            var str = XmlUtils.ClasseParaXmlString <NFe>(nfe);

            return(await Arquivo.SalvarArquivoAsync(diretorio, nomeArquivo, str));
        }
Exemplo n.º 29
0
        /// <summary>
        ///     Obter endereço serviço
        /// <para>O tipo selecionado na tag NFe.infNFe.ide.tpEmis direciona para qual url deve ser direcionado o serviço, se normal ou em contingencia</para>
        /// </summary>
        /// <returns></returns>
        private string ObterUrlServico(NFe entity)
        {
            //O tipo selecionado na tag NFe.infNFe.ide.tpEmis direciona para qual url deve ser direcionado o serviço, se normal ou em contingencia
            //Verificar pelo tipo de emissão se trata-se de emissão em contingencia
            _contingencia = false;
            var tpEmissao = entity.infNFe.ide.tpEmis;

            //Obter uma url em contingencia por ter sido informado o tipo de emissão diferente de normal
            if (tpEmissao != TipoEmissao.Normal)
            {
                return(ObterUrlContingencia(entity));
            }

            //Obter uma url para um serviço de envio normal
            return(ObterUrlServicoNormal(entity));
        }
Exemplo n.º 30
0
        public NFeDI(NFe nota, string xml)
        {
            if (nota.Informacoes.identificacao.Modelo == 65)
            {
                throw new Exception();
            }

            Id           = nota.Informacoes.Id;
            NomeCliente  = nota.Informacoes.destinatario.Nome;
            NomeEmitente = nota.Informacoes.Emitente.Nome;
            CNPJEmitente = nota.Informacoes.Emitente.CNPJ.ToString();
            DataEmissao  = DateTime.Parse(nota.Informacoes.identificacao.DataHoraEmissão).ToString("yyyy-MM-dd HH:mm:ss");
            NumeroNota   = nota.Informacoes.identificacao.Numero;
            SerieNota    = nota.Informacoes.identificacao.Serie;
            Status       = nota.Signature != null && nota.Signature != null ? (int)StatusNota.Assinada : (int)StatusNota.Salva;
            IsNFCe       = false;
            XML          = xml;
        }
Exemplo n.º 31
0
        internal static DanfeViewModel CreateFromXmlString(String xml)
        {
            bool xml_processado = false;

            // validar se é um xml processado ou não
            if (xml.ToLower().Contains("<nfeproc"))
            {
                xml_processado = true;
            }

            ProcNFe       procNfe            = null;
            XmlSerializer serializer_procNFe = new XmlSerializer(typeof(ProcNFe));

            NFe           nfe            = null;
            XmlSerializer serializer_nfe = new XmlSerializer(typeof(NFe));

            try
            {
                using (TextReader reader = new StringReader(xml))
                {
                    if (xml_processado)
                    {
                        procNfe = (ProcNFe)serializer_procNFe.Deserialize(reader);
                    }
                    else
                    {
                        nfe = (NFe)serializer_nfe.Deserialize(reader);
                    }
                }

                if (xml_processado)
                {
                    return(CreateFromXml(procNfe));
                }
                else
                {
                    return(CreateFromXMLNFe(nfe));
                }
            }
            catch (System.InvalidOperationException e)
            {
                throw new Exception("Não foi possível interpretar o texto Xml.", e);
            }
        }
Exemplo n.º 32
0
        public void Populate(NFe.Settings.Empresa empresa)
        {
            this.empresa = empresa;
            uninfeDummy.ClearControls(this, true, false);

            edtFTP_Ativo.Checked = empresa.FTPAtivo;
            edtFTP_Passivo.Checked = empresa.FTPPassivo;
            edtFTP_GravaXMLPastaUnica.Checked = empresa.FTPGravaXMLPastaUnica;
            edtFTP_Password.Text = empresa.FTPSenha;
            edtFTP_PastaDestino.Text = empresa.FTPPastaAutorizados;
            edtFTP_PastaRetornos.Text = empresa.FTPPastaRetornos;
            edtFTP_Porta.Text = empresa.FTPPorta.ToString();
            edtFTP_Server.Text = empresa.FTPNomeDoServidor;
            edtFTP_UserName.Text = empresa.FTPNomeDoUsuario;

            edtFTP_PastaDestino.Visible =
                lbl_edtFTP_PastaDestino.Visible =
                edtFTP_GravaXMLPastaUnica.Visible = (empresa.Servico == TipoAplicativo.Nfe || empresa.Servico == TipoAplicativo.Todos);
        }
Exemplo n.º 33
0
 public static string WebServicesProducao(ref NFe.Components.PadroesNFSe padrao, int idMunicipio = 0)
 {
     return getURLs(NFe.Components.NFeStrConstants.LocalProducao, ref padrao, idMunicipio);
 }
Exemplo n.º 34
0
        /// <summary>
        /// Determina se pode reenviar a nota fiscal eletrônica de acordo com o status
        /// </summary>
        /// <param name="statusNFe">Status da nota fiscal eletrônica a analisar</param>
        /// <returns>Se verdadeiro, pode reenviar a nota fiscal eletrônica</returns>
        private bool ReenviarNFe(NFe.Status statusNFe)
        {
            IList<NFe.Status> statusNFes = new List<NFe.Status>();
            statusNFes.Add(NFe.Status.AcessoBDNFe);
            statusNFes.Add(NFe.Status.AcessoCadastradoContribuinte);
            statusNFes.Add(NFe.Status.AcessoCadastroContribuinte);
            statusNFes.Add(NFe.Status.AmbienteNFEDifereAmbienteWebService);
            statusNFes.Add(NFe.Status.AnoInutilizacaoInferior2006);
            statusNFes.Add(NFe.Status.AnoInutilizacaoSuperiorAnoAtual);
            statusNFes.Add(NFe.Status.AnoInvalidoChaveAcesso);
            statusNFes.Add(NFe.Status.AssinaturaDiferePadraoSistema);
            statusNFes.Add(NFe.Status.CertificadoAssinaturaInvalido);
            statusNFes.Add(NFe.Status.CertificadoAssinaturaRevogado);

            statusNFes.Add(NFe.Status.CertificadoDeTransmissorInvalido);
            statusNFes.Add(NFe.Status.CertificadoRaizDifereDaICPBrasil);
            statusNFes.Add(NFe.Status.CertificadoTransmissorRevogado);
            statusNFes.Add(NFe.Status.ChaveAcessoDifereExistenteBD);
            statusNFes.Add(NFe.Status.ChaveAcessoInexistenteTipoEvento);
            statusNFes.Add(NFe.Status.CNPJAutorEventoInvalido);
            statusNFes.Add(NFe.Status.CNPJContribuinteNaoEncontrado);
            statusNFes.Add(NFe.Status.CNPJEmitenteDifereCNPJCertificadoDigital);
            statusNFes.Add(NFe.Status.CNPJInvalidoChaveAcesso);
            statusNFes.Add(NFe.Status.CNPJTransmissorLoteDifereCNPJTrasnmissorConsulta);

            statusNFes.Add(NFe.Status.CodigoNumericoChaveAcessoDifereBD);
            statusNFes.Add(NFe.Status.CPFAutorEventoInvalido);
            statusNFes.Add(NFe.Status.DataEventoNaoPodeSerMaiorDataProcessamento);
            statusNFes.Add(NFe.Status.DataEventoNaoPodeSerMenorDataAutorizacaoContingencia);
            statusNFes.Add(NFe.Status.DataEventoNaoPodeSerMenorDataEmissao);
            statusNFes.Add(NFe.Status.EventoDestinatarioVerificarCNPJAutorDifereCNPJBaseChaveAcesso);
            statusNFes.Add(NFe.Status.EventoEmissorVerificarCNPJAutorDifereCNPJBaseChaveAcesso);
            statusNFes.Add(NFe.Status.EventoRegistradoNaoVinculado);
            statusNFes.Add(NFe.Status.EventoRegistradoVinculado);
            statusNFes.Add(NFe.Status.FaltaExtensaoCNPJCertificado);

            statusNFes.Add(NFe.Status.IDInvalidoConcatenacaoOutrosCampos);
            statusNFes.Add(NFe.Status.IEContribuinteNaoEncontrado);
            statusNFes.Add(NFe.Status.LCRDoCertificadoAssinatura);
            statusNFes.Add(NFe.Status.LCRDoCertificadoTransmissor);
            statusNFes.Add(NFe.Status.MesChaveAcessoDifereMesDaNFe);
            statusNFes.Add(NFe.Status.MesInvalidoChaveAcesso);
            statusNFes.Add(NFe.Status.Modelo55DiferenteChaveAcesso);
            statusNFes.Add(NFe.Status.NenhumDocumentoLocalizadoParaDestinatario);
            statusNFes.Add(NFe.Status.NFeNaoConstaBaseDadosSEFAZ);
            statusNFes.Add(NFe.Status.NumeroNFInvalidoChaveAcesso);

            statusNFes.Add(NFe.Status.QuantidadeMaximaInutilizacaoUltrapassa1000);
            statusNFes.Add(NFe.Status.SerieDifereDe0A899);
            statusNFes.Add(NFe.Status.SerieSCANDifereFaixa900A999);
            statusNFes.Add(NFe.Status.SerieSCANEntre900A999);
            statusNFes.Add(NFe.Status.TamanhoXMLSuperiorA500Kb);
            statusNFes.Add(NFe.Status.TipoAutorizadorReciboDivergeOrgaoAutorizador);
            statusNFes.Add(NFe.Status.UFChaveAcessoDifereUFWebService);
            statusNFes.Add(NFe.Status.UFConsultaDifereUFWebService);
            statusNFes.Add(NFe.Status.UFInexistenteSoapHeader);
            statusNFes.Add(NFe.Status.UFInvalidoChaveAcesso);

            statusNFes.Add(NFe.Status.UFPedidoInutilizacaoDifereUFWebService);
            statusNFes.Add(NFe.Status.UFReciboDifereUFWebService);
            statusNFes.Add(NFe.Status.ValidadeDoCertificado);
            statusNFes.Add(NFe.Status.ValorAssinaturaDifereValorCalculado);
            statusNFes.Add(NFe.Status.VerificaACadeiaDeCertificacao);
            statusNFes.Add(NFe.Status.VerificaDetEventoValido);
            statusNFes.Add(NFe.Status.VerificaDigitoZeroCNPJ);
            statusNFes.Add(NFe.Status.VerificaDigitoZeroIE);
            statusNFes.Add(NFe.Status.VerificaJaExixtePedidoInutilizacao);
            statusNFes.Add(NFe.Status.VerificaNFeJaCancelada);

            statusNFes.Add(NFe.Status.VerificaPrefixoNameSpace);
            statusNFes.Add(NFe.Status.VerificarCampoNumericoChaveNumericoDifereBD);
            statusNFes.Add(NFe.Status.VerificarCNPJAutorConstaTabelaOrgaos);
            statusNFes.Add(NFe.Status.VerificarCNPJSolicitanteEmissorNFe);
            statusNFes.Add(NFe.Status.VerificarDuplicidadeDoEvento);
            statusNFes.Add(NFe.Status.VerificarIDCorrespondeCampoEvento);
            statusNFes.Add(NFe.Status.VerificarNFeEstaAutorizada);
            statusNFes.Add(NFe.Status.VerificarSequencialEventoEntre1A20);
            statusNFes.Add(NFe.Status.VerificarSituacaoIrregularEmitente);
            statusNFes.Add(NFe.Status.VerificarUFInformadaNoCampoCUF);

            statusNFes.Add(NFe.Status.VerificaTipoEventoValido);
            statusNFes.Add(NFe.Status.VerificaVersaoEventoValido);
            statusNFes.Add(NFe.Status.VerificaXMLAreaDados);
            statusNFes.Add(NFe.Status.NaoDefinido);
            statusNFes.Add(NFe.Status.LoteEmProcessamento);
            statusNFes.Add(NFe.Status.LoteProcessado);
            statusNFes.Add(NFe.Status.LoteRecebido);
            statusNFes.Add(NFe.Status.NFeSemEnderecoDestinatario);

            var status = from s in statusNFes
                         where s.Equals(statusNFe)
                         select s;

            if(status.Count() > 0)
                return true;

            return false;
        }
Exemplo n.º 35
0
        public static void ExecutaUniDanfe(string nomeArquivoRecebido, DateTime dataEmissaoNFe, NFe.Settings.Empresa emp, Dictionary<string, string> args = null)
        {
#if DEBUG
            Auxiliar.WriteLog("ExecutaUniDanfe: Preparando a execução do UniDANFe p/ o arquivo: \"" + nomeArquivoRecebido + "\"", false);
#endif
            const string erroMsg = "Arquivo {0} não encontrado para impressão do DANFE/DACTE/CCe/DAMDFe {1}";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

                    string temps = "";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                    if (fAuxiliar != "")
                    {
                        System.ComponentModel.BackgroundWorker worker = new System.ComponentModel.BackgroundWorker();
                        worker.WorkerSupportsCancellation = true;
                        worker.RunWorkerCompleted += ((sender, e) => ((System.ComponentModel.BackgroundWorker)sender).Dispose());
                        worker.DoWork += new System.ComponentModel.DoWorkEventHandler(ExcluirArqAuxiliar);
                        worker.RunWorkerAsync(fAuxiliar);
                    }
                }
            }
        }
Exemplo n.º 36
0
 public string nome(NFe.Components.Servicos servico, int uf, string versao)
 {
     this.Servico = servico;
     return xNomeClasseWS(this.Servico, uf, versao);
 }
Exemplo n.º 37
0
        public void loadData(NFe.Components.TipoAplicativo opcao, string uf)
        {
            this._tipo = opcao;
            this.uf = uf;

            listageral.Clear();
            listaEstados.Clear();

            edtEstados.SelectedIndexChanged -= metroComboBox1_SelectedIndexChanged;
            int oIndex = 0;
            try
            {
                string padraobase = NFe.Components.PadroesNFSe.NaoIdentificado.ToString();
                if (this.configname == null)
                {
                    string fn = System.IO.Path.Combine(Application.StartupPath, "uninfe_ws.xml");
                    NFe.Components.XMLIniFile xml = new NFe.Components.XMLIniFile(fn);
                    switch (this._tipo)
                    {
                        case NFe.Components.TipoAplicativo.Nfse:
                            configname = xml.ReadValue("webservice", "uninfse", "");
                            break;

                        default:
                            padraobase = "";
                            configname = xml.ReadValue("webservice", "uninfe", "");
                            this.metroLabel5.Text = "SVC";
                            this.edtPadrao.Items.Clear();
                            this.edtPadrao.Items.Add(NFe.Components.TipoEmissao.teNone.ToString());
                            this.edtPadrao.Items.Add(NFe.Components.TipoEmissao.teSVCAN.ToString());
                            this.edtPadrao.Items.Add(NFe.Components.TipoEmissao.teSVCRS.ToString());
                            break;
                    }
                    filebackup = this.configname + ".xml.bck";

                    xlabels = new List<string>();
                    ///
                    /// varre os nomes das propriedades da classe, eliminando o esquecimento quando da criacao de novas propriedades
                    /// 
                    NFe.Components.URLws temp = new NFe.Components.URLws();
                    foreach (var se in temp.GetType().GetProperties())
                    {
                        if (se.Name.StartsWith("NFe") || se.Name.StartsWith("CTe") || se.Name.StartsWith("DFe") || se.Name.StartsWith("MDFe"))
                        {
                            if (this._tipo == NFe.Components.TipoAplicativo.Nfe)
                                this.xlabels.Add(se.Name);
                        }
                        else
                            if (this._tipo == NFe.Components.TipoAplicativo.Nfse)
                                this.xlabels.Add(se.Name);
                    }

                    int X = 2;
                    foreach (var label in xlabels)
                    {
                        UserControl2 uc1 = new UserControl2();
                        this.tpProd.Controls.Add(uc1);
                        uc1.folder = System.IO.Path.GetDirectoryName(configname) + "\\producao";
                        uc1.metroLabel1.Text = label;
                        uc1.metroTextBox1.Text = label;
                        uc1.Name = "P_" + label;
                        uc1.Location = new Point(2, X);
                        uc1.Size = new System.Drawing.Size(this.tpProd.Size.Width - 20, uc1.Size.Height);

                        UserControl2 uc2 = new UserControl2();
                        this.tpHomo.Controls.Add(uc2);
                        uc2.folder = System.IO.Path.GetDirectoryName(configname) + "\\homologacao";
                        uc2.metroLabel1.Text = label;
                        uc2.metroTextBox1.Text = label;
                        uc2.Name = "H_" + label;
                        uc2.Location = new Point(2, X);
                        uc2.Size = new System.Drawing.Size(this.tpHomo.Size.Width - 20, uc2.Size.Height);

                        X += uc2.Size.Height + 4;
                    }
                }
                else
                    oIndex = edtEstados.SelectedIndex;

                if (this._tipo == NFe.Components.TipoAplicativo.Nfe)
                {
                    NFe.Components.Propriedade.Estados = null;
                    NFe.Components.Propriedade.NomeArqXMLWebService_NFe = configname;
                }
                XElement axml = XElement.Load(configname);
                var s = (from p in axml.Descendants(NFe.Components.NFeStrConstants.Estado)
                         where  (uf == null && p.Attribute(NFe.Components.TpcnResources.UF.ToString()).Value != "XX") ||
                                (uf != null && p.Attribute(NFe.Components.TpcnResources.UF.ToString()).Value == "XX")
                         orderby p.Attribute(NFe.Components.NFeStrConstants.Nome).Value
                         select p);
                foreach (var item in s)
                {
                    listaEstados.Add(new Estado
                    {
                        Nome = item.Attribute(NFe.Components.NFeStrConstants.Nome).Value,
                        ID = item.Attribute(NFe.Components.TpcnResources.ID.ToString()).Value,
                        UF = item.Attribute(NFe.Components.TpcnResources.UF.ToString()).Value,
                        svc = (this._tipo == NFe.Components.TipoAplicativo.Nfse ? "" : (item.Attribute(NFe.Components.NFeStrConstants.SVC) == null ? NFe.Components.TipoEmissao.teNone.ToString() : item.Attribute(NFe.Components.NFeStrConstants.SVC).Value)),
                        Padrao = item.Attribute(NFe.Components.NFeStrConstants.Padrao) == null ? (this._tipo == NFe.Components.TipoAplicativo.Nfse ? padraobase : "") : item.Attribute(NFe.Components.NFeStrConstants.Padrao).Value
                    });
                    listageral.Add(listaEstados[listaEstados.Count - 1].key);
                }
                edtEstados.DataSource = null;
                edtEstados.Items.Clear();
                edtEstados.DisplayMember = "text";
                edtEstados.ValueMember = NFe.Components.TpcnResources.ID.ToString();
                edtEstados.DataSource = listaEstados;
            }
            catch (Exception ex)
            {
                MetroFramework.MetroMessageBox.Show(null, ex.Message, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }
            finally
            {
                edtEstados.SelectedIndex = oIndex;
                metroComboBox1_SelectedIndexChanged(null, null);
                edtEstados.SelectedIndexChanged += metroComboBox1_SelectedIndexChanged;
            }
        }
Exemplo n.º 38
0
        public void Populate(NFe.Settings.Empresa empresa)
        {
            if (this.Tag == null)
            {
                loc1 = lbl_textBox_PastaRetornoXML.Location;
                loc2 = textBox_PastaXmlRetorno.Location;

                loc3 = lbl_textBox_PastaXmlErro.Location;
                loc4 = textBox_PastaXmlErro.Location;

                loc5 = lbl_textBox_PastaValidar.Location;
                loc6 = textBox_PastaValidar.Location;
            }
            this.Tag = 1;
            this.empresa = empresa;
            uninfeDummy.ClearControls(this, true, false);

            textBox_PastaXmlEmLote.Visible = lbl_textBox_PastaLote.Visible =
                textBox_PastaBackup.Visible = lbl_textBox_PastaBackup.Visible =
                textBox_PastaXmlEnviado.Visible = lbl_textBox_PastaEnviados.Visible =
                textBox_PastaDownloadNFeDest.Visible = lbl_textBox_PastaDownload.Visible = (empresa.Servico != TipoAplicativo.Nfse);

            if (empresa.Servico == TipoAplicativo.Nfse)
            {
                lbl_textBox_PastaRetornoXML.Location = new Point(lbl_textBox_PastaBackup.Location.X, 67);
                textBox_PastaXmlRetorno.Location = new Point(lbl_textBox_PastaBackup.Location.X, 86);

                lbl_textBox_PastaXmlErro.Location = new Point(lbl_textBox_PastaBackup.Location.X, 110);
                textBox_PastaXmlErro.Location = new Point(lbl_textBox_PastaBackup.Location.X, 129);

                lbl_textBox_PastaValidar.Location = new Point(lbl_textBox_PastaBackup.Location.X, 153);
                textBox_PastaValidar.Location = new Point(lbl_textBox_PastaBackup.Location.X, 172);
            }
            else
            {
                lbl_textBox_PastaRetornoXML.Location = loc1;
                textBox_PastaXmlRetorno.Location = loc2;

                lbl_textBox_PastaXmlErro.Location = loc3;
                textBox_PastaXmlErro.Location = loc4;

                lbl_textBox_PastaValidar.Location = loc5;
                textBox_PastaValidar.Location = loc6;
            }
            textBox_PastaXmlEnvio.Text = empresa.PastaXmlEnvio;
            textBox_PastaXmlRetorno.Text = empresa.PastaXmlRetorno;
            textBox_PastaXmlEnviado.Text = empresa.PastaXmlEnviado;
            textBox_PastaXmlErro.Text = empresa.PastaXmlErro;
            textBox_PastaXmlEmLote.Text = empresa.PastaXmlEmLote;
            textBox_PastaValidar.Text = empresa.PastaValidar;
            textBox_PastaDownloadNFeDest.Text = empresa.PastaDownloadNFeDest;
            textBox_PastaBackup.Text = empresa.PastaBackup;
            cbCriaPastas.Checked = empresa.CriaPastasAutomaticamente;

            var Components = this.Controls.Cast<object>()
                                       .OfType<MetroFramework.Controls.MetroTextBox>();
            foreach (var c in Components)
            {
                if (!__oldvalues.ContainsKey(c))
                    __oldvalues.Add(c, c.Text);
                else
                    __oldvalues[c] = c.Text;
            }
        }
Exemplo n.º 39
0
        public void Populate(NFe.Settings.Empresa empresa, bool novaempresa)
        {
            this.loading = true;
            try
            {
                uninfeDummy.ClearControls(this, true, false);

                this.empresa = empresa;

                if (empresa.Servico == TipoAplicativo.Nfse)
                {
                    labelUF.Text = "Município";
                    lbl_udDiasLimpeza.Location = new Point(this.lbl_udTempoConsulta.Location.X, this.lbl_udTempoConsulta.Location.Y);
                    udDiasLimpeza.Location = new Point(this.udTempoConsulta.Location.X, this.udTempoConsulta.Location.Y);
                }
                else
                {
                    labelUF.Text = "Unidade Federativa (UF-Estado)";
                    lbl_udDiasLimpeza.Location = loc_1;
                    udDiasLimpeza.Location = loc_2;
                }
                this.lbl_CodMun.Visible =
                    this.edtCodMun.Visible =
                    this.edtPadrao.Visible =
                    this.lbl_Padrao.Visible = (empresa.Servico == TipoAplicativo.Nfse);

                cboDiretorioSalvarComo.Visible =
                    lbl_DiretorioSalvarComo.Visible =
                    comboBox_tpEmis.Visible =
                    metroLabel11.Visible =
                    checkBoxGravarEventosNaPastaEnviadosNFe.Visible =
                    checkBoxRetornoNFETxt.Visible =
                    checkBoxGravarEventosDeTerceiros.Visible =
                    checkBoxGravarEventosCancelamentoNaPastaEnviadosNFe.Visible =
                    checkBoxCompactaNFe.Visible =
                    udTempoConsulta.Visible = lbl_udTempoConsulta.Visible =
                    cbIndSinc.Visible = !(empresa.Servico == TipoAplicativo.Nfse);

                /*

                if (empresa.Servico == TipoAplicativo.Nfe || empresa.Servico == TipoAplicativo.NFCe || empresa.Servico == TipoAplicativo.Todos)
                {
                    grpQRCode.Visible =
                    edtIdentificadorCSC.Visible =
                    edtTokenCSC.Visible = true;
                }
                else
                {
                    grpQRCode.Visible =
                    edtIdentificadorCSC.Visible =
                    edtTokenCSC.Visible = false;
                }
                */

                if (empresa.Servico == TipoAplicativo.Nfse)
                    comboBox_UF.DataSource = arrMunicipios;
                else
                    comboBox_UF.DataSource = arrUF;

                comboBox_UF.DisplayMember = NFe.Components.NFeStrConstants.Nome;
                comboBox_UF.ValueMember = "Codigo";

                cnpjCurrent = this.edtCNPJ.Text = empresa.CNPJ;
                this.edtNome.Text = empresa.Nome;

                if (!string.IsNullOrEmpty(empresa.CNPJ))
                    this.edtCNPJ.Text = uninfeDummy.FmtCnpjCpf(this.edtCNPJ.Text, true);

                comboBox_tpEmis.SelectedValue = this.empresa.tpEmis;
                comboBox_Ambiente.SelectedValue = this.empresa.AmbienteCodigo;
                comboBox_UF.SelectedValue = this.empresa.UnidadeFederativaCodigo;
                cbServico.SelectedValue = (int)this.empresa.Servico;

                if (empresa.Servico == TipoAplicativo.Nfse && this.empresa.UnidadeFederativaCodigo == 0)
                    comboBox_UF.SelectedIndex = 0;

                checkBoxRetornoNFETxt.Checked = this.empresa.GravarRetornoTXTNFe;
                checkBoxGravarEventosDeTerceiros.Checked = this.empresa.GravarEventosDeTerceiros;
                checkBoxGravarEventosNaPastaEnviadosNFe.Checked = this.empresa.GravarEventosNaPastaEnviadosNFe;
                checkBoxGravarEventosCancelamentoNaPastaEnviadosNFe.Checked = this.empresa.GravarEventosCancelamentoNaPastaEnviadosNFe;
                checkBoxCompactaNFe.Checked = this.empresa.CompactarNfe;
                cbIndSinc.Checked = this.empresa.IndSinc;
                edtIdentificadorCSC.Text = this.empresa.IndentificadorCSC;
                edtTokenCSC.Text = this.empresa.TokenCSC;

                cboDiretorioSalvarComo.Text = this.empresa.DiretorioSalvarComo;
                udDiasLimpeza.Text = this.empresa.DiasLimpeza.ToString();
                udTempoConsulta.Text = this.empresa.TempoConsulta.ToString();

                this.txtSenhaWS.Text = this.empresa.SenhaWS;
                this.txtUsuarioWS.Text = this.empresa.UsuarioWS;

                HabilitaUsuarioSenhaWS(this.empresa.UnidadeFederativaCodigo);
                servicoCurrent = this.empresa.Servico;

                HabilitaOpcaoCompactar(this.empresa.Servico == TipoAplicativo.Nfe);

                this.edtCNPJ.ReadOnly = !string.IsNullOrEmpty(empresa.CNPJ);
                this.cbServico.Enabled = !this.edtCNPJ.ReadOnly;

                if (this.empresa.Servico != TipoAplicativo.Nfse && !novaempresa)
                    this.cbServico.Enabled = true;
            }
            finally
            {
                this.loading = false;
                cbServico_SelectedIndexChanged(null, null);
                comboBox_UF_SelectedIndexChanged(null, null);
            }
        }