protected void btnPesPortador_Click(object sender, EventArgs e)
        {
            Session["tabelaPesquisa"] = null;
            DataTable dt = CriarDtPesquisa();

            PortadoresBL potBL = new PortadoresBL();
            Portadores pt = new Portadores();
            List<Portadores> portador = potBL.PesquisarBL();

            foreach (Portadores cat in portador)
            {
                DataRow linha = dt.NewRow();

                linha["ID"] = cat.Id;
                linha["CODIGO"] = cat.Codigo;
                linha["DESCRICAO"] = cat.Descricao;

                dt.Rows.Add(linha);
            }

            Session["tabelaPesquisa"] = null;

            if (dt.Rows.Count > 0)
                Session["tabelaPesquisa"] = dt;

            Session["objBLPesquisa"] = potBL;
            Session["objPesquisa"] = pt;

            ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "WinOpen('/Pesquisar.aspx?caixa=" + txtPortador.ClientID + "&id=" + hfIdPortador.ClientID + "&lbl=" + lblDesPortador.ClientID + "','',600,500);", true);
        }
        protected void dtgPortadores_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            PortadoresBL porBL = new PortadoresBL();
            Portadores por = new Portadores();
            por.Id = utils.ComparaIntComZero(dtgPortadores.DataKeys[e.RowIndex][0].ToString());

            if (porBL.ExcluirBL(por))
                ExibirMensagem("Registro excluído com sucesso !");
            else
                ExibirMensagem("Não foi possível excluir o registro, existem registros dependentes");
            Pesquisar(null);
        }
        protected void btnSalvar_Click(object sender, EventArgs e)
        {
            PortadoresBL porBL = new PortadoresBL();
            Portadores portadores = new Portadores();

            portadores.Id = utils.ComparaIntComZero(hfId.Value);
            portadores.Codigo = utils.ComparaIntComZero(txtCodigo.Text);
            portadores.Descricao = txtDescricao.Text;
            portadores.AgenciaId = utils.ComparaIntComNull(ddlAgencia.SelectedValue);
            portadores.BancoId = utils.ComparaIntComNull(ddlBanco.SelectedValue);
            portadores.ContaId = utils.ComparaIntComNull(ddlConta.SelectedValue);
            portadores.CodCedente = utils.ComparaIntComNull(txtNroConvenio.Text);
            portadores.Carteira = txtCarteira.Text;

            if (portadores.Id > 0)
            {

                if (porBL.EditarBL(portadores))
                    ExibirMensagem("Portador atualizado com sucesso !");
                else
                    ExibirMensagem("Não foi possível gravar o portador. Revise as informações.");

            }
            else
            {

                if (porBL.InserirBL(portadores))
                {
                    ExibirMensagem("Portador gravado com sucesso !");
                    LimparCampos();
                }
                else
                    ExibirMensagem("Não foi possível gravar o portador. Revise as informações.");

            }
        }
        private void CarregarDDlPortador()
        {
            PortadoresBL porBL = new PortadoresBL();
            List<Portadores> portador = porBL.PesquisarBL();

            ddlPortador.Items.Add(new ListItem());
            foreach (Portadores ltPor in portador)
                ddlPortador.Items.Add(new ListItem(ltPor.Codigo.ToString() + " - " + ltPor.Descricao, ltPor.Id.ToString()));
            ddlPortador.SelectedIndex = 0;
        }
        private void carregarDados(int id_por)
        {
            PortadoresBL porBL = new PortadoresBL();
            List<Portadores> por = porBL.PesquisarBL(id_por);
            string id_age;

            foreach (Portadores ltPor in por)
            {
                hfId.Value = ltPor.Id.ToString();
                txtCodigo.Text = ltPor.Codigo.ToString();
                txtDescricao.Text = ltPor.Descricao;
                ddlBanco.SelectedValue = ltPor.BancoId.ToString();
                CarregarDDLAgencia(utils.ComparaIntComZero(ddlBanco.SelectedValue));
                ddlAgencia.SelectedValue = ltPor.AgenciaId.ToString();
                id_age = ltPor.AgenciaId.ToString();
                CarregarDDLConta(utils.ComparaIntComZero(id_age));
                ddlConta.SelectedValue = ltPor.ContaId.ToString();
                txtNroConvenio.Text = ltPor.CodCedente.ToString();
                txtCarteira.Text = ltPor.Carteira.ToString();
            }
        }
        protected void txtCodigo_TextChanged(object sender, EventArgs e)
        {
            PortadoresBL porBL = new PortadoresBL();

            if (porBL.CodigoJaUtilizadoBL(utils.ComparaIntComZero(txtCodigo.Text)))
            {
                lblInformacao.Text = "O código " + txtCodigo.Text + " já existe. Informe um novo código.";
                txtCodigo.Text = "";
                txtCodigo.Focus();
            }
            else
            {
                lblInformacao.Text = "";
                txtDescricao.Focus();
            }
        }
        protected void btnGerar_Click(object sender, EventArgs e)
        {
            TitulosBL titulosBL = new TitulosBL();
            PortadoresBL portadoresBL = new PortadoresBL();
            SelecaoTitulos selTitulos = new SelecaoTitulos();
            InstituicoesBL instBL = new InstituicoesBL();

            CriarDtBoletos();
            DataSet dsInst = instBL.PesquisarDsBL();
            List<Titulos> titulos = titulosBL.PesquisarBuscaBL(selTitulos);

            StringBuilder linhaDigitavel = new StringBuilder();
            DateTime dtInicialFV = new DateTime(1997, 10, 07);

            foreach (Titulos ltTit in titulos)
            {
                DataRow linha = dt_boletos.NewRow();

                //cedente que vai receber o valor
                List<Portadores> portadores = portadoresBL.PesquisarBL(utils.ComparaIntComZero(ltTit.Portadorid.ToString()));

                foreach (Portadores ltPor in portadores)
                {
                    linha["CodCedente"] = ltPor.CodCedente;
                    linha["CedNossonumero"] = "2222";
                    //linha["CED_CPFCNPJ"] =  ;
                    linha["Cedente"] = dsInst.Tables[0].Rows[0]["razao"].ToString();
                    linha["CedAgencia"] = ltPor.Agencia.Codigo;
                    //linha["CED_CONTA"] = ltPor.Contas.Codigo;
                    //linha["CED_DIGITOCONTA"] = ltPor.Contas.Digito;

                    if (ltPor.Banco != null)
                        linha["Banco"] = ltPor.Banco.Codigo;
                    else
                        linha["Banco"] = "";
                }

                ////sacado quem vai pagar o titulo
                //linha["SAC_CPFCNPJ"] = ltTit.Pessoas.CpfCnpj;
                //linha["SAC_NOME"] = ltTit.Pessoas.Nome;
                //linha["SAC_ENDERECO"] = ltTit.Pessoas.Endereco;
                //linha["SAC_BAIRRO"] = ltTit.Pessoas.Bairro.Descricao;
                //linha["SAC_CIDADE"] = ltTit.Pessoas.Cidade.Descricao;
                //linha["SAC_CEP"] = ltTit.Pessoas.Cep;
                //linha["SAC_UF"] = ltTit.Pessoas.Cidade.Estados.Uf;

                linha["DataVencimento"] = ltTit.DataVencimento;
                linha["ValorBoleto"] = ltTit.Valor;
                linha["NumeroDocumento"] = ltTit.Numero;
                linha["Instrucoes1"] = ddlInstrucao1.SelectedValue;
                linha["Instrucoes2"] = ddlInstrucao2.SelectedValue;
                linha["Carteira"] = "teste";
                linha["LocalPagamento"] = "Até o vencimento, preferencialmente no Banco Banrisul";
                linha["Aceite"] ="N"; //implementar o aceite.
                linha["DataDocumento"] = ltTit.DataEmissao;
                linha["DataProcessamento"] = DateTime.Now;
                linha["Quantidade"] = 1;

                //codigo do banco 01 - 03
                linhaDigitavel.Append(linha["LinhaDigitavel"]);
                //moeda 9 real 04 - 04
                linhaDigitavel.Append("9");
                //DAC 05 - 05
                linhaDigitavel.Append(" ");
                //fator de vencimento 06 - 09
                linhaDigitavel.Append(utils.CalcularNumeroDiasEntreDatas(dtInicialFV, DateTime.Now));
                //valor 10 -19
                utils.IncluirCampoNumerico(linhaDigitavel, linha["ValorBoleto"].ToString(), 10);
                //campo livre 20 - 44
                linhaDigitavel.Append("");
                //Produto 20 - 20 2 cobrança direta, fichario emitido pelo cliente
                linhaDigitavel.Append("2");
                //Constante 1
                linhaDigitavel.Append("1");
                //Codigo da agencia 22 - 25
                utils.IncluirCampoNumerico(linhaDigitavel, linha["CedAgencia"].ToString(), 4);
                //Codigo do cedente 26 - 32
                utils.IncluirCampoNumerico(linhaDigitavel, linha["CodCedente"].ToString(), 7);
                //Nosso numero 33 - 40
                linhaDigitavel.Append("");
                //Constante 40 41 - 42
                linhaDigitavel.Append("40");
                //Duplo digito modulos 10 e 11
                linhaDigitavel.Append("");

                linha["LinhaDigitavel"] = linhaDigitavel.ToString();

                dt_boletos.Rows.Add(linha);
            }

            Session["ldsRel"] = dt_boletos;
            if (((DataTable)Session["ldsRel"]).Rows.Count != 0)
            {                                                                                                                                                                                                                                                                                                                                                                                                                                           //l//c
                ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "WinOpen('/Relatorios/RelBoletos.aspx?Eventos=" + ddlPortador.SelectedValue + "','',600,1000);", true);
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "alert('Sua pesquisa não retornou dados.');", true);
            }
        }
        private void CarregarDdlPortador()
        {
            PortadoresBL porDBL = new PortadoresBL();
            List<Portadores> port = porDBL.PesquisarBL();

            ddlPortadorMulta.Items.Add(new ListItem("Selecione", ""));
            foreach (Portadores ltPort in port)
                ddlPortadorMulta.Items.Add(new ListItem(ltPort.Codigo + " - " + ltPort.Descricao, ltPort.Id.ToString()));

            ddlPortadorMulta.SelectedIndex = 0;
        }
        private void Pesquisar(string valor)
        {
            DataTable tabela = new DataTable();
            DataColumn coluna1 = new DataColumn("ID", Type.GetType("System.Int32"));
            DataColumn coluna2 = new DataColumn("CODIGO", Type.GetType("System.Int32"));
            DataColumn coluna3 = new DataColumn("DESCRICAO", Type.GetType("System.String"));
            DataColumn coluna4 = new DataColumn("CODAGENCIA", Type.GetType("System.String"));
            DataColumn coluna5 = new DataColumn("CODBANCO", Type.GetType("System.String"));
            DataColumn coluna6 = new DataColumn("DESBANCO", Type.GetType("System.String"));
            DataColumn coluna7 = new DataColumn("DESAGENCIA", Type.GetType("System.String"));

            tabela.Columns.Add(coluna1);
            tabela.Columns.Add(coluna2);
            tabela.Columns.Add(coluna3);
            tabela.Columns.Add(coluna4);
            tabela.Columns.Add(coluna5);
            tabela.Columns.Add(coluna6);
            tabela.Columns.Add(coluna7);

            PortadoresBL porBL = new PortadoresBL();
            List<Portadores> portadores;

            portadores = porBL.PesquisarBuscaBL(valor);

            foreach (Portadores ltPor in portadores)
            {
                DataRow linha = tabela.NewRow();

                linha["ID"] = ltPor.Id;
                linha["CODIGO"] = ltPor.Codigo;
                linha["DESCRICAO"] = ltPor.Descricao;

                if (ltPor.Banco != null)
                {
                    linha["CODBANCO"] = ltPor.Banco.Codigo.ToString();
                    linha["DESBANCO"] = ltPor.Banco.Descricao;
                }
                else
                {
                    linha["CODBANCO"] = "";
                    linha["DESBANCO"] = "";
                }

                if (ltPor.Agencia != null)
                {
                    linha["CODAGENCIA"] = ltPor.Agencia.Codigo.ToString();
                    linha["DESAGENCIA"] = ltPor.Agencia.Descricao;
                }
                else
                {
                    linha["CODAGENCIA"] = "";
                    linha["DESAGENCIA"] = "";

                }
                tabela.Rows.Add(linha);
            }

            dtbPesquisa = tabela;
            dtgPortadores.DataSource = tabela;
            dtgPortadores.DataBind();
        }
        public void pesquisaPortador(string lCampoPesquisa)
        {
            Session["tabelaPesquisa"] = null;

            DataTable dt = CriarTabelaPesquisa();

            PortadoresBL porBL = new PortadoresBL();
            Portadores po = new Portadores();
            List<Portadores> portadores;
            if (this.txtPortador.Text != string.Empty && lCampoPesquisa != string.Empty)
            {
                portadores = porBL.PesquisarBuscaBL(this.txtPortador.Text);
            }
            else
            {
                portadores = porBL.PesquisarBL();
            }

            foreach (Portadores pes in portadores)
            {
                DataRow linha = dt.NewRow();

                linha["ID"] = pes.Id;
                linha["CODIGO"] = pes.Codigo;
                linha["DESCRICAO"] = pes.Descricao;

                dt.Rows.Add(linha);
            }

            if (dt.Rows.Count > 0)
                Session["tabelaPesquisa"] = dt;
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "ALERTA", "alert('Portador não encontrado.');", true);
            }

            Session["objBLPesquisa"] = porBL;
            Session["objPesquisa"] = po;
        }
        protected void btnGerar_Click(object sender, EventArgs e)
        {
            //UTF-8 ISO-8859-1 verificar qual utilizar
            Remessa remessa = new Remessa();

            Nomedoarquivo = Path.Combine(Path.GetTempPath(), System.IO.Path.GetRandomFileName() + ".txt");
            StreamWriter sw = new StreamWriter(Nomedoarquivo, true, System.Text.Encoding.GetEncoding("UTF-8"));

            PortadoresBL portadoresBL = new PortadoresBL();
            TitulosBL titulosBL = new TitulosBL();
            SelecaoTitulos selTitulos = new SelecaoTitulos();

            selTitulos.CodTitulos = txtIntTitulos.Text;
            selTitulos.PortadorId = ddlPortador.SelectedValue;
            selTitulos.DataEmissaoIni = txtDtEmiIni.Text;
            selTitulos.DataEmissaoFim = txtDtEmiFim.Text;
            selTitulos.DataVencimentoIni = txtDtVencIni.Text;
            selTitulos.DataVencimentoFim = txtDtVencFim.Text;
            selTitulos.Tipo = "R";

            remessa.DiasProtesto = txtDiasUm.Text;
            remessa.Instrucao1 = ddlInstrucao1.SelectedValue;
            remessa.Instrucao2 = ddlInstrucao2.SelectedValue;
            remessa.CodOcorrencia = ddlRemessa.SelectedValue;
            remessa.JuroMora = ddlJuroMora.SelectedValue;

            StringBuilder arquivo = new StringBuilder();
            int v_seq = 1;
            string codCedente = "";

            List<Portadores> portadores = portadoresBL.PesquisarBL(utils.ComparaIntComZero(ddlPortador.SelectedValue));

            foreach (Portadores ltPor in portadores)
            {
                titulosBL.ArquivoRemessaMontarHeader(arquivo, ltPor, v_seq.ToString());
                sw.WriteLine(arquivo);
                codCedente = ltPor.CodCedente.ToString();
            }

            List<Titulos> titulos = titulosBL.PesquisarBuscaBL(selTitulos);

            foreach (Titulos ltTit in titulos)
            {
                v_seq++;
                arquivo.Clear();
                titulosBL.ArquivoRemessaMontarTransacao(arquivo, ltTit, remessa, v_seq.ToString(), codCedente);
                sw.WriteLine(arquivo);
            }

            arquivo.Clear();
            v_seq++;
            titulosBL.ArquivoRemessaMontarTrailler(arquivo, "300", v_seq.ToString());
            sw.WriteLine(arquivo);

            sw.Close();
            lkbDownload.Visible = true;
            lkbDownload.Text = "remessa_" + ddlPortador.SelectedItem.Text.Replace(" ", "_") + "_" + DateTime.Now.ToString("dd_MM_yyyy") + ".txt";
            btnGerar.Visible = false;
        }