Example #1
0
        private string sMontaStringConexao()
        {
            try
            {
                Globais LeRegWin = new Globais();
                StringBuilder sbConexao = new StringBuilder();

                sbConexao.Append("User ="******"SYSDBA");
                sbConexao.Append(";");
                sbConexao.Append("Password="******"masterkey");
                sbConexao.Append(";");
                string sPorta = LeRegWin.LeRegConfig("Porta");
                if (sPorta.Trim() != "")
                {
                    sbConexao.Append("Port=" + sPorta + ";");
                }
                sbConexao.Append("Database=");
                string sdatabase = LeRegWin.LeRegConfig("BancoDados");
                sbConexao.Append(sdatabase);
                sbConexao.Append(";");
                sbConexao.Append("DataSource=");
                sbConexao.Append(LeRegWin.LeRegConfig("Servidor"));
                sbConexao.Append(";");
                sbConexao.Append("Dialect=3; Charset=NONE;Role=;Connection lifetime=15;Pooling=true; MinPoolSize=0;MaxPoolSize=2000;Packet Size=8192;ServerType=0;");
                return (string)sbConexao.ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        public FbConnection MontaConexaoEscritor()
        {
            FbConnection Conn = new FbConnection();
            try
            {

                Globais MontaStringConexao = new Globais();
                StringBuilder sbConexao = new StringBuilder();

                sbConexao.Append("User ="******"Usuario"));
                sbConexao.Append(";");
                sbConexao.Append("Password="******"Senha"));
                sbConexao.Append(";");
                sbConexao.Append("Database=");
                string sdatabase = MontaStringConexao.LeRegConfig("BancoEscritor");
                sbConexao.Append(sdatabase);
                sbConexao.Append(";");
                sbConexao.Append("DataSource=");
                sbConexao.Append(MontaStringConexao.LeRegConfig("ServidorEscritor"));
                sbConexao.Append(";");
                sbConexao.Append("Port=3050;Dialect=1; Charset=NONE;Role=;Connection lifetime=15;Pooling=true; MinPoolSize=0;MaxPoolSize=50;Packet Size=8192;ServerType=0;");


                Conn = new FbConnection(sbConexao.ToString());
                Conn.Open();
                return Conn;
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Não foi possivel se conectar ao banco de dados do Escritor, Verifique as Configurações do Sistema, Erro.: {0}",
                                                  ex.Message));
            }
            finally
            {
                Conn.Close();
            }

            return Conn;
        }
        private void frmSelecionaConfigs_Load(object sender, EventArgs e)
        {
            try
            {
                DirectoryInfo dinfo = new DirectoryInfo(belStatic.Pasta_xmls_Configs);
                FileInfo[] finfo = dinfo.GetFiles();

                RegistryKey key = Registry.CurrentConfig.OpenSubKey("hlp\\nivel0006");
                string sCodEmpresaPadrao = (key != null ? key.GetValue("Código da firma digitado no início do Sistema", "").ToString() : "");
                string sAquivoPadrao = "";

                XmlDocument xml = new XmlDocument();

                foreach (FileInfo item in finfo)
                {
                    if (Path.GetExtension(item.FullName).ToUpper().Equals(".XML"))
                    {
                        cbxArquivos.Items.Add(item.Name);

                        xml.Load(item.FullName);
                        XmlNodeList Xnode = xml.GetElementsByTagName("nfe_configuracoes");

                        belStatic.sConfig = item.Name;

                        Globais objGlobais = new Globais();
                        if (sCodEmpresaPadrao == objGlobais.LeRegConfig("Empresa"))
                        {
                            sAquivoPadrao = item.Name;
                        }
                        belStatic.sConfig = "";
                    }
                }


                if ((belStatic.sConfig != "") && (belStatic.sConfig != null))
                {
                    cbxArquivos.Text = belStatic.sConfig;
                }
                else if ((cbxArquivos.Items.Count > 0) && (sAquivoPadrao == ""))
                {
                    cbxArquivos.SelectedIndex = 0;
                }
                else if (sAquivoPadrao != "")
                {
                    cbxArquivos.Text = sAquivoPadrao;
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        private void frmVisualizaNotas_Load(object sender, EventArgs e)
        {
            dtpHSaiEnt.Value = HLP.Util.Util.GetDateServidor();
            Globais glob = new Globais();
            sCasasVlUnit = glob.LeRegConfig("QtdeCasasVlUnit");
            sCasasVlUnit = (sCasasVlUnit == "" ? "1" : sCasasVlUnit);

            geraDgvDup();
            geraDgvProd();
            lblCtrNota.Text = notAtual + " de " + notTotal;
            belUF objuf = new belUF();
            cbxUF.DisplayMember = "SiglaUF";
            cbxUF.ValueMember = "CUF";
            cbxUF.DataSource = objuf.retListaUF();

            cbxUF_embarque.DisplayMember = "SiglaUF";
            cbxUF_embarque.ValueMember = "CUF";
            cbxUF_embarque.DataSource = objuf.retListaUF();
            cbxUF_embarque.SelectedIndex = -1;

            populaNF(this.lObjTotNotas[notAtual - 1]);

            HabilitaCampos(this.Controls, false);
            desabilitaBotoes(false);
            EmEdicao(false);
            ControlaSeta();
            HabilitaGrids(false);
            // btnAtualizar_Click(sender, e);

            if (belStatic.bDentroHlp == false)
            {
                tsHlpTeste.Visible = false;
            }


        }
        private void VerificaCamposEmail()
        {
            Globais LeRegWin = new Globais();
            string hostservidor = LeRegWin.LeRegConfig("HostServidor").ToString().Trim();
            string porta = LeRegWin.LeRegConfig("PortaServidor").ToString().Trim();
            string remetente = LeRegWin.LeRegConfig("EmailRemetente").ToString().Trim();
            string senha = LeRegWin.LeRegConfig("SenhaRemetente").ToString().Trim();
            bool autentica = Convert.ToBoolean(LeRegWin.LeRegConfig("RequerSSL").ToString().Trim());

            if (remetente == "" || senha == "" || hostservidor == "")
            {
                throw new Exception("As configurações de e-mail não estão corretas!");
            }
        }
Example #6
0
        private bool _autentica;//Danner - o.s. 24329 - 08/04/2010

        /// <summary>
        /// Email de Cancelamento
        /// </summary>      
        public belEmail(string sSeq, string sEmp, string sHost, string sPorta, string sDe, string sSenha, string sPara, bool bAutentica)//NFe_2.0
        {
            try
            {
                XmlDocument xml = new XmlDocument();
                Globais objGlobais = new Globais();
                xml.Load(objGlobais.LeRegConfig("PastaProtocolos") + "\\" + sSeq + "_ped-can.xml");
                _anexo2 = objGlobais.LeRegConfig("PastaProtocolos") + "\\" + sSeq + "_ped-can.xml";
                string sPath = belStaticPastas.CANCELADOS + "\\" + HLP.Util.Util.GetDateServidor().Date.ToString("yyMM") + "\\" + xml.GetElementsByTagName("chNFe")[0].InnerText + "-can.xml.xml";

                //DirectoryInfo dinfo = new DirectoryInfo(objGlobais.LeRegConfig("PastaXmlCancelados"));
                //string sArq = xml.GetElementsByTagName("chNFe")[0].InnerText + "-can.xml.xml";

                //foreach (FileInfo arq in dinfo.GetFiles("*.xml"))
                //{

                //}

                if (System.IO.File.Exists(sPath))
                {
                    if (sPara == "")
                    {
                        _para = retEmailDestinatario(sSeq, sEmp);
                    }
                    else
                    {
                        _para = sPara;
                    }

                    _paraTransp = "";
                    _envia = true;
                    _sSeq = sSeq;

                    _autentica = bAutentica;
                    _de = sDe;
                    _porta = Convert.ToInt16(sPorta);
                    _host = sHost;
                    _senha = sSenha;
                    _corpo = geraCorpoEmailCanc(sPath);
                    _anexo = sPath;
                    _assunto = "Mensagem Automática de Nota Fiscal Eletrônica de " + _razaoemit;
                }
                else
                {
                    throw new Exception("Arquivo ref. a Nota Fiscal " + xml.GetElementsByTagName("chNFe")[0].InnerText.Substring(25, 9) + " não se Encontra na Pasta de Cancelados" +
                    Environment.NewLine
                    + Environment.NewLine
                    + "Arquivo : " + xml.GetElementsByTagName("chNFe")[0].InnerText);
                }

            }
            catch (Exception ex)
            {

                throw ex;
            }


        }
Example #7
0
        private void frmGerarXmlNfe_Load(object sender, EventArgs e)
        {
            try
            {
                foreach (Control ctl in this.Controls)
                {
                    if ((ctl) is MdiClient)
                    {
                        ctl.BackColor = Color.White;
                        break;
                    }
                }
                if (ApplicationDeployment.IsNetworkDeployed)
                {
                    ApplicationDeployment ad = ApplicationDeployment.CurrentDeployment;
                    lblVersao.Text = "Versão Atual: " + ad.CurrentVersion.ToString();
                    belStatic.sVersaoAtual = ad.CurrentVersion.ToString();
                    belVersionamento objbelVersion = new belVersionamento();
                    if (objbelVersion.VerificaPublicacaoDisponivel())
                    {
                        frmPopup popup = new frmPopup(PopupSkins.InfoSkin);
                        popup.ShowPopup("Atualização", "Uma nova versão do Sistema já está Disponível!", 200, 4000, 2000);
                        tsAtualizacao.Visible = true;
                    }
                    else
                    {
                        tsAtualizacao.Visible = false;
                    }
                    versãoHlpToolStripMenuItem.Visible = false;
                }

                //Carrega os arquivos de configuração
                if (!Util.VerificaConfiguracaoPastasXml())
                {
                    frmLocalXml objfrm = new frmLocalXml("");
                    objfrm.ShowDialog();
                }
                else
                {
                    DirectoryInfo dinfo = new DirectoryInfo(belStatic.Pasta_xmls_Configs);
                    if (!dinfo.Exists)
                    {
                        KryptonMessageBox.Show(null, "O caminho configurado abaixo não foi encontrado!! "
                            + Environment.NewLine
                            + Environment.NewLine
                            + belStatic.Pasta_xmls_Configs, "A V I S O", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        frmLocalXml objfrm = new frmLocalXml(belStatic.Pasta_xmls_Configs);
                        objfrm.ShowDialog();
                    }
                }

                int iCountFiles = 0;
                DirectoryInfo dPastaData = new DirectoryInfo(belStatic.Pasta_xmls_Configs);
                if (!dPastaData.Exists)
                {
                    dPastaData.Create();
                }
                else
                {
                    FileInfo[] finfo = dPastaData.GetFiles("*.xml");
                    foreach (FileInfo item in finfo)
                    {
                        iCountFiles++;
                    }
                }


                belStatic.IPrimeiroLoad = 1;
                if (iCountFiles != 0)
                {
                    frmSelecionaConfigs objFrmSeleciona = new frmSelecionaConfigs();
                    objFrmSeleciona.ShowDialog();
                    if (objFrmSeleciona.bFecharApp)
                    {
                        throw new Exception("Fechar");
                    }
                    if (!objFrmSeleciona.bESCRITA)
                    {
                        objFrmSeleciona.Hide();
                        belStatic.IPrimeiroLoad = 1;
                        frmLogin objfrm = new frmLogin();
                        objfrm.ShowDialog();
                        CarregaDadosEmpresa();
                        VerificaAcessoUserEmprersa(sender, e);
                        belStatic.IPrimeiroLoad = 0;
                        lblUsuario.Text = "Usuário: " + belStatic.SUsuario;
                        lblEmpresa.Text = belStatic.sNomeEmpresa;
                        gerarAquivosXmlsToolStripMenuItem.Visible = true;
                        tsNfe.Enabled = true;
                        tsNfes.Enabled = true;
                        headerMenuLateral.Visible = true;
                        cx = new belConnection();
                    }
                    else
                    {
                        gerarAquivosXmlsToolStripMenuItem.Visible = false;
                        tsNfe.Enabled = false;
                        tsNfes.Enabled = false;
                        headerMenuLateral.Visible = false;
                    }

                }
                else
                {
                    if (KryptonMessageBox.Show(null, "Não existe nenhum arquivo de configuração na pasta Selecionada."
                         + Environment.NewLine
                         + Environment.NewLine
                         + "Deseja selecionar uma outra Pasta ?",
                         "A V I S O",
                         MessageBoxButtons.YesNo,
                         MessageBoxIcon.Question) == DialogResult.Yes)
                    {
                        frmLocalXml objfrm = new frmLocalXml(belStatic.Pasta_xmls_Configs);
                        objfrm.ShowDialog();
                        Application.Restart();
                        this.Close();
                    }


                    belStatic.BSemArquivo = true;
                    frmLoginConfig objFrm = new frmLoginConfig();
                    objFrm.ShowDialog();

                    lblUsuario.Text = "   Usuário : " + belStatic.SUsuario;
                }
                CarregaStatuModoSistema();

                //carrega Logotipo
                Globais LeRegWin = new Globais();
                LeRegWin.CarregaInfStaticas(); // INICIALIZA AS CONFIGURAÇÕES PADRÕES
                Byte[] bimagem = belUtil.carregaImagem(LeRegWin.LeRegConfig("Logotipo"));

                if (bimagem != null)
                {
                    pictureBox1.BackgroundImage = belUtil.byteArrayToImage(bimagem);
                }

                HLP.Dao.daoEmailContador objdaoemailCont = new HLP.Dao.daoEmailContador();
                if (objdaoemailCont.VerificaDiaParaEnviarEmail())
                {
                    try
                    {
                        KryptonMessageBox.Show("Hoje é dia de enviar Email para o Contador, Verifique suas Pendências!!", "A V I S O", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        NfeGerarXml.NFe.frmEmailContadorNfe objfrm = new NfeGerarXml.NFe.frmEmailContadorNfe();
                        objfrm.MdiParent = this;
                        objfrm.Show();
                    }
                    catch (Exception ex)
                    {
                        KryptonMessageBox.Show(null, ex.Message, "A V I S O", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }

                }

                if (belStatic.RAMO == "TRANSPORTE")
                {
                    btnNfe.Enabled = false;
                    tsNfe.Enabled = false;

                    btnNfes.Enabled = false;
                    tsNfes.Enabled = false;

                    btnCte.Enabled = true;
                    tsCte.Enabled = true;

                    btnCce.Enabled = false;
                    tsCce.Enabled = false;

                    //btnEmail.Enabled = false;
                    //tsEmail.Enabled = false;

                    tsOrganizarPasta.Enabled = false;
                    tsProtocolos.Enabled = false;
                    tsImportarXmlEscritor.Enabled = false;
                }
                else
                {
                    btnNfe.Enabled = true;
                    tsNfe.Enabled = true;

                    btnNfes.Enabled = true;
                    tsNfes.Enabled = true;

                    btnCte.Enabled = false;
                    tsCte.Enabled = false;

                    btnCce.Enabled = true;
                    tsCce.Enabled = true;

                    btnEmail.Enabled = true;
                    tsEmail.Enabled = true;

                    tsOrganizarPasta.Enabled = true;
                    tsProtocolos.Enabled = true;
                    tsImportarXmlEscritor.Enabled = true;
                }




            }
            catch (FbException fbx)
            {
                KryptonMessageBox.Show(null, "Ocorreu uma falha ao montar a string de Conexão!"
                    + Environment.NewLine
                    + "Verifique se o arquivo está configurado corretamente!"
                    + Environment.NewLine,
                    "A V I S O", MessageBoxButtons.OK, MessageBoxIcon.Information);
                frmLocalXml objfrm = new frmLocalXml(belStatic.Pasta_xmls_Configs);

                frmLoginConfig objFrm = new frmLoginConfig();
                objFrm.ShowDialog();
                lblUsuario.Text = "   Usuário : " + belStatic.SUsuario;
                Application.Restart();

            }
            catch (Exception ex)
            {
                if (ex.Message.Equals("Fechar"))
                {
                    this.Close();
                }
                else
                {
                    KryptonMessageBox.Show(ex.Message);
                }
            }
        }
Example #8
0
        private void EnviaEmailCancelamento(List<string> objListaEmail) //NFe_2.0
        {
            try
            {
                Globais LeRegWin = new Globais();
                string hostservidor = LeRegWin.LeRegConfig("HostServidor").ToString().Trim();
                string porta = LeRegWin.LeRegConfig("PortaServidor").ToString().Trim();
                string remetente = LeRegWin.LeRegConfig("EmailRemetente").ToString().Trim();
                string senha = LeRegWin.LeRegConfig("SenhaRemetente").ToString().Trim();
                bool autentica = Convert.ToBoolean(LeRegWin.LeRegConfig("RequerSSL").ToString().Trim());
                List<belEmail> objlbelEmail = new List<belEmail>();
                int iCount = 0;

                if ((hostservidor != "") && (porta != "0") && (remetente != "") && (senha != ""))
                {
                    for (int i = 0; i < objListaEmail.Count; i++)
                    {
                        belEmail objemail = new belEmail(objListaEmail[i].Substring(0, 6), LeRegWin.LeRegConfig("Empresa").ToString().Trim(), hostservidor, porta, remetente, senha, "", autentica);
                        objlbelEmail.Add(objemail);
                    }
                }
                else
                {
                    if (KryptonMessageBox.Show(null, "Campos para o envio de e-Mail automático não estão preenchidos corretamente!" +
                                    Environment.NewLine + Environment.NewLine +
                                    "Deseja Preencher os campos corretamente agora ?", "E-Mail não pode ser enviado", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                    {
                        Boolean ok = false;
                        foreach (Form frm in this.MdiChildren)
                        {
                            if (frm is frmLoginConfig)
                            {
                                frm.BringToFront();
                                ok = true;
                            }
                        }
                        if (!ok)
                        {
                            frmLoginConfig objfrm = new frmLoginConfig(objPrincipal);
                            objfrm.MdiParent = this;
                            objfrm.Show();
                        }
                    }
                }
                if (objlbelEmail.Count > 0)
                {
                    frmEmailNfe objfrmEmail = new frmEmailNfe(objlbelEmail);
                    objfrmEmail.sTipo = "C";
                    objfrmEmail.ShowDialog();
                    for (int i = 0; i < objfrmEmail.objLbelEmail.Count; i++)
                    {
                        if ((objfrmEmail.objLbelEmail[i]._envia == true) && (objfrmEmail.objLbelEmail[i]._para != "" || objfrmEmail.objLbelEmail[i]._paraTransp != ""))
                        {
                            try
                            {
                                objfrmEmail.objLbelEmail[i].enviaEmail();
                                iCount++;
                            }
                            catch (Exception ex)
                            {
                                KryptonMessageBox.Show(null, ex.Message + Environment.NewLine + Environment.NewLine + "E-mail: " + objfrmEmail.objLbelEmail[i]._para + "   - Seq: " + objfrmEmail.objLbelEmail[i]._sSeq, "E R R O - E N V I O", MessageBoxButtons.OK, MessageBoxIcon.Information);
                            }
                        }
                    }
                    if (iCount > 0)
                    {
                        KryptonMessageBox.Show(null, "Procedimento de Envio de E-mail Finalizado!"
                            + Environment.NewLine
                            + Environment.NewLine,
                            "A V I S O",
                             MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception ex)
            {
                KryptonMessageBox.Show(null, ex.Message, "ALERTA", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }

        }
Example #9
0
        private void button1_Click(object sender, EventArgs e)
        {
            if (belStatic.RAMO != "TRANSPORTE")
            {
                HLP.bel.NFe.belConfigInicial.CarregaConfiguracoesIniciais();
            }
            try
            {
                Globais objglobal = new Globais();
                string sEmp = objglobal.LeRegConfig("Empresa");
                belStatic.SUsuario = txtUsuario.Text.Trim().PadLeft(10, '0');
                belStatic.BAlteraDadosNfe = false;
                string sSenha = txtSenha.Text.Trim();
                string sTipoUsuario = "";
                StringBuilder sQueryUsuario = new StringBuilder();
                sQueryUsuario.Append("select count(acesso.CD_OPERADO) Total from acesso ");
                sQueryUsuario.Append("where acesso.CD_OPERADO = '" + belStatic.SUsuario + "'");
                FbCommand cmd = new FbCommand(sQueryUsuario.ToString(), cx.get_Conexao());
                cx.Open_Conexao();
                cmd.ExecuteNonQuery();
                FbDataReader dr = cmd.ExecuteReader();
                dr.Read();
                if (Convert.ToInt16(dr["Total"]) > 0)
                {
                    StringBuilder sQuery = new StringBuilder();
                    if (belStatic.RAMO != "TRANSPORTE")
                    {
                        sQuery.Append("select acesso.tp_operado, acesso.cd_senha, COALESCE(acesso.st_altera_dados_nfe,'S') st_altera_dados_nfe ");
                        sQuery.Append("from acesso ");
                        sQuery.Append("where acesso.cd_senha = '" + belCriptografia.Encripta(sSenha) + "' ");
                        sQuery.Append("and acesso.CD_OPERADO = '" + belStatic.SUsuario + "'");
                    }
                    else
                    {
                        sQuery.Append("select acesso.tp_operado, acesso.cd_senha ");
                        sQuery.Append("from acesso ");
                        sQuery.Append("where acesso.cd_senha = '" + belCriptografia.Encripta(sSenha) + "' ");
                        sQuery.Append("and acesso.CD_OPERADO = '" + belStatic.SUsuario + "'");
                    }

                    cmd = new FbCommand(sQuery.ToString(), cx.get_Conexao());
                    cmd.ExecuteNonQuery();
                    dr = cmd.ExecuteReader();

                    while (dr.Read())
                    {
                        sTipoUsuario = dr["tp_operado"].ToString();
                        if (belStatic.RAMO != "TRANSPORTE")
                        {
                            belStatic.BAlteraDadosNfe = (dr["st_altera_dados_nfe"].ToString().Equals("N") ? false : true);
                        }
                    }
                    if (sTipoUsuario != "")
                    {
                        belStatic.IPrimeiroLoad = 0;
                        this.Close();
                    }
                    else
                    {
                        KryptonMessageBox.Show(null, "SENHA INCORRETA", "A V I S O ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        txtSenha.Focus();
                        txtSenha.Text = "";
                    }
                }
                else
                {
                    KryptonMessageBox.Show(null, "USUÁRIO INCORRETO", "A V I S O ", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    txtUsuario.Focus();
                    txtUsuario.Text = "";
                }
            }
            catch (Exception ex)
            {
                KryptonMessageBox.Show(null, ex.Message, "A V I S O", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.bFechaAplicativo = true;
            }
            finally
            {
                cx.Close_Conexao();
            }
        }
Example #10
0
        private void EnviaEmail(List<TcInfNfse> bjListaNfseRetorno)
        {
            Globais LeRegWin = new Globais();
            string hostservidor = LeRegWin.LeRegConfig("HostServidor").ToString().Trim();
            string porta = LeRegWin.LeRegConfig("PortaServidor").ToString().Trim();
            string remetente = LeRegWin.LeRegConfig("EmailRemetente").ToString().Trim();
            string senha = LeRegWin.LeRegConfig("SenhaRemetente").ToString().Trim();
            bool autentica = Convert.ToBoolean(LeRegWin.LeRegConfig("RequerSSL").ToString().Trim());

            List<belEmail> objlbelEmail = new List<belEmail>();

            //OS_25285
            daoPrestador objdaoPrestador = new daoPrestador();
            string sMsgPadraoPrestador = objdaoPrestador.RetPrestadorEmail();


            if ((hostservidor != "") && (porta != "0") && (remetente != "") && (senha != ""))
            {
                for (int e = 0; e < bjListaNfseRetorno.Count; e++)
                {
                    belEmail objemail = new belEmail(bjListaNfseRetorno[e], sMsgPadraoPrestador, hostservidor, porta, remetente, senha, "", autentica);
                    objlbelEmail.Add(objemail);

                }
            }
            else
            {
                if (KryptonMessageBox.Show(null, "Campos para o envio de e-Mail automático não estão preenchidos corretamente!" +
                                Environment.NewLine + Environment.NewLine +
                                "Deseja Preencher os campos corretamente agora ?", "E-Mail não pode ser enviado", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                {
                    frmConfiguracao objconfiguracao = new frmConfiguracao(2);
                    objconfiguracao.ShowDialog();
                }
            }


            if (objlbelEmail.Count > 0)
            {
                frmEmailNfe objfrmEmail = new frmEmailNfe(objlbelEmail);
                objfrmEmail.ShowDialog();
                int icount = 0;
                for (int i = 0; i < objfrmEmail.objLbelEmail.Count; i++)
                {
                    if ((objfrmEmail.objLbelEmail[i]._envia == true) && (objfrmEmail.objLbelEmail[i]._para != "" || objfrmEmail.objLbelEmail[i]._paraTransp != ""))
                    {
                        try
                        {
                            objfrmEmail.objLbelEmail[i].enviaEmail();
                            icount++;
                        }
                        catch (Exception ex)
                        {
                            KryptonMessageBox.Show(null, ex.Message + Environment.NewLine + Environment.NewLine + "E-mail: " + objfrmEmail.objLbelEmail[i]._para + "   - Seq: " + objfrmEmail.objLbelEmail[i]._sSeq, "E R R O - E N V I O", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
                if (icount > 0)
                {
                    KryptonMessageBox.Show(null, "Procedimento de Envio de E-mail Finalizado!"
                           + Environment.NewLine
                           + Environment.NewLine,
                           "A V I S O",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
Example #11
0
        private void btnEnviar_Click(object sender, EventArgs e)
        {
            frmStatusEnvioNfs objfrmStatus = null;
            try
            {
                Globais objGlobais = new Globais();
                if (objGlobais.LeRegConfig("GrupoServico").Equals(""))
                {
                    throw new Exception("Parametrize o Grupo Padrão de Faturamento (Serviço) no Config do Sistema antes de Enviar Notas");
                }

                for (int i = 0; i < dgvNF.RowCount; i++)
                {
                    if (dgvNF["ASSINANF", i].Value != null)
                    {
                        if (dgvNF["ASSINANF", i].Value.ToString().Equals("True"))
                        {
                            if (VerificaCampoReciboPreenchido(belStatic.codEmpresaNFe, dgvNF["CD_NFSEQ", i].Value.ToString()) != "")
                            {
                                throw new Exception("A Nota de Sequencia = " + dgvNF["CD_NFSEQ", i].Value.ToString() + " Já tem um retorno Salvo no Banco de Dados, tente Buscar Retorno");
                            }
                        }
                    }
                }
                #region Busca Notas Selecionadas na Grid
                string sNfCancelada = string.Empty;
                sListaNotas = new List<string>();
                for (int i = 0; i < dgvNF.RowCount; i++)
                {
                    if (((dgvNF["ASSINANF", i].Value != null) && (dgvNF["ASSINANF", i].Value.ToString().Equals("True"))) && ((dgvNF["CANCELADA", i].Value == null) || (dgvNF["CANCELADA", i].Value.ToString() == "0"))) //Danner - o.s. SEM - 17/12/2009
                    {
                        sListaNotas.Add((string)dgvNF["CD_NFSEQ", i].Value);
                    }
                    if ((dgvNF["CANCELADA", i].Value != null) && (dgvNF["CANCELADA", i].Value.ToString() == "1"))
                    {
                        sNfCancelada += "Nota Fiscal " + dgvNF["CD_NOTAFIS", i].Value.ToString() + " - Esta Cancelada e não é Permitido o Reenvio da mesma Nota!" + Environment.NewLine + Environment.NewLine;
                    }
                }

                if (sListaNotas.Count == 0)
                {
                    KryptonMessageBox.Show("Nenhuma nota Valida foi Selecionada!", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    if (sNfCancelada != "")
                    {
                        KryptonMessageBox.Show(sNfCancelada, "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                    return;
                }

                #endregion
                daoLoteRps objdaoLoteRps = new daoLoteRps();

                if (ValidaSeqNoBanco())
                {
                    tcLoteRps objLoteRps = objdaoLoteRps.BuscaDadosNFes(sListaNotas);
                    //Chamar Form para visualizar;
                    frmVisualizaNfs objFrmVisualiza = new frmVisualizaNfs(objLoteRps);
                    objFrmVisualiza.ShowDialog();
                    if (objFrmVisualiza.bCancela)
                    {
                        MessageBoxIcon _msgIcon = MessageBoxIcon.Information;
                        throw new Exception("Envio da(s) Nota(s) Cancelado");
                    }

                    AssinaNFeXml Assinatura = new AssinaNFeXml();
                    X509Certificate2 cert = Assinatura.BuscaNome("");
                    if (!ValidaCertificado(cert))
                    {
                        throw new Exception("Certificado não Selecionado!!");
                    }
                    objfrmStatus = new frmStatusEnvioNfs();
                    objfrmStatus.Show();
                    objfrmStatus.lblMsg.Text = "Montando XML de Acordo com os dados inseridos!!";
                    objfrmStatus.lblMsg.Refresh();
                    objfrmStatus.Refresh();

                    HLP.bel.NFes.belCreateXml objCreateXml = new belCreateXml(cert);
                    objCreateXml.GerarAqruivoXml(objFrmVisualiza.objLoteRpsAlter);

                    objfrmStatus.lblMsg.Text = "Enviando Lote para o Webservice!!";
                    objfrmStatus.lblMsg.Refresh();

                    //Envia Lote
                    belRecepcao objBelRecepcao = new belRecepcao(objCreateXml.sXmlLote, cert, objFrmVisualiza.objLoteRpsAlter);
                    if (objBelRecepcao.sMsgTransmissao != "")
                    {
                        throw new Exception(objBelRecepcao.sMsgTransmissao);
                    }
                    daoRecepcao objdaoRecepcao = new daoRecepcao(objBelRecepcao.Protocolo, objFrmVisualiza.objLoteRpsAlter);
                    objfrmStatus.lblMsg.Text = "Gravando recibo na base de dados!!";
                    objfrmStatus.lblMsg.Refresh();
                    objdaoRecepcao.GravaRecibo();
                    string sMsgErro = objBelRecepcao.BuscaRetorno(objFrmVisualiza.objLoteRpsAlter.Rps[0].InfRps.Prestador, objfrmStatus.lblMsg, objfrmStatus.progressBarStatus);

                    if (objBelRecepcao.sCodigoRetorno.Equals("E4"))
                    {
                        objfrmStatus.Close();
                        KryptonMessageBox.Show(null, sMsgErro + Environment.NewLine + Environment.NewLine + "IMPORTANTE: Tente Buscar Retorno da NFse pois o serviço do Web service está demorando para responder; ", "MENSAGEM DE RETORNO", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                    else if (objBelRecepcao.objListaNfseRetorno.Count > 0) //Lote Enviado
                    {
                        objfrmStatus.lblMsg.Text = "Alterando Status da Nota para Enviada!!";
                        objfrmStatus.lblMsg.Refresh();
                        objdaoRecepcao.AlteraStatusDaNota(objBelRecepcao.objListaNfseRetorno);
                        objfrmStatus.Close();
                        objdaoRecepcao.VerificaNotasParaCancelar(objBelRecepcao.objListaNfseRetorno);

                        for (int i = 0; i < dgvNF.RowCount; i++)
                        {
                            //CD_NFSEQ
                            int ienviado = objBelRecepcao.objListaNfseRetorno.Count(lote => lote.IdentificacaoRps.Nfseq == dgvNF["CD_NFSEQ", i].Value.ToString());
                            if (ienviado > 0)
                            {
                                dgvNF["ST_NFE", i].Value = true;
                            }
                        }
                        KryptonMessageBox.Show(null, objBelRecepcao.MontaMsgDeRetornoParaCliente(), "MENSAGEM DE RETORNO", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        EnviaEmail(objBelRecepcao.objListaNfseRetorno);
                    }
                    else
                    {
                        objdaoRecepcao.LimpaRecibo(objFrmVisualiza.objLoteRpsAlter);
                        objfrmStatus.Close();
                        KryptonMessageBox.Show(null, sMsgErro + Environment.NewLine, "MENSAGEM DE RETORNO", MessageBoxButtons.OK, MessageBoxIcon.Information);

                    }
                }

                VerificaGeneratorLote();
                PopulaDataGridView();
            }
            catch (Exception ex)
            {
                if (objfrmStatus != null)
                {
                    objfrmStatus.Close();
                }
                VerificaGeneratorLote();
                KryptonMessageBox.Show(null, string.Format(Msg_Padrao.CException, Environment.NewLine) + (ex.InnerException != null ? ex.InnerException.Message + Environment.NewLine + ex.Message : ex.Message).ToString(), "AVISO ", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            finally { cx.Close_Conexao(); }
        }
        private void btnLogin_Click(object sender, EventArgs e)
        {
            try
            {
                lblVerificacao.Text = "Verificando atualizações. Por favor, aguarde..";
                statusStrip.Refresh();
                if (cbxArquivos.Items.Count > 0)
                {
                    belStatic.sConfig = cbxArquivos.SelectedItem.ToString();
                    Globais LeRegWin = new Globais();                    
                    belStatic.codEmpresaNFe = LeRegWin.LeRegConfig("Empresa");                   

                    if (sTipoNFe.Equals("G"))
                    {
                        belStatic.IPrimeiroLoad = 0;
                        if (cbxArquivos.SelectedItem.ToString().Replace(".xml", "").ToUpper().Equals("ESCRITA"))
                        {
                            bESCRITA = true;
                        }
                        this.Close();
                    }
                    else
                    {
                        this.Hide();
                        if (sTipoNFe.Equals("N"))
                        {
                            frmArquivosXmlNfe objfrm = new frmArquivosXmlNfe(objfrmPrincipal);
                            objfrm.MdiParent = objfrmPrincipal;
                            objfrm.Show();
                        }
                        else if (sTipoNFe.Equals("S"))
                        {
                            frmEnviaNfs objfrm = new frmEnviaNfs(objfrmPrincipal);
                            objfrm.MdiParent = objfrmPrincipal;
                            objfrm.Show();

                        }
                        else if (sTipoNFe.Equals("I"))
                        {
                            frmImportaEscritorNfe objfrm = new frmImportaEscritorNfe();
                            objfrm.MdiParent = objfrmPrincipal;
                            objfrm.Show();
                        }
                        this.Close();
                    }                    
                }
                else
                {
                    KryptonMessageBox.Show(null, "Não existem arquivos na pasta de Config.", "A V I S O", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                }
            }
            catch (Exception ex)
            {
                KryptonMessageBox.Show(null, "Ocorreu uma Exceção não tratada, Informe a Mensagem abaixo ao suporte HLP."
                    + Environment.NewLine
                    + ex.Message, "E R R O", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Application.Exit();
            }
        }
Example #13
0
        private void EnviaEmailCCe(List<belPesquisaCCe> lsNotas)
        {
            Globais LeRegWin = new Globais();

            string hostservidor = LeRegWin.LeRegConfig("HostServidor").ToString().Trim();
            string porta = LeRegWin.LeRegConfig("PortaServidor").ToString().Trim();
            string remetente = LeRegWin.LeRegConfig("EmailRemetente").ToString().Trim();
            string senha = LeRegWin.LeRegConfig("SenhaRemetente").ToString().Trim();
            bool autentica = Convert.ToBoolean(LeRegWin.LeRegConfig("RequerSSL").ToString().Trim());

            List<belEmail> objlbelEmail = new List<belEmail>();

            if ((hostservidor != "") && (porta != "0") && (remetente != "") && (senha != ""))
            {
                for (int e = 0; e < lsNotas.Count; e++)
                {
                    // InformaStatusEnvio("Estruturando Email", e, lsNotas.Count);
                    belEmail objemail = new belEmail(lsNotas[e], lsNotas[e].CD_NFSEQ, lsNotas[e].CD_NOTAFIS, belStatic.codEmpresaNFe, hostservidor, porta, remetente, senha, "", autentica);
                    objlbelEmail.Add(objemail);
                }
            }
            else
            {
                if (KryptonMessageBox.Show(null, "Campos para o envio de e-Mail automático não estão preenchidos corretamente!" +
                                Environment.NewLine + Environment.NewLine +
                                "Deseja Preencher os campos corretamente agora ?", "E-Mail não pode ser enviado", MessageBoxButtons.YesNo, MessageBoxIcon.Exclamation) == DialogResult.Yes)
                {
                    frmConfiguracao objconfiguracao = new frmConfiguracao(2);
                    objconfiguracao.ShowDialog();
                }
            }


            if (objlbelEmail.Count > 0)
            {
                frmEmailNfe objfrmEmail = new frmEmailNfe(objlbelEmail);
                objfrmEmail.ShowDialog();
                int icount = 0;
                for (int i = 0; i < objfrmEmail.objLbelEmail.Count; i++)
                {
                    if ((objfrmEmail.objLbelEmail[i]._envia == true) && (objfrmEmail.objLbelEmail[i]._para != "" || objfrmEmail.objLbelEmail[i]._paraTransp != ""))
                    {
                        try
                        {
                            // InformaStatusEnvio("Enviando Email", i, lCaminhosXml.Count);
                            objfrmEmail.objLbelEmail[i].enviaEmail();
                            icount++;
                        }
                        catch (Exception ex)
                        {
                            KryptonMessageBox.Show(null, ex.Message + Environment.NewLine + Environment.NewLine + "E-mail: " + objfrmEmail.objLbelEmail[i]._para + "   - Seq: " + objfrmEmail.objLbelEmail[i]._sSeq, "E R R O - E N V I O", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        }
                    }
                }
                if (icount > 0)
                {
                    KryptonMessageBox.Show(null, "Procedimento de Envio de E-mail Finalizado!"
                           + Environment.NewLine
                           + Environment.NewLine,
                           "A V I S O",
                            MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
        }
Example #14
0
        private void btnImprimir_Click(object sender, EventArgs e)
        {
            try
            {
                Globais LeRegWin = new Globais();
                if ((bsGrid.DataSource as List<belPesquisaCCe>).Where(c => c.bSeleciona && c.QT_ENVIO > 0).Count() > 0)
                {
                    daoCarregaDataSet objdaoCarregaDataSet = new daoCarregaDataSet((bsGrid.DataSource as List<belPesquisaCCe>).Where(c => c.bSeleciona && c.QT_ENVIO > 0).ToList<belPesquisaCCe>());

                    ReportDocument rpt = new ReportDocument();
                    if (LeRegWin.LeRegConfig("UsaRelatorioEspecifico") == "True")
                    {
                        string sCaminho = LeRegWin.LeRegConfig("CaminhoRelatorioEspecifico") + "\\" + "CCe.rpt";
                        rpt.Load(sCaminho);
                    }
                    else
                    {
                        rpt.Load(Application.StartupPath + "\\Relatorios" + "\\" + "\\" + "CCe.rpt");
                    }

                    DirectoryInfo dinfo = new DirectoryInfo(belStaticPastas.ENVIADOS + "\\Servicos" + "\\PDF");
                    if (!dinfo.Exists)
                    {
                        dinfo.Create();
                    }
                    string sCaminhoSave;
                    foreach (DANFE.dsCCe ds in objdaoCarregaDataSet.objListaDS)
                    {
                        sCaminhoSave = dinfo.FullName + "\\" + ds.CCe[0].NFE.ToString() + ".pdf";
                        if (belFecharJanela.IsFileOpen(sCaminhoSave) == false)
                        {
                            rpt.SetDataSource(ds);
                            rpt.Refresh();
                            ExportPDF(rpt, sCaminhoSave);
                        }
                    }

                    EnviaEmailCCe((bsGrid.DataSource as List<belPesquisaCCe>).Where(c => c.bSeleciona && c.QT_ENVIO > 0).ToList<belPesquisaCCe>());

                    //Visualização
                    sCaminhoSave = dinfo.FullName + "\\" + Environment.MachineName + "_Grupo_CCe.pdf";
                    string[] processos = windows_net.EnumerateOpenedWindows.GetDesktopWindowsTitles();
                    foreach (string window in processos)
                    {
                        if (window.Contains("Grupo_CCe"))
                        {
                            belFecharJanela.FecharJanela(window);
                            File.Delete(sCaminhoSave);
                            break;
                        }
                    }
                    rpt.SetDataSource(objdaoCarregaDataSet.objDS);
                    rpt.Refresh();
                    ExportPDF(rpt, sCaminhoSave);
                    System.Diagnostics.Process.Start(sCaminhoSave);
                }
                else
                {
                    hlpMessageBox.ShowAviso("Não há Cartas de Correções válidas selecionadas!");
                }
            }
            catch (Exception ex)
            {
                new HLPexception(ex.Message, ex);
            }

        }
Example #15
0
        public static bool ValidacEAN(string scodigo)
        {
            try
            {
                Globais objGlobais = new Globais();
                if (((scodigo.Length == 8) || (scodigo.Length == 12) || (scodigo.Length == 13) || (scodigo.Length == 14))
                    && (Convert.ToBoolean(objGlobais.LeRegConfig("CodBarrasXml"))))
                {
                    return true;
                }
                else
                {
                    return false;
                }

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #16
0
        public void BusRetFazendaEnvio()
        {

            Globais glob = new Globais();
            XNamespace pf = "http://www.portalfiscal.inf.br/nfe";
            this.bModoSCAN = belStatic.bModoSCAN;
            _emp = belStatic.codEmpresaNFe;

            string qtdeTentativas = glob.LeRegConfig("QtdeTentativas").ToString();

            //Retorno da fazenda com Status de cada NFe do lote.
            belNfeRetRecepcao objnferetrecepcao = new belNfeRetRecepcao("1.02", _sRecibo, "2.00", _xCert, bModoSCAN);
            XmlDocument xret = new XmlDocument();

            //Variavel pra sabe se alguma nota possui erro
            XmlNodeList nodescStat;
            XmlNodeList nodesxMotivo;
            //contador de tentativas          

            while (!bStopRetorno)
            {
                _loteres = "";
                xret = objnferetrecepcao.Retornaxml(_UF_Empresa);
                nodescStat = xret.GetElementsByTagName("cStat");
                nodesxMotivo = xret.GetElementsByTagName("xMotivo");

                if (nodescStat[0].InnerText == "105")
                {
                    _loteres = nodescStat[0].InnerText + " - " + nodesxMotivo[0].InnerText;
                    countTentativas++;
                }
                else if (nodescStat[0].InnerText != "104")
                {
                    throw new Exception("Erro " + nodescStat[0].InnerText + " - " + nodesxMotivo[0].InnerText);
                }
                else
                {
                    for (int i = 0; i < _lnfes.Count; i++)
                    {
                        //Variavel que gera a mensagem de resposta
                        _loteres = _loteres + "Nota de número de sequência: " + _lsSeqs[i] + " - " + nodesxMotivo[i + 1].InnerText + " Cod. " + nodescStat[i + 1].InnerText + Environment.NewLine;

                        if (nodescStat[i + 1].InnerText == "100")
                        {
                            _nfeautorizadas.Add(_lsSeqs[i]);
                            XmlNode xRetUni = xret.GetElementsByTagName("infProt")[i]; // Diego OS_24777

                            //Método responsavel por gravar o nProt e chNfe no banco e gerar o xml protocolado.
                            geraProcNFe(_lsSeqs[i], _lnfes[i], xret.GetElementsByTagName("chNFe")[i].InnerText,
                                                xRetUni["nProt"].InnerText, xret.GetElementsByTagName("protNFe")[i], pf);

                            xret.Save(belStaticPastas.PROTOCOLOS + "\\" + _sRecibo + "-pro-rec.xml");
                            countTentativas++;
                        }
                        else if (nodescStat[i + 1].InnerText == "204")
                        {
                            string sRet = nodesxMotivo[i + 1].InnerText.Substring((nodesxMotivo[i + 1].InnerText.IndexOf("nRec") + 5), 15);
                            SalvaRetornoNotaDuplicada(sRet, _lsSeqs[i]);
                        }
                        else if ((nodescStat[i + 1].InnerText == "110") || (nodescStat[i + 1].InnerText == "302") || (nodescStat[i + 1].InnerText == "302"))
                        {
                            NotaDenegada(_lsSeqs[i]);
                        }
                        else if (nodescStat[i + 1].InnerText != "105") // Lote em processamento
                        {
                            LimpaCampoRecibo(_emp, _lsSeqs[i]);
                        }
                    }
                    bStopRetorno = true;
                }
                _lblQtde.Text = countTentativas.ToString() + " - " + _loteres;

            }

        }