/*===========================================================================================================================
* Instituto Costarricense de Acueductos y Alcantarillados. - 2015
* Administración de la Seguridad
* Nombre de la Pantalla: frwRol.aspx
*
* Explicación de los contenidos del archivo
*===========================================================================================================================
* HISTORIAL
*
* PERSONA DIA – MES - AÑO DESCRIPCIÓN
* Esteban Gutierrez Rapso 11 – 05 - 2015 Se inicia con el diseño de la pagina
* …………………………………………………………
* …………………………………………………………
*===========================================================================================================================
* Derechos Reservados (C) 2015 AyA.
* ESTE CÓDIGO ES PROVEÍDO “TAL CUAL ES” SIN GARANTÍA ALGUNA
* DE NINGÚN TIPO, SEA IMPLICITA O EXPLICITA.
* NO SE PERMITE SU REPRODUCCIÓN PARCIAL O TOTAL, NI SU COMERCIALIZACIÓN
*===========================================================================================================================
*/
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using AyABL;
using AyABL.AUT.Autenticacion;
using AyABL.APL;
using AyABL.Usuario;
using System.Configuration;
using AyADAL;
using AyABL.RCS;
using AyAEL.USR;
public partial class Forms_Usuarios_frwRol : General
{
#region Inicializar Formulario (R0)
override protected void OnInit(EventArgs e) //M0
{
try
{
base.OnInit(e);
InicializarFormulario();
}
catch (Exception ex)
{
MensajeError("Error en R0M0", ex);
}
}
private void InicializarFormulario() //M1
{
try
{
Response.Cache.SetCacheability(HttpCacheability.NoCache);
construirGridView();
Javascript.CheckAllGridViewItems(Page);
cuwBusquedaList.Buscar += new _controlesusuario_Estandar_cuwBusquedaList.SearchEvent(Buscar);
}
catch (Exception ex)
{
MensajeError("Error en R0M1", ex);
}
}
#endregion
#region Variables (R1)
GridView grvListaDatosRolesTemp;
RolItemMenuComandoBL objRolItemMenuComandoBL;
ItemMenuBL objItemMenuBL;
ComandoBL objComandoBL;
UsuarioRolBL objUsuarioRolBL;
AplicacionBL objAplicacionBL;
ActividadesBL objActividadesBL;
RolBL objRolBL = new RolBL();
ArrayList arlCondicionesFiltroBusqueda = new ArrayList();
#endregion
#region Eventos Formulario (R2)
protected void Page_Load(object sender, EventArgs e) //M0
{
try
{
if ((!IsPostBack) && (Session.Count > 0))
{
//ComandosxMenu();
llenarGridView(true);
ComandosxMenu();
llenarlblApp();
llenarDDLAcceso();
llenarDDLActividades();
mostrarFilaTabla(1);
}
}
catch (Exception ex)
{
MensajeError("Error en R2M0", ex);
}
}
#endregion
#region Eventos Controles Web (R3)
///
/// Metodo que se utiliza para extraer información del registro de la base de datos y ser mostrado en el acordeon de Controles
///
///
///
protected void grvListaDatosRoles_RowCommand(object sender, GridViewCommandEventArgs e) //M0
{
try
{
if (e.CommandName == "editar")
{
int i = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = grvListaDatosRoles.Rows[i];
int intPkRol = Convert.ToInt32(selectedRow.Cells[2].Text);
ViewState["PkRol"] = intPkRol;
ViewState["MODO"] = "Modifica";
mostrarFilaTabla(2);
limpiarCampos();
mostrarDatos(intPkRol);
}
}
catch (Exception ex)
{
MensajeError("Error en R3M0 " , ex);
}
}
///
/// Metodo que se utiliza para la paginación del Grid en caso de que el Rol desee ver mas registros
///
///
///
protected void grvListaDatosRoles_PageIndexChanging(object sender, GridViewPageEventArgs e) //M1
{
try
{
grvListaDatosRoles.PageIndex = e.NewPageIndex;
llenarGridView(true);
}
catch (Exception ex)
{
MensajeError("Error en R3M1", ex);
}
}
///
///Activar el botón de Refrescar
///
///
///
protected void btnRefrescar_Click(object sender, System.Web.UI.ImageClickEventArgs e) //M2
{
try
{
llenarGridView(true);
}
catch (Exception ex)
{
MensajeError("Error en R3M2 " + MensajesAplicacion.RefrescarFallido.ToString(), ex);
}
}
///
/// Activa el evento del botón Buscar (binoculares)
///
///
///
protected void btnBuscar_Click(object sender, System.Web.UI.ImageClickEventArgs e) //M3
{
try
{
llenarGridView(true);
}
catch (Exception ex)
{
MensajeError("Error en R3M3" + MensajesAplicacion.BusquedaFallido.ToString(), ex);
}
}
///
/// Activa el evento del boton Nuevo
///
///
///
protected void btnNuevo_Click(object sender, EventArgs e) //M4
{
try
{
ViewState["MODO"] = "Nuevo";
ViewState["PkRol"] = "";
mostrarFilaTabla(2);
limpiarCampos();
cargarArbol();
txtRol.Focus();
}
catch (Exception ex)
{
MensajeError("Error en R3M4 " + MensajesAplicacion.GuardadoFallido.ToString(), ex);
}
}
///
/// Metodo que activa el botón de Eliminar
///
///
///
protected void btnEliminar_Click(object sender, EventArgs e) //M5
{
try
{
objUsuarioRolBL = new UsuarioRolBL();
// recorro el grid
foreach (GridViewRow row in grvListaDatosRoles.Rows)
{
HtmlInputCheckBox chkTemp = (HtmlInputCheckBox)row.Controls[0].Controls[1];
if (chkTemp != null)
{
// si el registro esta marcado
if (chkTemp.Checked)
{
int intPkEliminar = Convert.ToInt32(row.Cells[2].Text);
objUsuarioRolBL.objUsuarioRolEL.Rol = intPkEliminar;
// si no hay usuarios en ese role
if (!objUsuarioRolBL.usuariosAsociados())
{
eliminarDatos(intPkEliminar);
}
else
{
MensajeAlerta("No se puede eliminar el rol debido a que tiene usuarios asociados.");
}
}
}
}
llenarGridView(true);
}
catch (Exception ex)
{
MensajeError("Error en R3M5 " + MensajesAplicacion.BorradoFallido.ToString(), ex);
}
}
///
///Activa el metodo del boton Anterior, regresa a la primera fila de la tabla
///
///
///
protected void btnAnterior_Click(object sender, EventArgs e) //M7
{
try
{
llenarGridView(true);
divDatosSuperiores.Visible = true;
divDatosInferiores.Visible = false;
divDatosInferiores2.Visible = false;
divDatosInferiores3.Visible = false;
}
catch (Exception ex)
{
MensajeError("Error en R3M7", ex);
}
}
///
/// Activa el evento del boton guardar.
///
///
///
protected void btnGuardar_Click(object sender, EventArgs e) //M8
{
try
{
if (Page.IsValid)
{
string strMensaje = string.Empty;
if (txtRol.Text != string.Empty && txtDescripcion.Text != string.Empty && ddlAcceso.SelectedValue != "-1")
{
if (validarTreeview())
{
if (GuardarDatos())
{
MensajeInformativo("La información se guardó satisfactoriamente");
llenarGridView(true);
ComandosxMenu();
llenarlblApp();
llenarDDLAcceso();
mostrarFilaTabla(1);
}
else
MensajeInformativo("La información no se guardó, revise y vuelva a intentarlo");
mostrarFilaTabla(1);
}
else
{
MensajeAlerta("Debe seleccionar al menos una opcion del arbol organizacional.");
}
}
else
{
MensajeAlerta("Debe completar los datos del rol antes de proseguir.");
txtRol.Focus();
}
}
}
catch (Exception ex)
{
MensajeError("Error en R3M8" + MensajesAplicacion.GuardadoFallido.ToString(), ex);
}
}
///
/// Asocia los actividades al rol de usuario
///
///
///
protected void btnAgregarActividad_Click(object sender, EventArgs e) //M9
{
try
{
string strMensaje = string.Empty;
if (txtRol.Text != string.Empty && txtDescripcion.Text != string.Empty && ddlAcceso.SelectedValue != "-1")
{
if (AgregarActividades())
{
//Guarda los datos del arbol
MensajeInformativo("Se agregó la actividad satisfactoriamente");
llenarGridViewActividades();
ddlActividad.SelectedValue = "-1";
}
else
MensajeInformativo("La actividad no se agregó, revise y vuelva a intentarlo");
//mostrarFilaTabla(1);
}
else
{
MensajeAlerta("Debe completar los datos del rol antes de proseguir.");
txtRol.Focus();
}
}
catch (Exception ex)
{
MensajeError("Error en R3M9" + MensajesAplicacion.GuardadoFallido.ToString(), ex);
}
}
///
/// Metodo que se utiliza para extraer información del registro de la base de datos y ser mostrado en el acordeon de Controles
///
///
///
protected void grvListaActividadesRoles_RowCommand(object sender, GridViewCommandEventArgs e) //M0
{
try
{
if (e.CommandName == "eliminar")
{
int i = Convert.ToInt32(e.CommandArgument);
GridViewRow selectedRow = grvListaActividades.Rows[i];
int intPkActividad = Convert.ToInt32(selectedRow.Cells[0].Text);
ViewState["PkActividad"] = intPkActividad;
ViewState["MODO"] = "Modifica";
mostrarFilaTabla(2);
eliminarActividad(intPkActividad);
llenarGridViewActividades();
}
}
catch (Exception ex)
{
MensajeError("Error en R3M0 ", ex);
}
}
#endregion
#region Metodos Personalizados (R4)
///
/// Oculta las filas que lo requieran
///
///
private void mostrarFilaTabla(int p_intFila) //M0
{
try
{
divDatosSuperiores.Visible = false;
divDatosInferiores.Visible = false;
divDatosInferiores2.Visible = false;
divDatosInferiores3.Visible = false;
switch (p_intFila)
{
case 1:
llenarGridView(true);
divDatosSuperiores.Visible = true;
break;
case 2:
llenarGridView(true);
divDatosInferiores.Visible = true;
divDatosInferiores2.Visible = true;
divDatosInferiores3.Visible = true;
break;
}
}
catch (Exception ex)
{
throw ex;
}
}
///
/// Metodo que se utiliza para contruir el Grid al inicio de la pantalla
///
private void construirGridView() //M1
{
try
{
grvListaDatosRolesTemp = (GridView)tdLista.FindControl("grvListaDatosRoles");
GridViewBoundField bdfPkRol = new GridViewBoundField("PKROL", "PK", false, false, false);
GridViewBoundField bdfNombreRol = new GridViewBoundField("NOMBREROL", "Rol", true, false, true);
GridViewBoundField bdfDescripcion = new GridViewBoundField("DESCRIPCIONROL", "Descripción", true, false, true);
GridViewBoundField bdfActivoRol = new GridViewBoundField("ACTIVOROL", "Activo", true, "Si", "No", true);
//GridViewBoundField bdfAplicacion = new GridViewBoundField("ETIQUETAAPLICACION", "Aplicación", true, false, true);
grvListaDatosRolesTemp.Columns.Add(bdfPkRol);
grvListaDatosRolesTemp.Columns.Add(bdfNombreRol);
grvListaDatosRolesTemp.Columns.Add(bdfDescripcion);
grvListaDatosRolesTemp.Columns.Add(bdfActivoRol);
//grvListaDatosRolesTemp.Columns.Add(bdfAplicacion);
grvListaDatosRolesTemp.Columns[0].ItemStyle.Width = 25;
grvListaDatosRolesTemp.Columns[1].ItemStyle.Width = 25;
cuwBusquedaList.LlenarCHKLBusqueda(grvListaDatosRolesTemp);
}
catch (Exception ex)
{
throw ex;
}
}
///
/// Metodo que se encarga de agregar el filtro de busqueda seleccionado por el usuario
///
///
private void condicionesBusqueda() //M2
{
AyABL.AyABL objBL = new AyABL.AyABL();
CondicionDAL condicion;
DateTime dteFechaInicio = new DateTime();
DateTime dteFechaFin = new DateTime();
ListItem li = new ListItem();
string p_parametros;
p_parametros = this.cuwBusquedaList.getValorBusqueda();
try
{
if (p_parametros != "")
{
//aqui se construye el listItem con los datos que vienen del control en formato {valor : texto , valor : texto}
char[] separadorTuplas = { ',' };
char[] separadorValores = { ':' };
string[] arrayTupla = p_parametros.Split(separadorTuplas);
for (int i = 0; i <= (arrayTupla.Length - 1); i++)
{
if (arrayTupla[i].ToString() != "")
{
string[] arrayValores = arrayTupla[i].ToString().Split(separadorValores);
li = new ListItem(arrayValores[1], arrayValores[0]);
if (li.Value.Contains("FECHA") && li.Text != string.Empty)
{
if (li.Value.Contains("INICIO"))
{
dteFechaInicio = Convert.ToDateTime(li.Text.ToString());
dteFechaFin = DateTime.Now;
}
if (li.Value.Contains("FIN"))
{
dteFechaFin = Convert.ToDateTime(li.Text.ToString());
if (dteFechaFin != null || dteFechaInicio != null)
if (dteFechaInicio < dteFechaFin || dteFechaFin == dteFechaInicio)
{
objBL = new AyABL.AyABL();
arlCondicionesFiltroBusqueda = objBL.buscarPorFechas(Tablas.BITACORA, dteFechaInicio, dteFechaFin, operadorLogico.AND, arlCondicionesFiltroBusqueda);
}
else
MensajeInformativo(AyABL.BASESDEDATOS.ADS + "Interfaz: " + "Verifique que la Fecha de Inicio sea menor que la Fecha Final" + "M2");
else
MensajeInformativo(AyABL.BASESDEDATOS.ADS + "Interfaz: " + "Verifique que los campos de las fechas no estén vacíos" + "M2");
}
else
{
objBL = new AyABL.AyABL();
arlCondicionesFiltroBusqueda = objBL.buscarPorFechas(Tablas.BITACORA, dteFechaInicio, dteFechaFin, operadorLogico.AND, arlCondicionesFiltroBusqueda);
}
}
else
{
if (li.Value.Contains("booleano") && li.Text != "2")
{
condicion = new CondicionDAL();
char[] separadorColumna = { '|' };
string[] strColumna = li.Value.Split(separadorColumna);
condicion.valorIzquierdo = strColumna[1].ToString();
condicion.operadorGeneral = operadorGeneral.EQUAL;
condicion.operadorLogico = operadorLogico.AND;
condicion.valorDerecho = li.Text.Trim();
arlCondicionesFiltroBusqueda.Add(condicion);
}
else
{
if (li.Text != string.Empty && !li.Value.Contains("booleano"))
{
condicion = new CondicionDAL();
condicion.valorIzquierdo = li.Value;
condicion.operadorGeneral = operadorGeneral.LIKEALL;
condicion.operadorLogico = operadorLogico.AND;
condicion.valorDerecho = "%" + li.Text.Trim() + "%";
arlCondicionesFiltroBusqueda.Add(condicion);
}
}
}
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
///
/// Metodo que se utiliza para limpiar los campos en la pantalla
///
private void limpiarCampos() //M3
{
try
{
txtRol.Text = string.Empty;
txtDescripcion.Text = string.Empty;
ddlAcceso.SelectedValue = "-1";
ddlActividad.SelectedValue = "-1";
grvListaActividades.DataSource = null;
grvListaActividades.DataBind();
}
catch (Exception ex)
{
throw ex;
}
}
///
/// Metodo que se utiliza con el buscador de la parte superior de la pantalla, y hace que se despliegue la información de acuerdo
/// a lo solicitado
///
private void Buscar() //M4
{
try
{
llenarGridView(true);
}
catch (Exception ex)
{
throw ex;
}
}
///
/// Metodo que se utiliza para el despliegue de los botones
///
private void ComandosxMenu() //M6
{
try
{
//General general = null;
DataSet dsComandos = getComandos();
if (dsComandos != null)
{
foreach (DataRow drTemp in dsComandos.Tables[0].Rows)
{
switch (drTemp["NOMBRECOMANDO"].ToString().ToUpper())
{
case "NUEVO":
btnNuevo.Visible = true;
break;
case "ELIMINAR":
btnEliminar.Visible = true;
break;
case "MODIFICA":
//Inicio de variable tipo VIEWSTATE
ViewState["PUEDEMODIFICAR"] = true;
btnGuardar.Visible = true;
break;
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Metodos Controles a Datos (R5)
///
/// guarda y modifica registros en la tabla.
///
///
private bool GuardarDatos() //M0
{
bool blnValorRetornado = false; //Se utiliza para verificar si se ejecuto el proceso tanto de guardar como el de eliminar
int intPk = 0;
TransaccionDAL tdlTransaccion = new TransaccionDAL("ADS");
try
{
string strModo = ViewState["MODO"].ToString();
ViewState["PUEDEMODIFICAR"] = true;
objRolBL = new RolBL();
objRolBL.objRolEL.PK = 0;
objRolBL.objRolEL.Nombre = this.txtRol.Text.Trim();
objRolBL.objRolEL.Descripcion = this.txtDescripcion.Text.Trim();
objRolBL.objRolEL.Activo = true;
if (ddlAcceso.SelectedValue != "-1")
{
objRolBL.objRolEL.ACCESOINFORMACION = int.Parse(ddlAcceso.SelectedValue);
Session["ACCESOINSORMACION"] = int.Parse(ddlAcceso.SelectedValue);
}
tdlTransaccion.BeginTransaction();
if (strModo == "Nuevo")
{
int intPkRolAcceso = 0;
intPk = objRolBL.insertarRol(ref intPkRolAcceso);
//Guarda los datos del arbol
InsertaDatosArbol(intPk);
blnValorRetornado = true;
GuardarEventoBitacora(
Session["LOGIN"].ToString(),
AccionBitacora.INSERT.ToString(),
MensajesBitacora.IngresarRegistro + ": " + intPk + ", " + txtRol.Text + ", " + txtDescripcion.Text,
"frwRole.aspx",
Convert.ToInt32(ConfigurationManager.AppSettings["pkApp"])
);
tdlTransaccion.CommitTransaction();
}
else if (strModo == "Modifica")
{
if (Convert.ToBoolean(ViewState["PUEDEMODIFICAR"]) != false)
{
objRolBL.objRolEL.PK = Convert.ToInt32(ViewState["PkRol"]);
objRolBL.actualizarRol();
objRolItemMenuComandoBL = new RolItemMenuComandoBL();
objRolItemMenuComandoBL.objRolItemMenuComandoEL.Rol = Convert.ToInt32(ViewState["PkRol"]);
objRolItemMenuComandoBL.eliminarRolexComandoxMenuItem();
InsertaDatosArbol(Convert.ToInt32(ViewState["PkRol"]));
blnValorRetornado = true;
GuardarEventoBitacora(
Session["LOGIN"].ToString(),
AccionBitacora.UPDATE.ToString(),
MensajesBitacora.ModificarRegistro + ": " + Convert.ToInt32(ViewState["PkRol"]) + ", " + txtRol.Text + ", " + txtDescripcion.Text,
"frwRole.aspx",
Convert.ToInt32(ConfigurationManager.AppSettings["pkApp"])
);
tdlTransaccion.CommitTransaction();
}
}
}
catch (Exception ex)
{
tdlTransaccion.RollBackTransaction();
throw (ex);
}
return blnValorRetornado;
}
#region Guarda Datos Arbol
///
/// Metodo utilitario para insertar cada nodo del árbol y sus respectivos permisos en la base de datos
///
///
///
private void InsertaDatosArbol(int p_intPkRole) //M1
{
// recorro los hijos de la raíz del árbol (El nombre de la aplicación)
foreach (TreeNode tndRol in trvRol.Nodes[0].ChildNodes)
{
InsertaPantallasArbol(p_intPkRole, Convert.ToInt32(tndRol.Value), tndRol);
}
}
///
/// Metodo que se utiliza para insertar el datos de las pantallas
///
///
///
///
///
///
private bool InsertaPantallasArbol(int p_intPkRole, int p_intPKmenu, TreeNode p_tndPantallas)//M2
{
bool hijoInsertado = false; // determina si algún hijo del menu o pantalla actual fue insertado
try
{
// si tiene hijos
if (p_tndPantallas.ChildNodes.Count > 0)
{
// si el nodo no es un comando, agarro como PKMENU el que viene del nodo, si es un comando, conservo el valor PKMENU que viene como parametro
if (p_tndPantallas.Target != "C")
{
p_intPKmenu = Convert.ToInt32(p_tndPantallas.Value);
}
// recorro los hijos del nodo recibido como parametro del metodo
foreach (TreeNode tndHijo in p_tndPantallas.ChildNodes)
{
// los mando a insertarDatosArbol y acumulo las respuestas de los inserts de hijos
bool aux = InsertaPantallasArbol(p_intPkRole, p_intPKmenu, tndHijo);
// ** nota, solo el comando consultar va a activar en el arbol de permisos, los permisos a consultar la pantalla o modulo que se encuentren
// por encima de este, si tengo otros comandos al mismo nivel del comando consultar, estos no brindaran el permiso de consulta a la pantalla padre
// o modulo en el que se encuentren
if (/*(tndHijo.Text == "Consultar") || */(tndHijo.Target == string.Empty))
{
hijoInsertado = (hijoInsertado || aux);
}
}
// si inserte un hijo o si el nodo esta chequeado, chequeo el nodo
p_tndPantallas.Checked = (p_tndPantallas.Checked || hijoInsertado);
if (p_tndPantallas.Checked)
{
bool aux = InsertarComandos(p_intPkRole, p_intPKmenu, p_tndPantallas);
hijoInsertado = (hijoInsertado || aux);
}
}
// si no tiene hijos (hoja)
else
{
hijoInsertado = InsertarComandos(p_intPkRole, p_intPKmenu, p_tndPantallas);
}
}
catch (Exception ex)
{
throw ex;
}
return hijoInsertado;
}
///
/// Metodo que se utiliza para insertar la información de los comandos
///
///
///
///
///
///
private bool InsertarComandos(int p_intPkRole, int p_intPkMenu, TreeNode p_tndNode ) //M3
{
bool insertado = false;
try
{
// si es un comando
if (p_tndNode.Target == "C")
{
// si esta chequeado
if (p_tndNode.Checked)
{
objRolItemMenuComandoBL = new RolItemMenuComandoBL();
objRolItemMenuComandoBL.objRolItemMenuComandoEL.Rol = p_intPkRole;
objRolItemMenuComandoBL.objRolItemMenuComandoEL.ItemMenu = p_intPkMenu;
objRolItemMenuComandoBL.objRolItemMenuComandoEL.Comando = Convert.ToInt32(p_tndNode.Value);
objRolItemMenuComandoBL.insertarRolexComandoxMenuItem();
insertado = true;
}
}
//si es un módulo o pantalla
else
{
// si este no tiene como hijo a un comando
if (!tieneHijoComando(p_tndNode))
{
objRolItemMenuComandoBL = new RolItemMenuComandoBL();
objRolItemMenuComandoBL.objRolItemMenuComandoEL.Rol = p_intPkRole;
objRolItemMenuComandoBL.objRolItemMenuComandoEL.ItemMenu = p_intPkMenu;
objRolItemMenuComandoBL.objRolItemMenuComandoEL.Comando = Convert.ToInt32(Comandos.Consultar);
objRolItemMenuComandoBL.insertarRolexComandoxMenuItem();
insertado = true;
}
// si el nodo actual tiene un hijo que sea comando
else
{
// si este comando esta chequeado
if (hijoComandoChequeado(p_tndNode))
{
// regreso true porque el paso recursivo anterior me tuvo que agregar el consultar del menu
return true;
}
else
{
return false;
}
}
}
}
catch (Exception ex)
{
throw ex;
}
return insertado;
}
///
/// Devuelve si el nodo enviado como parametro tiene un comando de hijo
///
///
///
private bool tieneHijoComando(TreeNode p_tndNode) //M4
{
bool blnConComando = false;
try
{
foreach (TreeNode tndHijo in p_tndNode.ChildNodes)
{
// si es un comando
if (tndHijo.Target == "C")
{
blnConComando = true;
break;
}
}
}
catch (Exception ex)
{
throw ex;
}
return blnConComando;
}
///
/// Devuelve si el nodo enviado como parametro tiene un comando de hijo
///
///
///
private bool hijoComandoChequeado(TreeNode p_tndNode) //M5
{
bool comandoChequeado = false;
try
{
foreach (TreeNode tndHijo in p_tndNode.ChildNodes)
{
// si es un comando
if (tndHijo.Checked)
{
comandoChequeado = true;
break;
}
}
}
catch (Exception ex)
{
throw ex;
}
return comandoChequeado;
}
private bool validarTreeview()
{
bool valorRetornado = false;
try
{
// recorro los hijos de la raíz del árbol (El nombre de la aplicación)
foreach (TreeNode tndRol in trvRol.Nodes[0].ChildNodes)
{
if (tndRol.Checked == true)
return true;
}
}
catch(Exception ex)
{ throw ex; }
return valorRetornado;
}
#endregion
///
/// Metodo que se utiliza para eliminar registros de la base de datos
///
///
private void eliminarDatos(int p_intPkRole) //M6
{
try
{
objRolItemMenuComandoBL = new RolItemMenuComandoBL();
objRolItemMenuComandoBL.objRolItemMenuComandoEL.Rol = p_intPkRole;
objRolItemMenuComandoBL.eliminarRolexComandoxMenuItem();
objRolBL = new RolBL();
objRolBL.objRolEL.PK = p_intPkRole;
objRolBL.eliminarRol();
// Se procede a ingresar el registro de bitacora para almacenar la accion del usuario
GuardarEventoBitacora(Session["LOGIN"].ToString(), AccionBitacora.DELETE, MensajesBitacora.EliminarRegistro + " con la PK " + p_intPkRole, "frwRol.aspx", Convert.ToInt32(ConfigurationManager.AppSettings["pkApp"]));
}
catch (Exception ex)
{
throw ex;
}
}
///
/// guarda y modifica registros en la tabla.
///
///
private bool AgregarActividades() //M7
{
bool blnValorRetornado = false; //Se utiliza para verificar si se ejecuto el proceso tanto de guardar como el de eliminar
TransaccionDAL tdlTransaccion = new TransaccionDAL("SIGDD");
int intPkRolAcceso = 0;
int intPk = 0;
try
{
tdlTransaccion.BeginTransaction();
if (ViewState["PkRol"].ToString() == "" || ViewState["PkRol"].ToString() == null)
{
string strModo = ViewState["MODO"].ToString();
ViewState["PUEDEMODIFICAR"] = true;
objRolBL = new RolBL();
objRolBL.objRolEL.PK = 0;
objRolBL.objRolEL.Nombre = this.txtRol.Text.Trim();
objRolBL.objRolEL.Descripcion = this.txtDescripcion.Text.Trim();
objRolBL.objRolEL.Activo = true;
if (ddlAcceso.SelectedValue != "-1")
objRolBL.objRolEL.ACCESOINFORMACION = int.Parse(ddlAcceso.SelectedValue);
intPk = objRolBL.insertarRol(ref intPkRolAcceso);
ViewState["PkRol"] = intPk.ToString();
//Guarda los datos del arbol
InsertaDatosArbol(intPk);
//asocia actividades al rol
}
else
{
objRolBL = new RolBL();
objRolBL.objRolEL.PK = Convert.ToInt32(ViewState["PkRol"]);
DataSet dsActividades = objRolBL.dsRolAccesoPorRol(null);
if (dsActividades.Tables.Count > 0)
{
if (dsActividades.Tables[0].Rows.Count > 0)
{
intPkRolAcceso = int.Parse(dsActividades.Tables[0].Rows[0]["PKROLACCESO"].ToString());
}
}
}
objRolBL.objRolAccesoActividadEL.FKACTIVIDAD = int.Parse(ddlActividad.SelectedValue);
objRolBL.objRolAccesoActividadEL.FKROLACCESO = intPkRolAcceso;
intPk = objRolBL.asociarActividadRol(tdlTransaccion);
ViewState["MODO"] = "Modifica";
blnValorRetornado = true;
GuardarEventoBitacora(
Session["LOGIN"].ToString(),
AccionBitacora.INSERT.ToString(),
MensajesBitacora.IngresarRegistro + ": " + intPk + ", " + txtRol.Text + ", " + ddlActividad.SelectedItem.Text,
"frwRol.aspx",
Convert.ToInt32(ConfigurationManager.AppSettings["pkApp"])
);
tdlTransaccion.CommitTransaction();
}
catch (Exception ex)
{
tdlTransaccion.RollBackTransaction();
throw (ex);
}
return blnValorRetornado;
}
///
/// Metodo que se utiliza para eliminar actividades de la base de datos
///
///
private void eliminarActividad(int p_intPkActividad) //M6
{
try
{
objRolBL = new RolBL();
objRolBL.objRolAccesoActividadEL.PK = p_intPkActividad;
p_intPkActividad = objRolBL.elminarActividadRol();
// Se procede a ingresar el registro de bitacora para almacenar la accion del usuario
GuardarEventoBitacora(Session["LOGIN"].ToString(), AccionBitacora.DELETE, MensajesBitacora.EliminarRegistro + " con la PK " + p_intPkActividad, "frwRol.aspx", Convert.ToInt32(ConfigurationManager.AppSettings["pkApp"]));
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
#region Metodos Datos a Controles (R6)
///
/// Carga el grid principal
///
///
private void llenarGridView(bool p_Llenar) //M0
{
try
{
if (!IsPostBack || p_Llenar)
{
condicionesBusqueda();
objRolBL = new RolBL();
objRolBL.objRolEL.Aplicacion = Convert.ToInt32(ConfigurationManager.AppSettings["pkApp"]);
DataSet dsRoles = objRolBL.dsListaRoles(arlCondicionesFiltroBusqueda);
General.detalleGridView(dsRoles, grvListaDatosRolesTemp, lblTotalDatos);
}
}
catch (Exception ex)
{
throw ex;
}
}
///
/// Muestra los datos del registro
///
///
private void mostrarDatos(int p_intPkConsultar) //M1
{
try
{
objRolBL = new RolBL();
objRolBL.objRolEL.PK = p_intPkConsultar;
objRolBL.objRolEL.Rol= Int32.Parse(ViewState["PkRol"].ToString());
DataSet dsRol = objRolBL.dsListaRoles(arlCondicionesFiltroBusqueda);
if (dsRol.Tables[0].Rows.Count > 0)
{
txtRol.Text = dsRol.Tables[0].Rows[0]["NOMBREROL"].ToString();
txtDescripcion.Text = dsRol.Tables[0].Rows[0]["DESCRIPCIONROL"].ToString();
cargarArbol();
}
objRolBL.objRolEL.PK = p_intPkConsultar;
DataSet dsAcceso = objRolBL.dsAccesoUsuario(objRolBL.objRolEL);
if (dsAcceso.Tables[0].Rows.Count > 0)
{
ddlAcceso.SelectedValue = dsAcceso.Tables[0].Rows[0]["ACCESOINFORMACIONROLACCESO"].ToString();
}
llenarGridViewActividades();
}
catch (Exception ex)
{
throw ex;
}
}
///
/// Muestra en pantalla los roles que se le pueden asignar al usuario
///
private void llenarlblApp() //M2
{
try
{
objAplicacionBL = new AplicacionBL();
objAplicacionBL.objAplicacionEL.PK = Convert.ToInt32(ConfigurationManager.AppSettings["pkApp"]);
DataSet dsAplicacion = objAplicacionBL.dsListaAplicacion(objAplicacionBL.objAplicacionEL);
}
catch(Exception ex)
{
throw ex;
}
}
///
/// Llena el dropdownlist de Cantonales según la aplicación
///
private void llenarDDLAcceso() //M2
{
try
{
ddlAcceso.Items.Clear();
ddlAcceso.Items.Insert(0, new ListItem("Todo", "0"));
ddlAcceso.Items.Insert(0, new ListItem("Region", "1"));
ddlAcceso.Items.Insert(0, new ListItem("Dependencia", "2"));
ddlAcceso.Items.Insert(0, new ListItem("Seleccione", "-1"));
}
catch (Exception ex)
{
throw ex;
}
}
///
/// Metodo secundario para cargar el arbol que muestra el menu y sus comandos
///
///
///
private void cargarArbol() //M3
{
try
{
//Construir el Nodo Raíz
TreeNode tdnNodoRaiz = new TreeNode();
tdnNodoRaiz.ShowCheckBox = true;
tdnNodoRaiz.Text = ConfigurationManager.AppSettings["SIGLAS"].ToString();
tdnNodoRaiz.Value = "-1";
// limpio el arbol
trvRol.Nodes.Clear();
cargarArbolItems(Convert.ToInt32(tdnNodoRaiz.Value), tdnNodoRaiz, Convert.ToInt32(ConfigurationManager.AppSettings["pkApp"]));
//tdnNodoRaiz.ExpandAll();
trvRol.Nodes.Add(tdnNodoRaiz);
}
catch (Exception ex)
{
throw ex;
}
}
///
/// Metodo para cargar en el arbol los comandos
///
///
///
private void cargarArbolItems(int p_intPadre, TreeNode p_tndNodoRaiz, int p_intFkApp) //M5
{
int intPadreItem = 0;
try
{
//Obtener los datos
objRolBL = new RolBL();
objRolBL.objRolEL.Padre = p_intPadre;
objRolBL.objRolEL.ItemMenu = 0;
objRolBL.objRolEL.Aplicacion = p_intFkApp;
DataSet dsPantallas = objRolBL.getComandosxItemxApl(Convert.ToInt32(ConfigurationManager.AppSettings["pkApp"]));
//Verifica si el Dataset esta vacio
if (dsPantallas.Tables[0].Rows.Count > 0)
{
//Agregar cada pantalla
foreach (DataRow drPantallas in dsPantallas.Tables[0].Rows)
{
TreeNode tdnNodoPantallas = new TreeNode();
tdnNodoPantallas.Text = drPantallas["ETIQUETAITEMMENU"].ToString();
tdnNodoPantallas.Value = drPantallas["PKITEMMENU"].ToString();
intPadreItem = Int32.Parse(drPantallas["PKITEMMENU"].ToString());
p_tndNodoRaiz.ChildNodes.Add(tdnNodoPantallas);
//if (ViewState["MODO"].ToString() == "Modifica")
// tdnNodoPantallas.Checked = true;
//Verifica que el Modo se esté en Modificar para checkear los Items Menu
if (ViewState["MODO"].ToString() == "Modifica")
{
//Obtiener el comando consulta
objRolBL = new RolBL();
objRolBL.objRolEL.ItemMenu = Int32.Parse(drPantallas["PKITEMMENU"].ToString());
objRolBL.objRolEL.Aplicacion = p_intFkApp;
objRolBL.objRolEL.Rol= Int32.Parse(ViewState["PkRol"].ToString());
DataSet dsPantallasRole = objRolBL.getComandosxItemxRol();
//Verifica que el Dataset esté vacío
if (dsPantallasRole.Tables[0].Rows.Count > 0)
{
//Buscar el MenuItem para checkearlo
foreach (DataRow drPantallasRole in dsPantallasRole.Tables[0].Rows)
{
if (drPantallas["PKITEMMENU"].ToString() == drPantallasRole["PKITEMMENU"].ToString())
{
if (ViewState["MODO"].ToString() == "Modifica")
{
objRolItemMenuComandoBL = new RolItemMenuComandoBL();
objRolItemMenuComandoBL.objRolItemMenuComandoEL.Rol = Int32.Parse(ViewState["PkRol"].ToString());
objRolItemMenuComandoBL.objRolItemMenuComandoEL.ItemMenu = Convert.ToInt32(drPantallas["PKITEMMENU"]);
objRolItemMenuComandoBL.objRolItemMenuComandoEL.Comando = Convert.ToInt32(drPantallas["PKCOMANDO"]);
tdnNodoPantallas.Checked = objRolItemMenuComandoBL.RolexMenuxComandoCheckeado();
//if (tdnNodoPantallas.Checked == true)
// tdnNodoPantallas.Parent.Checked = true;
}
}
}
}
// busco los hijos del hijo
cargarArbolItems(Int32.Parse(drPantallas["PKITEMMENU"].ToString()), tdnNodoPantallas, p_intFkApp);
}
else
cargarArbolItems(Int32.Parse(drPantallas["PKITEMMENU"].ToString()), tdnNodoPantallas, p_intFkApp);
}
}
else
{
cargarComandosItems(p_intPadre, p_tndNodoRaiz);
}
}
catch (Exception ex)
{
throw ex;
}
}
///
/// Carga los comandos
///
///
///
private void cargarComandosItems(int p_intPKMenu, TreeNode p_tndNodoPantalla) //M6
{
try
{
objRolBL = new RolBL();
objRolBL.objRolEL.ItemMenu = p_intPKMenu;
objRolBL.objRolEL.Aplicacion = Convert.ToInt32(ConfigurationManager.AppSettings["pkApp"]);
DataSet dsComandosRole = objRolBL.getComandosxItem();
// si el role, menu y comando tiene comandos
if (dsComandosRole.Tables[0].Rows.Count != 0 && dsComandosRole.Tables[0].Rows[0]["ETIQUETAITEMMENU"].ToString() != "Inicio")
{
// agrego cada comando
foreach (DataRow drComando in dsComandosRole.Tables[0].Rows)
{
TreeNode tdnNodoComandos = new TreeNode();
tdnNodoComandos.Text = drComando["NOMBRECOMANDO"].ToString();
tdnNodoComandos.Value = drComando["PKCOMANDO"].ToString();
tdnNodoComandos.Target = "C";
p_tndNodoPantalla.ChildNodes.Add(tdnNodoComandos);
if (ViewState["MODO"].ToString() == "Modifica")
{
objRolItemMenuComandoBL = new RolItemMenuComandoBL();
objRolItemMenuComandoBL.objRolItemMenuComandoEL.Rol = Int32.Parse(ViewState["PkRol"].ToString());
objRolItemMenuComandoBL.objRolItemMenuComandoEL.ItemMenu = p_intPKMenu;
objRolItemMenuComandoBL.objRolItemMenuComandoEL.Comando = Convert.ToInt32(drComando["PKCOMANDO"]);
tdnNodoComandos.Checked = objRolItemMenuComandoBL.RolexMenuxComandoCheckeado();
if (tdnNodoComandos.Checked == true)
tdnNodoComandos.Parent.Checked = true;
}
}
}
}
catch (Exception ex)
{
throw ex;
}
}
///
/// Llena el combo de actividades
///
///
private void llenarDDLActividades() //M7
{
try
{
//Limpia el control
ddlActividad.Items.Clear();
//Instancia el bjeto
objActividadesBL = new ActividadesBL();
objActividadesBL.objactividadesEL.ASTATE = true;
DataSet dsActividades = objActividadesBL.listarActividadesMantenimiento(null, true, null);
if (dsActividades.Tables[0].Rows.Count != 0)
{
ddlActividad.DataSource = dsActividades;
ddlActividad.DataTextField = dsActividades.Tables[0].Columns["DESCRIPCIONACTIVIDAD"].ColumnName;
ddlActividad.DataValueField = dsActividades.Tables[0].Columns["PKACTIVIDAD"].ColumnName;
ddlActividad.DataBind();
ddlActividad.Items.Insert(0, new ListItem("Seleccione", "-1"));
}
else
ddlActividad.Items.Insert(0, new ListItem("----- No existen actividades -----", "-1"));
}
catch (Exception ex)
{
throw ex;
}
}
///
/// Carga el grid principal
///
///
private void llenarGridViewActividades() //M8
{
try
{
condicionesBusqueda();
objRolBL = new RolBL();
objRolBL.objRolEL.PK = Convert.ToInt32(ViewState["PkRol"]);
DataSet dsActividades = objRolBL.dsListaActividadesPorRol(null);
if (dsActividades.Tables.Count > 0)
{
if (dsActividades.Tables[0].Rows.Count > 0)
{
grvListaActividades.DataSource = dsActividades;
grvListaActividades.DataBind();
}
else
{
grvListaActividades.DataSource = null;
grvListaActividades.DataBind();
}
}
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
}