Пример #1
0
        private void LerRetornoEvento(int emp)
        {
            //<<<UTF8 -> tem acentuacao no retorno
            TextReader  txt = new StreamReader(NomeArquivoXML, Encoding.Default);
            XmlDocument docEventoOriginal = new XmlDocument();

            docEventoOriginal.Load(Functions.StringXmlToStreamUTF8(txt.ReadToEnd()));
            txt.Close();

            /*
             * vStrXmlRetorno = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
             *  "<retEventoCTe xmlns=\"http://www.portalfiscal.inf.br/cte\" versao=\"2.00\">" +
             *  "  <infEvento Id=\"ID342130000096132\">" +
             *  "    <tpAmb>2</tpAmb>" +
             *  "    <verAplic>RS20130820221405</verAplic>" +
             *  "    <cOrgao>42</cOrgao>" +
             *  "    <cStat>136</cStat>" +
             *  "    <xMotivo>Evento registrado e vinculado a CT-e</xMotivo>" +
             *  "    <chCTe>41120178408960000182570010000000044000000047</chCTe>" +
             *  "    <tpEvento>110140</tpEvento>" +
             *  "    <xEvento>Cancelamento</xEvento>" +
             *  "    <nSeqEvento>1</nSeqEvento>" +
             *  "    <dhRegEvento>2013-11-13T15:27:12</dhRegEvento>" +
             *  "    <nProt>342130000096132</nProt>" +
             *  "</infEvento>" +
             *  "</retEventoCTe>";
             */

            MemoryStream msXml = Functions.StringXmlToStreamUTF8(vStrXmlRetorno);
            XmlDocument  doc   = new XmlDocument();

            doc.Load(msXml);

            XmlNodeList retEnvRetornoList = doc.GetElementsByTagName("retEventoCTe");

            foreach (XmlNode retConsSitNode in retEnvRetornoList)
            {
                XmlElement retConsSitElemento = (XmlElement)retConsSitNode;

                XmlNodeList envEventosList = doc.GetElementsByTagName("infEvento");
                for (int i = 0; i < envEventosList.Count; ++i)
                {
                    XmlElement eleRetorno = retEnvRetornoList.Item(i) as XmlElement;

                    string cStatCons = eleRetorno.GetElementsByTagName(TpcnResources.cStat.ToString())[0].InnerText;

                    if (cStatCons == "134" || cStatCons == "135" || cStatCons == "136")
                    {
                        string chCTe      = eleRetorno.GetElementsByTagName(TpcnResources.chCTe.ToString())[0].InnerText;
                        Int32  nSeqEvento = Convert.ToInt32("0" + eleRetorno.GetElementsByTagName(TpcnResources.nSeqEvento.ToString())[0].InnerText);
                        string tpEvento   = eleRetorno.GetElementsByTagName(TpcnResources.tpEvento.ToString())[0].InnerText;
                        string Id         = NFe.Components.TpcnResources.ID.ToString() + tpEvento + chCTe + nSeqEvento.ToString("00");
                        ///
                        ///procura no Xml de envio pelo Id retornado
                        ///nao sei se a Sefaz retorna na ordem em que foi enviado, então é melhor pesquisar
                        foreach (XmlNode env in docEventoOriginal.GetElementsByTagName("infEvento"))
                        {
                            string Idd = env.Attributes.GetNamedItem(TpcnResources.Id.ToString()).Value;
                            if (Idd == Id)
                            {
                                DateTime dhRegEvento = Functions.GetDateTime(eleRetorno.GetElementsByTagName(TpcnResources.dhRegEvento.ToString())[0].InnerText);

                                //Gerar o arquivo XML de distribuição do evento, retornando o nome completo do arquivo gravado
                                oGerarXML.XmlDistEventoCTe(emp, chCTe, nSeqEvento, Convert.ToInt32(tpEvento), env.ParentNode.OuterXml, eleRetorno.OuterXml, dhRegEvento, true);

                                switch ((NFe.ConvertTxt.tpEventos)Convert.ToInt32(tpEvento))
                                {
                                case ConvertTxt.tpEventos.tpEvCancelamentoNFe:
                                case ConvertTxt.tpEventos.tpEvCCe:
                                case ConvertTxt.tpEventos.tpEvEPEC:
                                    try
                                    {
                                        NFe.Service.TFunctions.ExecutaUniDanfe(oGerarXML.NomeArqGerado, DateTime.Today, Empresas.Configuracoes[emp]);
                                    }
                                    catch (Exception ex)
                                    {
                                        Auxiliar.WriteLog("TaskCTeEventos: " + ex.Message, false);
                                    }
                                    break;
                                }

                                break;
                            }
                        }
                    }
                }
            }
        }
Пример #2
0
        static void Main(string[] args)
        {
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler((sender, e) =>
            {
                Auxiliar.WriteLog(e.Exception.Message + "\r\n" + e.Exception.StackTrace, false);
                if (e.Exception.InnerException != null)
                {
                    Auxiliar.WriteLog(e.Exception.InnerException.Message + "\r\n" + e.Exception.InnerException.StackTrace, false);

                    if (e.Exception.InnerException.InnerException != null)
                    {
                        Auxiliar.WriteLog(e.Exception.InnerException.InnerException.Message + "\r\n" + e.Exception.InnerException.InnerException.StackTrace, false);
                    }

                    if (e.Exception.InnerException.InnerException.InnerException != null)
                    {
                        Auxiliar.WriteLog(e.Exception.InnerException.InnerException.InnerException.Message + "\r\n" + e.Exception.InnerException.InnerException.InnerException.StackTrace, false);
                    }
                }
            });

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler((sender, e) =>
            {
                Auxiliar.WriteLog(e.ExceptionObject.ToString(), false);
            });

            //Esta deve ser a primeira linha do Main, não coloque nada antes dela. Wandrey 31/07/2009
            Propriedade.AssemblyEXE = Assembly.GetExecutingAssembly();

            bool silencioso = false;

            ConfiguracaoApp.AtualizaWSDL = false;

            //Começar a contar o tempo de execução do aplicativo - Renan 24/06/2015
            ConfiguracaoApp.ExecutionTime = new System.Diagnostics.Stopwatch();
            ConfiguracaoApp.ExecutionTime.Start();

            if (args.Length >= 1)
            {
                foreach (string param in args)
                {
                    if (param.ToLower().Equals("/silent"))
                    {
                        silencioso = true;
                        continue;
                    }
                    if (param.ToLower().Equals("/updatewsdl"))
                    {
                        ConfiguracaoApp.AtualizaWSDL = true;
                        continue;
                    }
                    if (param.ToLower().Equals("/quit") || param.ToLower().Equals("/restart"))
                    {
                        string procName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
                        int    Id       = System.Diagnostics.Process.GetCurrentProcess().Id;

                        foreach (System.Diagnostics.Process clsProcess in System.Diagnostics.Process.GetProcesses())
                        {
                            if (clsProcess.ProcessName.Equals(procName))
                            {
                                try
                                {
                                    if (param.ToLower().Equals("/quit") ||
                                        (param.ToLower().Equals("/restart") && clsProcess.Id != Id))
                                    {
                                        Empresas.ClearLockFiles(false);
                                        clsProcess.Kill();
                                    }
                                }
                                catch
                                {
                                }
                                if (param.ToLower().Equals("/quit"))
                                {
                                    return;
                                }
                            }
                        }
                    }
                }
            }

            Propriedade.TipoAplicativo = TipoAplicativo.Todos;

#if DEBUG
            NFe.Components.NativeMethods.AllocConsole();
            Console.WriteLine("start....." + Propriedade.NomeAplicacao);
#endif

            bool executando = Aplicacao.AppExecutando();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            if (executando)
            {
                if (!silencioso)
                {
                    MetroFramework.MetroMessageBox.Show(null,
                                                        "Somente uma instância do " + Propriedade.NomeAplicacao + " pode ser executada." + (Empresas.ExisteErroDiretorio ? "\r\nPossíveis erros:\r\n" + Empresas.ErroCaminhoDiretorio : ""), "",
                                                        MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                if (!silencioso)
                {
                    if (Empresas.ExisteErroDiretorio)
                    {
                        MetroFramework.MetroMessageBox.Show(null,
                                                            "Ocorreu um erro ao efetuar a leitura das configurações da empresa. " +
                                                            "Por favor entre na tela de configurações da(s) empresa(s) listada(s), acesse a aba \"Pastas\" e reconfigure-as.\r\n\r\n" + Empresas.ErroCaminhoDiretorio, "",
                                                            MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }

                Application.Run(new NFe.UI.Form_Main());
            }
#if DEBUG
            NFe.Components.NativeMethods.FreeConsole();
#endif
        }
Пример #3
0
        /// <summary>
        /// Efetua a leitura do XML de retorno do processamento do lote de notas fiscais e
        /// atualiza o arquivo de fluxo e envio de notas
        /// </summary>
        /// <by>Wandrey Mundin Ferreira</by>
        /// <date>20/04/2009</date>
        private void LerRetornoLoteMDFe(int emp)
        {
            var oLerXml  = new LerXML();
            var fluxoNFe = new FluxoNfe();

            var doc = new XmlDocument();

            doc.Load(Functions.StringXmlToStreamUTF8(vStrXmlRetorno));

            var retConsReciNFeList = doc.GetElementsByTagName("retConsReciMDFe");

            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)

                    #region Validação do certificado de transmissão

                case "280":
                case "281":
                case "282":
                case "283":
                case "284":
                case "285":
                case "286":

                    #endregion Validação do certificado de transmissão

                    #region Validação inicial da mensagem no webservice

                case "214":
                case "243":
                case "108":
                case "109":

                    #endregion Validação inicial da mensagem no webservice

                    #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 Validação das informações de controle da chamada ao webservice

                    #region Validação da forma da área de dados

                case "215":
                case "598":
                case "599":
                case "404":
                case "402":

                    #endregion Validação da forma da área de dados

                    #region Validação das regras de negócio da consulta recibo

                case "252":
                case "226":
                case "247":
                case "494":
                case "227":
                case "253":

                    #endregion Validação das regras de negócio da consulta recibo

                    break;

                    #region Lote não foi localizado pelo recibo que está sendo consultado

                case "106":     //E-Verifica se o lote não está na fila de saída, nem na fila de entrada (Lote não encontrado)
                    //No caso do lote não encontrado através do recibo, o ERP vai ter que consultar a situação da NFe para encerrar ela
                    //Vou somente excluir ela do fluxo para não ficar consultando o recibo que não existe
                    if (nRec != string.Empty)
                    {
                        fluxoNFe.ExcluirNfeFluxoRec(nRec.Trim());
                    }
                    break;

                    #endregion Lote não foi localizado pelo recibo que está sendo consultado

                    #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 foi processado, agora tenho que tratar as notas fiscais dele

                case "104":     //Lote processado
                    var protNFeList = retConsReciNFeElemento.GetElementsByTagName("protMDFe");

                    foreach (XmlNode protNFeNode in protNFeList)
                    {
                        var protNFeElemento = (XmlElement)protNFeNode;

                        var strProtNfe = protNFeElemento.OuterXml;

                        var infProtList = protNFeElemento.GetElementsByTagName("infProt");

                        foreach (XmlNode infProtNode in infProtList)
                        {
                            bool tirarFluxo      = true;
                            var  infProtElemento = (XmlElement)infProtNode;

                            var strChaveNFe = string.Empty;
                            var strStat     = string.Empty;

                            if (infProtElemento.GetElementsByTagName(TpcnResources.chMDFe.ToString())[0] != null)
                            {
                                strChaveNFe = "MDFe" + infProtElemento.GetElementsByTagName(TpcnResources.chMDFe.ToString())[0].InnerText;
                            }

                            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 strNomeArqNfe = fluxoNFe.LerTag(strChaveNFe, FluxoNfe.ElementoFixo.ArqNFe);

                            // se por algum motivo o XML não existir no "Fluxo", então o arquivo tem que existir
                            // na pasta "EmProcessamento" assinada.
                            if (string.IsNullOrEmpty(strNomeArqNfe))
                            {
                                if (string.IsNullOrEmpty(strChaveNFe))
                                {
                                    throw new Exception("LerRetornoLoteMDFe(): Não pode obter o nome do arquivo");
                                }

                                strNomeArqNfe = strChaveNFe.Substring(4) + Propriedade.Extensao(Propriedade.TipoEnvio.MDFe).EnvioXML;
                            }
                            var strArquivoNFe = Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" + PastaEnviados.EmProcessamento.ToString() + "\\" + strNomeArqNfe;

                            //Atualizar a Tag de status da NFe no fluxo para que se ocorrer alguma falha na exclusão eu tenha esta campo para ter uma referencia em futuras consultas
                            fluxoNFe.AtualizarTag(strChaveNFe, FluxoNfe.ElementoEditavel.cStat, strStat);

                            //Atualizar a tag da data e hora da ultima consulta do recibo
                            fluxoNFe.AtualizarDPedRec(nRec, DateTime.Now);

                            switch (strStat)
                            {
                            case "100":         //MDFe Autorizado
                                if (File.Exists(strArquivoNFe))
                                {
                                    //Juntar o protocolo com a NFE já copiando para a pasta de autorizadas
                                    var strArquivoNFeProc = Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" +
                                                            PastaEnviados.EmProcessamento.ToString() + "\\" +
                                                            Functions.ExtrairNomeArq(strNomeArqNfe, Propriedade.Extensao(Propriedade.TipoEnvio.MDFe).EnvioXML) + Propriedade.ExtRetorno.ProcMDFe;

                                    //Ler o XML para pegar a data de emissão para criar a pasta dos XML´s autorizados
                                    XmlDocument conteudoXMLMDFe = new XmlDocument();
                                    conteudoXMLMDFe.Load(strArquivoNFe);
                                    oLerXml.Mdfe(conteudoXMLMDFe);

                                    //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, oLerXml.oDadosNfe.versao);
                                        }
                                    }

                                    if (!(procNFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoNFe, oLerXml.oDadosNfe.dEmi, Propriedade.Extensao(Propriedade.TipoEnvio.MDFe).EnvioXML, Propriedade.ExtRetorno.ProcMDFe)))
                                    {
                                        //Mover a nfePRoc da pasta de NFE em processamento para a NFe Autorizada
                                        //Para envitar falhar, tenho que mover primeiro o XML de distribuição (-procnfe.xml) para
                                        //depois mover o da nfe (-nfe.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);

                                        //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);
                                    }

                                    if (!NFeJaNaAutorizada && procNFeJaNaAutorizada)
                                    {
                                        //Mover a NFE da pasta de NFE em processamento para NFe Autorizada
                                        //Para envitar falhar, tenho que mover primeiro o XML de distribuição (-procnfe.xml) para
                                        //depois mover o da nfe (-nfe.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(strArquivoNFe, PastaEnviados.Autorizados, oLerXml.oDadosNfe.dEmi);
                                    }

                                    //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("TaskMDFeRetRecepcao: " + ex.Message, false);
                                        }
                                    }
                                    //Vou verificar se estão os dois arquivos na pasta Autorizados, se tiver eu tiro do fluxo caso contrário não. Wandrey 13/02/2012
                                    NFeJaNaAutorizada     = oAux.EstaAutorizada(strArquivoNFe, oLerXml.oDadosNfe.dEmi, Propriedade.Extensao(Propriedade.TipoEnvio.MDFe).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.MDFe).EnvioXML);
                                    procNFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoNFe, oLerXml.oDadosNfe.dEmi, Propriedade.Extensao(Propriedade.TipoEnvio.MDFe).EnvioXML, Propriedade.ExtRetorno.ProcMDFe);
                                    if (!procNFeJaNaAutorizada || !NFeJaNaAutorizada)
                                    {
                                        tirarFluxo = false;
                                    }
                                }
                                break;

                            default:         //NFe foi rejeitada
                                //O Status da NFe tem que ser maior que 1 ou deu algum erro na hora de ler o XML de retorno da consulta do recibo, sendo assim, vou mantar a nota no fluxo para consultar novamente.
                                if (Convert.ToInt32(strStat) >= 1)
                                {
                                    //Mover o XML da NFE a pasta de XML´s com erro
                                    oAux.MoveArqErro(strArquivoNFe);
                                }
                                else
                                {
                                    tirarFluxo = false;
                                }
                                break;
                            }

                            //Deletar a NFE do arquivo de controle de fluxo
                            if (tirarFluxo)
                            {
                                fluxoNFe.ExcluirNfeFluxo(strChaveNFe);
                            }

                            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
                    if (Convert.ToInt32(cStatLote) >= 1)
                    {
                        //Vou retirar as notas do fluxo pelo recibo
                        if (nRec != string.Empty)
                        {
                            fluxoNFe.ExcluirNfeFluxoRec(nRec.Trim());
                        }
                    }

                    break;

                    #endregion Qualquer outro tipo de status que não for os acima relacionados, vai tirar a nota fiscal do fluxo.
                }
            }
        }
Пример #4
0
        /// <summary>
        /// Efetua a leitura do XML de retorno do processamento do lote de notas fiscais e
        /// atualiza o arquivo de fluxo e envio de notas
        /// </summary>
        /// <by>Wandrey Mundin Ferreira</by>
        /// <date>20/04/2009</date>
        private void LerRetornoLoteCTe()
        {
            int emp      = Empresas.FindEmpresaByThread();
            var oLerXml  = new LerXML();
            var msXml    = Functions.StringXmlToStream(vStrXmlRetorno);
            var fluxoNFe = new FluxoNfe();

            var doc = new System.Xml.XmlDocument();

            doc.Load(msXml);

            var retConsReciNFeList = doc.GetElementsByTagName("retConsReciCTe");

            foreach (System.Xml.XmlNode retConsReciNFeNode in retConsReciNFeList)
            {
                var retConsReciNFeElemento = (System.Xml.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

                    #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

                    #region Lote não foi localizado pelo recibo que está sendo consultado
                case "106":     //E-Verifica se o lote não está na fila de saída, nem na fila de entrada (Lote não encontrado)
                    //No caso do lote não encontrado através do recibo, o ERP vai ter que consultar a situação da NFe para encerrar ela
                    //Vou somente excluir ela do fluxo para não ficar consultando o recibo que não existe
                    if (nRec != string.Empty)
                    {
                        fluxoNFe.ExcluirNfeFluxoRec(nRec.Trim());
                    }
                    break;
                    #endregion

                    #region Lote foi processado, agora tenho que tratar as notas fiscais dele
                case "104":     //Lote processado
                    var protNFeList = retConsReciNFeElemento.GetElementsByTagName("protCTe");

                    foreach (System.Xml.XmlNode protNFeNode in protNFeList)
                    {
                        var protNFeElemento = (System.Xml.XmlElement)protNFeNode;

                        var strProtNfe = protNFeElemento.OuterXml;

                        var infProtList = protNFeElemento.GetElementsByTagName("infProt");

                        foreach (System.Xml.XmlNode infProtNode in infProtList)
                        {
                            var infProtElemento = (System.Xml.XmlElement)infProtNode;

                            var strChaveNFe = string.Empty;
                            var strStat     = string.Empty;

                            if (infProtElemento.GetElementsByTagName(TpcnResources.chCTe.ToString())[0] != null)
                            {
                                strChaveNFe = "CTe" + infProtElemento.GetElementsByTagName(TpcnResources.chCTe.ToString())[0].InnerText;
                            }

                            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 strNomeArqNfe = fluxoNFe.LerTag(strChaveNFe, FluxoNfe.ElementoFixo.ArqNFe);

                            // se por algum motivo o XML não existir no "Fluxo", então o arquivo tem que existir
                            // na pasta "EmProcessamento" assinada.
                            if (string.IsNullOrEmpty(strNomeArqNfe))
                            {
                                if (string.IsNullOrEmpty(strChaveNFe))
                                {
                                    throw new Exception("LerRetornoLoteCTe(): Não pode obter o nome do arquivo");
                                }

                                strNomeArqNfe = strChaveNFe.Substring(3) + Propriedade.Extensao(Propriedade.TipoEnvio.CTe).EnvioXML;
                            }
                            var strArquivoNFe = Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" + PastaEnviados.EmProcessamento.ToString() + "\\" + strNomeArqNfe;

                            //Atualizar a Tag de status da NFe no fluxo para que se ocorrer alguma falha na exclusão eu tenha esta campo para ter uma referencia em futuras consultas
                            fluxoNFe.AtualizarTag(strChaveNFe, FluxoNfe.ElementoEditavel.cStat, strStat);

                            //Atualizar a tag da data e hora da ultima consulta do recibo
                            fluxoNFe.AtualizarDPedRec(nRec, DateTime.Now);

                            switch (strStat)
                            {
                            case "100":         //NFe Autorizada
                                if (File.Exists(strArquivoNFe))
                                {
                                    //Juntar o protocolo com a NFE já copiando para a pasta em processamento
                                    var strArquivoNFeProc = oGerarXML.XmlDistCTe(strArquivoNFe, strProtNfe);

                                    //Ler o XML para pegar a data de emissão para criar a pasta dos XML´s autorizados
                                    oLerXml.Cte(strArquivoNFe);

                                    //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
                                    oLerXml.Cte(strArquivoNFe);

                                    //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("TaskCTeRetRecepcao: " + 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;
                            }

                            //Deletar a NFE do arquivo de controle de fluxo
                            fluxoNFe.ExcluirNfeFluxo(strChaveNFe);
                            break;
                        }
                    }
                    break;
                    #endregion

                    #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

                    //Vou retirar as notas do fluxo pelo recibo
                    if (nRec != string.Empty)
                    {
                        fluxoNFe.ExcluirNfeFluxoRec(nRec.Trim());
                    }

                    break;
                    #endregion
                }
            }
        }
Пример #5
0
        public async Task <IActionResult> IngresaUsuario(UsuarioViewModel usuarionNew)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Logout", "Account"));
            }

            //if (string.IsNullOrEmpty(HttpContext.Session.GetString("cod_rol")))
            //    return RedirectToAction("Logout", "Account");

            // if (usuarionNew == null)
            //   return RedirectToAction("Logout", "Account");

            int codigoRol       = Convert.ToInt32(HttpContext.Session.GetString("cod_rol"));
            int codigoProvincia = Convert.ToInt32(HttpContext.Session.GetString("cod_provincia"));

            auxiliar = new Auxiliar();

            switch (codigoRol)
            {
            case 1:
                var provincias = (from Provincia in auc.PROVINCIA
                                  where Provincia.COD_PROVINCIA == 0
                                  orderby Provincia.NOM_PROVINCIA
                                  select new SelectListItem()
                {
                    Text = Provincia.NOM_PROVINCIA,
                    Value = Provincia.COD_PROVINCIA.ToString()
                }).ToList();

                var roles = (from Rol in auc.ROL
                             where Rol.COD_ROL == 2
                             select new SelectListItem()
                {
                    Text = Rol.DES_ROL,
                    Value = Rol.COD_ROL.ToString(),
                    Selected = false
                }).ToList();

                usuarionNew.provincias = provincias;
                usuarionNew.roles      = roles;
                break;

            case 2:
                provincias = (from Provincia in auc.PROVINCIA
                              where Provincia.COD_PROVINCIA >= 0 && Provincia.COD_PROVINCIA < 26
                              orderby Provincia.NOM_PROVINCIA
                              select new SelectListItem()
                {
                    Text = Provincia.NOM_PROVINCIA,
                    Value = Provincia.COD_PROVINCIA.ToString()
                }).ToList();

                provincias.Insert(0, new SelectListItem()
                {
                    Text  = "----Elija Provincia----",
                    Value = string.Empty
                });

                roles = (from Rol in auc.ROL
                         where Rol.COD_ROL == 3 || Rol.COD_ROL == 5 || Rol.COD_ROL == 8
                         select new SelectListItem()
                {
                    Text = Rol.DES_ROL,
                    Value = Rol.COD_ROL.ToString(),
                    Selected = false
                }).ToList();

                roles.Insert(0, new SelectListItem()
                {
                    Text  = "----Elija Rol----",
                    Value = string.Empty
                });
                usuarionNew.provincias = provincias;
                usuarionNew.roles      = roles;

                break;

            case 3:
                provincias = (from Provincia in auc.PROVINCIA
                              where Provincia.COD_PROVINCIA == codigoProvincia
                              orderby Provincia.NOM_PROVINCIA
                              select new SelectListItem()
                {
                    Text = Provincia.NOM_PROVINCIA,
                    Value = Provincia.COD_PROVINCIA.ToString()
                }).ToList();

                roles = (from Rol in auc.ROL
                         where Rol.COD_ROL == 4
                         select new SelectListItem()
                {
                    Text = Rol.DES_ROL,
                    Value = Rol.COD_ROL.ToString(),
                    Selected = false
                }).ToList();

                usuarionNew.provincias = provincias;
                usuarionNew.roles      = roles;
                break;
            }

            if (!auxiliar.validarCedula(usuarionNew.CEDULAC))
            {
                ModelState.AddModelError(string.Empty, "La cédula ingresada es incorrecta.");
                return(View(usuarionNew));
            }


            Usuario validacionUsuario = servicioUsuario.GetUsuarioxCedulaMail(usuarionNew.CEDULAC.Substring(0, 9), usuarionNew.MAIL);

            // validacionUsuario = servicioUsuario.GetUsuario(usuarionNew.CEDULAC);


            if (validacionUsuario != null)
            {
                ModelState.AddModelError(string.Empty, "Ya existe un usuario con la cédula o correo ingresada.");
                return(View(usuarionNew));
            }

            UsuarioResponse usuario = new UsuarioResponse()
            {
                CEDULA           = usuarionNew.CEDULAC,
                CODIGO_PROVINCIA = usuarionNew.codProvincia,
                CLAVE            = usuarionNew.CLAVE,
                CODIGO_ROL       = usuarionNew.codRol,
                COD_USUARIO      = usuarionNew.COD_USUARIO,
                ESTADO           = true,
                LOGEO            = usuarionNew.LOGEO,
                MAIL             = usuarionNew.MAIL.ToLower(),
                NOMBRE           = usuarionNew.NOMBRE,
                TELEFONO         = usuarionNew.TELEFONO,
                PROVINCIA        = usuarionNew.PROVINCIA,
                ROL = usuarionNew.ROL
            };

            if (usuario.CODIGO_PROVINCIA == 0 && usuario.CODIGO_ROL == 3)
            {
                ModelState.AddModelError(string.Empty, "Debe seleccionar una provincia");
                return(View(usuarionNew));
            }
            if ((usuario.CODIGO_PROVINCIA > 0) && (usuario.CODIGO_ROL == 8 || usuario.CODIGO_ROL == 5))
            {
                ModelState.AddModelError(string.Empty, "El rol seleccionado es de carácter nacional, seleccione Ecuador");
                return(View(usuarionNew));
            }

            int respuesta = await servicioUsuario.IngresaUsuario(usuario);

            if (respuesta > 0)
            {
                var nombreUsuario = User.Claims.FirstOrDefault(x => x.Type == "Id").Value;
                _logger.LogInformation("Usuario:" + nombreUsuario + " Ingresa: " + usuario.CEDULA);
                ViewBag.Message = "Usuario ingresado exitosamente!";
                return(RedirectToAction(nameof(Index)));
            }
            else
            {
                if (usuario.CLAVE == "12345678" || usuario.CLAVE == "87654321")
                {
                    ModelState.AddModelError(string.Empty, "La clave no puede ser números consecutivos");
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Existió un error al ingresar el usuario.");
                }
                return(View(usuarionNew));
            }
        }
Пример #6
0
 protected static string GetCampo<T, O>(Expression<Func<T>> exp, O obj)
 {
     return Auxiliar.GetFieldName(exp, obj);
 }
Пример #7
0
        private void btnExcluir_Click(object sender, EventArgs e)
        {
            if (btnExcluir.Text.Equals("Excluir"))
            {
                if (MetroFramework.MetroMessageBox.Show(uninfeDummy.mainForm, "Deseja realmente excluir esta empresa?", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    try
                    {
                        var list     = (cbEmpresas.DataSource as System.Collections.ArrayList)[cbEmpresas.SelectedIndex] as ComboElem;
                        var _Empresa = Empresas.FindConfEmpresa(list.Valor, EnumHelper.StringToEnum <TipoAplicativo>(list.Servico));
                        if (_Empresa != null)
                        {
                            Empresas.Configuracoes.Remove(_Empresa);
                            new ConfiguracaoApp().GravarArqEmpresas();
                            CreateControles();

                            Auxiliar.WriteLog("Empresa '" + _Empresa.CNPJ + "' - Serviço: '" + _Empresa.Servico.ToString() + "' excluída", false);

                            /*
                             *                          if (MetroFramework.MetroMessageBox.Show(uninfeDummy.mainForm, "Deseja excluir as pastas desta empresa?\r\n\r\nExcluindo-as, serão eliminadas todos os XML's autorizados/denegados/eventos", "", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                             *                          {
                             *                              ///
                             *                              /// exclui as pastas criadas
                             *                              ///
                             *                              try
                             *                              {
                             *                                  _Empresa.ExcluiPastas();
                             *                              }
                             *                              catch { }
                             *                          }
                             */
                        }
                        else
                        {
                            MetroFramework.MetroMessageBox.Show(uninfeDummy.mainForm, "Não foi possível acessar a empresa para excluí-la");
                        }
                    }
                    catch (Exception ex)
                    {
                        MetroFramework.MetroMessageBox.Show(uninfeDummy.mainForm, ex.Message, "");
                    }
                }
            }
            else
            {
                ///
                /// compara o que foi mudado
                ///
                try
                {
                    bool pergunta = DadosMudaramDaEmpresa(false);

                    if (EmpresaValidada)
                    {
                        if (pergunta)
                        {
                            pergunta = !(MetroFramework.MetroMessageBox.Show(uninfeDummy.mainForm,
                                                                             constAbandono, "",
                                                                             MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes);
                        }
                        if (!pergunta)
                        {
                            Modificado = false;
                            empcnpj    = "";

                            if (Empresas.Configuracoes.Count > 0)
                            {
                                cbEmpresas_SelectedIndexChanged(sender, e);
                            }
                            else
                            {
                                ///
                                /// as propriedades gerais mudou?
                                if (uc_geral.Modificado)
                                {
                                    new ConfiguracaoApp().GravarConfigGeral();
                                    uc_geral.PopulateConfGeral();
                                }
                                ///
                                /// como nao tem nenhuma empresa, fecha este processo voltando ao menu principal
                                BackFuncao();
                            }
                            cbEmpresas.Visible = metroLabel2.Visible = true;
                            btnExcluir.Visible = cbEmpresas.Items.Count > 0;
                        }
                    }
                }
                catch (Exception ex)
                {
                    MetroFramework.MetroMessageBox.Show(uninfeDummy.mainForm, ex.Message, "");
                }
            }
        }
Пример #8
0
        /// <summary>
        /// Evento que executa thread´s para processar os arquivos que são colocados nas pastas que estão sendo monitoradas pela FileSystemWatcher
        /// </summary>
        /// <param name="fi">Arquivo detectado pela FileSystemWatcher</param>
        private void fsw_OnFileChanged(FileInfo fi)
        {
            try
            {
                int    empresa;
                string arq = fi.FullName.ToLower();

                if (fi.Directory.FullName.ToLower().EndsWith("geral\\temp"))
                {
                    ///
                    /// encerra o UniNFe no arquivo -sair.xml
                    ///
                    var sext = Components.Propriedade.Extensao(Components.Propriedade.TipoEnvio.sair_XML);
                    if (arq.EndsWith(sext.EnvioTXT) || arq.EndsWith(sext.EnvioXML))
                    {
                        File.Delete(fi.FullName);
                        Empresas.ClearLockFiles(false);
                        if (!Components.Propriedade.ExecutandoPeloUniNFe)
                        {
                            if (Components.ServiceProcess.StatusService(Components.Propriedade.ServiceName) == System.ServiceProcess.ServiceControllerStatus.Running)
                            {
                                Components.ServiceProcess.StopService(Components.Propriedade.ServiceName, 40000);
                            }
                        }
                        else
                        {
                            ThreadService.Stop();
                        }
                        Environment.Exit(0);
                        return;
                    }

                    string    ExtRetorno   = null;
                    string    finalArqErro = null;
                    Exception exx          = null;

                    ///
                    /// Atualiza WSDL / Schemas
                    ///
                    var ext = Components.Propriedade.Extensao(Components.Propriedade.TipoEnvio.pedUpdatewsdl);
                    if (arq.EndsWith(ext.EnvioTXT) || arq.EndsWith(ext.EnvioXML))
                    {
                        #region ---Atualiza WSDL e Schemas

                        File.Delete(fi.FullName);

                        Components.Functions.DeletarArquivo(Components.Propriedade.XMLVersaoWSDLXSD);

                        string cerros = "";
                        try
                        {
                            ConfiguracaoApp.ForceUpdateWSDL(false, ref cerros);

                            if (!string.IsNullOrEmpty(cerros))
                            {
                                throw new Exception(cerros);
                            }

                            string       ExtRet     = (arq.EndsWith(".xml") ? ext.RetornoXML : ext.RetornoTXT);
                            string       arqRetorno = Components.Propriedade.PastaGeralRetorno + "\\" + Components.Functions.ExtrairNomeArq(fi.FullName, null) + ExtRet;
                            const string rst        = "Schemas atualizados com sucesso!!!";

                            if (arq.EndsWith(".xml"))
                            {
                                var xml = new XDocument(new XDeclaration("1.0", "utf-8", null),
                                                        new XElement("UPDT",
                                                                     new XElement("Result", rst)));
                                xml.Save(arqRetorno);
                            }
                            else
                            {
                                File.WriteAllText(arqRetorno, rst);
                            }
                            return;
                        }
                        catch (Exception ex)
                        {
                            ExtRetorno   = (arq.EndsWith(".xml") ? ext.EnvioXML : ext.EnvioTXT);
                            finalArqErro = ext.EnvioXML.Replace(".xml", ".err");
                            exx          = ex;
                        }

                        #endregion ---Atualiza WSDL e Schemas
                    }

                    ///
                    /// restart o UniNFe
                    ///
                    var uext = Components.Propriedade.Extensao(Components.Propriedade.TipoEnvio.pedRestart);
                    if (arq.EndsWith(uext.EnvioTXT) || arq.EndsWith(uext.EnvioXML))
                    {
                        #region ---Reinicia o UniNFe

                        File.Delete(fi.FullName);
                        try
                        {
                            if (Propriedade.ServicoRodando)
                            {
                                RestartService();
                            }
                            else
                            {
                                System.Diagnostics.Process.Start(Components.Propriedade.PastaExecutavel + "\\uninfe.exe", "/restart");
                            }

                            return;
                        }
                        catch (Exception ex)
                        {
                            ExtRetorno   = (arq.EndsWith(".xml") ? uext.EnvioXML : uext.EnvioTXT);
                            finalArqErro = uext.EnvioXML.Replace(".xml", ".err");
                            exx          = ex;
                        }

                        #endregion ---Reinicia o UniNFe
                    }

                    if (ExtRetorno != null)
                    {
                        try
                        {
                            Service.TFunctions.GravarArqErroServico(fi.FullName, ExtRetorno, finalArqErro, exx);
                        }
                        catch { }
                        return;
                    }

                    ///
                    /// solicitacao de layouts
                    ///
                    var lext = Components.Propriedade.Extensao(Components.Propriedade.TipoEnvio.pedLayouts);
                    if (arq.EndsWith(lext.EnvioTXT) || arq.EndsWith(lext.EnvioXML))
                    {
                        Service.TaskLayouts l = new Service.TaskLayouts();
                        l.NomeArquivoXML = fi.FullName;
                        l.Execute();
                        return;
                    }
                    empresa = 0; //Vou criar fixo como 0 quando for na pasta geral, pois na pasta geral não tem como detectar qual é a empresa. Wandrey 20/03/2013
                }
                else
                {
                    empresa = LocalizaEmpresa(fi);
                }

                if (empresa >= 0)
                {
                    /*<#8084>
                     * Aqui foi modificado porque a ThreadControl deixou de existir.
                     * E todo o processamento que antes existia na thread control foi deixado apenas no método Run(), que é chamado abaixo
                     *
                     * Marcelo
                     */
                    new ThreadItem(fi, empresa).Run();
                    //</#8084>
                }
                else
                {
                    Auxiliar.WriteLog(fi.FullName + " - Não localizou a empresa.", true);
                }
            }
            catch (Exception ex)
            {
                if (fi.Directory.Name.ToLower().EndsWith("geral\\temp"))
                {
                    Components.Functions.WriteLog(ex.Message + "\r\n" + ex.StackTrace, false, true, "");
                }
                else
                {
                    Auxiliar.WriteLog(ex.Message + "\r\n" + ex.StackTrace, false);
                }
            }
        }
Пример #9
0
        /// <summary>
        /// Popular campos das configurações por empresa
        /// </summary>
        /// <remarks>
        /// Autor: Wandrey Mundin Ferreira
        /// Data: 29/07/2010
        /// </remarks>
        private void PopulateConfEmpresa()
        {
            #region Definir um texto explicativo sobre a impressão do DANFE. Wandrey 02/02/2010
            tbTextoDANFE.Text = "Você pode automatizar o processo de geração/impressão do DANFE através do UniDANFe ou do DANFeMon, bastando preencher os campos abaixo." +
                                "\r\n\r\n" +
                                "As configurações adicionais devem ser definidas no UniDANFe ou no arquivo XML auxiliar. Para maiores detalhes, consulte a documentação do UniDANFe.";
            #endregion

            #region Montar Array DropList da UF
            ArrayList arrUF = new ArrayList();

            try
            {
                arrUF = Auxiliar.CarregaUF();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            comboBox_UF.DataSource    = arrUF;
            comboBox_UF.DisplayMember = "Nome";
            comboBox_UF.ValueMember   = "Codigo";
            #endregion

            #region Montar Array DropList do Ambiente
            //
            // danasa 8-2009
            // atribuido "TipoEmbiente"
            //
            ArrayList arrAmb = new ArrayList();
            arrAmb.Add(new ComboElem("Produção", TipoAmbiente.taProducao));
            arrAmb.Add(new ComboElem("Homologação", TipoAmbiente.taHomologacao));

            comboBox_Ambiente.DataSource    = arrAmb;
            comboBox_Ambiente.DisplayMember = "valor";
            comboBox_Ambiente.ValueMember   = "codigo";
            #endregion

            #region Montar Array DropList do Tipo de Emissão da NF-e
            ArrayList arrTpEmis = new ArrayList();
            ArrayList.Synchronized(arrTpEmis);
            //
            // danasa 8-2009
            // danasa 9-2009
            // atribuido "TipoEmissao.
            //
            arrTpEmis.Add(new ComboElem(UniNFeConsts.tpEmissao[TipoEmissao.teNormal], TipoEmissao.teNormal));
            arrTpEmis.Add(new ComboElem(UniNFeConsts.tpEmissao[TipoEmissao.teContingencia], TipoEmissao.teContingencia));
            arrTpEmis.Add(new ComboElem(UniNFeConsts.tpEmissao[TipoEmissao.teSCAN], TipoEmissao.teSCAN));
            arrTpEmis.Add(new ComboElem(UniNFeConsts.tpEmissao[TipoEmissao.teDPEC], TipoEmissao.teDPEC));
            arrTpEmis.Add(new ComboElem(UniNFeConsts.tpEmissao[TipoEmissao.teFSDA], TipoEmissao.teFSDA));

            comboBox_tpEmis.DataSource    = arrTpEmis;
            comboBox_tpEmis.DisplayMember = "Valor";
            comboBox_tpEmis.ValueMember   = "Codigo";
            #endregion

            #region Carregar as configurações da empresa selecionada
            if (Empresa.Configuracoes.Count > 0)
            {
                Empresa oEmpresa = Empresa.FindConfEmpresa(cbEmpresa.SelectedValue.ToString().Trim());

                ///
                /// danasa 20-9-2010
                /// tirado daqui pois se entrado + de 1 vez na configuracao da empresa, a propriedade CriaPastasAutomaticamente será definida como false
                /// já que na segunda vez os nomes das pastas já estão atribuidas
                //oEmpresa.CriaPastasAutomaticamente = false;

                if (string.IsNullOrEmpty(oEmpresa.PastaEnvio))
                {
                    ///
                    /// tenta achar uma configuracao valida
                    ///
                    foreach (Empresa empresa in Empresa.Configuracoes)
                    {
                        if (empresa.CNPJ.Trim() != oEmpresa.CNPJ.Trim() && !string.IsNullOrEmpty(empresa.PastaEnvio))
                        {
                            oEmpresa.PastaEnvio       = CopiaPastaDeEmpresa(empresa.CNPJ, empresa.PastaEnvio, oEmpresa);
                            oEmpresa.PastaRetorno     = CopiaPastaDeEmpresa(empresa.CNPJ, empresa.PastaRetorno, oEmpresa);
                            oEmpresa.PastaEnviado     = CopiaPastaDeEmpresa(empresa.CNPJ, empresa.PastaEnviado, oEmpresa);
                            oEmpresa.PastaErro        = CopiaPastaDeEmpresa(empresa.CNPJ, empresa.PastaErro, oEmpresa);
                            oEmpresa.PastaEnvioEmLote = CopiaPastaDeEmpresa(empresa.CNPJ, empresa.PastaEnvioEmLote, oEmpresa);
                            oEmpresa.PastaValidar     = CopiaPastaDeEmpresa(empresa.CNPJ, empresa.PastaValidar, oEmpresa);
                            oEmpresa.PastaBackup      = CopiaPastaDeEmpresa(empresa.CNPJ, empresa.PastaBackup, oEmpresa);

                            oEmpresa.PastaConfigUniDanfe = empresa.PastaConfigUniDanfe;
                            oEmpresa.PastaExeUniDanfe    = empresa.PastaExeUniDanfe;
                            oEmpresa.PastaDanfeMon       = empresa.PastaDanfeMon;
                            oEmpresa.XMLDanfeMonNFe      = empresa.XMLDanfeMonNFe;
                            oEmpresa.XMLDanfeMonProcNFe  = empresa.XMLDanfeMonProcNFe;
                            oEmpresa.GravarRetornoTXTNFe = empresa.GravarRetornoTXTNFe;

                            oEmpresa.CriaPastasAutomaticamente = true;
                            break;
                        }
                    }
                    ///
                    /// se ainda assim nao foi encontrada nenhuma configuracao válida assume a pasta de instalacao do uninfe
                    ///
                    if (string.IsNullOrEmpty(oEmpresa.PastaEnvio))
                    {
                        oEmpresa.PastaEnvio       = Path.Combine(InfoApp.PastaExecutavel(), oEmpresa.CNPJ + "\\Envio");
                        oEmpresa.PastaEnviado     = Path.Combine(InfoApp.PastaExecutavel(), oEmpresa.CNPJ + "\\Enviado");
                        oEmpresa.PastaRetorno     = Path.Combine(InfoApp.PastaExecutavel(), oEmpresa.CNPJ + "\\Retorno");
                        oEmpresa.PastaErro        = Path.Combine(InfoApp.PastaExecutavel(), oEmpresa.CNPJ + "\\Erro");
                        oEmpresa.PastaEnvioEmLote = Path.Combine(InfoApp.PastaExecutavel(), oEmpresa.CNPJ + "\\EnvioEmLote");
                        oEmpresa.PastaValidar     = Path.Combine(InfoApp.PastaExecutavel(), oEmpresa.CNPJ + "\\Validar");

                        oEmpresa.CriaPastasAutomaticamente = true;
                    }
                }

                textBox_PastaEnvioXML.Text   = oEmpresa.PastaEnvio;
                textBox_PastaRetornoXML.Text = oEmpresa.PastaRetorno;
                textBox_PastaEnviados.Text   = oEmpresa.PastaEnviado;
                textBox_PastaXmlErro.Text    = oEmpresa.PastaErro;
                tbPastaLote.Text             = oEmpresa.PastaEnvioEmLote;
                tbPastaValidar.Text          = oEmpresa.PastaValidar;

                textBox_PastaBackup.Text      = (oEmpresa.PastaBackup == string.Empty ? string.Empty : oEmpresa.PastaBackup);
                tbPastaConfigUniDanfe.Text    = (oEmpresa.PastaConfigUniDanfe == string.Empty ? string.Empty : oEmpresa.PastaConfigUniDanfe);
                tbPastaExeUniDanfe.Text       = (oEmpresa.PastaExeUniDanfe == string.Empty ? string.Empty : oEmpresa.PastaExeUniDanfe);
                tbPastaXmlParaDanfeMon.Text   = (oEmpresa.PastaDanfeMon == string.Empty ? string.Empty : oEmpresa.PastaDanfeMon);
                cbDanfeMonNfe.Checked         = oEmpresa.XMLDanfeMonNFe;
                cbDanfeMonProcNfe.Checked     = oEmpresa.XMLDanfeMonProcNFe;
                checkBoxRetornoNFETxt.Checked = oEmpresa.GravarRetornoTXTNFe;

                oMeuCert = oEmpresa.X509Certificado;
                DemonstraDadosCertificado();

                cboDiretorioSalvarComo.Text = oEmpresa.DiretorioSalvarComo;
                udDiasLimpeza.Value         = oEmpresa.DiasLimpeza;

                //Carregar o conteúdo do droplist do tipo de emissão para forçar demonstrar
                //o conteúdo já informado pelo usuário. Wandrey 30/10/2008
                for (int i = 0; i < arrTpEmis.Count; i++)
                {
                    if (((ComboElem)(new System.Collections.ArrayList(arrTpEmis))[i]).Codigo == oEmpresa.tpEmis)
                    {
                        this.comboBox_tpEmis.Text = ((ComboElem)(new System.Collections.ArrayList(arrTpEmis))[i]).Valor;
                        break;
                    }
                }

                //Carregar o conteúdo do droplist da Unidade Federativa (UF) para forçar demonstrar
                //o conteúdo já informado pelo usuário. Wandrey 30/10/2008
                for (int i = 0; i < arrUF.Count; i++)
                {
                    if (((ComboElem)(new System.Collections.ArrayList(arrUF))[i]).Codigo == oEmpresa.UFCod)
                    {
                        this.comboBox_UF.Text = ((ComboElem)(new System.Collections.ArrayList(arrUF))[i]).Nome;
                        break;
                    }
                }

                //Carregar o conteúdo do droplist do Ambiente para forçar demonstrar
                //o conteúdo já informado pelo usuário. Wandrey 30/10/2008
                for (int i = 0; i < arrAmb.Count; i++)
                {
                    if (((ComboElem)(new System.Collections.ArrayList(arrAmb))[i]).Codigo == oEmpresa.tpAmb)
                    {
                        this.comboBox_Ambiente.Text = ((ComboElem)(new System.Collections.ArrayList(arrAmb))[i]).Valor;
                        break;
                    }
                }
            }
            #endregion
        }
Пример #10
0
        // Functie exportare data to excel file
        public async Task <IActionResult> ExportToExcelAsync(string dataFrom, string dataTo)
        {
            //return Content(dataFrom + "<==>" + dataTo);
            List <ProbaModel> listaExcel = await _context.ProbaModels.ToListAsync();

            // Extrage datele cuprinse intre limitele date de operator
            IEnumerable <ProbaModel> listaDeAfisat = listaExcel.Where(model => Auxiliar.IsDateBetween(model.DataPrelevare, dataFrom, dataTo));

            var stream = new MemoryStream();

            using (var pck = new ExcelPackage(stream))
            {
                ExcelWorksheet ws = pck.Workbook.Worksheets.Add("Sheet1");
                ws.Cells["A1:Z1"].Style.Font.Bold = true;

                ws.Cells["A1"].Value = "Id";
                ws.Cells["B1"].Value = "Data prelevare";
                ws.Cells["C1"].Value = "Sigla furnizor";
                ws.Cells["D1"].Value = "Sarja";
                ws.Cells["E1"].Value = "Diametru";
                ws.Cells["F1"].Value = "Calitate";
                ws.Cells["G1"].Value = "Nr cuptor";
                ws.Cells["H1"].Value = "Tip Tratament Termic";
                ws.Cells["I1"].Value = "Cap bara";
                ws.Cells["J1"].Value = "Tip proba";
                ws.Cells["K1"].Value = "User name";
                ws.Cells["L1"].Value = "Obs operator";
                ws.Cells["M1"].Value = "Data preluare";
                ws.Cells["N1"].Value = "Data raspuns";
                ws.Cells["O1"].Value = "User name calitate";
                ws.Cells["P1"].Value = "Rezultat proba";
                ws.Cells["Q1"].Value = "KV1";
                ws.Cells["R1"].Value = "KV2";
                ws.Cells["S1"].Value = "KV3";
                ws.Cells["T1"].Value = "Temperatura";
                ws.Cells["U1"].Value = "Duritate HB";
                ws.Cells["V1"].Value = "Obs Calitate";

                int rowStart = 2;
                foreach (var elem in listaDeAfisat)
                {
                    ws.Cells[string.Format("A{0}", rowStart)].Value = elem.ProbaModelId;
                    ws.Cells[string.Format("B{0}", rowStart)].Value = elem.DataPrelevare;
                    ws.Cells[string.Format("C{0}", rowStart)].Value = elem.SiglaFurnizor;
                    ws.Cells[string.Format("D{0}", rowStart)].Value = elem.Sarja;
                    ws.Cells[string.Format("E{0}", rowStart)].Value = elem.Diametru;
                    ws.Cells[string.Format("F{0}", rowStart)].Value = elem.Calitate;
                    ws.Cells[string.Format("G{0}", rowStart)].Value = elem.NumarCuptor;
                    ws.Cells[string.Format("H{0}", rowStart)].Value = elem.TipTratamentTermic;
                    ws.Cells[string.Format("I{0}", rowStart)].Value = elem.TipCapBara;
                    ws.Cells[string.Format("J{0}", rowStart)].Value = elem.Tipproba;
                    ws.Cells[string.Format("K{0}", rowStart)].Value = elem.UserName;
                    ws.Cells[string.Format("L{0}", rowStart)].Value = elem.ObservatiiOperator;
                    ws.Cells[string.Format("M{0}", rowStart)].Value = elem.DataPreluare;
                    ws.Cells[string.Format("N{0}", rowStart)].Value = elem.DataRaspunsCalitate;
                    ws.Cells[string.Format("O{0}", rowStart)].Value = elem.NumeUtilizatorCalitate;
                    ws.Cells[string.Format("P{0}", rowStart)].Value = elem.RezultatProba;
                    ws.Cells[string.Format("Q{0}", rowStart)].Value = elem.KV1;
                    ws.Cells[string.Format("R{0}", rowStart)].Value = elem.KV2;
                    ws.Cells[string.Format("S{0}", rowStart)].Value = elem.KV3;
                    ws.Cells[string.Format("T{0}", rowStart)].Value = elem.Temperatura;
                    ws.Cells[string.Format("U{0}", rowStart)].Value = elem.DuritateHB;
                    ws.Cells[string.Format("V{0}", rowStart)].Value = elem.ObservatiiCalitate;

                    rowStart++;
                }

                ws.Cells["A:AZ"].AutoFitColumns();

                pck.Save();
            }
            stream.Position = 0;
            string excelName = "RaportTrackingMostre.xlsx";

            return(File(stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", excelName));
        }
Пример #11
0
        /// <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="ChaveNFe">Chave da NFe que está sendo consultada</param>
        /// <remarks>
        /// Autor: Wandrey Mundin Ferreira
        /// Data: 16/06/2010
        /// </remarks>
        private void LerRetornoSitNFe(string ChaveNFe)
        {
            int emp = Empresas.FindEmpresaByThread();

            oGerarXML.XmlDistEvento(emp, vStrXmlRetorno);

            LerXML   oLerXml   = new LerXML();
            FluxoNfe oFluxoNfe = new FluxoNfe();

            XmlDocument doc = new XmlDocument();

            doc.Load(Functions.StringXmlToStreamUTF8(vStrXmlRetorno));

            XmlNodeList retConsSitList = doc.GetElementsByTagName("retConsSitNFe");

            foreach (XmlNode retConsSitNode in retConsSitList)
            {
                XmlElement retConsSitElemento = (XmlElement)retConsSitNode;

                //Definir a chave da NFe a ser pesquisada
                string strChaveNFe = "NFe" + ChaveNFe;

                //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(3) + Propriedade.Extensao(Propriedade.TipoEnvio.NFe).EnvioXML;
                }
                string strArquivoNFe = Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" + PastaEnviados.EmProcessamento.ToString() + "\\" + strNomeArqNfe;

                #region CNPJ da chave não é de uma empresa Uninfe

                bool notDaEmpresa = (ChaveNFe.Substring(6, 14) != Empresas.Configuracoes[emp].CNPJ ||
                                     ChaveNFe.Substring(0, 2) != Empresas.Configuracoes[emp].UnidadeFederativaCodigo.ToString());

                if (!File.Exists(strArquivoNFe))
                {
                    if (notDaEmpresa)
                    {
                        return;
                    }
                }

                #endregion CNPJ da chave não é de uma empresa Uninfe

                //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 Validação do Certificado de Transmissão

                    #region Validação Inicial da Mensagem no WebService

                case "214":
                case "243":
                case "108":
                case "109":

                    #endregion Validação Inicial da Mensagem no WebService

                    #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 Validação das informações de controle da chamada ao WebService

                    #region Validação da forma da área de dados

                case "215":
                case "516":
                case "517":
                case "545":
                case "587":
                case "588":
                case "404":
                case "402":

                    #endregion Validação da forma da área de dados

                    #region Validação das regras de negócios da consulta a NF-e

                case "252":
                case "226":
                case "236":
                case "614":
                case "615":
                case "616":
                case "617":
                case "618":
                case "619":
                case "620":
                    break;

                    #endregion Validação das regras de negócios da consulta a NF-e

                    #region Nota fiscal rejeitada

                case "217":     //J-NFe não existe na base de dados do SEFAZ
                    goto case "TirarFluxo";

                case "562":     //J-Verificar se o campo "Código Numérico" informado na chave de acesso é diferente do existente no BD
                    goto case "TirarFluxo";

                case "561":     //J-Verificar se campo MM (mês) informado na Chave de Acesso é diferente do existente no BD
                    goto case "TirarFluxo";

                    #endregion Nota fiscal rejeitada

                    #endregion 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 Nota fiscal autorizada

                case "100":     //Autorizado o uso da NFe
                case "150":     //Autorizado o uso da NFe fora do prazo
                    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(), false);

                            //Pegar a versão do XML
                            var    protNFeElemento = (XmlElement)retConsSitElemento.GetElementsByTagName("protNFe")[0];
                            string versao          = protNFeElemento.GetAttribute(TpcnResources.versao.ToString());

                            switch (strStat)
                            {
                            case "100":         //NFe Autorizada
                            case "150":         //NFe Autorizada fora do prazo
                                string strProtNfe = retConsSitElemento.GetElementsByTagName("protNFe")[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.NFe).EnvioXML) + Propriedade.ExtRetorno.ProcNFe;

                                //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
                                    XmlDocument conteudoXML = new XmlDocument();
                                    conteudoXML.Load(strArquivoNFe);
                                    oLerXml.Nfe(conteudoXML);

                                    //Verificar se a -nfe.xml existe na pasta de autorizados
                                    bool NFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoNFe, oLerXml.oDadosNfe.dEmi, Propriedade.Extensao(Propriedade.TipoEnvio.NFe).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.NFe).EnvioXML);

                                    //Verificar se o -procNfe.xml existe na past de autorizados
                                    bool procNFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoNFe, oLerXml.oDadosNfe.dEmi, Propriedade.Extensao(Propriedade.TipoEnvio.NFe).EnvioXML, Propriedade.ExtRetorno.ProcNFe);

                                    //Se o XML de distribuição não estiver na pasta de autorizados
                                    if (!procNFeJaNaAutorizada)
                                    {
                                        if (!File.Exists(strArquivoNFeProc))
                                        {
                                            Auxiliar.WriteLog("TaskNFeConsultaSituacao: Gerou o arquivo de distribuição através da consulta situação da NFe.", false);
                                            oGerarXML.XmlDistNFe(strArquivoNFe, strProtNfe, Propriedade.ExtRetorno.ProcNFe, versao);
                                        }
                                    }

                                    //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.NFe).EnvioXML, Propriedade.ExtRetorno.ProcNFe)))
                                    {
                                        //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.NFe).EnvioXML, Propriedade.ExtRetorno.ProcNFe);
                                    }

                                    //Se a NFe não existir ainda na pasta de autorizados
                                    if (!(NFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoNFe, oLerXml.oDadosNfe.dEmi, Propriedade.Extensao(Propriedade.TipoEnvio.NFe).EnvioXML, Propriedade.Extensao(Propriedade.TipoEnvio.NFe).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)
                                    {
                                        try
                                        {
                                            string strArquivoDist = Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" +
                                                                    PastaEnviados.Autorizados.ToString() + "\\" +
                                                                    Empresas.Configuracoes[emp].DiretorioSalvarComo.ToString(oLerXml.oDadosNfe.dEmi) +
                                                                    Path.GetFileName(strArquivoNFe);

                                            TFunctions.ExecutaUniDanfe(strArquivoDist, oLerXml.oDadosNfe.dEmi, Empresas.Configuracoes[emp]);
                                        }
                                        catch (Exception ex)
                                        {
                                            Auxiliar.WriteLog("TaskNFeConsultaSituacao:  (Falha na execução do UniDANFe) " + 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;

                            //danasa 11-4-2012
                            case "110":         //Uso Denegado
                            case "301":
                            case "302":
                            case "303":
                                if (File.Exists(strArquivoNFe))
                                {
                                    ///
                                    /// se o ERP copiou o arquivo da NFe para a pasta em Processamento, o Uninfe irá montar o XML de distribuicao, caso nao exista,
                                    /// e imprimir o DANFE
                                    ///
                                    ProcessaNFeDenegada(emp, oLerXml, strArquivoNFe, null, protNFeElemento.OuterXml, versao);
                                }
                                //ProcessaNFeDenegada(emp, oLerXml, strArquivoNFe, retConsSitElemento.GetElementsByTagName("protNFe")[0].OuterXml, versao);
                                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 Nota fiscal autorizada

                    #region Nota fiscal cancelada

                case "101":     //Cancelamento Homologado ou Nfe Cancelada
                    goto case "100";

                    #endregion Nota fiscal cancelada

                    #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 "205":     //Nfe já está denegada na base do SEFAZ
                    goto case "100";

                    #endregion Nota fiscal Denegada

                    #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 Conteúdo para retirar a nota fiscal do fluxo

                default:
                    goto case "TirarFluxo";
                }
            }
        }
        public ActionResult UploadImagen(CatFierroModels Fierro)
        {
            try
            {
                if (Token.IsTokenValid())
                {
                    HttpPostedFileBase bannerImage = Request.Files[0] as HttpPostedFileBase;

                    MemoryStream ms = new MemoryStream();
                    bannerImage.InputStream.CopyTo(ms);
                    bannerImage.InputStream.Position = ms.Position = 0;
                    Stream s2 = ms;

                    if (!string.IsNullOrEmpty(bannerImage.FileName))
                    {
                        if (bannerImage != null && bannerImage.ContentLength > 0)
                        {
                            Stream s = bannerImage.InputStream;

                            if (Path.GetExtension(bannerImage.FileName).ToLower() == ".heic")
                            {
                                Image  img   = (Image)Auxiliar.ProcessFile(s);
                                Bitmap image = new Bitmap(ComprimirImagen.VaryQualityLevel((Image)img.Clone(), 35L));
                                Fierro.ImgFierro = image.ToBase64String(ImageFormat.Jpeg);
                            }
                            else
                            {
                                Bitmap img = new Bitmap(s);
                                Fierro.ImgFierro = img.ToBase64String(img.RawFormat);
                            }
                        }
                    }
                    else
                    {
                        ModelState.AddModelError(string.Empty, "Cargar imagen Fierro");
                    }
                    CatFierro_Datos FierroDatos = new CatFierro_Datos();
                    Fierro.Conexion = Conexion;
                    Fierro.Opcion   = 1;
                    Fierro.Usuario  = User.Identity.Name;

                    Fierro = FierroDatos.AbcCatFierro(Fierro);
                    if (!string.IsNullOrEmpty(Fierro.IDFierro))
                    {
                        if (!string.IsNullOrEmpty(bannerImage.FileName))
                        {
                            string baseDir       = Server.MapPath("~/Imagenes/Fierro/");
                            string fileExtension = Path.GetExtension(bannerImage.FileName);
                            fileExtension = fileExtension == (".heic") ? ".png" : fileExtension;

                            string fileName = Fierro.IDFierro + fileExtension;
                            Bitmap IMG3     = null;


                            if (Path.GetExtension(bannerImage.FileName) == ".heic")
                            {
                                Image  img   = (Image)Auxiliar.ProcessFile(s2);
                                Bitmap image = new Bitmap(ComprimirImagen.VaryQualityLevel((Image)img.Clone(), 35L));
                                IMG3 = ComprimirImagen.SaveJpeg(baseDir + fileName, image, 50, true);
                            }
                            else
                            {
                                Image Img2 = new Bitmap(s2);
                                IMG3 = ComprimirImagen.SaveJpeg(baseDir + fileName, Img2, 50, true);
                            }

                            Fierro.ImgFierro = IMG3.ToBase64String(ImageFormat.Jpeg);

                            Fierro.NombreArchivo = fileName;
                            Fierro = FierroDatos.ActualizarImagen(Fierro);
                            if (Fierro.Completado == true)
                            {
                                if (!string.IsNullOrEmpty(Fierro.Id_servicio))
                                {
                                    TempData["typemessage"] = "1";
                                    TempData["message"]     = "El fierro se registro correctamente a la compra.";
                                    Token.ResetToken();
                                    return(RedirectToAction("DocumentosCompra", "Compra", new { Id_1 = Fierro.Id_servicio }));
                                }
                                else
                                {
                                    TempData["typemessage"] = "1";
                                    TempData["message"]     = "Los datos se guardaron correctamente.";
                                    Token.ResetToken();
                                    return(RedirectToAction("Index"));
                                }
                            }
                            else
                            {
                                if (!string.IsNullOrEmpty(Fierro.Id_servicio))
                                {
                                    TempData["typemessage"] = "2";
                                    TempData["message"]     = "Ocurrio un error al intentar guardar la imagen de fierro. Intente más tarde.";
                                    return(RedirectToAction("DocumentosCompra", "Compra", new { Id_1 = Fierro.Id_servicio }));
                                }
                                else
                                {
                                    TempData["typemessage"] = "2";
                                    TempData["message"]     = "Ocurrio un error al intentar guardar los datos. Intente más tarde.";
                                    return(View(Fierro));
                                }
                            }
                        }
                    }
                    else
                    {
                        if (!string.IsNullOrEmpty(Fierro.Id_servicio))
                        {
                            TempData["typemessage"] = "2";
                            TempData["message"]     = "Ocurrio un error al intentar guardar la imagen del fierro. Intente más tarde.";
                            return(RedirectToAction("DocumentosCompra", "Compra", new { Id_1 = Fierro.Id_servicio }));
                        }
                        else
                        {
                            TempData["typemessage"] = "2";
                            TempData["message"]     = "Ocurrio un error al intentar guardar los datos. Intente más tarde.";
                            return(View(Fierro));
                        }
                    }
                }
                else
                {
                    if (!string.IsNullOrEmpty(Fierro.Id_servicio))
                    {
                        TempData["typemessage"] = "2";
                        TempData["message"]     = "Verifique sus datos";
                        return(RedirectToAction("DocumentosCompra", "Compra", new { Id_1 = Fierro.Id_servicio }));
                    }
                    else
                    {
                        TempData["typemessage"] = "2";
                        TempData["message"]     = "Verifique sus datos";
                        return(View(Fierro));
                    }
                }
                return(View(Fierro));
            }
            catch (Exception ex)
            {
                if (!string.IsNullOrEmpty(Fierro.Id_servicio))
                {
                    TempData["typemessage"] = "2";
                    TempData["message"]     = "Verifique sus datos";
                    return(RedirectToAction("DocumentosCompra", "Compra", new { Id_1 = Fierro.Id_servicio }));
                }
                else
                {
                    TempData["typemessage"] = "2";
                    TempData["message"]     = "Verifique sus datos";
                    return(View(Fierro));
                }
            }
        }
Пример #13
0
        private void LerRetornoEvento(int emp)
        {
            XmlDocument docEventoOriginal = new XmlDocument();

            docEventoOriginal.Load(NomeArquivoXML);

            // <<<UTF8 -> tem acentuacao no retorno
            MemoryStream msXml = Functions.StringXmlToStreamUTF8(this.vStrXmlRetorno);
            XmlDocument  doc   = new XmlDocument();

            doc.Load(msXml);
            //doc.Load(@"C:\Users\wandrey\Downloads\51160417625687000153550010001224661001224662-ret-env-canc (1).xml");

            XmlNodeList retEnvRetornoList = doc.GetElementsByTagName("retEnvEvento");

            foreach (XmlNode retConsSitNode in retEnvRetornoList)
            {
                XmlElement retConsSitElemento = (XmlElement)retConsSitNode;

                //Pegar o status de retorno da NFe que está sendo consultada a situação
                var cStatCons = string.Empty;
                if (retConsSitElemento.GetElementsByTagName(NFe.Components.TpcnResources.cStat.ToString())[0] != null)
                {
                    cStatCons = retConsSitElemento.GetElementsByTagName(NFe.Components.TpcnResources.cStat.ToString())[0].InnerText;
                }
                switch (cStatCons)
                {
                case "128":     //Lote de Evento Processado
                {
                    XmlNodeList envEventosList = doc.GetElementsByTagName("retEvento");
                    for (int i = 0; i < envEventosList.Count; ++i)
                    {
                        XmlElement eleRetorno = envEventosList.Item(i) as XmlElement;
                        cStatCons = eleRetorno.GetElementsByTagName(NFe.Components.TpcnResources.cStat.ToString())[0].InnerText;
                        if (cStatCons == "135" || cStatCons == "136" || cStatCons == "155")
                        {
                            string chNFe      = eleRetorno.GetElementsByTagName(NFe.Components.TpcnResources.chNFe.ToString())[0].InnerText;
                            Int32  nSeqEvento = Convert.ToInt32("0" + eleRetorno.GetElementsByTagName(NFe.Components.TpcnResources.nSeqEvento.ToString())[0].InnerText);
                            NFe.ConvertTxt.tpEventos tpEvento = NFe.Components.EnumHelper.StringToEnum <NFe.ConvertTxt.tpEventos>(eleRetorno.GetElementsByTagName(NFe.Components.TpcnResources.tpEvento.ToString())[0].InnerText);
                            string Id = NFe.Components.TpcnResources.ID.ToString() + ((Int32)tpEvento).ToString("000000") + chNFe + nSeqEvento.ToString("00");
                            ///
                            ///procura no Xml de envio pelo Id retornado
                            ///nao sei se a Sefaz retorna na ordem em que foi enviado, então é melhor pesquisar
                            foreach (XmlNode env in docEventoOriginal.GetElementsByTagName("infEvento"))
                            {
                                string Idd = env.Attributes.GetNamedItem(NFe.Components.TpcnResources.Id.ToString()).Value;
                                if (Idd == Id)
                                {
                                    DateTime dhRegEvento = Functions.GetDateTime(eleRetorno.GetElementsByTagName(NFe.Components.TpcnResources.dhRegEvento.ToString())[0].InnerText);

                                    ///
                                    /// Gerar o arquivo XML de distribuição do evento
                                    ///
                                    oGerarXML.XmlDistEvento(emp, chNFe, nSeqEvento, tpEvento,
                                                            env.ParentNode.OuterXml,
                                                            eleRetorno.OuterXml,
                                                            dhRegEvento,
                                                            true);

                                    switch (tpEvento)
                                    {
                                    case ConvertTxt.tpEventos.tpEvCancelamentoNFe:
                                    case ConvertTxt.tpEventos.tpEvCCe:
                                        try
                                        {
                                            NFe.Service.TFunctions.ExecutaUniDanfe(oGerarXML.NomeArqGerado, DateTime.Today, Empresas.Configuracoes[emp]);
                                        }
                                        catch (Exception ex)
                                        {
                                            Auxiliar.WriteLog("TaskNFeEventos: " + ex.Message, false);
                                        }
                                        break;

                                    case ConvertTxt.tpEventos.tpEvEPEC:
                                        if (cStatCons == "136")
                                        {
                                            //Evento autorizado sem vinculação do evento à respectiva NF-e
                                            try
                                            {
                                                NFe.Service.TFunctions.ExecutaUniDanfe(oGerarXML.NomeArqGerado, DateTime.Today, Empresas.Configuracoes[emp]);
                                            }
                                            catch (Exception ex)
                                            {
                                                Auxiliar.WriteLog("TaskNFeEventos: " + ex.Message, false);
                                            }
                                        }
                                        break;
                                    }
                                    break;
                                }
                            }
                        }
                    }
                }
                break;
                }
            }
        }
Пример #14
0
 public TestController(ReportDbContext context, ILogger <TestController> logger, Auxiliar auxiliar)
 {
     _context  = context;
     _logger   = logger;
     _auxiliar = auxiliar;
     // log
     _logger.LogInformation("{data}<=>{Messege}", DateTime.Now.ToString("dd.MM.yyyy hh:mm:ss"), "TESTCONTROLLER constructor log information");
     _logger.LogError("{data}<=>{Messege}", DateTime.Now.ToString("dd.MM.yyyy hh:mm:ss"), "TESTCONTROLLER constructor log error");
     _logger.LogWarning("{data}<=>{Messege}", DateTime.Now.ToString("dd.MM.yyyy hh:mm:ss"), "TESTCONTROLLER constructor log warning");
 }
Пример #15
0
        /// <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, vStrXmlRetorno);

            LerXML   oLerXml   = new LerXML();
            FluxoNfe oFluxoNfe = new FluxoNfe();

            XmlDocument doc = new XmlDocument();

            doc.Load(Functions.StringXmlToStreamUTF8(vStrXmlRetorno));

            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))
                {
                    if (notDaEmpresa)
                    {
                        return;
                    }
                }

                #endregion CNPJ da chave não é de uma empresa Uninfe

                //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 Rejeições do XML de consulta do recibo (Não é o lote que foi rejeitado e sim o XML de consulta do recibo)

                    #region Nota fiscal rejeitada

                case "217":     //J-NFe não existe na base de dados do SEFAZ
                    goto case "TirarFluxo";

                    #endregion Nota fiscal rejeitada

                    #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
                                    XmlDocument conteudoXML = new XmlDocument();
                                    conteudoXML.Load(strArquivoCTe);
                                    oLerXml.Cte(conteudoXML);

                                    //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, oLerXml.oDadosNfe.versao);
                                    }

                                    //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))
                                {
                                    //Ler o XML para pegar a data de emissão para criar a pasta dos XML´s autorizados
                                    XmlDocument conteudoXML = new XmlDocument();
                                    conteudoXML.Load(strArquivoCTe);
                                    oLerXml.Cte(conteudoXML);

                                    //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 Nota fiscal autorizada

                    #region Nota fiscal cancelada

                case "101":     //Cancelamento Homologado ou Nfe Cancelada
                    goto case "100";

                    #endregion Nota fiscal cancelada

                    #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 Nota fiscal Denegada

                    #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 Conteúdo para retirar a nota fiscal do fluxo

                default:
                    break;
                }
            }
        }
Пример #16
0
        /// <summary>
        /// Processa/envia os XML´s gravados na pasta de envio
        /// </summary>
        /// <param name="oNfe">Objeto referente a UniNfeClass</param>
        /// <param name="strPasta">Pasta de envio</param>
        /// <param name="strMascara">Mascara dos arquivos a serem pesquisados e processados</param>
        /// <param name="strAtividade">Atividade a ser executada com o(s) XML(s) encontrados</param>
        /// <by>Wandrey Mundin Ferreira</by>
        /// <date>03/04/2009</date>
        protected void ProcessaXML(Object oNfe, Servicos srvServico)
        {
            string        strPasta    = string.Empty;
            List <string> lstArquivos = new List <string>();

            lstArquivos.Clear();

            string strMascaraArq = string.Empty;
            string strMetodo     = string.Empty;
            int    emp           = new FindEmpresaThread(Thread.CurrentThread).Index;

            switch (srvServico)
            {
            case Servicos.EmProcessamento:
                EmProcessamento();
                break;

            case Servicos.CancelarNFe:
                strMetodo   = "Cancelamento";
                lstArquivos = this.ArquivosPasta(Empresa.Configuracoes[emp].PastaEnvio, "*" + ExtXml.PedCan);
                lstArquivos.AddRange(this.ArquivosPasta(Empresa.Configuracoes[emp].PastaEnvio, "*" + ExtXml.PedCan_TXT));
                goto default;

            case Servicos.InutilizarNumerosNFe:
                strMetodo   = "Inutilizacao";
                lstArquivos = this.ArquivosPasta(Empresa.Configuracoes[emp].PastaEnvio, "*" + ExtXml.PedInu);
                lstArquivos.AddRange(this.ArquivosPasta(Empresa.Configuracoes[emp].PastaEnvio, "*" + ExtXml.PedInu_TXT));
                goto default;

            case Servicos.PedidoConsultaSituacaoNFe:
                strMetodo   = "Consulta";
                lstArquivos = this.ArquivosPasta(Empresa.Configuracoes[emp].PastaEnvio, "*" + ExtXml.PedSit);
                lstArquivos.AddRange(this.ArquivosPasta(Empresa.Configuracoes[emp].PastaEnvio, "*" + ExtXml.PedSit_TXT));
                goto default;

            case Servicos.PedidoConsultaStatusServicoNFe:
                strMetodo   = "StatusServico";
                lstArquivos = this.ArquivosPasta(Empresa.Configuracoes[emp].PastaEnvio, "*" + ExtXml.PedSta);
                lstArquivos.AddRange(this.ArquivosPasta(Empresa.Configuracoes[emp].PastaEnvio, "*" + ExtXml.PedSta_TXT));
                goto default;

            case Servicos.PedidoSituacaoLoteNFe:
                strMetodo = "RetRecepcao";
                this.GerarXMLPedRec(oNfe);
                lstArquivos = this.ArquivosPasta(Empresa.Configuracoes[emp].PastaEnvio, "*" + ExtXml.PedRec);     //Tem que ficar depois de ter gerado os XML de consulta do recibo ou dá falha. Wandrey 22/05/2009
                goto default;

            case Servicos.ConsultaCadastroContribuinte:
                strMetodo   = "ConsultaCadastro";
                lstArquivos = this.ArquivosPasta(Empresa.Configuracoes[emp].PastaEnvio, "*" + ExtXml.ConsCad);
                lstArquivos.AddRange(this.ArquivosPasta(Empresa.Configuracoes[emp].PastaEnvio, "*" + ExtXml.ConsCad_TXT));
                goto default;

            case Servicos.ConsultaInformacoesUniNFe:
                strMetodo   = "GravarXMLDadosCertificado";
                lstArquivos = this.ArquivosPasta(Empresa.Configuracoes[emp].PastaEnvio, "*" + ExtXml.ConsInf);
                lstArquivos.AddRange(this.ArquivosPasta(Empresa.Configuracoes[emp].PastaEnvio, "*" + ExtXml.ConsInf_TXT));
                goto default;

            case Servicos.AlterarConfiguracoesUniNFe:
                strMetodo   = "ReconfigurarUniNfe";
                lstArquivos = this.ArquivosPasta(Empresa.Configuracoes[emp].PastaEnvio, "*" + ExtXml.AltCon);
                lstArquivos.AddRange(this.ArquivosPasta(Empresa.Configuracoes[emp].PastaEnvio, "*" + ExtXml.AltCon_TXT));
                goto default;

            case Servicos.EnviarDPEC:
                strMetodo   = "RecepcaoDPEC";
                lstArquivos = this.ArquivosPasta(Empresa.Configuracoes[emp].PastaEnvio, "*" + ExtXml.EnvDPEC);
                lstArquivos.AddRange(this.ArquivosPasta(Empresa.Configuracoes[emp].PastaEnvio, "*" + ExtXml.EnvDPEC_TXT));
                goto default;

            case Servicos.ConsultarDPEC:
                strMetodo   = "ConsultaDPEC";
                lstArquivos = this.ArquivosPasta(Empresa.Configuracoes[emp].PastaEnvio, "*" + ExtXml.ConsDPEC);
                lstArquivos.AddRange(this.ArquivosPasta(Empresa.Configuracoes[emp].PastaEnvio, "*" + ExtXml.ConsDPEC_TXT));
                goto default;

            case Servicos.AssinarNFePastaEnvio:
                this.AssinarValidarNFe(oNfe, Empresa.Configuracoes[emp].PastaEnvio);
                break;

            case Servicos.AssinarNFePastaEnvioEmLote:
                if (Empresa.Configuracoes[emp].PastaEnvioEmLote != string.Empty)
                {
                    this.AssinarValidarNFe(oNfe, Empresa.Configuracoes[emp].PastaEnvioEmLote);
                }
                break;

            case Servicos.MontarLoteUmaNFe:
                this.MontarLoteUmaNfe(oNfe);
                break;

            case Servicos.MontarLoteVariasNFe:
                if (Empresa.Configuracoes[emp].PastaEnvioEmLote != string.Empty)
                {
                    this.MontarLoteVariasNfe(oNfe);
                }
                break;

            case Servicos.EnviarLoteNfe:
                strMetodo   = "Recepcao";
                lstArquivos = this.ArquivosPasta(Empresa.Configuracoes[emp].PastaEnvio, "*" + ExtXml.EnvLot);
                goto default;

            case Servicos.ValidarAssinar:
                this.AssinarValidarXML();     //Somente validar e assinar os diversos XML´s da NFe
                break;

            case Servicos.ConverterTXTparaXML:
                this.ConvTXT(Empresa.Configuracoes[emp].PastaEnvio);
                break;

            case Servicos.GerarChaveNFe:
                this.GerarChaveNFe();
                break;

            case Servicos.LimpezaTemporario:
                ExecutaLimpeza();
                break;

            default:      //Assinar, validar, enviar ou somente processar os arquivos XML encontrados na pasta de envio
                for (int i = 0; i < lstArquivos.Count; i++)
                {
                    //Se o arquivo estiver ainda em uso eu pulo ele para tentar mais tarde
                    if (Auxiliar.FileInUse(lstArquivos[i]))
                    {
                        continue;
                    }

                    try
                    {
                        //Processa ou envia o XML
                        this.EnviarArquivo(lstArquivos[i], oNfe, strMetodo);
                    }
                    catch
                    {
                        //Não pode ser tratado nenhum erro aqui, visto que já estão sendo tratados e devidamente retornados
                        //para o ERP no ponto da execução dos serviços. Foi muito bem testado e analisado. Wandrey 09/03/2010
                    }
                }
                break;
            }
        }
Пример #17
0
        /// <summary>
        /// Criar uma lista com os recibos a serem consultados no servidor do SEFAZ
        /// </summary>
        /// <returns>Lista dos recibos</returns>
        /// <by>Wandrey Mundin Ferreira</by>
        public List <ReciboCons> CriarListaRec()
        {
            CriarXml(true);

            List <ReciboCons> lstRecibo = new List <ReciboCons>();
            List <string>     lstNumRec = new List <string>();

            DateTime startTime;
            DateTime stopTime;
            TimeSpan elapsedTime;

            long elapsedMillieconds;

            startTime = DateTime.Now;

            while (true)
            {
                stopTime           = DateTime.Now;
                elapsedTime        = stopTime.Subtract(startTime);
                elapsedMillieconds = (int)elapsedTime.TotalMilliseconds;
                FileStream fsArquivo = null;

                try
                {
                    lock (Smf.Fluxo)
                    {
                        XmlDocument doc = new XmlDocument(); //Criar instância do XmlDocument Class
                        fsArquivo = OpenFileFluxo(false);
                        doc.Load(fsArquivo);                 //Carregar o arquivo aberto no XmlDocument
                        fsArquivo.Close();

                        XmlNodeList documentoList = doc.GetElementsByTagName(ElementoFixo.Documento.ToString()); //Pesquisar o elemento Documento no arquivo XML
                        foreach (XmlNode documentoNode in documentoList)
                        {
                            XmlElement documentoElemento = (XmlElement)documentoNode;

                            string nRec        = Functions.LerTag(documentoElemento, ElementoEditavel.nRec.ToString(), "");
                            string versao      = Functions.LerTag(documentoElemento, ElementoEditavel.versao.ToString(), "");
                            string ChaveNFe    = documentoElemento.GetAttribute(ElementoFixo.ChaveNFe.ToString());
                            string NomeArquivo = Functions.LerTag(documentoElemento, ElementoFixo.ArqNFe.ToString(), "");
                            string NomeArquivoEmProcessamento = Empresas.Configuracoes[empresa].PastaXmlEnviado + "\\" + PastaEnviados.EmProcessamento.ToString() + "\\" + NomeArquivo;
                            string NomeArquivoAssinado        = Empresas.Configuracoes[empresa].PastaXmlEnvio + "\\temp\\" + NomeArquivo;
                            string NomeArquivoAssinadoLote    = Empresas.Configuracoes[empresa].PastaXmlEmLote + "\\temp\\" + NomeArquivo;
                            string mod        = Functions.LerTag(documentoElemento, ElementoEditavel.mod.ToString(), "");
                            bool   excluiNota = false;
                            if (File.Exists(NomeArquivoEmProcessamento))
                            {
                                int      tMed    = 3; //3 segundos
                                DateTime dPedRec = DateTime.Now.AddMinutes(-60);

                                tMed    = Convert.ToInt32(Functions.LerTag(documentoElemento, ElementoEditavel.tMed.ToString(), tMed.ToString()));
                                dPedRec = Convert.ToDateTime(Functions.LerTag(documentoElemento, ElementoEditavel.dPedRec.ToString(), dPedRec.ToString("yyyy-MM-dd HH:mm:ss")));

                                //Se tiver mais de 2 dias no fluxo, vou excluir a nota dele.
                                //Não faz sentido uma nota ficar no fluxo todo este tempo, então vou fazer uma limpeza
                                //Wandrey 11/09/2009
                                if (DateTime.Now.Subtract(dPedRec).Days >= 2)
                                {
                                    excluiNota = true;
                                }
                                else
                                {
                                    if (nRec != string.Empty && !lstNumRec.Contains(nRec))
                                    {
                                        lstNumRec.Add(nRec);

                                        ReciboCons oReciboCons = new ReciboCons();
                                        oReciboCons.dPedRec = dPedRec;
                                        oReciboCons.nRec    = nRec;
                                        oReciboCons.tMed    = tMed;
                                        oReciboCons.versao  = versao;
                                        oReciboCons.mod     = mod;
                                        lstRecibo.Add(oReciboCons);
                                    }
                                }
                            }
                            else if (!File.Exists(NomeArquivoAssinado) && !File.Exists(NomeArquivoAssinadoLote))
                            {
                                excluiNota = true;
                            }

                            if (excluiNota)
                            {
                                //Deletar o arquivo da pasta em processamento
                                Auxiliar oAux = new Auxiliar();
                                oAux.MoveArqErro(NomeArquivoEmProcessamento);

                                //Deletar a NFE do arquivo de controle de fluxo
                                ExcluirNfeFluxo(ChaveNFe);
                            }
                        }
                        break;
                    }
                }
                catch
                {
                    if (fsArquivo != null)
                    {
                        fsArquivo.Close();
                    }

                    if (elapsedMillieconds >= 120000) //120.000 ms que corresponde á 120 segundos que corresponde a 2 minuto
                    {
                        throw;
                    }
                }

                Thread.Sleep(100);
            }

            return(lstRecibo);
        }
Пример #18
0
        /// <summary>
        /// Monta o um lote com várias NFe´s
        /// </summary>
        /// <param name="oNfe">Objeto referente a instância da classe absServicoNFe</param>
        /// <by>Wandrey Mundin Ferreira</by>
        /// <date>28/04/2009</date>
        private void MontarLoteVariasNfe(Object oNfe)
        {
            int emp = new FindEmpresaThread(Thread.CurrentThread).Index;

            List <string> lstArqMontarLote = new List <string>();

            //Aguardar a assinatura de todos os arquivos da pasta de lotes
            lstArqMontarLote = this.ArquivosPasta(Empresa.Configuracoes[emp].PastaEnvioEmLote, "*" + ExtXml.Nfe);
            if (lstArqMontarLote.Count > 0)
            {
                return;
            }

            //Verificar se existe o arquivo que solicita a montagem do lote
            lstArqMontarLote = this.ArquivosPasta(Empresa.Configuracoes[emp].PastaEnvioEmLote, "*" + ExtXml.MontarLote);

            for (int b = 0; b < lstArqMontarLote.Count; b++)
            {
                string NomeArquivo = lstArqMontarLote[b];

                //O arquivo existe mas pode estar em uso
                if (Auxiliar.FileInUse(NomeArquivo) == true)
                {
                    return;
                }

                Auxiliar      oAux      = new Auxiliar();
                List <string> lstNfe    = new List <string>();
                FileStream    fsArquivo = null;
                FluxoNfe      oFluxoNfe = new FluxoNfe();

                string MensagemErro = string.Empty;
                bool   lTeveErro    = false;

                try
                {
                    XmlDocument doc = new XmlDocument();                                                          //Criar instância do XmlDocument Class
                    fsArquivo = new FileStream(NomeArquivo, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); //Abrir um arquivo XML usando FileStream
                    doc.Load(fsArquivo);                                                                          //Carregar o arquivo aberto no XmlDocument

                    XmlNodeList documentoList = doc.GetElementsByTagName("MontarLoteNFe");                        //Pesquisar o elemento Documento no arquivo XML
                    foreach (XmlNode documentoNode in documentoList)
                    {
                        XmlElement documentoElemento = (XmlElement)documentoNode;

                        int QtdeArquivo = documentoElemento.GetElementsByTagName("ArquivoNFe").Count;

                        for (int d = 0; d < QtdeArquivo; d++)
                        {
                            string ArquivoNFe = Empresa.Configuracoes[emp].PastaEnvioEmLote + InfoApp.NomePastaXMLAssinado + "\\" + documentoElemento.GetElementsByTagName("ArquivoNFe")[d].InnerText;

                            if (File.Exists(ArquivoNFe))
                            {
                                try
                                {
                                    LerXML.DadosNFeClass oDadosNfe = this.LerXMLNFe(ArquivoNFe);
                                    if (!oFluxoNfe.NFeComLote(oDadosNfe.chavenfe))
                                    {
                                        lstNfe.Add(ArquivoNFe);
                                    }
                                    else
                                    {
                                        MensagemErro += "Arquivo: " + ArquivoNFe + " já está no fluxo de envio e não será incluido em novo lote.\r\n";
                                        lTeveErro     = true;

                                        FileInfo oArq = new FileInfo(ArquivoNFe);
                                        oArq.Delete();
                                    }
                                }
                                catch (IOException ex)
                                {
                                    MensagemErro += ex.Message + "\r\n";
                                    lTeveErro     = true;
                                }
                                catch (Exception ex)
                                {
                                    MensagemErro += ex.Message + "\r\n";
                                    lTeveErro     = true;
                                }
                            }
                            else
                            {
                                lTeveErro     = true;
                                MensagemErro += "Arquivo: " + ArquivoNFe + " não existe e não será incluido no lote!\r\n";
                            }
                        }
                    }

                    fsArquivo.Close(); //Fecha o arquivo XML

                    //Definir o tipo do serviço
                    Type tipoServico = oNfe.GetType();

                    try
                    {
                        //Gerar lote
                        tipoServico.InvokeMember("LoteNfe", System.Reflection.BindingFlags.InvokeMethod, null, oNfe, new object[] { lstNfe });
                    }
                    catch (IOException ex)
                    {
                        MensagemErro += ex.Message + "\r\n";
                        lTeveErro     = true;
                    }
                    catch (Exception ex)
                    {
                        MensagemErro += ex.Message + "\r\n";
                        lTeveErro     = true;
                    }
                }
                catch (Exception ex)
                {
                    if (fsArquivo != null)
                    {
                        fsArquivo.Close();
                    }

                    lTeveErro     = true;
                    MensagemErro += ex.Message + "\r\n";
                }

                //Deletar o arquivo de solicitão de montagem do lote de NFe
                try
                {
                    FileInfo oArquivo = new FileInfo(NomeArquivo);
                    oArquivo.Delete();
                }
                catch (IOException ex)
                {
                    lTeveErro     = true;
                    MensagemErro += ex.Message + "\r\n";
                }
                catch (Exception ex)
                {
                    lTeveErro     = true;
                    MensagemErro += ex.Message + "\r\n";
                }

                if (lTeveErro)
                {
                    try
                    {
                        oAux.GravarArqErroServico(NomeArquivo, ExtXml.MontarLote, "-montar-lote.err", MensagemErro);
                    }
                    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
                    }
                }
            }
        }
Пример #19
0
        private const int _Minutos = 12;  //12 minutos para atender o consumo indevido da SEFAZ

        public void Analisar(int emp)
        {
            oAux = new Auxiliar();

            try
            {
                if (string.IsNullOrEmpty(Empresas.Configuracoes[emp].PastaXmlEnviado) || !Directory.Exists(Empresas.Configuracoes[emp].PastaXmlEnviado))
                {
                    return;
                }

                // le todos os arquivos que estão na pasta em processamento
                string[] files = Directory.GetFiles(Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" +
                                                    PastaEnviados.EmProcessamento.ToString()).Where(w => w.EndsWith(Propriedade.Extensao(Propriedade.TipoEnvio.NFe).EnvioXML, StringComparison.InvariantCultureIgnoreCase) ||
                                                                                                    w.EndsWith(Propriedade.Extensao(Propriedade.TipoEnvio.CTe).EnvioXML, StringComparison.InvariantCultureIgnoreCase) ||
                                                                                                    w.EndsWith(Propriedade.Extensao(Propriedade.TipoEnvio.MDFe).EnvioXML, StringComparison.InvariantCultureIgnoreCase)).ToArray <string>();

                // considera os arquivos em que a data do ultimo acesso é superior a 5 minutos
                DateTime UltimaData = DateTime.Now.AddMinutes(-_Minutos);

                foreach (string file in files)
                {
                    if (!Functions.FileInUse(file))
                    {
                        FileInfo fi = new FileInfo(file);

                        //usar a última data de acesso, e não a data de criação
                        if (fi.LastWriteTime <= UltimaData)
                        {
                            if (oLerXml == null)
                            {
                                oLerXml   = new LerXML();
                                oGerarXml = new GerarXML(emp);
                                fluxo     = new FluxoNfe(emp);
                            }

                            try
                            {
                                XmlDocument doc = new XmlDocument();
                                doc.Load(file);

                                TipoAplicativo tipoArquivo = TipoAplicativo.Nfe;
                                string         extNFe      = Propriedade.Extensao(Propriedade.TipoEnvio.NFe).EnvioXML;
                                string         extProcNFe  = Propriedade.ExtRetorno.ProcNFe;
                                string         arquivoSit  = string.Empty;
                                string         chNFe       = string.Empty;

                                switch (doc.DocumentElement.Name)
                                {
                                case "MDFe":
                                    tipoArquivo = TipoAplicativo.MDFe;
                                    extNFe      = Propriedade.Extensao(Propriedade.TipoEnvio.MDFe).EnvioXML;
                                    extProcNFe  = Propriedade.ExtRetorno.ProcMDFe;

                                    oLerXml.Mdfe(doc);
                                    arquivoSit = oLerXml.oDadosNfe.chavenfe.Substring(4);
                                    chNFe      = oLerXml.oDadosNfe.chavenfe.Substring(4);
                                    break;

                                case "NFe":
                                    tipoArquivo = TipoAplicativo.Nfe;
                                    extNFe      = Propriedade.Extensao(Propriedade.TipoEnvio.NFe).EnvioXML;
                                    extProcNFe  = Propriedade.ExtRetorno.ProcNFe;

                                    oLerXml.Nfe(doc);
                                    arquivoSit = oLerXml.oDadosNfe.chavenfe.Substring(3);
                                    chNFe      = oLerXml.oDadosNfe.chavenfe.Substring(3);
                                    break;

                                case "CTe":
                                    tipoArquivo = TipoAplicativo.Cte;
                                    extNFe      = Propriedade.Extensao(Propriedade.TipoEnvio.CTe).EnvioXML;
                                    extProcNFe  = Propriedade.ExtRetorno.ProcCTe;

                                    oLerXml.Cte(doc);
                                    arquivoSit = oLerXml.oDadosNfe.chavenfe.Substring(3);
                                    chNFe      = oLerXml.oDadosNfe.chavenfe.Substring(3);
                                    break;
                                }

                                //Ler a NFe

                                //Verificar se o -nfe.xml existe na pasta de autorizados
                                bool NFeJaNaAutorizada = oAux.EstaAutorizada(file, oLerXml.oDadosNfe.dEmi, extNFe, extNFe);

                                //Verificar se o -procNfe.xml existe na past de autorizados
                                bool procNFeJaNaAutorizada = oAux.EstaAutorizada(file, oLerXml.oDadosNfe.dEmi, extNFe, extProcNFe);

                                //Se um dos XML´s não estiver na pasta de autorizadas ele força finalizar o processo da NFe.
                                if (!NFeJaNaAutorizada || !procNFeJaNaAutorizada)
                                {
                                    //Verificar se a NFe está no fluxo, se não estiver vamos incluir ela para que funcione
                                    //a rotina de gerar o -procNFe.xml corretamente. Wandrey 21/10/2009
                                    if (!fluxo.NfeExiste(oLerXml.oDadosNfe.chavenfe))
                                    {
                                        fluxo.InserirNfeFluxo(oLerXml.oDadosNfe.chavenfe, oLerXml.oDadosNfe.mod, file);
                                    }

                                    //gera um -ped-sit.xml mesmo sendo autorizada ou denegada, pois assim sendo, o ERP precisaria dele
                                    oGerarXml.Consulta(tipoArquivo, arquivoSit + Propriedade.Extensao(Propriedade.TipoEnvio.PedSit).EnvioXML,
                                                       Convert.ToInt32(oLerXml.oDadosNfe.tpAmb),
                                                       Convert.ToInt32(oLerXml.oDadosNfe.tpEmis),
                                                       chNFe,
                                                       oLerXml.oDadosNfe.versao);
                                }
                                else
                                {
                                    //Move o XML da pasta em processamento para a pasta de XML´s com erro (-nfe.xml)
                                    oAux.MoveArqErro(file);

                                    //Move o XML da pasta em processamento para a pasta de XML´s com erro (-procNFe.xml)
                                    oAux.MoveArqErro(Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" + PastaEnviados.EmProcessamento.ToString() + "\\" + Functions.ExtrairNomeArq(file, extNFe) + extProcNFe);

                                    //Tirar a nota fiscal do fluxo
                                    fluxo.ExcluirNfeFluxo(oLerXml.oDadosNfe.chavenfe);
                                }
                            }
                            catch (Exception ex)
                            {
                                try
                                {
                                    // grava o arquivo com extensao .ERR
                                    oAux.GravarArqErroERP(Path.GetFileNameWithoutExtension(file) + ".err", ex.Message);
                                }
                                catch
                                {
                                    //Se deu erro na hora de gravar o erro para o ERP, infelizmente não posso fazer mais nada. Wandrey 28/04/2011
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                try
                {
                    // grava o arquivo generico
                    oAux.GravarArqErroERP(string.Format(Propriedade.NomeArqERRUniNFe, DateTime.Now.ToString("yyyyMMddTHHmmss")), ex.Message);
                }
                catch
                {
                    //Se deu erro na hora de gravar o erro para o ERP, infelizmente não posso fazer mais nada. Wandrey 28/04/2011
                }
            }
        }
Пример #20
0
        /// <summary>
        /// Converter arquivos de NFe no formato TXT para XML
        /// </summary>
        /// <by>Wandrey Mundin Ferreira</by>
        /// <date>03/069/2009</date>
        protected void ConvTXT(string vPasta)
        {
            int      emp  = new FindEmpresaThread(Thread.CurrentThread).Index;
            Auxiliar oAux = new Auxiliar();

            List <string> lstArquivos = this.ArquivosPasta(vPasta /*ConfiguracaoApp.vPastaXMLEnvio*/, "*-nfe.txt");

            for (int i = 0; i < lstArquivos.Count; i++)
            {
                if (Auxiliar.FileInUse(lstArquivos[i]))
                {
                    continue;
                }

                UnitxtTOxmlClass oUniTxtToXml = new UnitxtTOxmlClass();
                string           ccMessage    = string.Empty;
                string           ccExtension  = "-nfe.err";

                try
                {
                    ///
                    /// exclui o arquivo de erro
                    ///
                    oAux.DeletarArquivo(Empresa.Configuracoes[emp].PastaRetorno + "\\" + Path.GetFileName(oAux.ExtrairNomeArq(lstArquivos[i], "-nfe.txt") + ccExtension));
                    oAux.DeletarArquivo(Empresa.Configuracoes[emp].PastaRetorno + "\\" + Path.GetFileName(oAux.ExtrairNomeArq(lstArquivos[i], "-nfe.txt") + "-nfe-ret.xml"));
                    oAux.DeletarArquivo(Empresa.Configuracoes[emp].PastaErro + "\\" + Path.GetFileName(lstArquivos[i]));
                    ///
                    /// exclui o arquivo TXT original
                    ///
                    oAux.DeletarArquivo(Empresa.Configuracoes[emp].PastaRetorno + "\\" + Path.GetFileNameWithoutExtension(lstArquivos[i]) + "-orig.txt");

                    ///
                    /// processa a conversão
                    ///
                    oUniTxtToXml.Converter(lstArquivos[i], vPasta /*ConfiguracaoApp.vPastaXMLEnvio*/);

                    //Deu tudo certo com a conversão?
                    if (string.IsNullOrEmpty(oUniTxtToXml.cMensagemErro))
                    {
                        ///
                        /// danasa 8-2009
                        ///
                        if (oUniTxtToXml.cRetorno.Count == 0)
                        {
                            ccMessage = "cStat=02\r\n" +
                                        "xMotivo=Falha na conversão. Sem informações para converter o arquivo texto";

                            oAux.MoveArqErro(lstArquivos[i], ".txt");
                        }
                        else
                        {
                            ///
                            /// salva o arquivo texto original
                            ///
                            FileInfo otxtArquivo = new FileInfo(lstArquivos[i]);
                            if (vPasta.Equals(Empresa.Configuracoes[emp].PastaEnvio))
                            {
                                string vvNomeArquivoDestino = Empresa.Configuracoes[emp].PastaRetorno + "\\" + Path.GetFileNameWithoutExtension(lstArquivos[i]) + "-orig.txt";
                                otxtArquivo.MoveTo(vvNomeArquivoDestino);
                            }
                            ccExtension = "-nfe.txt";
                            ccMessage   = "cStat=01\r\n" +
                                          "xMotivo=Convertido com sucesso. Foi(ram) convertida(s) " + oUniTxtToXml.cRetorno.Count.ToString() + " nota(s) fiscal(is)";

                            foreach (txtTOxmlClassRetorno txtClass in oUniTxtToXml.cRetorno)
                            {
                                ///
                                /// monta o texto que será gravado no arquivo de aviso ao ERP
                                ///
                                ccMessage += Environment.NewLine +
                                             "Nota fiscal: " + txtClass.NotaFiscal.ToString("000000000") +
                                             " Série: " + txtClass.Serie.ToString("000") +
                                             " - ChaveNFe: " + txtClass.ChaveNFe;
                                ///
                                /// move o arquivo XML criado na pasta Envio\Convertidos para a pasta Envio
                                /// ou
                                /// move o arquivo XML criado na pasta Validar\Convertidos para a pasta Validar
                                ///
                                FileInfo oArquivo = new FileInfo(vPasta /*ConfiguracaoApp.vPastaXMLEnvio*/ + "\\convertidos\\" + txtClass.XMLFileName);

                                string vNomeArquivoDestino = vPasta /*ConfiguracaoApp.vPastaXMLEnvio*/ + "\\" + txtClass.XMLFileName;
                                ///
                                /// excluo o XML se já existe
                                ///
                                oAux.DeletarArquivo(vNomeArquivoDestino);

                                ///
                                /// move o arquivo da pasta "Envio\Convertidos" para a pasta "Envio"
                                /// ou
                                /// move o arquivo da pasta "Validar\Convertidos" para a pasta "Validar"
                                ///
                                oArquivo.MoveTo(vNomeArquivoDestino);
                            }
                        }
                    }
                    else
                    {
                        ///
                        /// danasa 8-2009
                        ///
                        ccMessage = "cStat=99\r\n" +
                                    "xMotivo=Falha na conversão\r\n" +
                                    "MensagemErro=" + oUniTxtToXml.cMensagemErro;
                    }
                }
                catch (Exception ex)
                {
                    ccMessage   = ex.Message;
                    ccExtension = "-nfe.err";
                }

                if (!string.IsNullOrEmpty(ccMessage))
                {
                    oAux.MoveArqErro(lstArquivos[i], ".txt");
                    ///
                    /// exclui todos os XML gerados na pasta Enviados\convertidos
                    ///
                    foreach (txtTOxmlClassRetorno txtClass in oUniTxtToXml.cRetorno)
                    {
                        oAux.DeletarArquivo(vPasta /*ConfiguracaoApp.vPastaXMLEnvio*/ + "\\convertidos\\" + txtClass.XMLFileName);
                    }
                    ///
                    /// danasa 8-2009
                    ///
                    /// Gravar o retorno para o ERP em formato TXT com o erro ocorrido
                    ///
                    oAux.GravarArqErroERP(oAux.ExtrairNomeArq(lstArquivos[i], "-nfe.txt") + ccExtension, ccMessage);
                }
            }
        }
Пример #21
0
        private void LeRetornoDFe(int emp, XmlDocument doc)
        {
            /*
             * if (string.IsNullOrEmpty(Empresas.Configuracoes[emp].PastaDownloadNFeDest))
             * {
             *  ///
             *  /// nao interpreto como erro, já que o ERP pode não querer descompactar os arquivos
             *  ///
             *  Auxiliar.WriteLog("LeRetornoNFe: Pasta de DownloadNFeDest nao definida");
             *  return;
             * }
             */

            try
            {
                ///
                /// pega o nome base dos arquivos a serem gravados
                ///
                string fileRetorno2 = Functions.ExtrairNomeArq(Path.GetFileName(this.NomeArquivoXML), Propriedade.ExtEnvio.EnvDFe_XML);
                ///
                /// pega o nome do arquivo de retorno
                ///
                string fileRetorno = Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno,
                                                  fileRetorno2 + Propriedade.ExtRetorno.retEnvDFe_XML);

                if (!File.Exists(fileRetorno))
                {
                    return;
                }
                ///
                /// cria a pasta para comportar as notas e eventos retornados já descompactados
                ///
                string folderTerceiros = Path.Combine(Empresas.Configuracoes[emp].PastaXmlRetorno, "dfe");
                if (!Directory.Exists(folderTerceiros))
                {
                    Directory.CreateDirectory(folderTerceiros);
                }

                ///
                /// exclui todos os arquivos que foram envolvidos no retorno
                ///
                foreach (var item in Directory.GetFiles(folderTerceiros, fileRetorno2 + "-*.xml", SearchOption.TopDirectoryOnly))
                {
                    if (!Functions.FileInUse(item))
                    {
                        File.Delete(item);
                    }
                }

                doc.Load(fileRetorno);
                XmlNodeList envEventoList = doc.GetElementsByTagName("retDistDFeInt");
                foreach (XmlNode ret1Node in envEventoList)
                {
                    XmlElement ret1Elemento = (XmlElement)ret1Node;

                    XmlNodeList ret1List = ret1Elemento.GetElementsByTagName("loteDistDFeInt");
                    foreach (XmlNode ret in ret1List)
                    {
                        for (int n = 0; n < ret.ChildNodes.Count; ++n)
                        {
                            if (ret.ChildNodes[n].Name.Equals("docZip"))
                            {
                                string FileToFtp = "";
                                string NSU       = ret.ChildNodes[n].Attributes[TpcnResources.NSU.ToString()].Value;

                                ///
                                /// descompacta o conteudo
                                ///
                                string xmlRes = TFunctions.Decompress(ret.ChildNodes[n].InnerText);
                                if (string.IsNullOrEmpty(xmlRes))
                                {
                                    Auxiliar.WriteLog("LeRetornoNFe: Não foi possivel descompactar o conteudo da NSU: " + NSU, false);
                                }
                                else
                                {
                                    if (ret.ChildNodes[n].Attributes["schema"].InnerText.StartsWith("resEvento"))
                                    {
                                        FileToFtp = Path.Combine(folderTerceiros, fileRetorno2 + "-" + NSU + Propriedade.ExtRetorno.Eve);
                                    }
                                    else if (ret.ChildNodes[n].Attributes["schema"].InnerText.StartsWith("procEventoNFe"))
                                    {
                                        FileToFtp = Path.Combine(folderTerceiros, fileRetorno2 + "-" + NSU + Propriedade.ExtRetorno.ProcEventoNFe);
                                    }
                                    else if (ret.ChildNodes[n].Attributes["schema"].InnerText.StartsWith("procNFe"))
                                    {
                                        FileToFtp = Path.Combine(folderTerceiros, fileRetorno2 + "-" + NSU + Propriedade.ExtRetorno.ProcNFe);
                                    }
                                    else if (ret.ChildNodes[n].Attributes["schema"].InnerText.StartsWith("resNFe"))
                                    {
                                        FileToFtp = Path.Combine(folderTerceiros, fileRetorno2 + "-" + NSU + Propriedade.ExtEnvio.Nfe);
                                    }
                                    else
                                    {
                                        Auxiliar.WriteLog("LerRetornoDFe:  Nao foi possivel ler o schema", false);
                                    }

                                    if (FileToFtp != "")
                                    {
                                        if (!File.Exists(FileToFtp))
                                        {
                                            File.WriteAllText(FileToFtp, xmlRes);
                                        }

                                        string vFolder = Empresas.Configuracoes[emp].FTPPastaRetornos;
                                        if (!string.IsNullOrEmpty(vFolder))
                                        {
                                            try
                                            {
                                                Empresas.Configuracoes[emp].SendFileToFTP(FileToFtp, vFolder);
                                            }
                                            catch (Exception ex)
                                            {
                                                ///
                                                /// grava um arquivo de erro com extensao "FTP" para diferenciar dos arquivos de erro
                                                oAux.GravarArqErroERP(Path.ChangeExtension(fileRetorno, ".ftp"), ex.Message);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                Auxiliar.WriteLog("LeRetornoNFe: " + ex.Message, false);
                ///
                /// Wandrey.
                /// Foi tudo processado mas houve algum erro na descompactacao dos retornos
                /// Se gravar o arquivo com extensao .err, o ERP pode ignorar o XML de retorno, que está correto
                ///
                //WriteLogError(ex);
            }
        }
Пример #22
0
        /// <summary>
        /// Efetua um select na base e retorna uma list de objeto T com base em um filtro e order by
        /// <c> List<Usuario> lista = DAL.ListarObjetos<Usuario>(typeof(Usuario));</c>
        /// </summary>
        /// <typeparam name="E">Tipo do List de retorno</typeparam>
        /// <param name="filtro">Use a classe Filtros para montar o filtro</param>
        /// <param name="ordem">É string, mas ao invés de passar os campos diretamente, use a classe Order</param>
        /// <returns>Retorna uma List de instâncias do Tipo</returns>
        public static List <E> ListarObjetos <E>(string filtro = "", string ordem = "", string group = "") where E : class, new()
        {
            List <E> list = new List <E>();
            string   sql  = GetSqlSelect(new E(), filtro, ordem, group);

            using (MySqlConnection conexao = new MySqlConnection(GetStringConexao()))
                using (Comando comando = new Comando(conexao, sql))
                {
                    //conexao.Open();
                    using (Leitor leitor = comando.Select())
                    {
                        var    typeName = "";
                        object valor    = null;

                        try
                        {
                            while (!leitor.Eof)
                            {
                                // cria uma instância do objeto
                                E item = new E();

                                // percorre as propriedades
                                foreach (PropertyInfo property in Auxiliar.PropertySimple(item))
                                {
                                    // valor busta pelo nome do campo
                                    valor = leitor.GetObject(Auxiliar.GetColumnName(property));

                                    if ((valor != null) && (!(valor is DBNull)))
                                    {
                                        typeName = valor.GetType().Name;

                                        if (typeName.Equals("TimeSpan"))
                                        {
                                            property.SetValue(item, valor.ToString());
                                        }
                                        else if (typeName.Equals("SByte"))
                                        {
                                            property.SetValue(item, (sbyte)valor == 1 ? true : false);
                                        }
                                        else if (typeName.Equals("Boolean"))
                                        {
                                            property.SetValue(item, (Boolean)valor);
                                        }
                                        else
                                        {
                                            property.SetValue(item, valor);
                                        }
                                    }
                                }
                                list.Add(item);

                                //Proximo
                                leitor.Next();
                            }
                        }
                        catch (Exception ex)
                        {
                            //  Console.WriteLine("Exception source: {0}", ex.Source);
                        }
                    }
                }
            return(list);
        }
Пример #23
0
        public ActionResult Edit(UsuarioViewModel usuarioMod)
        {
            if (!User.Identity.IsAuthenticated)
            {
                return(RedirectToAction("Logout", "Account"));
            }

            if (string.IsNullOrEmpty(HttpContext.Session.GetString("cod_rol")))
            {
                return(RedirectToAction("Logout", "Account"));
            }

            if (usuarioMod == null)
            {
                return(RedirectToAction("Logout", "Account"));
            }

            var provincias = (from Provincia in auc.PROVINCIA
                              where Provincia.COD_PROVINCIA > 0 && Provincia.COD_PROVINCIA < 26
                              orderby Provincia.NOM_PROVINCIA
                              select new SelectListItem()
            {
                Text = Provincia.NOM_PROVINCIA,
                Value = Provincia.COD_PROVINCIA.ToString()
            }).ToList();

            provincias.Insert(0, new SelectListItem()
            {
                Text  = "----Elija Provincia----",
                Value = string.Empty
            });

            var roles = (from Rol in auc.ROL
                         where Rol.COD_ROL > 1
                         select new SelectListItem()
            {
                Text = Rol.DES_ROL,
                Value = Rol.COD_ROL.ToString(),
                Selected = false
            }).ToList();

            roles.Insert(0, new SelectListItem()
            {
                Text  = "----Elija Rol----",
                Value = string.Empty
            });

            usuarioMod.provincias = provincias;
            usuarioMod.roles      = roles;

            auxiliar = new Auxiliar();

            if (!auxiliar.validarCedula(usuarioMod.CEDULA))
            {
                ModelState.AddModelError(string.Empty, "La cédula ingresada es incorrecta.");
                return(View(usuarioMod));
            }

            UsuarioResponse usuario = new UsuarioResponse()
            {
                CEDULA           = usuarioMod.CEDULA.Substring(0, 9),
                CODIGO_PROVINCIA = usuarioMod.codProvincia,
                CODIGO_ROL       = usuarioMod.codRol,
                COD_USUARIO      = usuarioMod.COD_USUARIO,
                DIGITO           = usuarioMod.DIGITO,
                ESTADO           = usuarioMod.ESTADO,
                LOGEO            = usuarioMod.LOGEO,
                MAIL             = usuarioMod.MAIL,
                NOMBRE           = usuarioMod.NOMBRE,
                TELEFONO         = usuarioMod.TELEFONO,
                PROVINCIA        = usuarioMod.PROVINCIA,
                ROL = usuarioMod.ROL
            };

            try
            {
                Usuario respuesta = servicioUsuario.ActualizaUsuario(usuario);
                if (respuesta == null)
                {
                    //ViewBag.Message = ;
                    ModelState.AddModelError(string.Empty, "Cédula o correo no permitito(pertenecen a otro usuario)");
                    return(View(usuarioMod));
                }
                else
                {
                    ModelState.AddModelError(string.Empty, "Usuario actualizado exitosamente!");
                    return(View(usuarioMod));
                    //return RedirectToAction("Index");
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, "Error al actualizar");
                return(View(usuarioMod));
            }
        }
Пример #24
0
        public ConverterTXT(string arquivo)
        {
            Auxiliar oAux = new Auxiliar();

            NFe.ConvertTxt.ConversaoTXT oUniTxtToXml = new NFe.ConvertTxt.ConversaoTXT();

            string pasta = new FileInfo(arquivo).DirectoryName;

            pasta = pasta.Substring(0, pasta.Length - 5); //Retirar a pasta \Temp do final - Wandrey 03/08/2011

            string ccMessage   = string.Empty;
            string ccExtension = Propriedade.ExtRetorno.Nfe_ERR;// "-nfe.err";
            var    EXT         = Propriedade.Extensao(Propriedade.TipoEnvio.NFe);

            try
            {
                int emp = Empresas.FindEmpresaByThread();

                ///
                /// exclui o arquivo de erro
                ///
                Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlRetorno + "\\" + Path.GetFileName(Functions.ExtrairNomeArq(arquivo, EXT.EnvioTXT) + ccExtension));
                Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlRetorno + "\\" + Path.GetFileName(Functions.ExtrairNomeArq(arquivo, EXT.EnvioTXT) + EXT.RetornoXML));
                Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlErro + "\\" + Path.GetFileName(arquivo));
                ///
                /// exclui o arquivo TXT original
                ///
                Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlRetorno + "\\" + Path.GetFileNameWithoutExtension(arquivo) + "-orig.txt");

                ///
                /// processa a conversão
                ///
                oUniTxtToXml.Converter(arquivo, pasta);//Empresas.Configuracoes[emp].PastaRetorno);

                //Deu tudo certo com a conversão?
                if (string.IsNullOrEmpty(oUniTxtToXml.cMensagemErro))
                {
                    ///
                    /// danasa 8-2009
                    ///
                    if (oUniTxtToXml.cRetorno.Count == 0)
                    {
                        ccMessage = "cStat=02\r\n" +
                                    "xMotivo=Falha na conversão. Sem informações para converter o arquivo texto";

                        oAux.MoveArqErro(arquivo, ".txt");
                    }
                    else
                    {
                        //
                        // salva o arquivo texto original
                        //
                        if (pasta.ToLower().Equals(Empresas.Configuracoes[emp].PastaXmlEnvio.ToLower()) || pasta.ToLower().Equals(Empresas.Configuracoes[emp].PastaValidar.ToLower()))
                        {
                            FileInfo ArqOrig = new FileInfo(arquivo);

                            string vvNomeArquivoDestino = Empresas.Configuracoes[emp].PastaXmlRetorno + "\\" + Path.GetFileNameWithoutExtension(arquivo) + "-orig.txt";
                            ArqOrig.MoveTo(vvNomeArquivoDestino);
                        }
                        ccExtension = "-nfe.txt";
                        ccMessage   = "cStat=01\r\n" +
                                      "xMotivo=Conversão efetuada com sucesso." + (oUniTxtToXml.cRetorno.Count == 1 ? "" : " Foram convertidas " + oUniTxtToXml.cRetorno.Count.ToString() + " notas fiscais");

                        foreach (NFe.ConvertTxt.txtTOxmlClassRetorno txtClass in oUniTxtToXml.cRetorno)
                        {
                            ///
                            /// monta o texto que será gravado no arquivo de aviso ao ERP
                            ///
                            ccMessage += Environment.NewLine +
                                         "Nota fiscal: " + txtClass.NotaFiscal.ToString("000000000") +
                                         " Serie: " + txtClass.Serie.ToString("000") +
                                         " - ChaveNFe: " + txtClass.ChaveNFe;

                            // move o arquivo XML criado na pasta Envio\Convertidos para a pasta Envio
                            // ou
                            // move o arquivo XML criado na pasta Validar\Convertidos para a pasta Validar
                            string nomeArquivoDestino = Path.Combine(pasta, Path.GetFileName(txtClass.XMLFileName));
                            Functions.Move(txtClass.XMLFileName, nomeArquivoDestino);

                            Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlErro + "\\" + txtClass.ChaveNFe + EXT.EnvioXML);
                            Functions.DeletarArquivo(Empresas.Configuracoes[emp].PastaXmlErro + "\\" + txtClass.ChaveNFe + EXT.EnvioTXT);
                        }
                    }
                }
                else
                {
                    ///
                    /// danasa 8-2009
                    ///
                    ccMessage = "cStat=99\r\n" +
                                "xMotivo=Falha na conversão\r\n" +
                                "MensagemErro=" + oUniTxtToXml.cMensagemErro;
                }
            }
            catch (Exception ex)
            {
                ccMessage   = ex.Message;
                ccExtension = Propriedade.ExtRetorno.Nfe_ERR;//"-nfe.err";
            }

            if (!string.IsNullOrEmpty(ccMessage))
            {
                oAux.MoveArqErro(arquivo, ".txt");

                if (ccMessage.StartsWith("cStat=02") || ccMessage.StartsWith("cStat=99"))
                {
                    ///
                    /// exclui todos os XML gerados na pasta Envio\convertidos somente se houve erro na conversão
                    ///
                    foreach (NFe.ConvertTxt.txtTOxmlClassRetorno txtClass in oUniTxtToXml.cRetorno)
                    {
                        Functions.DeletarArquivo(pasta + "\\convertidos\\" + Path.GetFileName(txtClass.XMLFileName));
                    }
                }
                ///
                /// danasa 8-2009
                ///
                /// Gravar o retorno para o ERP em formato TXT com o erro ocorrido
                ///
                oAux.GravarArqErroERP(Functions.ExtrairNomeArq(arquivo, EXT.EnvioTXT) + ccExtension, ccMessage);
            }
        }
Пример #25
0
        static void Main(string[] args)
        {
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler((sender, e) =>
            {
                Auxiliar.WriteLog(e.Exception.Message + "\r\n" + e.Exception.StackTrace, false);
                if (e.Exception.InnerException != null)
                {
                    Auxiliar.WriteLog(e.Exception.InnerException.Message + "\r\n" + e.Exception.InnerException.StackTrace, false);

                    if (e.Exception.InnerException.InnerException != null)
                    {
                        Auxiliar.WriteLog(e.Exception.InnerException.InnerException.Message + "\r\n" + e.Exception.InnerException.InnerException.StackTrace, false);
                    }

                    if (e.Exception.InnerException.InnerException.InnerException != null)
                    {
                        Auxiliar.WriteLog(e.Exception.InnerException.InnerException.InnerException.Message + "\r\n" + e.Exception.InnerException.InnerException.InnerException.StackTrace, false);
                    }
                }
            });

            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler((sender, e) =>
            {
                Auxiliar.WriteLog(e.ExceptionObject.ToString(), false);
            });
            //Esta deve ser a primeira linha do Main, não coloque nada antes dela. Wandrey 31/07/2009
            Propriedade.AssemblyEXE = Assembly.GetExecutingAssembly();

            bool silencioso = false;

            ConfiguracaoApp.AtualizaWSDL = false;

            if (args.Length >= 1)
            {
                foreach (string param in args)
                {
                    if (param.ToLower().Equals("/silent"))
                    {
                        silencioso = true;
                        continue;
                    }
                    if (param.ToLower().Equals("/updatewsdl"))
                    {
                        ConfiguracaoApp.AtualizaWSDL = true;
                        continue;
                    }
                    if (param.ToLower().Equals("/quit") || param.ToLower().Equals("/restart"))
                    {
                        string procName = System.Diagnostics.Process.GetCurrentProcess().ProcessName;
                        int    Id       = System.Diagnostics.Process.GetCurrentProcess().Id;

                        foreach (System.Diagnostics.Process clsProcess in System.Diagnostics.Process.GetProcesses())
                        {
                            if (clsProcess.ProcessName.Equals(procName))
                            {
                                try
                                {
                                    if (param.ToLower().Equals("/quit") ||
                                        (param.ToLower().Equals("/restart") && clsProcess.Id != Id))
                                    {
                                        Empresas.ClearLockFiles(false);
                                        clsProcess.Kill();
                                    }
                                }
                                catch
                                {
                                }
                                if (param.ToLower().Equals("/quit"))
                                {
                                    return;
                                }
                            }
                        }
                    }
                }
            }

            Propriedade.TipoAplicativo = TipoAplicativo.Nfe;

            if (Aplicacao.AppExecutando(silencioso, true))
            {
                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new MainForm());
        }
Пример #26
0
        /// <summary>
        /// Evento é executado quando a thread vai finalizar
        /// </summary>
        /// <param name="item"></param>
        protected void ThreadItem_OnEnded(ThreadItem item)
        {
            int listCount = FileSystemWatcher._pool.Release();

            Auxiliar.WriteLog("O arquivo " + item.FileInfo.FullName + " finalizou o processamento. Itens disponiveis no Semaforo (" + listCount.ToString() + "). (Data criação: " + item.FileInfo.LastWriteTime + ")", false);
        }
Пример #27
0
        // GET: IndexModelsCuptor
        public async Task <IActionResult> Index()
        {
            List <IndexModel> listaDeAfisat = await _context.IndexModels.ToListAsync();

            return(View(listaDeAfisat.Where(model => model.PlcName == "PlcCuptor" && Auxiliar.IsCurrentMonth(Auxiliar.ReturnareDataFromString(model.Data)))));
        }
Пример #28
0
        /// <summary>
        /// Grava XML com algumas informações do aplicativo, dentre elas os dados do certificado digital configurado nos parâmetros, versão, última modificação, etc.
        /// </summary>
        /// <param name="sArquivo">Pasta e nome do arquivo XML a ser gravado com as informações</param>
        public void GravarXMLInformacoes(string sArquivo)
        {
            int emp = Empresas.FindEmpresaByThread();

            string cStat   = "1";
            string xMotivo = "Consulta efetuada com sucesso";

            //Ler os dados do certificado digital
            string sSubject = "";
            string sValIni  = "";
            string sValFin  = "";

            CertificadoDigital cert = new CertificadoDigital();

            if (cert.PrepInfCertificado(Empresas.Configuracoes[emp]))
            {
                sSubject = cert.sSubject;
                sValIni  = cert.dValidadeInicial.ToString();
                sValFin  = cert.dValidadeFinal.ToString();
            }
            else
            {
                if (!Empresas.Configuracoes[emp].UsaCertificado)
                {
                    xMotivo = "Empresa sem certificado digital informado e/ou não necessário";
                }
                else
                {
                    cStat   = "2";
                    xMotivo = "Certificado digital não foi localizado";
                }
            }

            //danasa 22/7/2011
            //pega a data da ultima modificacao do 'uninfe.exe' diretamente porque pode ser que esteja sendo executado o servico
            //então, precisamos dos dados do uninfe.exe e não do servico
            string dtUltModif;
            URLws  item;
            string tipo = "";

            dtUltModif = File.GetLastWriteTime(Propriedade.NomeAplicacao + ".exe").ToString("dd/MM/yyyy - HH:mm:ss");

            //Gravar o XML com as informações do aplicativo
            try
            {
                bool   isXml = false;
                object oXmlGravar;

                if (Path.GetExtension(sArquivo).ToLower() == ".txt")
                {
                    oXmlGravar = new System.IO.StringWriter();
                }
                else
                {
                    isXml = true;

                    XmlWriterSettings oSettings = new XmlWriterSettings();
                    UTF8Encoding      c         = new UTF8Encoding(true);

                    //Para começar, vamos criar um XmlWriterSettings para configurar nosso XML
                    oSettings.Encoding            = c;
                    oSettings.Indent              = true;
                    oSettings.IndentChars         = "";
                    oSettings.NewLineOnAttributes = false;
                    oSettings.OmitXmlDeclaration  = false;

                    //Agora vamos criar um XML Writer
                    oXmlGravar = XmlWriter.Create(sArquivo, oSettings);
                }
                //Abrir o XML
                if (isXml)
                {
                    ((XmlWriter)oXmlGravar).WriteStartDocument();
                    ((XmlWriter)oXmlGravar).WriteStartElement("retConsInf");
                }
                Functions.GravaTxtXml(oXmlGravar, NFe.Components.TpcnResources.cStat.ToString(), cStat);
                Functions.GravaTxtXml(oXmlGravar, NFe.Components.TpcnResources.xMotivo.ToString(), xMotivo);

                //Dados do certificado digital
                if (isXml)
                {
                    ((XmlWriter)oXmlGravar).WriteStartElement("DadosCertificado");
                }
                Functions.GravaTxtXml(oXmlGravar, "sSubject", sSubject);
                Functions.GravaTxtXml(oXmlGravar, "dValIni", sValIni);
                Functions.GravaTxtXml(oXmlGravar, "dValFin", sValFin);
                if (isXml)
                {
                    ((XmlWriter)oXmlGravar).WriteEndElement();        //DadosCertificado
                }
                //Dados gerais do Aplicativo
                if (isXml)
                {
                    ((XmlWriter)oXmlGravar).WriteStartElement("DadosUniNfe");
                }
                Functions.GravaTxtXml(oXmlGravar, NFe.Components.TpcnResources.versao.ToString(), Propriedade.Versao);
                Functions.GravaTxtXml(oXmlGravar, "dUltModif", dtUltModif);
                Functions.GravaTxtXml(oXmlGravar, "PastaExecutavel", Propriedade.PastaExecutavel);
                Functions.GravaTxtXml(oXmlGravar, "NomeComputador", Environment.MachineName);
                //danasa 22/7/2011
                Functions.GravaTxtXml(oXmlGravar, "ExecutandoPeloServico", Propriedade.ServicoRodando.ToString());
                if (isXml)
                {
                    ((XmlWriter)oXmlGravar).WriteEndElement();        //DadosUniNfe
                }
                //Dados das configurações do aplicativo
                if (isXml)
                {
                    ((XmlWriter)oXmlGravar).WriteStartElement(NFeStrConstants.nfe_configuracoes);
                }
                Functions.GravaTxtXml(oXmlGravar, NFe.Components.NFeStrConstants.DiretorioSalvarComo, Empresas.Configuracoes[emp].DiretorioSalvarComo.ToString());

                bool hasFTP = false;
                foreach (var pT in Empresas.Configuracoes[emp].GetType().GetProperties())
                {
                    if (pT.CanWrite)
                    {
                        if (isXml)
                        {
                            if (!hasFTP && pT.Name.StartsWith("FTP"))
                            {
                                ((XmlWriter)oXmlGravar).WriteStartElement("FTP");
                                hasFTP = true;
                            }
                            else
                            if (hasFTP && !pT.Name.StartsWith("FTP"))
                            {
                                ((XmlWriter)oXmlGravar).WriteEndElement();
                                hasFTP = false;
                            }
                        }
                        object v = pT.GetValue(Empresas.Configuracoes[emp], null);
                        NFe.Components.Functions.GravaTxtXml(oXmlGravar, pT.Name, v == null ? "" : v.ToString());
                    }
                }
                if (hasFTP && isXml)
                {
                    ((XmlWriter)oXmlGravar).WriteEndElement();
                }

                ///
                /// o ERP poderá verificar se determinado servico está definido no UniNFe
                ///
                foreach (webServices list in WebServiceProxy.webServicesList)
                {
                    if (list.ID == Empresas.Configuracoes[emp].UnidadeFederativaCodigo ||
                        list.UF == "DPEC")
                    {
                        if (isXml)
                        {
                            ((XmlWriter)oXmlGravar).WriteStartElement(list.UF);
                        }
                        if (Empresas.Configuracoes[emp].AmbienteCodigo == 2)
                        {
                            item = list.LocalHomologacao;
                            if (isXml)
                            {
                                ((XmlWriter)oXmlGravar).WriteStartElement("Homologacao");
                            }
                            else
                            {
                                tipo = list.UF + ".Homologacao.";
                            }
                        }
                        else
                        {
                            item = list.LocalProducao;
                            if (isXml)
                            {
                                ((XmlWriter)oXmlGravar).WriteStartElement("Producao");
                            }
                            else
                            {
                                tipo = list.UF + ".Producao.";
                            }
                        }
                        switch (Empresas.Configuracoes[emp].Servico)
                        {
                        case TipoAplicativo.Nfse:
                            Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.NFSeCancelar.ToString(), (!string.IsNullOrEmpty(item.CancelarNfse)).ToString());
                            Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.NFSeConsultarLoteRps.ToString(), (!string.IsNullOrEmpty(item.ConsultarLoteRps)).ToString());
                            Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.NFSeConsultar.ToString(), (!string.IsNullOrEmpty(item.ConsultarNfse)).ToString());
                            Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.NFSeConsultarPorRps.ToString(), (!string.IsNullOrEmpty(item.ConsultarNfsePorRps)).ToString());
                            Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.NFSeConsultarSituacaoLoteRps.ToString(), (!string.IsNullOrEmpty(item.ConsultarSituacaoLoteRps)).ToString());
                            Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.NFSeRecepcionarLoteRps.ToString(), (!string.IsNullOrEmpty(item.RecepcionarLoteRps)).ToString());
                            Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.NFSeConsultarURL.ToString(), (!string.IsNullOrEmpty(item.ConsultarURLNfse)).ToString());
                            break;

                        default:
                            Functions.GravaTxtXml(oXmlGravar, tipo + "NFeConsulta", (!string.IsNullOrEmpty(item.NFeConsulta)).ToString());
                            Functions.GravaTxtXml(oXmlGravar, tipo + "NFeRecepcao", (!string.IsNullOrEmpty(item.NFeRecepcao)).ToString());

                            if (list.UF != "DPEC")
                            {
                                if (Empresas.Configuracoes[emp].Servico == TipoAplicativo.NFCe ||
                                    Empresas.Configuracoes[emp].Servico == TipoAplicativo.Nfe ||
                                    Empresas.Configuracoes[emp].Servico == TipoAplicativo.Todos)
                                {
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "NFeRecepcaoEvento", (!string.IsNullOrEmpty(item.NFeRecepcaoEvento)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "NFeConsultaCadastro", (!string.IsNullOrEmpty(item.NFeConsultaCadastro)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "NFeConsultaNFeDest", (!string.IsNullOrEmpty(item.NFeConsultaNFeDest)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.NFeDownload.ToString(), (!string.IsNullOrEmpty(item.NFeDownload)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "NFeInutilizacao", (!string.IsNullOrEmpty(item.NFeInutilizacao)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "NFeManifDest", (!string.IsNullOrEmpty(item.NFeManifDest)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "NFeStatusServico", (!string.IsNullOrEmpty(item.NFeStatusServico)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "NFeAutorizacao", (!string.IsNullOrEmpty(item.NFeAutorizacao)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "NFeRetAutorizacao", (!string.IsNullOrEmpty(item.NFeRetAutorizacao)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "DFeRecepcao", (!string.IsNullOrEmpty(item.DFeRecepcao)).ToString());
                                }
                                if (Empresas.Configuracoes[emp].Servico == TipoAplicativo.MDFe ||
                                    Empresas.Configuracoes[emp].Servico == TipoAplicativo.Todos)
                                {
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "MDFeRecepcao", (!string.IsNullOrEmpty(item.MDFeRecepcao)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "MDFeRetRecepcao", (!string.IsNullOrEmpty(item.MDFeRetRecepcao)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "MDFeConsulta", (!string.IsNullOrEmpty(item.MDFeConsulta)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "MDFeStatusServico", (!string.IsNullOrEmpty(item.MDFeStatusServico)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.MDFeRecepcaoEvento.ToString(), (!string.IsNullOrEmpty(item.MDFeRecepcaoEvento)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.MDFeConsultaNaoEncerrado.ToString(), (!string.IsNullOrEmpty(item.MDFeNaoEncerrado)).ToString());
                                }
                                if (Empresas.Configuracoes[emp].Servico == TipoAplicativo.Cte ||
                                    Empresas.Configuracoes[emp].Servico == TipoAplicativo.Todos)
                                {
                                    Functions.GravaTxtXml(oXmlGravar, tipo + NFe.Components.Servicos.CTeRecepcaoEvento.ToString(), (!string.IsNullOrEmpty(item.CTeRecepcaoEvento)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "CTeConsultaCadastro", (!string.IsNullOrEmpty(item.CTeConsultaCadastro)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "CTeInutilizacao", (!string.IsNullOrEmpty(item.CTeInutilizacao)).ToString());
                                    Functions.GravaTxtXml(oXmlGravar, tipo + "CTeStatusServico", (!string.IsNullOrEmpty(item.CTeStatusServico)).ToString());
                                }
                            }
                            break;
                        }
                        if (isXml)
                        {
                            ((XmlWriter)oXmlGravar).WriteEndElement();   //Ambiente
                            ((XmlWriter)oXmlGravar).WriteEndElement();   //list.UF
                        }
                    }
                }
                //Finalizar o XML
                if (isXml)
                {
                    ((XmlWriter)oXmlGravar).WriteEndElement(); //nfe_configuracoes
                    ((XmlWriter)oXmlGravar).WriteEndElement(); //retConsInf
                    ((XmlWriter)oXmlGravar).WriteEndDocument();
                    ((XmlWriter)oXmlGravar).Flush();
                    ((XmlWriter)oXmlGravar).Close();
                }
                else
                {
                    ((StringWriter)oXmlGravar).Flush();
                    File.WriteAllText(sArquivo, ((StringWriter)oXmlGravar).GetStringBuilder().ToString(), Encoding.Default);
                    ((StringWriter)oXmlGravar).Close();
                }
            }
            catch (Exception ex)
            {
                Functions.DeletarArquivo(sArquivo);
                ///
                /// danasa 8-2009
                ///
                Auxiliar oAux = new Auxiliar();
                oAux.GravarArqErroERP(Path.GetFileNameWithoutExtension(sArquivo) + ".err", ex.Message);
            }
        }
Пример #29
0
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            try
            {
                if (Request.QueryString["Id_Novedad"] == null)
                {
                    Response.Redirect(VariableSession.PaginaInicio, true);
                }
                if (Request.QueryString["solicitaCompImpedimentoFirma"] == null)
                {
                    Response.Redirect(VariableSession.PaginaInicio, true);
                }

                long idnov = Convert.ToInt64(Request.QueryString["Id_Novedad"].ToString());
                bool solicitaCompImpedimentoFirma = bool.Parse(Request.QueryString["solicitaCompImpedimentoFirma"].ToString());

                log.DebugFormat("Voy a buscar NovedadesTraerXId_TodaCuotas({0})", idnov);

                WSNovedad.Novedad Nov = new WSNovedad.Novedad();
                Nov = Novedad.NovedadesTraerXId_TodaCuotas(idnov);

                if (Nov == null || Nov.IdNovedad == 0)
                {
                    ErrorEnPagina();
                }

                log.Debug("Cargo los datos a la pagina");

                lbl_Solicitud.Text = Nov.IdNovedad.ToString();
                lbl_Sucursal.Text  = Nov.Nro_Sucursal;

                lbl_Monto_Prestamo.Text = Nov.MontoPrestamo.ToString();
                lbl_Cant_Ctas.Text      = Nov.CantidadCuotas.ToString();
                lbl_Ctas_Mensual.Text   = Nov.MensualCuota.ToString();
                lbl_TNA.Text            = Nov.TNA.ToString();
                lbl_CFTEA.Text          = Nov.CFTEAReal.ToString();

                log.DebugFormat("Convierto el Monto del Prestamo: {0} a letras", Nov.MontoPrestamo);

                lbl_Importe_texto.Text = Auxiliar.Convertir_Numero_a_Texto(Nov.MontoPrestamo, true);
                lbl_Importe.Text       = Nov.MontoPrestamo.ToString("0.00");

                log.DebugFormat("Convierto la cantidad de cuotas: {0} a letras", Nov.CantidadCuotas);

                lbl_Cuotas_Texto.Text = Auxiliar.Convertir_Numero_a_Texto(Nov.CantidadCuotas, false);
                lbl_Cuotas.Text       = Nov.CantidadCuotas.ToString();

                lbl_Codigo_Descuento.Text = Nov.UnConceptoLiquidacion.CodConceptoLiq.ToString();
                lbl_Descripcion.Text      = Nov.UnConceptoLiquidacion.DescConceptoLiq;

                lbl_Apellido.Text    = Nov.UnBeneficiario.ApellidoNombre;
                lbl_N_Beneficio.Text = Nov.UnBeneficiario.IdBeneficiario.ToString();

                lbl_CUIL.Text = Util.FormateoCUIL(Nov.UnBeneficiario.Cuil.ToString(), true);

                log.DebugFormat("Busco el domiciolio por id {0}", Nov.IdDomicilioBeneficiario);

                WSBeneficiario.Domicilio unD = new WSBeneficiario.Domicilio();

                string mensajeADP = string.Empty;

                bool domicilio = Beneficiario.TraerDomicilio(Nov.UnBeneficiario.Cuil.ToString(), Nov.IdDomicilioBeneficiario, out unD);

                if (!domicilio)
                {
                    log.Debug("No se encontro un domicilio para el id solicitado");
                    ErrorEnPagina();
                }
                else
                {
                    log.Debug("Cargo el domicilio a la página");

                    string piso = string.IsNullOrEmpty(unD.Piso) ? "" : "&nbsp;&nbsp;&nbsp;Piso: " + unD.Piso;
                    string Dto  = string.IsNullOrEmpty(unD.Departamento) ? "" : "&nbsp;&nbsp;&nbsp;Dto: " + unD.Departamento;


                    lbl_Domicilio.Text = unD.Calle + "&nbsp;&nbsp;&nbsp;N°: " + unD.NumeroCalle + piso + Dto;

                    if (!string.IsNullOrEmpty(unD.NumeroTel))
                    {
                        lbl_Telefono1.Text = unD.EsCelular ? "Celular: " : "" + unD.PrefijoTel + " - " + unD.NumeroTel;
                    }
                    else
                    {
                        lbl_Telefono1.Text = "Sin Información";
                    }

                    if (!string.IsNullOrEmpty(unD.NumeroTel2))
                    {
                        lbl_Telefono2.Text = unD.EsCelular2 ? "Celular: " : "" + unD.PrefijoTel2 + " - " + unD.NumeroTel2;
                    }
                    else
                    {
                        lbl_Telefono2.Text = "Sin Información";
                    }

                    lbl_Mail.Text = unD.Mail;

                    lbl_Localidad.Text = unD.Localidad;
                    lbl_Provincia.Text = Provincia.TraerProvinciasPorId(unD.UnaProvincia.CodProvincia);
                    lbl_CP.Text        = unD.CodigoPostal;
                }

                if (Nov.unaLista_Cuotas.Length <= 0)
                {
                    log.Debug("No hay cuotas para mostrar en la página");
                }
                else
                {
                    log.DebugFormat("Cargo {0} coutas a la página", Nov.unaLista_Cuotas.Length);
                    var nroCuotaMax = (from l in Nov.unaLista_Cuotas
                                       select l.NroCuota).Last();

                    dg_Cuotas.DataSource = (from l in Nov.unaLista_Cuotas
                                            where (l.NroCuota == 1 ||
                                                   l.NroCuota == nroCuotaMax)
                                            select new
                    {
                        nrocuota = l.NroCuota,
                        Intereses = l.Intereses,
                        Amortizacion = l.Amortizacion,
                        Cuota_Pura = l.Intereses + l.Amortizacion,
                        Gastos_Admin = l.Gasto_Adm + l.Gasto_Adm_Tarjeta,
                        Seguro_Vida = l.Seguro_Vida,
                        Importe_Cuota = l.Importe_Cuota
                    });

                    dg_Cuotas.DataBind();
                }

                lbl_Cuil_Operador.Text = "Operador:  " + Nov.UnAuditoria.Usuario;

                DateTime hora = DateTime.Now;

                lbl_Impreso.Text = "Impreso el " + hora.ToString("dd/MM/yyyy") + " a las " + hora.ToString("HH:mm") + " horas.";

                lbl_dia.Text = Nov.FechaNovedad.ToString("dd");
                lbl_Mes.Text = Nov.FechaNovedad.ToString("MMMM");
                lbl_Ano.Text = Nov.FechaNovedad.ToString("yyyy");

                img_CodeBar.ImageUrl = "CB.aspx?a=" + Nov.IdNovedad.ToString("0000000000") + "&now=" + DateTime.Now.Millisecond;

                pnl_Recibo.Visible = string.IsNullOrEmpty(Nov.CBU);
                if (pnl_Recibo.Visible)
                {
                    lbl_Reserva.Text = Nov.Nro_Ticket;

                    lbl_FechaRecibo.Text = Nov.FechaNovedad.ToString("dd") + " de " + Nov.FechaNovedad.ToString("MMMM") + " del " + Nov.FechaNovedad.ToString("yyyy");

                    lbl_importe_Recibo2.Text       = "$ " + Nov.MontoPrestamo.ToString("0.00");
                    lbl_Importe_Letras_recibo.Text = lbl_Importe_texto.Text;
                }

                if (solicitaCompImpedimentoFirma)
                {
                    div_ConsImpedimentoFirma.Visible = true;
                    lbl_FechaCredito.Text            = Nov.FechaNovedad.ToShortDateString();
                    lbl_NroCredito.Text = lbl_NroCredito.Text + Nov.IdNovedad.ToString();
                    lbl_ApeyNombreImpedidoFirma.Text = Nov.UnBeneficiario.ApellidoNombre;
                }
            }
            catch (Exception err)
            {
                log.Error(string.Format("{0} - Error:{1}->{2}", System.Reflection.MethodBase.GetCurrentMethod(), err.Source, err.Message));
                ErrorEnPagina();
            }
        }
    }
Пример #30
0
        /// <summary>
        /// Finalizar o envio da NFe
        /// </summary>
        public void FinalizarNFe(XmlNodeList protNFeList, FluxoNfe fluxoNFe, int emp)
        {
            var oLerXml = new LerXML();

            foreach (XmlNode protNFeNode in protNFeList)
            {
                var    protNFeElemento = (XmlElement)protNFeNode;
                string versao          = protNFeElemento.GetAttribute(NFe.Components.TpcnResources.versao.ToString());

                var strProtNfe = protNFeElemento.OuterXml;

                var infProtList = protNFeElemento.GetElementsByTagName("infProt");

                foreach (XmlNode infProtNode in infProtList)
                {
                    bool tirarFluxo      = true;
                    var  infProtElemento = (XmlElement)infProtNode;

                    var strChaveNFe = string.Empty;
                    var strStat     = string.Empty;

                    if (infProtElemento.GetElementsByTagName(NFe.Components.TpcnResources.chNFe.ToString())[0] != null)
                    {
                        strChaveNFe = "NFe" + infProtElemento.GetElementsByTagName(NFe.Components.TpcnResources.chNFe.ToString())[0].InnerText;
                    }

                    if (infProtElemento.GetElementsByTagName(NFe.Components.TpcnResources.cStat.ToString())[0] != null)
                    {
                        strStat = infProtElemento.GetElementsByTagName(NFe.Components.TpcnResources.cStat.ToString())[0].InnerText;
                    }

                    //Definir o nome do arquivo da NFe e seu caminho
                    var strNomeArqNfe = fluxoNFe.LerTag(strChaveNFe, FluxoNfe.ElementoFixo.ArqNFe);

                    // danasa 8-2009
                    // se por algum motivo o XML não existir no "Fluxo", então o arquivo tem que existir
                    // na pasta "EmProcessamento" assinada.
                    if (string.IsNullOrEmpty(strNomeArqNfe))
                    {
                        if (string.IsNullOrEmpty(strChaveNFe))
                        {
                            throw new Exception("LerRetornoLoteNFe(): Não pode obter o nome do arquivo");
                        }

                        strNomeArqNfe = strChaveNFe.Substring(3) + Propriedade.ExtEnvio.Nfe;
                    }
                    var strArquivoNFe = Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" +
                                        PastaEnviados.EmProcessamento.ToString() + "\\" +
                                        strNomeArqNfe;

                    //Atualizar a Tag de status da NFe no fluxo para que se ocorrer alguma falha na exclusão eu tenha esta campo para ter uma referencia em futuras consultas
                    fluxoNFe.AtualizarTag(strChaveNFe, FluxoNfe.ElementoEditavel.cStat, strStat);

                    switch (strStat)
                    {
                    case "100":     //NFe Autorizada
                    case "150":     //NFe Autorizada fora do prazo
                        if (File.Exists(strArquivoNFe))
                        {
                            //Juntar o protocolo com a NFE já copiando para a pasta de autorizadas
                            var strArquivoNFeProc = Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" +
                                                    PastaEnviados.EmProcessamento.ToString() + "\\" +
                                                    Functions.ExtrairNomeArq(strNomeArqNfe, Propriedade.ExtEnvio.Nfe) +
                                                    Propriedade.ExtRetorno.ProcNFe;

                            //Ler o XML para pegar a data de emissão para criar a pasta dos XML´s autorizados
                            oLerXml.Nfe(strArquivoNFe);

                            //Verificar se a -nfe.xml existe na pasta de autorizados
                            bool NFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoNFe, oLerXml.oDadosNfe.dEmi, Propriedade.ExtEnvio.Nfe, Propriedade.ExtEnvio.Nfe);

                            //Verificar se o -procNfe.xml existe na pasta de autorizados
                            bool procNFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoNFe, oLerXml.oDadosNfe.dEmi, Propriedade.ExtEnvio.Nfe, Propriedade.ExtRetorno.ProcNFe);

                            //Se o XML de distribuição não estiver na pasta de autorizados
                            if (!procNFeJaNaAutorizada)
                            {
                                if (!File.Exists(strArquivoNFeProc))
                                {
                                    Auxiliar.WriteLog("TaskNFeRetRecepcao: Gerou o arquivo de distribuição através da consulta recibo.", false);
                                    oGerarXML.XmlDistNFe(strArquivoNFe, strProtNfe, Propriedade.ExtRetorno.ProcNFe, versao);
                                }
                            }

                            if (!(procNFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoNFe, oLerXml.oDadosNfe.dEmi, Propriedade.ExtEnvio.Nfe, Propriedade.ExtRetorno.ProcNFe)))
                            {
                                //Mover a nfePRoc da pasta de NFE em processamento para a NFe Autorizada
                                //Para enviar falhar, tenho que mover primeiro o XML de distribuição (-procnfe.xml) para
                                //depois mover o da nfe (-nfe.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);

                                //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.ExtEnvio.Nfe, Propriedade.ExtRetorno.ProcNFe);
                            }

                            if (!NFeJaNaAutorizada && procNFeJaNaAutorizada)
                            {
                                //Mover a NFE da pasta de NFE em processamento para NFe Autorizada
                                //Para enviar falhar, tenho que mover primeiro o XML de distribuição (-procnfe.xml) para
                                //depois mover o da nfe (-nfe.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(strArquivoNFe, PastaEnviados.Autorizados, oLerXml.oDadosNfe.dEmi);
                            }

                            //Disparar a geração/impressão do UniDanfe. 03/02/2010 - Wandrey
                            if (procNFeJaNaAutorizada)
                            {
                                ///
                                /// tem que passar o arquivo de distribuicao da nfe
                                ///
                                string strArquivoDist = Empresas.Configuracoes[emp].PastaXmlEnviado + "\\" +
                                                        PastaEnviados.Autorizados.ToString() + "\\" +
                                                        Empresas.Configuracoes[emp].DiretorioSalvarComo.ToString(oLerXml.oDadosNfe.dEmi) +
                                                        Path.GetFileName(strArquivoNFeProc);
                                try
                                {
                                    TFunctions.ExecutaUniDanfe(strArquivoDist, oLerXml.oDadosNfe.dEmi, Empresas.Configuracoes[emp]);
                                }
                                catch (Exception ex)
                                {
                                    Auxiliar.WriteLog("TaskRecepcao: (Falha na execução do UniDANFe) " + ex.Message, false);
                                }
                            }
                            //Vou verificar se estão os dois arquivos na pasta Autorizados, se tiver eu tiro do fluxo caso contrário não. Wandrey 13/02/2012
                            NFeJaNaAutorizada     = oAux.EstaAutorizada(strArquivoNFe, oLerXml.oDadosNfe.dEmi, Propriedade.ExtEnvio.Nfe, Propriedade.ExtEnvio.Nfe);
                            procNFeJaNaAutorizada = oAux.EstaAutorizada(strArquivoNFe, oLerXml.oDadosNfe.dEmi, Propriedade.ExtEnvio.Nfe, Propriedade.ExtRetorno.ProcNFe);
                            if (!procNFeJaNaAutorizada || !NFeJaNaAutorizada)
                            {
                                tirarFluxo = false;
                            }

                            ///
                            /// se o -nfe.xml já existe na pasta de autorizados e ele está na pasta em processamento,
                            /// o exclui da pasta em processamento
                            if (NFeJaNaAutorizada && File.Exists(strArquivoNFe))
                            {
                                File.Delete(strArquivoNFe);
                            }
                        }
                        else
                        {
                            Auxiliar.WriteLog("TaskRetRecepcao: (Foi efetuada uma consulta recibo e não foi localizado o arquivo da NFe ( " + strNomeArqNfe + ") na pasta EmProcessamento) ", false);
                        }

                        break;

                    case "110":
                    case "205":
                    case "301":
                    case "302":
                    case "303":
                        ProcessaNFeDenegada(emp, oLerXml, strArquivoNFe, protNFeElemento.OuterXml, versao);
                        break;

                    default:     //NFe foi rejeitada
                        //O Status da NFe tem que ser maior que 1 ou deu algum erro na hora de ler o XML de retorno da consulta do recibo, sendo assim, vou mantar a nota no fluxo para consultar novamente.
                        if (Convert.ToInt32(strStat) >= 1)
                        {
                            Auxiliar.WriteLog("Arquivo: " + strNomeArqNfe + " codigo de retorno: " + strStat, false);
                            //Mover o XML da NFE a pasta de XML´s com erro
                            oAux.MoveArqErro(strArquivoNFe);
                        }
                        else
                        {
                            tirarFluxo = false;
                        }
                        break;
                    }

                    //Deletar a NFE do arquivo de controle de fluxo
                    if (tirarFluxo)
                    {
                        fluxoNFe.ExcluirNfeFluxo(strChaveNFe);
                    }

                    break;
                }
            }
        }