Example #1
0
        void BtnItensClick(object sender, EventArgs e)
        {
            if (dgvCadastro.Rows.Count == 0)
            {
                return;
            }
            int              i               = dgvCadastro.CurrentRow.Index;
            short            codigo          = Globais.StrToShort(dgvCadastro.Rows[i].Cells["Cod"].Value.ToString());
            string           fornecedor      = dgvCadastro.Rows[i].Cells["Fornecedor"].Value.ToString();
            DateTime         data            = DateTime.Parse(dgvCadastro.Rows[i].Cells["Data"].Value.ToString());
            string           cliente         = dgvCadastro.Rows[i].Cells["Cliente"].Value.ToString();
            string           caracteristica  = dgvCadastro.Rows[i].Cells["Característica"].Value.ToString().Trim();
            cCaracteristicas caracteristicas = new cCaracteristicas();
            string           formula         = caracteristicas.Formula(fornecedor, caracteristica);
            frmCadItens      frm             = new frmCadItens();

            frm.fornecedor    = fornecedor;
            frm.data          = data;
            frm.cod_orcamento = codigo;
            frm.cliente       = cliente;
            frm.tabela        = dgvCadastro.Rows[i].Cells["Tabela"].Value.ToString();
            frm.formula       = formula;
            frm.pedido        = dgvCadastro.Rows[i].Cells["P"].Value.ToString().Trim().Equals("S");
            frm.ShowDialog();
            string chave = dgvCadastro.Rows[i].Cells["Chave"].Value.ToString().Trim();

            CarregaOrcamentos();
            Grid.Sort(dgvCadastro, col_sorted, ord_sorted);
            Grid.MarcaSelecionados(dgvCadastro);
            Grid.Posiciona(dgvCadastro, chave);
        }
    public static void Editor_Azulejo_BloqDirecional(byte x, byte y)
    {
        Editor_Azulejos Objetos = Editor_Azulejos.Objetos;
        Point           Azulejo = new Point(Objetos.scrlAzulejoX.Value + x, Objetos.scrlAzulejoY.Value + y);
        byte            Y;

        // Previni erros
        if (Azulejo.X > Listas.Azulejo[Objetos.scrlAzulejo.Value].Azulejo.GetUpperBound(0))
        {
            return;
        }
        if (Azulejo.Y > Listas.Azulejo[Objetos.scrlAzulejo.Value].Azulejo.GetUpperBound(1))
        {
            return;
        }

        for (byte i = 0; i <= (byte)Globais.Direções.Quantidade - 1; i++)
        {
            // Estado do bloqueio
            if (Listas.Azulejo[Objetos.scrlAzulejo.Value].Azulejo[Azulejo.X, Azulejo.Y].Bloqueio[i])
            {
                Y = 8;
            }
            else
            {
                Y = 0;
            }

            // Renderiza
            Desenhar(Jan_Azulejo, Tex_Direções, x * Globais.Grade + Globais.Bloqueio_Posição(i).X, y * Globais.Grade + Globais.Bloqueio_Posição(i).Y, i * 8, Y, 6, 6);
        }
    }
Example #3
0
        void BtnExcluiClick(object sender, EventArgs e)
        {
            if (dgvCadastro.Rows.Count == 0)
            {
                return;
            }
            int          i      = dgvCadastro.CurrentRow.Index;
            int          codigo = Globais.StrToInt(dgvCadastro.Rows[i].Cells["Cod"].Value.ToString());
            DialogResult r      = MessageBox.Show(codigo.ToString(), "Confirma a exclusão?",
                                                  MessageBoxButtons.YesNo,
                                                  MessageBoxIcon.Question);

            if (r == DialogResult.No)
            {
                return;
            }
            string   fornecedor = dgvCadastro.Rows[i].Cells["Fornecedor"].Value.ToString();
            string   msg        = "";
            DateTime data       = DateTime.Parse(dgvCadastro.Rows[i].Cells["Data"].Value.ToString());

            if (orcamento.Exclui(fornecedor, data, codigo, ref msg))
            {
                CarregaOrcamentos();
                Grid.Sort(dgvCadastro, col_sorted, ord_sorted);
                Grid.MarcaSelecionados(dgvCadastro);
            }
        }
Example #4
0
        void DgvCadastroRowEnter(object sender, DataGridViewCellEventArgs e)
        {
            edtResumo.Text         = dgvCadastro.Rows[e.RowIndex].Cells["Resumo"].Value.ToString();
            edtUsuario.Text        = dgvCadastro.Rows[e.RowIndex].Cells["Usuário"].Value.ToString();
            dtpData.Value          = DateTime.Parse(dgvCadastro.Rows[e.RowIndex].Cells["Data"].Value.ToString());
            edtObservacao.Text     = dgvCadastro.Rows[e.RowIndex].Cells["Observação"].Value.ToString();
            edtTabela.Text         = dgvCadastro.Rows[e.RowIndex].Cells["Tabela"].Value.ToString();
            edtCaracteristica.Text = dgvCadastro.Rows[e.RowIndex].Cells["Característica"].Value.ToString();
            fornecedor             = dgvCadastro.Rows[e.RowIndex].Cells["Fornecedor"].Value.ToString();
            cliente   = dgvCadastro.Rows[e.RowIndex].Cells["Cliente"].Value.ToString();
            consultor = dgvCadastro.Rows[e.RowIndex].Cells["Consultor"].Value.ToString();
            DateTime data   = DateTime.Parse(dgvCadastro.Rows[e.RowIndex].Cells["Data"].Value.ToString());
            short    codigo = Globais.StrToShort(dgvCadastro.Rows[e.RowIndex].Cells["Cod"].Value.ToString());

            CarregaAnexos(fornecedor, data, codigo);


            // seta a comissao de acordo com o limiar da caracteristica
            if ((dgvCadastro.Rows[e.RowIndex].Cells["Fornecedor"].Value != null) &&
                (dgvCadastro.Rows[e.RowIndex].Cells["Característica"].Value != null))
            {
                float           vlr_itens      = Globais.StrToFloat(dgvCadastro.Rows[e.RowIndex].Cells["Valor Itens"].Value.ToString());
                float           vlr_desconto   = Globais.StrToFloat(dgvCadastro.Rows[e.RowIndex].Cells["Desconto"].Value.ToString());
                float           per_consultor  = Globais.StrToFloat(dgvCadastro.Rows[e.RowIndex].Cells["Comissão Consultor"].Value.ToString());
                string          caracteristica = dgvCadastro.Rows[e.RowIndex].Cells["Característica"].Value.ToString().Trim();
                float           limiar         = Globais.StrToFloat(dgvCadastro.Rows[e.RowIndex].Cells["Limiar"].Value.ToString());
                float           sinal          = orcamento.CalculaSinal(fornecedor, caracteristica, vlr_itens, vlr_desconto, per_consultor, limiar);
                cComissaoLimiar comissao       = new cComissaoLimiar();
                float           vlr_orcamento  = vlr_itens - vlr_desconto;
                float           per_comissao   = comissao.Calcula(fornecedor, caracteristica, vlr_orcamento, sinal);
                edtPerComissao.Text = per_comissao.ToString("#0.00");
                edtVlrComissao.Text = (per_comissao * vlr_orcamento / 100f).ToString("###,##0.00");
            }
        }
Example #5
0
        void Button1Click(object sender, EventArgs e)
        {
            float valor = Globais.StrToFloat(edtPago.Text);

            if (valor == 0)
            {
                valor = Globais.StrToFloat(edtValor.Text);
            }
            fSelecionaPedido frm = new fSelecionaPedido(valor);

            foreach (string pedido in cbxPedidos.Items)
            {
                frm.selecionados.Add(pedido);
            }
            frm.ShowDialog();
            if (frm.result)
            {
                cbxPedidos.Items.Clear();
                foreach (string selecionado in frm.selecionados)
                {
                    cbxPedidos.Items.Add(selecionado);
                }
                if (cbxPedidos.Items.Count > 0)
                {
                    cbxPedidos.Text = cbxPedidos.Items[0].ToString();
                }
                else
                {
                    cbxPedidos.Text = "";
                }
            }
            btnConfirma.Focus();
        }
Example #6
0
        void CalculaPreco()
        {
            string produto = edtProduto.Text.Trim();
            string subcod  = edtSubCodigo.Text.Trim();
            int    qtde;

            int.TryParse(edtQtde.Text.Trim(), out qtde);
            if ((fornecedor.Length == 0) || (caracteristica.Length == 0) || (produto.Length == 0) || (tabela.Length == 0))
            {
                return;
            }
            if (tabelas == null)
            {
                return;
            }
            preco_tabela   = tabelas.Preco(fornecedor, tabela, produto, subcod);
            preco_unitario = preco_tabela;
            cOrcamentos orcamento = new cOrcamentos();

            per_frete     = cCaracteristicas.Frete(fornecedor, caracteristica);
            preco_formula = preco_unitario;
            Globais.CalculaFormula(ref preco_formula, formula, ipi, per_frete, 0);
            edtPrecoFormula.Text = preco_formula.ToString("#,###,##0.00");
            if (qtde > 0)
            {
                edtPrecoTotal.Text = (Globais.Arredonda(preco_formula) * qtde).ToString("#,###,##0.00");
            }
        }
Example #7
0
        void BtnExcluiClick(object sender, EventArgs e)
        {
            string msg = "";
            bool   result;

            if (acao == 'c')
            {
                return;
            }
            string parceiro = edtParceiro.Text.Trim();
            string codigo   = edtCodigo.Text.Trim();

            result = tabelas.Exclui(parceiro, codigo, ref msg);
            if (!result)
            {
                MessageBox.Show(parceiro + "-" + codigo + "\r\n" + Globais.ErroExclusao("Tabela encontrada", msg), "Erro na exclusão da tabela", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            this.Cursor = Cursors.WaitCursor;
            tabelas.Carrega(dgvCadastro, chkAtivos.Checked);
            Grid.Sort(dgvCadastro, col_sorted, ord_sorted);
            this.Cursor = Cursors.Default;
            if (dgvCadastro.Rows.Count == 0)
            {
                InicializaCampos();
            }
        }
Example #8
0
        void BtnCalculoMouseEnter(object sender, EventArgs e)
        {
            dgvFormula.Visible = true;
            float     preco = preco_tabela;
            DataTable tab   = new DataTable();

            tab.Columns.Add("Percentual", typeof(string));
            tab.Columns.Add("Valor", typeof(float));
            tab.Rows.Add(new object[] { "Tabela", preco_tabela });
            //if (!item_especial || pedido)
            if (!item_especial)
            {
                Globais.MostraFormula(ref preco, formula, ipi, 0, 0, tab);
            }
            else
            {
                preco = preco_unitario;
                tab.Rows.Add(new object[] { "Especial", preco });
            }
            //preco += (preco * ipi / 100F);
            //tab.Rows.Add(new object[] {"IPI +"+ipi.ToString("#0")+"%", preco});
            int qtde = 0;

            int.TryParse(edtQtde.Text, out qtde);
            preco = Globais.Arredonda(preco) * qtde;
            tab.Rows.Add(new object[] { "x" + edtQtde.Text, preco });
            dgvFormula.DataSource = tab;
            dgvFormula.Columns["Percentual"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight;
            dgvFormula.Columns["Valor"].DefaultCellStyle.Alignment      = DataGridViewContentAlignment.MiddleRight;
            dgvFormula.Columns["Valor"].DefaultCellStyle.Format         = "###,###,##0.00";
        }
Example #9
0
        public void AtualizaDadosLocal(int i)
        {
            item_especial         = ckbEspecial.Checked = dgvCadastro.Rows[i].Cells["Especial"].Value.ToString().Trim().Equals("S");
            item_generico         = ckbGenerico.Checked = dgvCadastro.Rows[i].Cells["Genérico"].Value.ToString().Trim().Equals("S");
            edtArea.Text          = dgvCadastro.Rows[i].Cells["Área"].Value.ToString().Trim();
            edtDescricao.Text     = dgvCadastro.Rows[i].Cells["Seq"].Value.ToString().Trim();
            edtProduto.Text       = dgvCadastro.Rows[i].Cells["Produto"].Value.ToString().Trim();
            edtSubCodigo.Text     = dgvCadastro.Rows[i].Cells["Sub-Código"].Value.ToString().Trim();
            edtDescricaoProd.Text = dgvCadastro.Rows[i].Cells["Descrição"].Value.ToString().Trim();
            edtTexto.Text         = dgvCadastro.Rows[i].Cells["Texto"].Value.ToString().Trim();
            edtEspecificos.Text   = dgvCadastro.Rows[i].Cells["Específicos"].Value.ToString().Trim();
            ultimo_produto        = edtProduto.Text.Trim();
            ultimo_subcodigo      = edtSubCodigo.Text.Trim();
            edtQtde.Text          = dgvCadastro.Rows[i].Cells["Qtde"].Value.ToString().Trim();
            edtMedidas.Text       = dgvCadastro.Rows[i].Cells["Medidas"].Value.ToString().Trim();
            preco_formula         = Globais.StrToFloat(dgvCadastro.Rows[i].Cells["Preço"].Value.ToString());
            preco_unitario        = Globais.StrToFloat(dgvCadastro.Rows[i].Cells["Preço Unitário"].Value.ToString());
            preco_tabela          = Globais.StrToFloat(dgvCadastro.Rows[i].Cells["Preço Tabela"].Value.ToString());
            if (item_generico)
            {
                edtPrecoGenerico.Text = preco_tabela.ToString("#,###,##0.00");
            }
            else
            {
                edtPrecoGenerico.Text = 0.ToString("#,###,##0.00");
            }
            edtPrecoFormula.Text = preco_formula.ToString("#,###,##0.00");
            float total = Globais.Arredonda(preco_formula) * Globais.StrToInt(edtQtde.Text);

            edtPrecoTotal.Text = total.ToString("#,###,##0.00");
            MostraImagem();
        }
Example #10
0
        void BtnConfirmaClick(object sender, EventArgs e)
        {
            situacoes.Clear();
            foreach (DataGridViewRow row in dgvSituacoes.Rows)
            {
                if (!(bool)row.Cells["Seleciona"].Value)
                {
                    continue;
                }
                situacoes.Add(row.Cells["Código"].Value.ToString());
            }

            fornecedor     = edtCodigo.Text;
            filtrar_data   = ckbData.Checked;
            mesi           = (int)udMesI.Value;
            mesf           = (int)udMesF.Value;
            anoi           = Globais.StrToInt(edtAnoI.Text);
            anof           = Globais.StrToInt(edtAnoF.Text);
            vendedor       = cbxUsuarios.Text;
            cliente        = edtCliente.Text;
            consultor      = edtConsultor.Text;
            caracteristica = cbxCaracteristicas.Text;
            result         = true;
            idt_cadastroI  = dtpCadastroI.Checked ? "S" : "N";
            cadastroI      = dtpCadastroI.Value;
            idt_cadastroF  = dtpCadastroF.Checked ? "S" : "N";
            cadastroF      = dtpCadastroF.Value;
            resumo         = edtResumo.Text;
            Close();
        }
Example #11
0
        void BtnExcluiClick(object sender, EventArgs e)
        {
            string msg = "";
            bool   result;

            if (acao == 'c')
            {
                return;
            }
            string codigo = edtCodigo.Text.Trim();

            result = termos.Exclui(codigo, ref msg);
            if (!result)
            {
                MessageBox.Show(codigo + "\r\n" + Globais.ErroExclusao("Termo encontrado", msg), "Erro na exclusão do termo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            this.Cursor = Cursors.WaitCursor;
            termos.Carrega(dgvCadastro);
            this.Cursor = Cursors.Default;
            if (dgvCadastro.Rows.Count == 0)
            {
                InicializaCampos();
            }
        }
Example #12
0
        void DgvCadastroRowEnter(object sender, DataGridViewCellEventArgs e)
        {
            if (dgvCadastro.Rows.Count == 0)
            {
                return;
            }
            int i = e.RowIndex;

            if (dgvCadastro.Rows[i].Cells["isel"].Value == null)
            {
                return;
            }
            int isel = Globais.StrToInt(dgvCadastro.Rows[i].Cells["isel"].Value.ToString());

            if (rbtVendedor.Checked)
            {
                edtJustificativa.Text = dgvSelecao.Rows[isel].Cells["JusVendedor"].Value.ToString();
            }
            if (rbtConsultor.Checked)
            {
                edtJustificativa.Text = dgvSelecao.Rows[isel].Cells["JusConsultor"].Value.ToString();
            }
            if (rbtFilial.Checked)
            {
                edtJustificativa.Text = dgvSelecao.Rows[isel].Cells["JusFilial"].Value.ToString();
            }
        }
Example #13
0
        void BtnAlteraClick(object sender, EventArgs e)
        {
            if (dgvCadastro.Rows.Count == 0)
            {
                return;
            }
            int        i      = dgvCadastro.CurrentRow.Index;
            int        codigo = Globais.StrToInt(dgvCadastro.Rows[i].Cells["Código"].Value.ToString());
            fCadTitulo frm    = new fCadTitulo('a', codigo);

            frm.ShowDialog();
            if (frm.result)
            {
                CarregaTitulos();
                Grid.Sort(dgvCadastro, col_sorted, ord_sorted);
                for (i = 0; i < dgvCadastro.Rows.Count; i++)
                {
                    int cod = Globais.StrToInt(dgvCadastro.Rows[i].Cells["Código"].Value.ToString());
                    if (cod == codigo)
                    {
                        dgvCadastro.Rows[i].Cells["Parceiro"].Selected = true;
                        break;
                    }
                }
            }
        }
Example #14
0
        void ColoreProgramas()
        {
            string       usuario = dbgUsuarios.Rows[iUsuario].Cells[0].Value.ToString().Trim();
            string       filial  = dbgFiliais.Rows[iFilial].Cells[0].Value.ToString().Trim();
            int          sistema = Globais.StrToInt(dbgSistemas.Rows[iSistema].Cells[0].Value.ToString());
            FbCommand    cmd     = new FbCommand("select 1 from USUARIOS_PROGRAMAS where COD_USUARIO=@usuario and COD_FILIAL=@filial and COD_SISTEMA=@sistema and COD_PROGRAMA=@programa", Globais.bd);
            FbDataReader reader;

            cmd.Parameters.Add("@usuario", FbDbType.Char);
            cmd.Parameters.Add("@filial", FbDbType.Char);
            cmd.Parameters.Add("@sistema", FbDbType.Integer);
            cmd.Parameters.Add("@programa", FbDbType.Char);
            foreach (DataGridViewRow row in  dbgProgramas.Rows)
            {
                DataGridViewCell cell     = row.Cells[0];
                string           programa = cell.Value.ToString().Trim();
                cmd.Parameters["@usuario"].Value  = usuario;
                cmd.Parameters["@filial"].Value   = filial;
                cmd.Parameters["@sistema"].Value  = sistema;
                cmd.Parameters["@programa"].Value = programa;
                reader = cmd.ExecuteReader(CommandBehavior.SingleRow);
                if (!reader.Read())
                {
                    row.DefaultCellStyle.BackColor          = Color.Red;
                    row.DefaultCellStyle.SelectionBackColor = Color.Red;
                }
                else
                {
                    row.DefaultCellStyle.BackColor          = Color.Green;
                    row.DefaultCellStyle.SelectionBackColor = Color.Green;
                }
                reader.Close();
            }
        }
Example #15
0
        void BtnAlteraClick(object sender, EventArgs e)
        {
            if (dgvCadastro.Rows.Count == 0)
            {
                return;
            }
            int        i   = dgvCadastro.CurrentRow.Index;
            string     nf  = dgvCadastro.Rows[i].Cells["NF"].Value.ToString().Trim();
            short      seq = Globais.StrToShort(dgvCadastro.Rows[i].Cells["Seq"].Value.ToString());
            fCadTitulo frm = new fCadTitulo('a', nf, seq);

            frm.ShowDialog();
            if (frm.result)
            {
                CarregaTitulos();
                Grid.Sort(dgvCadastro, col_sorted, ord_sorted);
                for (i = 0; i < dgvCadastro.Rows.Count; i++)
                {
                    string NF = dgvCadastro.Rows[i].Cells["NF"].Value.ToString().Trim();
                    if (NF.Equals(nf))
                    {
                        dgvCadastro.Rows[i].Cells["Vencimento"].Selected = true;
                        break;
                    }
                }
            }
        }
Example #16
0
        void DbgProgramasCellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            string          msg       = "";
            int             iPrograma = e.RowIndex;
            DataGridViewRow row       = dbgProgramas.Rows[iPrograma];

            if (row.DefaultCellStyle.BackColor == Color.Green)
            {
                row.DefaultCellStyle.BackColor          = Color.Red;
                row.DefaultCellStyle.SelectionBackColor = Color.Red;
                controle.ExcluiPrograma(dbgUsuarios.Rows[iUsuario].Cells[0].Value.ToString().Trim(),
                                        dbgFiliais.Rows[iFilial].Cells[0].Value.ToString().Trim(),
                                        Globais.StrToInt(dbgSistemas.Rows[iSistema].Cells[0].Value.ToString()),
                                        dbgProgramas.Rows[iPrograma].Cells[0].Value.ToString().Trim(),
                                        ref msg);
            }
            else
            {
                row.DefaultCellStyle.BackColor          = Color.Green;
                row.DefaultCellStyle.SelectionBackColor = Color.Green;
                controle.IncluiPrograma(dbgUsuarios.Rows[iUsuario].Cells[0].Value.ToString().Trim(),
                                        dbgFiliais.Rows[iFilial].Cells[0].Value.ToString().Trim(),
                                        Globais.StrToInt(dbgSistemas.Rows[iSistema].Cells[0].Value.ToString()),
                                        dbgProgramas.Rows[iPrograma].Cells[0].Value.ToString().Trim(),
                                        ref msg);
            }
        }
Example #17
0
        void BtnConfirmaClick(object sender, EventArgs e)
        {
            cParametrosRemessa prms = new cParametrosRemessa();

            prms.COD_EMPRESA        = edtCodigo.Text;
            prms.NOM_EMPRESA        = edtRazao.Text;
            prms.NRO_REMESSA        = Globais.StrToInt(edtRemessa.Text);
            prms.NRO_NOSSO          = Globais.StrToInt(edtNosso.Text);
            prms.COD_CARTEIRA       = Globais.StrToInt(edtCarteira.Text);
            prms.COD_AGENCIA        = Globais.StrToInt(edtAgencia.Text);
            prms.DIG_AGENCIA        = Globais.StrToShort(edtDVAgencia.Text);
            prms.COD_CONTA          = Globais.StrToInt(edtConta.Text);
            prms.DIG_CONTA          = Globais.StrToShort(edtDVConta.Text);
            prms.PER_MULTA          = Globais.StrToFloat(edtMulta.Text);
            prms.VLR_BONIFICACAO    = Globais.StrToFloat(edtBonificacao.Text);
            prms.VLR_ATRASO         = Globais.StrToFloat(edtAtraso.Text);
            prms.QTD_PRAZO_DESCONTO = Globais.StrToShort(edtPrazo.Text);
            prms.VLR_DESCONTO       = Globais.StrToFloat(edtDesconto.Text);
            prms.DES_MENSAGEM1      = edtMsg1.Text;
            prms.DES_MENSAGEM2      = edtMsg2.Text;
            prms.DES_MENSAGEM3      = edtMsg3.Text;
            prms.DES_MENSAGEM4      = edtMsg4.Text;
            string msg = "";

            if (!prms.Altera(ref msg))
            {
                MessageBox.Show(msg, "Erro na gravação", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            Close();
        }
Example #18
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;
            }
        }
Example #19
0
        void Colore()
        {
            foreach (DataGridViewRow row in dgvCadastro.Rows)
            {
                if ((bool)row.Cells["S"].Value)
                {
                    row.DefaultCellStyle.BackColor = Color.SkyBlue;
                }
                else
                {
                    row.DefaultCellStyle.BackColor = Color.White;
                }
                if (row.Cells["Data"].Value != null)
                {
                    if (!row.Cells["Orçamento"].Value.ToString().Contains("/"))
                    {
                        int    mes = DateTime.Parse(row.Cells["Data"].Value.ToString()).Month;
                        int    ano = DateTime.Parse(row.Cells["Data"].Value.ToString()).Year;
                        string s   = mes.ToString("0#") + "/" + ano.ToString("####") + " - " + row.Cells["Orçamento"].Value.ToString();
                        row.Cells["Orçamento"].Value = s;
                    }
                }

                if (row.Cells["CodPedido"].Value != null)
                {
                    short codpedido = Globais.StrToShort(row.Cells["CodPedido"].Value.ToString());
                    if (codpedido == 2)
                    {
                        row.Cells["Fornecedor"].Value = "SERVICO";
                    }
                }
            }
        }
Example #20
0
        void BtnExcluiClick(object sender, EventArgs e)
        {
            if (dgvCadastro.Rows.Count == 0)
            {
                return;
            }
            int    i   = dgvCadastro.CurrentRow.Index;
            string nf  = dgvCadastro.Rows[i].Cells["NF"].Value.ToString().Trim();
            short  seq = Globais.StrToShort(dgvCadastro.Rows[i].Cells["Seq"].Value.ToString());
            string msg = "";

            if (filtro_pedido.Length == 0)
            {
                DialogResult r = MessageBox.Show(nf + "-" + seq.ToString(), "Confirma a exclusão?",
                                                 MessageBoxButtons.YesNo,
                                                 MessageBoxIcon.Question);
                if (r == DialogResult.No)
                {
                    return;
                }
                if (titulos.Exclui(nf, seq, ref msg))
                {
                    CarregaTitulos();
                    Grid.Sort(dgvCadastro, col_sorted, ord_sorted);
                }
            }
            else
            {
                titulos.Desassocia(nf, seq, ref msg);
                CarregaTitulos();
                Grid.Sort(dgvCadastro, col_sorted, ord_sorted);
            }
        }
 public belNfeInutilizacao(int sTpAmb, string sCoduf, string sCnpj, string sMod, string sSerie, string sJust,
                           string sNNFini, string sNNFfim, X509Certificate2 cert, string uf_empresa, bool bModoSCAN, int iStatusAtualSistema)
 {
     Globais LeRegWin = new Globais();
     _tpamp = sTpAmb;
     _cuf = sCoduf;
     _cnpj = Util.Util.TiraSimbolo(sCnpj, "");
     _mod = sMod;
     _serie = sSerie;
     _sjust = sJust;
     _nnffim = sNNFfim;
     _nnfini = sNNFini;
     _uf_empresa = uf_empresa;
     _spath = belStaticPastas.PROTOCOLOS;            
     this.pf = "http://www.portalfiscal.inf.br/nfe";
     this.cert = cert;
     if (HLP.bel.Static.belStatic.bModoSCAN)
     {
         buscaRetornoScan();
     }
     else
     {
         buscaRetorno();
     }
 }
Example #22
0
        public fGraficoNatureza(char origem)
        {
            this.origem = origem;
            InitializeComponent();
            if (origem == 'p')
            {
                titulos_pagar = new cTitulosPagar();
            }
            else
            {
                titulos_receber = new cTitulosXeceber();
            }
            valores          = new ArrayList();
            descricoes       = new ArrayList();
            dtpInicial.Value = DateTime.Now;
            int d = DateTime.Now.Day;
            int m = DateTime.Now.Month;
            int a = DateTime.Now.Year;

            dtpInicial.Value = Globais.StrToDateTime(string.Format("{0}/{1}/{2}", m, 1, a));
            if (m == 12)
            {
                a++;
            }
            else
            {
                m++;
            }
            dtpFinal.Value = Globais.StrToDateTime(string.Format("{0}/{1}/{2}", m, 1, a)).AddDays(-1);
        }
Example #23
0
        void MainFormLoad(object sender, EventArgs e)
        {
            string sBanco         = "";
            string sUltimoUsuario = "";
            string sUltimaFilial  = "";

            Globais.CarregaIni(ref sBanco, ref sUltimoUsuario, ref sUltimaFilial);
            string parametros = "User=SYSDBA;" +
                                "Password=masterkey;" +
                                "Database=" + sBanco;

            Globais.bd = new FbConnection(parametros);
            try
            {
                Log.Grava(Globais.sUsuario, parametros);
                Globais.bd.Open();
            }
            catch (Exception err)
            {
                Log.Grava(Globais.sUsuario, "erro:" + err.Message);
                MessageBox.Show("Erro na conexão com o banco de dados:\n" + sBanco +
                                "\n" + err.Message);
                Close();
                return;
            }

            if (login)
            {
                frmLogin frm = new frmLogin();
                frm.admin          = false;
                frm.sUltimoUsuario = sUltimoUsuario;
                frm.sUltimaFilial  = sUltimaFilial;
                frm.ShowDialog();
                if (!frm.bOK)
                {
                    Close();
                    return;
                }
                else
                {
                    Globais.GravaIni(sBanco, sUltimoUsuario, sUltimaFilial);
                }

                cControleAcesso acesso = new cControleAcesso();
                if (!Globais.bAdministrador && !acesso.PermissaoSistema(Globais.sUsuario, Globais.sFilial, 9))
                {
                    MessageBox.Show("Usuário sem permissão para esse Sistema", "Acesso negado", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    Close();
                }
            }
            frmFiltro = new Filtro();
            if (!Globais.bAdministrador)
            {
                frmFiltro.vendedor = Globais.sUsuario;
            }
            CarregaAcoes();
            col_sorted = "";
            ord_sorted = SortOrder.Ascending;
        }
Example #24
0
 void BtnConfirmaClick(object sender, EventArgs e)
 {
     result        = true;
     pago          = chkPago.Checked;
     justificativa = edtJustificativa.Text;
     percentual    = Globais.StrToFloat(edtPercentual.Text);
     Close();
 }
Example #25
0
        void BtnAlteraComissaoClick(object sender, EventArgs e)
        {
            if (dgvCadastro.Rows.Count == 0)
            {
                return;
            }
            int i = dgvCadastro.CurrentRow.Index;
            //float percentual_anterior = Globais.StrToFloat(dgvCadastro.Rows[i].Cells["Pago"].Value.ToString());
            fAlteraComissao frm = new fAlteraComissao();

            frm.total         = Globais.StrToFloat(dgvCadastro.Rows[i].Cells["Valor"].Value.ToString());
            frm.percentual    = Globais.StrToFloat(dgvCadastro.Rows[i].Cells["Pago"].Value.ToString());
            frm.pago          = bool.Parse(dgvCadastro.Rows[i].Cells["PG"].Value.ToString());
            frm.justificativa = dgvCadastro.Rows[i].Cells["Justificativa"].Value.ToString();
            frm.ShowDialog();
            if (!frm.result)
            {
                return;
            }
            //pago_zerado = (percentual_anterior > 0.001) && (frm.percentual < 0.001);
            pago_zerado = (frm.pago && (frm.percentual < 0.001));
            dgvCadastro.Rows[i].Cells["PG"].Value            = frm.pago;
            dgvCadastro.Rows[i].Cells["Justificativa"].Value = frm.justificativa;
            string   fornecedor = dgvCadastro.Rows[i].Cells["FornecedorOrcamento"].Value.ToString();
            DateTime data       = DateTime.Parse(dgvCadastro.Rows[i].Cells["Data"].Value.ToString());
            short    orcamento  = CodOrcamento(dgvCadastro.Rows[i].Cells["Orcamento"].Value.ToString());
            short    pedido     = Globais.StrToShort(dgvCadastro.Rows[i].Cells["CodPedido"].Value.ToString());
            cPedidos ped        = new cPedidos();
            int      isel       = Globais.StrToInt(dgvCadastro.Rows[i].Cells["isel"].Value.ToString());
            int      nsel       = dgvSelecao.Rows.Count;

            if (rbtVendedor.Checked)
            {
                ped.AlteraPerVendedor(fornecedor, data, orcamento, pedido, frm.percentual, frm.justificativa);
                dgvSelecao.Rows[isel].Cells["PerVendedor"].Value = frm.percentual;
                dgvSelecao.Rows[isel].Cells["JusVendedor"].Value = frm.justificativa;
                ped.AlteraIdtVendedor(fornecedor, data, orcamento, pedido, frm.pago);
                dgvSelecao.Rows[isel].Cells["IdtVendedor"].Value = frm.pago ? "S" : "N";
            }
            if (rbtConsultor.Checked)
            {
                ped.AlteraPerConsultor(fornecedor, data, orcamento, pedido, frm.percentual, frm.justificativa);
                dgvSelecao.Rows[isel].Cells["PerConsultor"].Value = frm.percentual;
                dgvSelecao.Rows[isel].Cells["JusConsultor"].Value = frm.justificativa;
                ped.AlteraIdtConsultor(fornecedor, data, orcamento, pedido, frm.pago);
                dgvSelecao.Rows[isel].Cells["IdtConsultor"].Value = frm.pago ? "S" : "N";
            }
            if (rbtFilial.Checked)
            {
                ped.AlteraPerFilial(fornecedor, data, orcamento, pedido, frm.percentual, frm.justificativa);
                dgvSelecao.Rows[isel].Cells["PerFilial"].Value = frm.percentual;
                dgvSelecao.Rows[isel].Cells["JusFilial"].Value = frm.justificativa;
                ped.AlteraIdtFilial(fornecedor, data, orcamento, pedido, frm.pago);
                dgvSelecao.Rows[isel].Cells["IdtFilial"].Value = frm.pago ? "S" : "N";
            }
            calcula();
            Posiciona(fornecedor, data, orcamento, pedido);
        }
    public static void Editor_Mapas_Mapa_Iluminação(short Índice)
    {
        Editor_Mapas Objetos       = Editor_Mapas.Objetos;
        byte         LuzGlobal_Tex = Listas.Mapa[Índice].LuzGlobal;
        Point        Início        = Globais.Zoom(Editor_Mapas.Objetos.scrlMapaX.Value, Editor_Mapas.Objetos.scrlMapaY.Value);
        byte         Luz           = (byte)((255 * ((decimal)Listas.Mapa[Índice].Iluminação / 100) - 255) * -1);

        // Somente se necessário
        if (!Editor_Mapas.Objetos.butVisualização.Checked)
        {
            return;
        }

        // Escuridão
        Jan_Mapa_Iluminação.Clear(CCor(0, 0, 0, Luz));

        // Desenha o ponto iluminado
        if (Listas.Mapa[Índice].Luz.Count > 0)
        {
            for (byte i = 0; i <= Listas.Mapa[Índice].Luz.Count - 1; i++)
            {
                Desenhar(Jan_Mapa_Iluminação, Tex_Iluminação, Editor_Mapas.Zoom_Grade(Listas.Mapa[Índice].Luz[i].Retângulo), null, new RenderStates(BlendMode.Multiply));
            }
        }

        // Pré visualização
        if (Editor_Mapas.Objetos.butMIluminação.Checked)
        {
            Desenhar(Jan_Mapa_Iluminação, Tex_Iluminação, Globais.Zoom(Editor_Mapas.Mapa_Seleção), null, new RenderStates(BlendMode.Multiply));
        }

        // Apresenta o que foi renderizado
        Jan_Mapa_Iluminação.Display();
        Jan_Mapa.Draw(new Sprite(Jan_Mapa_Iluminação.Texture));

        // Luz global
        if (LuzGlobal_Tex > 0)
        {
            Desenhar(Jan_Mapa, Tex_Luz[LuzGlobal_Tex], Editor_Mapas.Zoom(new Rectangle(new Point(-Início.X, -Início.Y), TTamanho(Tex_Luz[LuzGlobal_Tex]))), CCor(255, 255, 255, 175), new RenderStates(BlendMode.Add));
        }

        // Ponto de remoção da luz
        if (Objetos.butMIluminação.Checked)
        {
            if (Listas.Mapa[Índice].Luz.Count > 0)
            {
                for (byte i = 0; i <= Listas.Mapa[Índice].Luz.Count - 1; i++)
                {
                    DesenharRetângulo(Jan_Mapa, Listas.Mapa[Índice].Luz[i].Retângulo.X * Globais.Grade_Zoom, Listas.Mapa[Índice].Luz[i].Retângulo.Y * Globais.Grade_Zoom, Globais.Grade_Zoom, Globais.Grade_Zoom, CCor(175, 42, 42, 175));
                }
            }
        }

        // Trovoadas
        Size Tamanho = new Size(Editor_Mapas.Zoom((Listas.Mapa[Índice].Largura + 1) * Globais.Grade), Editor_Mapas.Zoom((Listas.Mapa[Índice].Altura + 1) * Globais.Grade));

        Desenhar(Jan_Mapa, Tex_Preenchido, 0, 0, 0, 0, Tamanho.Width, Tamanho.Height, CCor(255, 255, 255, Globais.Relâmpago));
    }
Example #27
0
 private void txtNome_Validated(object sender, EventArgs e)
 {
     // Atualiza a lista
     if (Selecionado > 0)
     {
         Listas.NPC[Selecionado].Nome    = txtNome.Text;
         lstLista.Items[Selecionado - 1] = Globais.Numeração(Selecionado, lstLista.Items.Count) + ":" + txtNome.Text;
     }
 }
Example #28
0
    private void butLimpar_Click(object sender, EventArgs e)
    {
        // Limpa os dados
        Limpar.NPC(Selecionado);

        // Atualiza os valores
        lstLista.Items[Selecionado - 1] = Globais.Numeração(Selecionado, lstLista.Items.Count) + ":";
        Atualizar();
    }
Example #29
0
        void CarregaProgramas()
        {
            int sistema = Globais.StrToInt(dbgSistemas.Rows[iSistema].Cells[0].Value.ToString());

            programas   = new cProgramas();
            this.Cursor = Cursors.WaitCursor;
            programas.Carrega(dbgProgramas, sistema);
            this.Cursor = Cursors.Default;
        }
Example #30
0
        public belNfeConsultaNF(string sVersao, string sVerDados,  string sChnfe, string sXServ)
        {
            Globais Gb = new Globais();
            _tpamb = belStatic.TpAmb;         
            _versao = sVersao;
            _versaodados = "2.01";
            _xserv = sXServ;
            _chnfe = sChnfe;

        }
    private static void Listar_Marcadores()
    {
        // Adiciona os itens à lista
        for (byte i = 1; i <= Listas.Marcador.GetUpperBound(0); i++)
        {
            Objetos.lstLista.Items.Add(Globais.Numeração(i, Listas.Marcador.GetUpperBound(0)) + ":" + Listas.Marcador[i].Geral.Nome);
        }

        // Abre o painel
        Objetos.panMarcador.Visible = true;
    }
Example #32
0
        void BtnConfirmaClick(object sender, EventArgs e)
        {
            fornecedor                 = edtCodigo.Text;
            idt_dataI                  = dtpDataI.Checked ? "S" : "N";
            dataI                      = dtpDataI.Value;
            idt_dataF                  = dtpDataF.Checked ? "S" : "N";
            dataF                      = dtpDataF.Value;
            idt_ou_entrega             = chkOuEntrega.Checked ? "S" : "N";
            idt_nao_entregues          = chkNaoEntregues.Checked ? "S" : "N";
            dias_nao_entregues         = Globais.StrToShort(edtNaoEntregues.Text);
            idt_ou_montagem            = chkOuMontagem.Checked ? "S" : "N";
            idt_nao_montados           = chkNaoMontados.Checked ? "S" : "N";
            dias_nao_montados          = Globais.StrToShort(edtNaoMontados.Text);
            idt_entrega_previstaI      = dtpEntregaPrevistaI.Checked ? "S" : "N";
            entrega_previstaI          = dtpEntregaPrevistaI.Value;
            idt_entrega_previstaF      = dtpEntregaPrevistaF.Checked ? "S" : "N";
            entrega_previstaF          = dtpEntregaPrevistaF.Value;
            idt_entrega_realI          = dtpEntregaRealI.Checked ? "S" : "N";
            entrega_realI              = dtpEntregaRealI.Value;
            idt_entrega_realF          = dtpEntregaRealF.Checked ? "S" : "N";
            entrega_realF              = dtpEntregaRealF.Value;
            idt_montagem_previstaI     = dtpMontagemPrevistaI.Checked ? "S" : "N";
            montagem_previstaI         = dtpMontagemPrevistaI.Value;
            idt_montagem_previstaF     = dtpMontagemPrevistaF.Checked ? "S" : "N";
            montagem_previstaF         = dtpMontagemPrevistaF.Value;
            idt_montagem_realI         = dtpMontagemRealI.Checked ? "S" : "N";
            montagem_realI             = dtpMontagemRealI.Value;
            idt_montagem_realF         = dtpMontagemRealF.Checked ? "S" : "N";
            idt_omitir_anos_anteriores = chkAnosAnteriores.Checked ? "S" : "N";
            idt_sem_previsao           = chkSemPrevisao.Checked ? "S" : "N";
            idt_pendentes_consultor    = chkPendentesConsultor.Checked ? "S" : "N";
            idt_pendentes_vendedor     = chkPendentesVendedor.Checked ? "S" : "N";
            montagem_realF             = dtpMontagemRealF.Value;
            vendedor                   = cbxUsuarios.Text;
            cliente                    = edtCliente.Text;
            consultor                  = edtConsultor.Text;
            pedido_fornec              = edtPedidoFornec.Text;
            nf_fornec                  = edtNFFornec.Text;
            observacao                 = edtObservacao.Text;
            idt_cadastroI              = dtpCadastroI.Checked ? "S" : "N";
            cadastroI                  = dtpCadastroI.Value;
            idt_cadastroF              = dtpCadastroF.Checked ? "S" : "N";
            cadastroF                  = dtpCadastroF.Value;
            result                     = true;
            float valor = 0;

            float.TryParse(edtVlrInicial.Text, out valor);
            vlr_inicial = (valor != 0) ? valor.ToString() : "";
            float.TryParse(edtVlrFinal.Text, out valor);
            vlr_final      = (valor != 0) ? valor.ToString() : "";
            numero_pedido  = edtPedido.Text;
            caracteristica = cbxCaracteristicas.Text;
            Close();
        }
Example #33
0
 void BtnFechaClick(object sender, EventArgs e)
 {
     if (dgvCadastro.Rows.Count > 0)
     {
         int i = dgvCadastro.CurrentRow.Index;
         nf     = dgvCadastro.Rows[i].Cells["NF"].Value.ToString().Trim();
         seq    = Globais.StrToShort(dgvCadastro.Rows[i].Cells["Seq"].Value.ToString());
         result = true;
     }
     Close();
 }
        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;
            }
        }
        public frmEmailContadorNfe()
        {
            InitializeComponent();
            VerificaCamposEmail();
            Globais objGlobais = new Globais();
            sArqConfigDia = belStaticPastas.ENVIADOS + "\\Contador_xml\\" + "ConfigDia.txt";

            objListaSemanas.Add(new DiasSemana { Display = "Domingo", Valor = "Sunday" });
            objListaSemanas.Add(new DiasSemana { Display = "Segunda", Valor = "Monday" });
            objListaSemanas.Add(new DiasSemana { Display = "Terça", Valor = "Tuesday" });
            objListaSemanas.Add(new DiasSemana { Display = "Quarta", Valor = "Wednesday" });
            objListaSemanas.Add(new DiasSemana { Display = "Quinta", Valor = "Thursday" });
            objListaSemanas.Add(new DiasSemana { Display = "Sexta", Valor = "Friday" });
            objListaSemanas.Add(new DiasSemana { Display = "Sabado", Valor = "Saturday" });

            cbxDia.DisplayMember = "Display";
            cbxDia.ValueMember = "Valor";
            cbxDia.DataSource = objListaSemanas;

            FileInfo finfo = new FileInfo(sArqConfigDia);
            if (finfo.Exists)
            {
                FileStream theFile = File.Open(sArqConfigDia, FileMode.Open, FileAccess.Read);
                StreamReader reader = new StreamReader(theFile);
                string sDia = reader.ReadToEnd().Trim();
                if (sDia == "month")
                {
                    cbxDia.Enabled = false;
                    cbxDia.SelectedIndex = -1;
                    chkMensal.Checked = true;
                }
                else
                {
                    cbxDia.SelectedValue = sDia;
                    chkSemanal.Checked = true;
                    cbxDia.Enabled = true;
                }
                reader.Close();
            }
            else
            {
                KryptonMessageBox.Show("Para utilizar essa Rotina, primeiro Acerte a Configuração de Alerta!", "A V I S O", MessageBoxButtons.OK, MessageBoxIcon.Information);
                tabControl1.SelectedTab = tabPage2;
            }
        }
        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;
        }
        public belNfeCancelamento(string versao, string tpamb, string xserv, string xjust, string versaodados, string sEmp, string sSeq,
                                  X509Certificate2 xCert, string UF_Empresa, bool bModoSCAN, int iStatusAtualSistema)
        {
            this._versao = versao;
            this._emp = sEmp;
            this._tpamb = tpamb;
            this._xserv = xserv;
            this._seq = sSeq;
            this._xjust = xjust;
            this._versaodados = versaodados;
            Globais caminho = new Globais();
            this._spath = belStaticPastas.PROTOCOLOS;
            this._cert = xCert;

            if ((bModoSCAN) && (iStatusAtualSistema == 3))
            {
                buscaRetornoSCAN(UF_Empresa);
            }
            else
            {
                buscaRetorno(UF_Empresa);
            }
        }
        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 CampactaZip()
        {
            HLP.bel.NFe.GeraXml.Globais objGlobais = new Globais();
            try
            {
                foreach (belEmailContador item in objListaEmailContador.Where(c => c.bSelect == true).ToList())
                {
                    using (ZipFile zip = new ZipFile())
                    {
                        zip.StatusMessageTextWriter = zip.StatusMessageTextWriter;

                        // Compacta arquivos Enviados
                        DirectoryInfo dinfoArq = new DirectoryInfo(item.sCaminhoEnviado);
                        if (dinfoArq.Exists)
                        {
                            foreach (FileSystemInfo arq in dinfoArq.GetFileSystemInfos())
                            {
                                try
                                {
                                    List<XElement> xListElem = item.xmlArqEnviados.Descendants("Email").Elements("Envio").Where(c => c.Attribute("Tipo").Value.ToString() == "enviados").ToList();
                                    if (xListElem.Where(x => x.Value.ToString() == arq.Name).Count() == 0)
                                    {
                                        zip.AddFile(arq.FullName);
                                        item.xmlArqEnviados.Element("Email").Add(new XElement("Envio", new XAttribute("Tipo", "enviados"), arq.Name));
                                    }
                                }
                                catch (Exception ex)
                                {
                                    throw ex;
                                }

                            }
                        }

                        //  Compacta arquivos Cancelados
                        dinfoArq = new DirectoryInfo(item.sCaminhoCancelado);
                        if (dinfoArq.Exists)
                        {
                            foreach (FileSystemInfo arq in dinfoArq.GetFileSystemInfos())
                            {
                                List<XElement> xListElem = item.xmlArqEnviados.Descendants("Email").Elements("Envio").Where(c => c.Attribute("Tipo").Value.ToString() == "cancelados").ToList();
                                if (xListElem.Where(x => x.Value.ToString() == arq.Name.ToString()).Count() == 0)
                                {
                                    zip.AddFile(arq.FullName);
                                    item.xmlArqEnviados.Element("Email").Add(new XElement("Envio", new XAttribute("Tipo", "cancelados"), arq.Name));
                                }
                            }
                        }

                        //  Compacta arquivos CCe
                        if (!string.IsNullOrEmpty(item.sCaminhoCCe))
                        {
                            dinfoArq = new DirectoryInfo(item.sCaminhoCCe);
                            if (dinfoArq.Exists)
                            {
                                foreach (FileSystemInfo arq in dinfoArq.GetFileSystemInfos())
                                {
                                    List<XElement> xListElem = item.xmlArqEnviados.Descendants("Email").Elements("Envio").Where(c => c.Attribute("Tipo").Value.ToString() == "cce").ToList();
                                    if (xListElem.Where(x => x.Value.ToString() == arq.Name.ToString()).Count() == 0)
                                    {
                                        zip.AddFile(arq.FullName);
                                        item.xmlArqEnviados.Element("Email").Add(new XElement("Envio", new XAttribute("Tipo", "cce"), arq.Name));
                                    }
                                }
                            }
                        }


                        if (File.Exists(item.sCaminhoZip))
                        {
                            File.Delete(item.sCaminhoZip);
                        }
                        zip.Save(item.sCaminhoZip);
                        item.xmlArqEnviados.Save(item.dinfo.FullName + "\\" + item.sName + HLP.Util.Util.GetDateServidor().Date.Day.ToString().PadLeft(2, '0') + ".xml");
                    }
                }
            }
            catch (Exception)
            {

                throw;
            }
        }
Example #40
0
        //Danner - o.s. 23851 - 19/11/2009
        private void geraNFeCanc(string sChnfe, Globais glob)
        {
            DirectoryInfo dinfo = new DirectoryInfo(belStaticPastas.ENVIADOS + "\\" + sChnfe.Substring(2, 4));
            string path = "";
            string nome = "";
            try
            {
                FileInfo[] finfo = dinfo.GetFiles();

                foreach (var item in finfo)
                {
                    if (item.Name.Contains(sChnfe))
                    {
                        path = item.FullName;
                        nome = item.Name;
                        break;
                    }

                }
                DirectoryInfo dinfoPasta = new DirectoryInfo(belStaticPastas.CANCELADOS + "\\" + HLP.Util.Util.GetDateServidor().Date.ToString("yyMM"));
                if (!dinfoPasta.Exists) { dinfoPasta.Create(); }

                File.Move(path, dinfoPasta.FullName + "\\" + nome.Replace("nfe", "can") + ".xml");
            }
            catch (Exception x)
            {

                throw new Exception("Erro ao tentar mover o arquivo - " + x.Message);
            }
            File.Delete(path);
        }
        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!");
            }
        }
        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 #43
0
        private void frmConfiguracao_FormClosing(object sender, FormClosingEventArgs e)
        {
            errorProvider1.Clear();
            if (verificaPastasPreenchidas() == 0)
            {

                if (txtCaminhoPadrao.Text != "")
                {
                    belStaticPastas.CAMINHO = txtCaminhoPadrao.Text.Trim();
                }
                SalvarXml();
                KryptonMessageBox.Show("Todas as alterações foram salvas.", "S A L V A R", MessageBoxButtons.OK, MessageBoxIcon.Information);

                if (belStatic.BSemArquivo == true)
                {
                    belStatic.BSemArquivo = false;
                    belStatic.IPrimeiroLoad = 1;
                    frmSelecionaConfigs objFrmSeleciona = new frmSelecionaConfigs();
                    objFrmSeleciona.ShowDialog();

                    frmLogin objfrm = new frmLogin();
                    objfrm.ShowDialog();
                    belStatic.IPrimeiroLoad = 0;
                }
                HLP.bel.NFe.belConfigInicial.CarregaConfiguracoesIniciais();
                Globais LeRegWin = new Globais();
                LeRegWin.CarregaInfStaticas(); // INICIALIZA AS PASTAS PADRÕES
            }
            else
            {
                KryptonMessageBox.Show(null, "Os Campos em Alerta são Obrigatórios para o Parametro!! ", "A L E R T A", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                e.Cancel = true;
            }

            // Diego OS-24205 - 05/03/2010 - FIM
        }
        private void NfeDadosMsg()
        {
            XmlSchemaCollection myschema = new XmlSchemaCollection();
            XmlValidatingReader reader;
            Globais sPath = new Globais();
            belConnection cx = new belConnection();
            try
            {
                StringBuilder sSql = new StringBuilder();
                sSql.Append("select ");
                sSql.Append("cd_chavenferet, ");
                sSql.Append("cd_nprotnfe ");
                sSql.Append("from nf ");
                sSql.Append("where ");
                sSql.Append("(cd_empresa = '");
                sSql.Append(_emp);
                sSql.Append("') ");
                sSql.Append("and ");
                sSql.Append("(cd_nfseq = '");
                sSql.Append(_seq);
                sSql.Append("')");




                FbCommand cmdcanc = new FbCommand(sSql.ToString(), cx.get_Conexao());
                cx.Open_Conexao();
                cmdcanc.ExecuteNonQuery();



                FbDataReader drCanc = cmdcanc.ExecuteReader();
                drCanc.Read();

                _chnfe = drCanc["cd_chavenferet"].ToString();
                _nprot = drCanc["cd_nprotnfe"].ToString();
                _id = "ID" + _chnfe;

                XNamespace xname = "http://www.portalfiscal.inf.br/nfe";
                XDocument xdoc = new XDocument(new XElement(xname + "cancNFe", new XAttribute("versao", _versaodados),
                                                   new XElement(xname + "infCanc", new XAttribute("Id", _id),
                                                       new XElement(xname + "tpAmb", _tpamb),
                                                       new XElement(xname + "xServ", _xserv),
                                                       new XElement(xname + "chNFe", _chnfe),
                                                       new XElement(xname + "nProt", _nprot),
                                                       new XElement(xname + "xJust", _xjust))));
                xdoc.Save(_spath + "\\" + _seq + "_ped-can.xml");

                AssinaNFeCancXml assinaCanc = new AssinaNFeCancXml();
                assinaCanc.ConfigurarArquivo(_spath + "\\" + _seq + "_ped-can.xml", "infCanc", _cert);

                StreamReader ler;

                ler = File.OpenText(_spath + "\\" + _seq + "_ped-can.xml");



                XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);

                reader = new XmlValidatingReader(ler.ReadToEnd().ToString(), XmlNodeType.Element, context);

                myschema.Add("http://www.portalfiscal.inf.br/nfe", belStaticPastas.SCHEMA_NFE + "\\cancNFe_v2.00.xsd");

                reader.ValidationType = ValidationType.Schema;

                reader.Schemas.Add(myschema);

                while (reader.Read())
                { }

            }
            catch (Exception x)
            {
                throw new Exception(x.Message);
            }
            finally { cx.Close_Conexao(); }
        }
Example #45
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 #46
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 #47
0
        /// <summary>
        /// Email de CCe
        /// </summary>
        /// <param name="sSeq"></param>
        /// <param name="sNum"></param>
        /// <param name="sEmp"></param>
        /// <param name="sHost"></param>
        /// <param name="sPorta"></param>
        /// <param name="sDe"></param>
        /// <param name="sSenha"></param>
        /// <param name="sPath"></param>
        /// <param name="sPara"></param>
        /// <param name="bAutentica"></param>
        public belEmail(belPesquisaCCe cce, string sSeq, string sNum, string sEmp, string sHost, string sPorta, string sDe, string sSenha, string sPara, bool bAutentica)
        {
            this.sNum = sNum;
            if (sPara == "")
            {
                _para = retEmailDestinatario(sSeq, sEmp);
            }
            else
            {
                _para = sPara;
            }

            _paraTransp = retEmailTransportador(sSeq, sEmp); // 24776 - Diego
            _envia = true;
            _sSeq = sSeq;

            _autentica = bAutentica;//Danner - o.s. 24329 - 08/04/2010
            _de = sDe;
            _porta = Convert.ToInt16(sPorta);
            _host = sHost;
            _senha = sSenha;
            _corpo = geraCorpoEmail(cce);
            Globais LeRegWin = new Globais();
            string sPath = belStaticPastas.ENVIADOS + "\\Servicos" + "\\PDF\\" + cce.CD_NOTAFIS + ".pdf";
            _anexo = sPath;
            _assunto = "Mensagem Automática 'Carta de Correção Eletrônica de " + belStatic.sNomeEmpresaCompleto + "'";

        }
Example #48
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 #49
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 #50
0
        private void btnCanc_Click(object sender, EventArgs e)
        {
            Globais pega = new Globais();
            //Danner - o.s. 23851 - 19/11/2009
            AssinaNFeXml bc = new AssinaNFeXml();
            X509Certificate2 cert = new X509Certificate2();
            cert = bc.BuscaNome("");
            //Fim - Danner - o.s. 23851 - 19/11/2009
            try
            {

                if (txtJust.Text.Length < 15)
                {
                    KryptonMessageBox.Show(null, "Justificativa Insuficiente, Mínimo de 15 Caracteres", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    txtJust.Focus();
                }
                else
                {
                    belNfeCancelamento nfecanc = new belNfeCancelamento("1.02", "2", "CANCELAR", txtJust.Text, "1.07", _emp, _snotacanc[0].ToString(), cert, UF_Empresa, belStatic.bModoSCAN, belStatic.iStatusAtualSistema);//Danner - o.s. 23984 - 07/01/2010
                    XmlDocument xmlret = new XmlDocument();
                    xmlret.LoadXml(nfecanc.Sret);
                    string cstat = xmlret.GetElementsByTagName("cStat")[0].InnerText;
                    string xmotivo = xmlret.GetElementsByTagName("xMotivo")[0].InnerText;
                    if (cstat != "101")
                    {
                        throw new Exception("Erro " + cstat + ": " + xmotivo);
                    }
                    else
                    {
                        string nprot = xmlret.GetElementsByTagName("nProt")[0].InnerText;
                        string chnfe = xmlret.GetElementsByTagName("chNFe")[0].InnerText;


                        StringBuilder sSql = new StringBuilder();

                        sSql.Append("update nf ");
                        sSql.Append("set cd_recibocanc = '");
                        sSql.Append(nprot);
                        sSql.Append("' ");
                        sSql.Append("where ");
                        sSql.Append("cd_empresa = '");
                        sSql.Append(_emp);
                        sSql.Append("' ");
                        sSql.Append("and ");
                        sSql.Append("cd_nfseq = '");
                        sSql.Append(_snotacanc[0]);
                        sSql.Append("'");

                        using (FbCommand cmdUpdate = new FbCommand(sSql.ToString(), cx.get_Conexao()))
                        {
                            cx.Open_Conexao();
                            cmdUpdate.ExecuteNonQuery();
                        }

                        geraNFeCanc(chnfe, pega);
                        KryptonMessageBox.Show(null, "Nota Cancelada com Sucesso", "Cancelamento", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    }
                }
            }
            catch (Exception x)
            {
                throw new Exception(x.Message + " - Nota não foi cancelada com sucesso!");
            }
            finally { cx.Close_Conexao(); }

        }
Example #51
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 #52
0
        private string NfeDadosMsg()
        {
            XNamespace xnome = "http://www.portalfiscal.inf.br/nfe";
            XmlSchemaCollection myschema = new XmlSchemaCollection();
            XmlValidatingReader reader;
            try
            {
                XNamespace xname = "http://www.portalfiscal.inf.br/nfe";
                XDocument xdoc = new XDocument(new XElement(xname + "consReciNFe", new XAttribute("versao", "2.00"),
                                               new XElement(xname + "tpAmb", _tpamb.ToString()),
                                               new XElement(xname + "nRec", _nrec)));

                //Danner -  o.s. sem - 04/11/2009
                Globais xml = new Globais();

                XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);

                reader = new XmlValidatingReader(xdoc.ToString(), XmlNodeType.Element, context);

                myschema.Add("http://www.portalfiscal.inf.br/nfe", belStaticPastas.SCHEMA_NFE + "\\consReciNFe_v2.00.xsd");

                reader.ValidationType = ValidationType.Schema;

                reader.Schemas.Add(myschema);

                while (reader.Read())
                { }
                return xdoc.ToString();
            }
            catch (XmlException x)
            {
                throw new Exception(x.Message.ToString());
            }
            catch (XmlSchemaException x)
            {
                throw new Exception(x.Message.ToString());
            }
            //Fim - Danner -  o.s. sem - 04/11/2009
        }
        private void RefreshGrid()
        {
            HLP.bel.NFe.GeraXml.Globais objGlobais = new Globais();
            DirectoryInfo dEnviados = new DirectoryInfo(belStaticPastas.ENVIADOS);
            int icount = 0;
            objListaEmailContador = new List<belEmailContador>();

            foreach (FileSystemInfo pasta in dEnviados.GetFileSystemInfos())
            {
                if (belStatic.RAMO == "TRANSPORTE")
                {
                    if (pasta.Name.Length == 5)
                    {
                        belEmailContador objEmailCont = new belEmailContador();
                        objEmailCont.iId = icount++;
                        objEmailCont.Mes = pasta.Name.Substring(0, 2);
                        objEmailCont.sAno = "20" + pasta.Name.Substring(3, 2);
                        objEmailCont.sName = pasta.Name;
                        objEmailCont.sCaminhoEnviado = pasta.FullName;
                        objEmailCont.sCaminhoCancelado = belStaticPastas.CANCELADOS + "\\" + pasta.Name;
                        DirectoryInfo dinfoEnviados = new DirectoryInfo(objEmailCont.sCaminhoEnviado);
                        DirectoryInfo dinfoCancelados = new DirectoryInfo(objEmailCont.sCaminhoCancelado);
                        objEmailCont.iFaltantes = (dinfoEnviados.Exists ? dinfoEnviados.GetFileSystemInfos().Count() : 0) + (dinfoCancelados.Exists ? dinfoCancelados.GetFileSystemInfos().Count() : 0);

                        string sCaminho = belStaticPastas.ENVIADOS + "\\Contador_xml\\" + pasta.Name + HLP.Util.Util.GetDateServidor().Date.Day.ToString().PadLeft(2, '0') + ".xml";
                        if (File.Exists(sCaminho))
                        {
                            XDocument xmlDoc = XDocument.Load(sCaminho);
                            objEmailCont.xmlArqEnviados = xmlDoc;
                            //Count nos arquivos que já foram enviados q estão no Xml.
                            objEmailCont.iEnviadoContador = xmlDoc.Descendants("Email").Elements("Envio").Count();
                        }
                        else
                        {
                            objEmailCont.xmlArqEnviados = new XDocument();
                            objEmailCont.xmlArqEnviados.Add(new XElement("Email"));
                            objEmailCont.xmlArqEnviados.Save(sCaminho);
                        }

                        objListaEmailContador.Add(objEmailCont);
                    }
                }
                else if (pasta.Name.Length == 4)
                {
                    belEmailContador objEmailCont = new belEmailContador();
                    objEmailCont.iId = icount++;
                    objEmailCont.Mes = pasta.Name.Substring(2, 2);
                    objEmailCont.sAno = "20" + pasta.Name.Substring(0, 2);
                    objEmailCont.sName = pasta.Name;

                    objEmailCont.sCaminhoEnviado = pasta.FullName;
                    objEmailCont.sCaminhoCancelado = belStaticPastas.CANCELADOS + "\\" + pasta.Name;
                    objEmailCont.sCaminhoCCe = belStaticPastas.CCe + "\\" + pasta.Name;

                    DirectoryInfo dinfoEnviados = new DirectoryInfo(objEmailCont.sCaminhoEnviado);
                    DirectoryInfo dinfoCancelados = new DirectoryInfo(objEmailCont.sCaminhoCancelado);
                    DirectoryInfo dCartaCorrecao = new DirectoryInfo(objEmailCont.sCaminhoCCe);

                    objEmailCont.iFaltantes = (dinfoEnviados.Exists ? dinfoEnviados.GetFileSystemInfos().Count() : 0) + (dinfoCancelados.Exists ? dinfoCancelados.GetFileSystemInfos().Count() : 0) +
                                              (dCartaCorrecao.Exists ? dCartaCorrecao.GetFileSystemInfos().Count() : 0);

                    string sCaminho = belStaticPastas.ENVIADOS + "\\Contador_xml\\" + pasta.Name + HLP.Util.Util.GetDateServidor().Date.Day.ToString().PadLeft(2, '0') + ".xml";
                    if (File.Exists(sCaminho))
                    {
                        XDocument xmlDoc = XDocument.Load(sCaminho);
                        objEmailCont.xmlArqEnviados = xmlDoc;
                        //Count nos arquivos que já foram enviados q estão no Xml.
                        objEmailCont.iEnviadoContador = xmlDoc.Descendants("Email").Elements("Envio").Count();
                    }
                    else
                    {
                        objEmailCont.xmlArqEnviados = new XDocument();
                        objEmailCont.xmlArqEnviados.Add(new XElement("Email"));
                        objEmailCont.xmlArqEnviados.Save(sCaminho);
                    }

                    objListaEmailContador.Add(objEmailCont);
                }
            }
            dataGridView1.Rows.Clear();
            belEmailContadorBindingSource.DataSource = new object();
            belEmailContadorBindingSource.DataSource = objListaEmailContador.OrderByDescending(c => c.iId);

            string sCaminhoXml = objListaEmailContador.First().dinfo.FullName + "\\" + "emailContador.xml";

            foreach (HLP.bel.NFe.belEmailContador obj in objListaEmailContador)
            {
                if (obj.iFaltantes == 0)
                {
                    obj.Ienviado = GeraXml.Properties.Resources.confirmar;
                }
                else
                {
                    obj.Ienviado = GeraXml.Properties.Resources.cancel__3_;
                }
            }
        }
Example #54
0
        public void enviaEmail()
        {
            try
            {
                SmtpClient cliente = new SmtpClient(_host, _porta);
                cliente.EnableSsl = _autentica;
                cliente.Timeout = 200000;
                MailAddress remetente = new MailAddress(_de);
                MailAddress destinatario = new MailAddress((_para != "" ? _para : _paraTransp));
                MailMessage mensagem = new MailMessage(remetente, destinatario);
                // Diego - 24776
                if ((_paraTransp != "") && (_para != ""))
                {
                    MailAddress dest_Trasnp = new MailAddress(_paraTransp);
                    mensagem.To.Add(dest_Trasnp);
                }
                // Diego - 24776 - FIM
                mensagem.IsBodyHtml = bCorpoHTML;
                mensagem.Body = _corpo;
                mensagem.Subject = _assunto;

                if (_anexo != null)
                {
                    Attachment anexo = new Attachment(_anexo);
                    mensagem.Attachments.Add(anexo);
                }
                if ((_anexo2 != "") && (_anexo2 != null))
                {
                    Attachment anexo2 = new Attachment(_anexo2);
                    mensagem.Attachments.Add(anexo2);
                }
                Globais objGlobais = new Globais();
                string sPDF_cancelado = belStaticPastas.ENVIADOS + "\\PDF\\" + this.sNum + "_cancelado.pdf";
                string sPDF_danfe = belStaticPastas.ENVIADOS + "\\PDF\\" + this.sNum + "_enviado.pdf";
                string sTemp = belStaticPastas.CBARRAS;
                string sArquivo = "";
                sArquivo = string.Format("_{0}{1}{2}", HLP.Util.Util.GetDateServidor().Hour, HLP.Util.Util.GetDateServidor().Minute, HLP.Util.Util.GetDateServidor().Second);

                if (File.Exists(sPDF_cancelado))
                {
                    sArquivo = sTemp + "\\" + this.sNum + sArquivo + "_cancelado.pdf";
                    File.Copy(sPDF_cancelado, sArquivo, true);
                    Attachment anexo = new Attachment(sArquivo);
                    mensagem.Attachments.Add(anexo);
                }
                else if (File.Exists(sPDF_danfe))
                {
                    sArquivo = sTemp + "\\" + this.sNum + sArquivo + "_enviado.pdf";
                    File.Copy(sPDF_danfe, sArquivo, true);
                    Attachment anexo = new Attachment(sArquivo);
                    mensagem.Attachments.Add(anexo);
                }

                if (objListaEmailContador.Count > 0)
                {
                    DirectoryInfo dinfo = new DirectoryInfo(belStaticPastas.ENVIADOS + "\\Contador_xml");
                    foreach (HLP.bel.NFe.belEmailContador item in objListaEmailContador)
                    {
                        Attachment anexo = new Attachment(item.sCaminhoZip);
                        mensagem.Attachments.Add(anexo);
                    }
                }

                NetworkCredential credenciais = new NetworkCredential(_de, _senha);

                cliente.Credentials = credenciais;

                cliente.Send(mensagem);

            }
            catch (SmtpException x)
            {

                throw new Exception(x.Message);
            }
        }
Example #55
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 #56
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;
            }


        }
        private XmlNode MontaMsg()
        {
            try
            {
                XmlSchemaCollection myschema = new XmlSchemaCollection();
                XmlValidatingReader reader;
                XNamespace pf = "http://www.portalfiscal.inf.br/nfe";

                XDocument xdoc = new XDocument(new XElement(pf + "ConsCad", new XAttribute("versao", "2.00"),
                                                    new XElement(pf + "infCons",
                                                               new XElement(pf + "xServ", "CONS-CAD"),
                                                               new XElement(pf + "UF", sUF),
                                                               (sIE != "" ? new XElement(pf + "IE", Util.Util.TiraSimbolo(sIE, "")) : null),
                                                               ((sCNPJ != "" && sIE == "") ? new XElement(pf + "CNPJ", Util.Util.TiraSimbolo(sCNPJ, "")) : null),
                                                               ((sCPF != "" && sIE == "" && sCNPJ == "") ? new XElement(pf + "CPF", Util.Util.TiraSimbolo(sCPF, "")) : null))));

              

                XmlParserContext context = new XmlParserContext(null, null, "", XmlSpace.None);

                reader = new XmlValidatingReader(xdoc.ToString(), XmlNodeType.Element, context);

                Globais Gb = new Globais();

                myschema.Add("http://www.portalfiscal.inf.br/nfe", belStaticPastas.SCHEMA_NFE + "\\consCad_v2.00.xsd");

                reader.ValidationType = ValidationType.Schema;

                reader.Schemas.Add(myschema);

                while (reader.Read())
                { }
                string sDados = xdoc.ToString();
                XmlDocument Xmldoc = new XmlDocument();
                Xmldoc.LoadXml(sDados);
                XmlNode xNode = Xmldoc.DocumentElement;
                return xNode;
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Example #58
0
        private void btnInutilizar_Click(object sender, EventArgs e)
        {
            XmlDocument xmldoc = new XmlDocument();
            try
            {


                if (txtNNFini.Text == "")
                {
                    KryptonMessageBox.Show("Número Inicial Não Preenchido!", "A T E N Ç Ã O", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

                }
                else if (txtNNFfim.Text == "")
                {
                    KryptonMessageBox.Show("Número Final Não Preenchido!", "A T E N Ç Ã O", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
                else if (txtXjust.Text == "")
                {
                    KryptonMessageBox.Show("Justificativa Não Preenchido!", "A T E N Ç Ã O", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);

                }
                else if (txtXjust.Text.Length < 15)
                {
                    KryptonMessageBox.Show("Justificativa Não Preenchido!", "A T E N Ç Ã O", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                }
                else
                {
                    retInfempresa();
                    AssinaNFeXml assina = new AssinaNFeXml();
                    X509Certificate2 cert = assina.BuscaNome("");
                    belNfeInutilizacao objinutilizacao = new belNfeInutilizacao(_tpamp, _cuf, _cnpj, _mod, cbxSerie.Text, txtXjust.Text,
                                                                                txtNNFini.Text, txtNNFfim.Text, cert, _uf_empresa, belStatic.bModoSCAN, belStatic.iStatusAtualSistema);


                    xmldoc.LoadXml(objinutilizacao.RetWs);
                    Globais LeRegWin = new Globais();

                    if (xmldoc.GetElementsByTagName("cStat")[0].InnerText == "102")
                    {
                        KryptonMessageBox.Show(null, "Tipo Ambiente: " + xmldoc.GetElementsByTagName("tpAmb")[0].InnerText + Environment.NewLine +
                                              "Status: " + xmldoc.GetElementsByTagName("cStat")[0].InnerText + Environment.NewLine +
                                              "Descrição: " + xmldoc.GetElementsByTagName("xMotivo")[0].InnerText + Environment.NewLine +
                                              "Ano: " + xmldoc.GetElementsByTagName("ano")[0].InnerText + Environment.NewLine +
                                              "Modelo da NF-e: " + xmldoc.GetElementsByTagName("mod")[0].InnerText + Environment.NewLine +
                                              "Serie da NF-e: " + xmldoc.GetElementsByTagName("serie")[0].InnerText + Environment.NewLine +
                                              "Número Inicial: " + xmldoc.GetElementsByTagName("nNFIni")[0].InnerText + Environment.NewLine +
                                              "Número Final: " + xmldoc.GetElementsByTagName("nNFFin")[0].InnerText + Environment.NewLine +
                                              "Data do Recbto: " + xmldoc.GetElementsByTagName("dhRecbto")[0].InnerText.Replace('T', ' ') + Environment.NewLine +
                                              "Número do Protocolo: " + xmldoc.GetElementsByTagName("nProt")[0].InnerText, "INUTILIZAÇÃO DE NUMERACAO",
                                              MessageBoxButtons.OK,
                                              MessageBoxIcon.Information);
                        xmldoc.Save(belStaticPastas.PROTOCOLOS + "\\" + xmldoc.GetElementsByTagName("nProt")[0].InnerText + "_inu.xml");
                    }
                    else
                    {
                        KryptonMessageBox.Show(null, "Tipo Ambiente: " + xmldoc.GetElementsByTagName("tpAmb")[0].InnerText + Environment.NewLine +
                                              "Status: " + xmldoc.GetElementsByTagName("cStat")[0].InnerText + Environment.NewLine +
                                              "Descrição: " + xmldoc.GetElementsByTagName("xMotivo")[0].InnerText,
                                              "INUTILIZAÇÃO DE NUMERACAO",
                                              MessageBoxButtons.OK,
                                              MessageBoxIcon.Information);
                    }
                    this.Close();
                }
            }
            catch (Exception ex)
            {

                KryptonMessageBox.Show(ex.Message);
            }

        }
Example #59
0
        /// <summary>
        /// 1 - Envio / 2 - Enviados
        /// </summary>
        /// <param name="sPasta"></param>
        private void OrganizaPastas(int iPasta)
        {
            try
            {
                HLP.bel.NFe.GeraXml.Globais objbelGlobais = new Globais();
                System.IO.DirectoryInfo diretorio = new System.IO.DirectoryInfo((iPasta == 1 ? belStaticPastas.ENVIO : belStaticPastas.ENVIADOS));
                System.IO.FileSystemInfo[] arquivos = diretorio.GetFileSystemInfos();
                int icount = 0;

                foreach (System.IO.FileSystemInfo item in arquivos)
                {
                    if ((item.Extension.Equals(".xml")) && (item.Name.ToString().Length == 52))
                    {
                        System.IO.DirectoryInfo pasta = new System.IO.DirectoryInfo(diretorio.FullName + "/" + item.Name.Substring(2, 4));
                        if (!pasta.Exists) { pasta.Create(); }

                        if (!File.Exists(@pasta.FullName + "/" + item))
                        {
                            File.Move(@item.FullName, @pasta.FullName + "/" + item);
                            icount++;
                        }
                    }
                }
                if (icount > 0)
                {
                    KryptonMessageBox.Show(null, icount.ToString() + " Arquivo(s) encontrado(s) e organizado(s) ", "ORGANIZAÇÃO DE ARQUIVOS", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                else
                {
                    KryptonMessageBox.Show(null, "Nenhum arquivo .xml encontrado no caminho:  " + Environment.NewLine + Environment.NewLine + "-->" + diretorio.FullName, "ORGANIZAÇÃO DE ARQUIVOS", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }


            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #60
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(); }
        }