Controle de Acesso por Treeview XmlDataSource Asp.Net e Mysql. com Recursividade

Nessa Publicação estarei ensinando a controlar a visibilidade das Páginas asp.net tais como outros privilégios como gravar alterar excluir e incluir que servirá de base para o nosso curso de Aplicação completa .Net

Bom partiremos do conceito que você tenha a conexão com o mysql pois o intuito não é mostrar Ado.net e sim um controle de acesso e privilégios que servirá de base para o nosso Sistema. primeiro vamos criar as tabelas:

# MySQL-Front 5.1  (Build 4.13)

/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE */;
/*!40101 SET SQL_MODE='STRICT_TRANS_TABLES,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES */;
/*!40103 SET SQL_NOTES='ON' */;


#
# Source for table menu
#

CREATE TABLE `menu` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `IDPAI` int(11) DEFAULT NULL,
  `MENU` varchar(255) DEFAULT NULL,
  `FORMULARIO` varchar(50) DEFAULT NULL,
  `ORDEM` int(11) DEFAULT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=InnoDB AUTO_INCREMENT=40 DEFAULT CHARSET=latin1;


CREATE TABLE `perfil_permissoes` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `IDPERFIL` int(11) DEFAULT NULL,
  `IDMENU` int(11) DEFAULT NULL,
  `VISUALIZA` int(11) DEFAULT NULL COMMENT '0 - NÃO  1-SIM',
  `INCLUI` int(11) DEFAULT NULL COMMENT '0 - NÃO  1-SIM',
  `ALTERA` int(11) DEFAULT NULL COMMENT '0 - NÃO  1-SIM',
  `EXCLUI` int(11) DEFAULT NULL COMMENT '0 - NÃO  1-SIM',
  `consulta` int(11) DEFAULT NULL,
  PRIMARY KEY (`ID`),
  KEY `perfilxpermissoes` (`IDPERFIL`),
  KEY `permissoesxmenu` (`IDMENU`)
) ENGINE=InnoDB AUTO_INCREMENT=57 DEFAULT CHARSET=latin1;

#
#  Foreign keys for table perfil_permissoes
#

ALTER TABLE `perfil_permissoes`
ADD CONSTRAINT `perfilxpermissoes` FOREIGN KEY (`IDPERFIL`) REFERENCES `usuarios` (`Id`),
ADD CONSTRAINT `permissoesxmenu` FOREIGN KEY (`IDMENU`) REFERENCES `menu` (`ID`);








table usuarios

CREATE TABLE `usuarios` (
  `Id` int(11) NOT NULL AUTO_INCREMENT,
  `nome` varchar(100) DEFAULT NULL,
  `senha` varchar(8) DEFAULT NULL,
  `ativo` char(1) DEFAULT NULL,
  PRIMARY KEY (`Id`)
) ENGINE=InnoDB AUTO_INCREMENT=14 DEFAULT CHARSET=utf8;


essas tabelas são necessárias para o nosso tópico. Com o Visual Studio 2008 aberto crie um projeto web e salve na pasta de preferência e inclua dois componentes um Treeview e um Xmldatasource.

Após adicionado os componentes no codebehind da página coloque o seguinte código:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using MySql.Data;
using MySql.Data.MySqlClient;

namespace WebApplication1
{
    public partial class _Default : System.Web.UI.Page
    {

        private MySqlConnection con = new MySqlConnection(ConfigurationManager.ConnectionStrings["vemartConnectionString"].ConnectionString);
        private string XML;


        protected void ProcuraFilhos(int id) {

            DataTable da = new DataTable();
            MySqlDataReader reader = null;
            string Sql = " select men.idpai,men.id,men.menu,men.formulario,perfperm.inclui,perfperm.altera,perfperm.exclui from menu as men join perfil_permissoes as perfperm on perfperm.idmenu = men.id where perfperm.visualiza = 1 and men.idpai ="+Convert.ToString(id)+" order by men.ordem asc , men.idpai asc  ";
            con.Close();
            MySqlCommand com = new MySqlCommand(Sql, con);
            com.CommandType = CommandType.Text;
            try
            {
                con.Open();
                reader = com.ExecuteReader();

                da.Load(reader);
            }
            finally
            {
                con.Close();
                reader.Close();


            }
            for (int i = 0; i < da.Rows.Count; i++)
            {

                XML += "<" + da.Rows[i]["menu"].ToString() + @" values=""" + da.Rows[i]["menu"].ToString() + @""">";
                ProcuraFilhos(Convert.ToInt32(da.Rows[i]["id"].ToString()));
                XML += "";

            }



                   
       
        }

        protected void IncluiTreenodeBind() {


            TreeView1.DataBindings.Clear();


            DataTable da = new DataTable();
            MySqlDataReader reader = null;
            string Sql = " select men.idpai,men.id,men.menu,men.formulario,perfperm.inclui,perfperm.altera,perfperm.exclui from menu as men join perfil_permissoes as perfperm on perfperm.idmenu = men.id where perfperm.visualiza = 1 order by men.ordem asc , men.idpai asc  ";
            con.Close();
            MySqlCommand com = new MySqlCommand(Sql, con);
            com.CommandType = CommandType.Text;
            try
            {
                con.Open();
                reader = com.ExecuteReader();

                da.Load(reader);
            }
            finally
            {
                con.Close();
                reader.Close();


            }

            TreeNodeBinding noprincipal = new TreeNodeBinding();
            noprincipal.DataMember = "Principal";
            noprincipal.TextField = "values";
            noprincipal.NavigateUrl = "Paginateste.aspx";
            TreeView1.DataBindings.Add(noprincipal);

            for (int i = 0; i < da.Rows.Count; i++)
            {
                TreeNodeBinding no = new TreeNodeBinding();
                no.DataMember = da.Rows[i]["menu"].ToString();
                no.TextField = "values";
                no.NavigateUrl = da.Rows[i]["formulario"].ToString();
                TreeView1.DataBindings.Add(no);

            }


        
       
       
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DataTable da = new DataTable();
                MySqlDataReader reader = null;
                string Sql = " select men.idpai,men.id,men.menu,men.formulario,perfperm.inclui,perfperm.altera,perfperm.exclui from menu as men join perfil_permissoes as perfperm on perfperm.idmenu = men.id where perfperm.visualiza = 1 and men.idpai =0 order by men.ordem asc , men.idpai asc  ";
                con.Close();
                MySqlCommand com = new MySqlCommand(Sql, con);
                com.CommandType = CommandType.Text;
                try
                {
                    con.Open();
                    reader = com.ExecuteReader();
                 
                    da.Load(reader);
                }
                finally
                {
                    con.Close();
                    reader.Close();


                }
                XML  = string.Empty;
                XML  = @"";
                XML += @"<principal values="" principal="">";
                for (int i = 0; i < da.Rows.Count  ; i++)
                {
                  
                   XML += "<"+da.Rows[i]["menu"].ToString()+@" values="""+da.Rows[i]["menu"].ToString()+@""">";
                   ProcuraFilhos(Convert.ToInt32(da.Rows[i]["id"].ToString()));
                   XML += "";

                 }
                XML += "</principal>";

                XmlDataSource1.Data = XML;

                IncluiTreenodeBind();


            }

        }
    }
}








Bom pode não ter ficado muito didático mas como todo bom programador brasileiro da classe TPersist tenho certeza que voçês vão entender : ) Abraços a até a próxima dica. há para testar o exemplo altere os valores do campo visualiza da tabela perfil_permissoes onde 0 não visualiza e 1 visualiza.



  

Artigos relacionados