Exemple #1
0
    protected void enviar_Click(object sender, EventArgs e) //Botão Login ADM COORD e PROF
    {
        lblMsgErro.Text = "";

        // pegar valor dos textbox do login
        string user = txtLogin.Text.ToString();
        //string senha = Funcoes.Criptografar(txtSenha.Text.ToString(), "SHA1"); ->>> não lê a senha correta do banco por algum motivo
        string senha = txtSenha.Text.ToString();

        Perfil perfil = new Perfil();

        //Verificar se os campos não estão vazios
        if (!String.IsNullOrEmpty(user) && !String.IsNullOrEmpty(senha))
        {
            Professor prof = new Professor();      //instancia um novo professor
            prof = Professor.Validar(user, senha); //valida o professor e retorna para o obj professor

            if (prof != null)
            {
                Session["curso"]      = "";
                Session["semestre"]   = "";
                Session["disciplina"] = "";
                Session["mae"]        = "";
                Session["Professor"]  = prof;
                Session["matricula"]  = prof.Matricula;
                Session["nome"]       = prof.Nome;
                Session["menu"]       = "coordenador"; //ADM
                Session["perfil"]     = null;          //ADM
                Session["login"]      = user;          // E-MAIL DO PROFESSOR
                Session["DataSetCalendarioAndProfessor"] = null;
                Session["DS_AllPIsbyCalendarioAtual"]    = null;

                if (Funcoes_DB.ValidarAdmCoord(prof) == 2)
                {
                    //Coordenador e professor
                    //chama a página de escolher o perfil
                    Response.Redirect("~/EscolherPerfil");
                }
                else
                {
                    Response.Redirect("~/EscolherDisciplina");
                }
            }

            else
            {
                lblMsgErro.Text = "E-mail e/ou Senha incorretos.";
            }
        }
        else
        {
            // Campos estão vazios
            lblMsgErro.Text = "Preencha os campos.";
        }
    }
Exemple #2
0
    private void CarregaGrid()                                 //Carrega grid com todos os PIs
    {
        DataSet ds = Funcoes_DB.SelectAllPIs();                //dataset que recebe todos os PIs através desse método

        int qtd = ds.Tables[0].Rows.Count;                     //conta quantas linhas retornou o dataset

        if (qtd > 0)                                           //se a quantidade de linhas retornadas pelo dataset for > 0 vai preencher a grid
        {
            gdvProjetos.DataSource = ds.Tables[0].DefaultView; //fonte de dados do grid view recebe o ds criado anteriormente
            gdvProjetos.DataBind();                            //preenche o grid view com os dados

            //percorre cada linha da grid que vai servir para substituir o nome dos status e curso para melhor visualização
            foreach (GridViewRow linha in gdvProjetos.Rows)
            {
                Label lblStatus        = (Label)linha.FindControl("lblStatus");        //acha o label status da grid e liga a outro label
                Label lblSemestreCurso = (Label)linha.FindControl("lblSemestreCurso"); //acha o label semestre da grid e liga a outro label

                lblSemestreCurso.Text = lblSemestreCurso.Text + "º Semestre";          //acrescenta na label Curso ºSemestre

                bool valor = false;                                                    //variavel criada para verificar se o status do PI esta em andamento ou finalizado e habilitar o linkbutton

                if (lblStatus.Text == "False")                                         //verifica se o status na grid está retornando false
                {
                    lblStatus.Text = "Em andamento";                                   //se for, troca o "false" por "em andamento"
                }
                else //senao estiver retornando false, ou seja, true
                {
                    lblStatus.Text = "Finalizado"; //se não for "false", troca por "finalizado"
                }

                if (lblStatus.Text == "Em andamento")                                 // verifica se o status do PI está em andamento
                {
                    valor = true;                                                     //se sim a variavel recebe true
                }
                if (valor == true)                                                    //se o PI estiver em andamento o botao habilitar pra edição fica invisivel
                {
                    LinkButton botao = (LinkButton)linha.FindControl("lkbHabilitar"); //acha o label semestre da grid e liga a outro label
                    botao.Visible = false;                                            //deixa o botao invisivel
                }
            }
        }
    }
Exemple #3
0
    protected void btnEnviarM_Click(object sender, EventArgs e) //BOTÃO LOGIN MASTER
    {
        lblMsgErroM.Text = "";

        // pegar valor dos textbox do login
        string user = txtLoginM.Text; //.ToString() não precisa, o .Text já converte pra String
        //string senha = Funcoes.Criptografar(txtSenha.Text.ToString(), "SHA1"); ->>> precisa trocar pelo SHA1 do Visual Studio para funcionar
        string senha = txtSenhaM.Text;



        //Verificar se os campos não estão vazios
        if (!String.IsNullOrEmpty(user) && !String.IsNullOrEmpty(senha))
        {
            //verifica se é master e armazena um número que indica sucesso ou falha

            if (Funcoes_DB.ValidarAdmMaster(user, senha) == 1)
            {
                Perfil perfil = new Perfil("master");

                //Administrador master
                Session["login"]     = user;
                Session["menu"]      = "master";
                Session["matricula"] = perfil.Matricula;
                Session["nome"]      = "Master";
                Response.Redirect("~/Auditoria");
            }
            else
            {
                lblMsgErroM.Text = "Login inválido";
            }
        }
        else
        {
            lblMsgErroM.Text = "Os campos devem ser preenchidos!";
        }
    }
Exemple #4
0
    protected static int c = 1;                                       //instancia uma varíavel c para contar quantas vezes o usuário errou a senha
    protected void lkbConfirmaSenha_Click(object sender, EventArgs e) //EVENTO QUE VALIDA A SENHA DO MASTER AO CLICAR EM CONFIRMAR
    {
        string senha = txtSenha.Text;                                 //pega o valor digita no campo senha e armazena na string senha

        if (!String.IsNullOrEmpty(senha))                             //verifica se o campo de senha está fazio
        {
            if (Funcoes_DB.ValidaSenha(senha) == 1)                   //VERIFICA SE A FUNÇÃO DE VALIDAR RETORNOU 1
            {
                c = 1;
                string caminhoArquivo = Session["caminhoArquivo"].ToString();                                                 //PEGA O CAMINHO DO ARQUIVO DA VARÍAVEL DE SESSÃO
                string acao           = Session["acaoBackup"].ToString();                                                     //PEGA A AÇÃO DO USUÁRIO (DOWNLOAD OU BACKUP) E COLOCA NUMA STRING acao
                if (acao == "Download")                                                                                       //SE A ACAO FOR DOWNLOAD (SE CLICOU NO BOTÃO DOWNLOAD)
                {
                    PostBackTrigger trigger = new PostBackTrigger();                                                          //INSTANCIA UMA NOVA TRIGGER QUE RECARREGARÁ A PÁGINA (NECESSÁRIO PARA FAZER O DOWNLOAD)
                    trigger.ControlID = timerDownload.UniqueID;                                                               //DEFINE QUE O CONTROLE timerDownload IRÁ FAZER O POSTABACK(RECARREGAMENTO) DA PÁGINA
                    UpdatePanelModal.Triggers.Add(trigger);                                                                   //ADICIONA A TRIGGER AO UPDATEPANEL DA MODAL
                    lblMsgModal.Style.Add("color", "green");                                                                  //DEIXA O TEXTO DA MODAL VERDE
                    lblMsgModal.Text             = "Seu download iniciará em breve...";                                       //COLOCA A MENSAGEM DE INICANDO DOWNLAOD
                    timerDownload.Enabled        = true;                                                                      /*HABILITA O CONTADOR DO DOWNLOAD: QUANDO O TEMPO ESGOTAR, SERÁ DISPARADO O MÉTODO timerDownload_Tick
                                                                                                                               * ESSE MÉTODO ESTÁ QUASE NO FIM DA PÁGINA
                                                                                                                               */
                    Session["esperandoDownload"] = "sim";                                                                     //DEFINE UMA VARÍAVEL DE SESSÃO PARA CONTROLAR SE UM DOWNLOAD É ESPERADO OU NÃO
                }
                else if (acao == "Restauracao")                                                                               //SE A ACAO FOR RESTAURAÇÃO (SE CLICOU NO BOTÃO RESTAURAR)
                {
                    string constring    = ConfigurationManager.AppSettings["strConexao"];                                     //pega os dados do banco do Web.config
                    string database     = constring.Substring(9, 5);                                                          //corta a string dos dados do banco e pega somente o nome do banco (posicao 9, inter = 5 letras)
                    string nome_arquivo = "bkpSec_" + database + "_" + DateTime.Now.ToString("yyyy-MM-dd-HH-mm-ss") + ".sql"; //faz o nome do arquivo baseado no nome do banco e data local
                    string directory    = (Request.PhysicalApplicationPath + "Backup");                                       //solicita o caminho da aplicação e coloca numa string juntando com Backup

                    //COMEÇA O PROCESSO DE BACKUP DE SEGURANÇA ---------->
                    string file = (directory + "\\" + nome_arquivo);
                    using (MySqlConnection conn = new MySqlConnection(constring)) //instancia um novo objeto MySqlConnection usando os dados do banco contidos em constring
                    {
                        using (MySqlCommand cmd = new MySqlCommand())             //instancia um novo MySqlCommand
                        {
                            using (MySqlBackup mb = new MySqlBackup(cmd))         //instancia um novo MySqlBackup e usa o command de antes como parâmetro
                            {
                                cmd.Connection = conn;                            //define o comando Conection
                                conn.Open();                                      //abre a conexão com o banco
                                try                                               //tenta
                                {
                                    mb.ExportToFile(file);                        //CRIAR O BACKUP
                                    lblMsgModal.Style.Add("color", "green");
                                    lblMsgModal.Text = "Backup de segurança efetuado com sucesso!";
                                }
                                catch (Exception ex) //CASO NÃO CONSIGA CRIAR O BACKUP DE SEGURANÇA
                                {
                                    UpdatePanelBkp.Update();
                                    lblMsgModal.Style.Add("color", "#960d10");
                                    lblMsgModal.Text = "Erro ao criar Backup de Segurança! Cancelando a Restauração;"; //MENSAGEM DE ERRO
                                    conn.Close();
                                    System.Threading.Thread.Sleep(1000);
                                    Response.Redirect("~/Configuracoes"); //RECARREGA A PÁGINA
                                }
                                conn.Close();                             //FECHA A CONEXÃO COM O BANCO, NÃO É NECESSÁRIO O DISPOSE(LIMPAR DA MEMÓRIA) POR USAR USING LÁ EM CIMA
                            }
                        }
                    }
                    CarregaGrid();
                    UpdatePanelBkp.Update();

                    string   caminho  = pegaDirBackup();
                    string[] arquivos = Funcoes.tratarArquivosBackup(caminho);

                    //<---------------- TERMINA O BACKUP DE SEGURANÇA
                    if (arquivos[0] == nome_arquivo.Replace(".sql", "")) // Verifica se o Backup foi realmente criado
                    {
                        lblMsgModal2.Text = "Backup de segurança efetuado com sucesso!";

                        if (Funcoes_DB.DropDatabase() == 0)
                        {
                            using (MySqlConnection conn = new MySqlConnection(constring)) //instancia um novo objeto MySqlConnection usando os dados do banco contidos em constring
                            {
                                using (MySqlCommand cmd = new MySqlCommand())             //instancia um novo MySqlCommand
                                {
                                    using (MySqlBackup mb = new MySqlBackup(cmd))         //abre a conexão com o banco
                                    {
                                        cmd.Connection = conn;                            //define o comando Conection
                                        conn.Open();                                      //abre a conexão com o banco
                                        try                                               //TENTA
                                        {
                                            mb.ImportFromFile(caminhoArquivo);            //RESTAURA O SISTEMA USANDO O BACKUP CLICADO
                                            lblMsgModal2.Style.Add("color", "green");
                                            lblMsgModal2.Text = "Sistema Restaurado com sucesso!";
                                        }
                                        catch (Exception ex)
                                        {
                                            lblMsgModal2.Style.Add("color", "#960d10");
                                            lblMsgModal2.Text = "Erro ao restaurar Backup";
                                        }
                                        conn.Close();  //FECHA A CONEXÃO COM O BANCO, NÃO É NECESSÁRIO O DISPOSE(LIMPAR DA MEMÓRIA) POR USAR USING LÁ EM CIMA
                                    }
                                }
                            }
                        }
                    }
                }
            }
            else
            {
                if (c == 3)                       //SE HOUVE MAIS DE 3 TENTATIVAS DE CONFIRMAÇÃO DE SENHA
                {
                    c = 1;                        //RESETA A VARÍAVEL DE CONTROLE
                    Session.RemoveAll();          //REMOVE E LIMPA TODAS SESSÕES
                    Response.Redirect("~/Login"); //REDIRECIONA PARA A PÁGINA DE LOGIN
                }
                else //CASO AINDA NÃO ERROU 3 VEZES
                {
                    lblMsgModal.Style.Add("color", "#960d10");
                    lblMsgModal.Text = "Senha incorreta!";
                    c++; //AUMENTA O NÚMERO DE VEZES QUE A SENHA DIGITADA FOI INCORRETA EM 1
                }
            }
        }
        else
        {
            lblMsgModal.Style.Add("color", "#960d10");
            lblMsgModal.Text = "O campo senha deve ser preenchido!";
        }
    }
Exemple #5
0
    public void CarregaPesquisaAvançada() //Carrega a grid com todos os PIs relacionados a pesquisa
    {
        string curso;
        string semestre_ano;
        string status;
        string pesquisa = txtPesquisa.Text; //cria uma variavel para receber o valor digitado no campo pesquisa

        if (ddlCurso.SelectedValue == "0")
        {
            curso = "";
        }
        else
        {
            curso = ddlCurso.SelectedItem.ToString();
        }

        if (ddlSemestreAno.SelectedValue == "0")
        {
            semestre_ano = "";
        }
        else
        {
            semestre_ano = ddlSemestreAno.SelectedItem.ToString();
        }

        if (ddlStatus.SelectedValue == "0")
        {
            status = "";
        }
        else
        {
            if (ddlStatus.SelectedItem.ToString() == "Em andamento")
            {
                status = "0";
            }
            else
            {
                status = "1";
            }
        }

        if ((curso == "") && (semestre_ano == "") && (status == "") && (pesquisa == ""))
        {
            gdvProjetos.Visible = false;
            lblQtdRegistro.Text = "Preencha ao menos um campo para pesquisar!";
        }
        else //se o campo pesquisa nao estiver vazio
        {
            DataSet dsPesquisa = Funcoes_DB.SelectFiltroPI(curso, semestre_ano, status, pesquisa); //dataset recebe o retorno do método que faz a pesquisa pelo filtro q o usuario digitou

            int qtd = dsPesquisa.Tables[0].Rows.Count;                                     // conta quantas linhas o dataset retornou
            if (qtd > 0)                                                                   // verifica se a quantidade de linhas form maior que 0
            {
                gdvProjetos.Visible    = true;                                             //a grid fica visivel
                gdvProjetos.DataSource = dsPesquisa.Tables[0].DefaultView;                 //fonte de dados do grid view recebe o ds criado anteriormente
                gdvProjetos.DataBind();                                                    //preenche o grid view com os dados
                lblQtdRegistro.Text = "Foram encontrados " + qtd + " registros";           //exibe mensagem de quantos registros foram retornados

                foreach (GridViewRow linha in gdvProjetos.Rows)                            //percorre cada linha da grid
                {
                    Label lblStatus        = (Label)linha.FindControl("lblStatus");        //acha o label de Nome e liga a outro label
                    Label lblSemestreCurso = (Label)linha.FindControl("lblSemestreCurso"); //acha o label de Nome e liga a outro label

                    lblSemestreCurso.Text = lblSemestreCurso.Text + "º Semestre";          //acrestenta na label Curso ºSemestre

                    bool valor = false;                                                    //variavel criada para verificar se o status do PI esta em andamento ou finalizado e habilitar o linkbutton

                    if (lblStatus.Text == "False")                                         //verifica se o status na grid está retornando false
                    {
                        lblStatus.Text = "Em andamento";                                   //se for, troca o "false" por "em andamento"
                    }
                    else //senao estiver retornando false, ou seja, true
                    {
                        lblStatus.Text = "Finalizado"; //se não for "false", troca por "finalizado"
                    }

                    if (lblStatus.Text == "Em andamento")                                 // verifica se o status do PI está em andamento
                    {
                        valor = true;                                                     //se sim a variavel recebe true
                    }
                    if (valor == true)                                                    //se o PI estiver em andamento o botao habilitar pra edição fica invisivel
                    {
                        LinkButton botao = (LinkButton)linha.FindControl("lkbHabilitar"); //acha o label semestre da grid e liga a outro label
                        botao.Visible = false;                                            //deixa o botao invisivel
                    }
                }
            }
            else
            {
                gdvProjetos.Visible = false;                            //grid fica invisivel, pois o dataset nao retronou dados
                lblQtdRegistro.Text = "Nenhum Registro foi encontrado"; //informa ao usuario que nao foi encontrado nenhum registro
            }
        }
    }