conexion 3 capas c#

Upload: edy-amilkar-perez

Post on 07-Jul-2018

225 views

Category:

Documents


2 download

TRANSCRIPT

  • 8/18/2019 Conexion 3 Capas C#

    1/7

    CONEXION # CAPAS C#

      Cada una de las flechas nos indica las

    referencias  que tiene cada uno de los

    proyectos entre sí, los puntos iniciales

    indican las dependencias que tiene cada

    proyecto, como ejemplo, La Clase

    Objetos, es dependiente de Clase Datos,

    y la de Clase Funciones y al mismo

    Tiempo es también la de Capa de

    Presentación.

      El proyecto principal es la capa de

    presentación.

      La Clase datos, funciones y objetos son

    proyectos de tipo Class Library, clase

    librería, estas proyecto serán agregadas

    de la solución del proyecto en si y que sea

    de tipo Biblioteca de Clases.

    Capa DatosClase Conexion.csusing System;

    using  System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using  System.Threading.Tasks;

    using System.Data.SqlClient;

    using System.Data;

    namespace Clase_Datos{

    public class Conexion 

    {

    #region 

    private SqlConnection cnn = null;

    #endregion 

    #region  Constructor De la Clase para

    Instanciarlo.

    public  Conexion(string 

    strCadenaConexion)

    {

    this.cnn = new 

    SqlConnection(strCadenaConexion);

    }

    #endregion 

    #region Metodos y Funciones

    public void Conectado()

    {

    try {

    cnn.Open();

    cnn.BeginTransaction()

    }

    catch (Exception ex)

    {

    throw  new  Exception("Ha

    ocurrido un error al abrir la

    conexion"+"\n\nDetalles del

    error."+ex.Message);

    }

    }

    public void Desconectado()

    {

    try 

    {

    cnn.Close();

    cnn.Dispose();

    cnn.ChangeDatabase("NuevaBaseDatos");//Aca le

    escribimos la nueva base de datos.cnn = null;

    }

    catch(Exception ex)

    {

    throw  new  Exception("Ha

    Ocurrido un error al desconectar"+"\n\nDetallesdel error"+ex.Message );

    }

    }

    //Funcion: funcion para realizar unaconsulta Simple 

    public  DataTable  Consulta(string 

    strSQL)

    {

    try 

    {

    SqlDataAdapter  da = new 

    SqlDataAdapter();

    da.SelectCommand = new 

    SqlCommand();

    da.SelectCommand.CommandText =

    strSQL;

    da.SelectCommand.Connection =

    cnn;

    DataSet datos = new DataSet();

    da.Fill(datos);return datos.Tables[0];

    }

    catch(Exception ex)

    {

    throw new Exception("Ha ocurrido un

    error en la Consulta"+"\n\nDetalles del

    error"+ex.Message);

    }

    }

    //Funcion: pasando algunos parametros

    para

    Clase DatosClase

    Funciones

    Clase

    Objetos

    CapaPresentacion

  • 8/18/2019 Conexion 3 Capas C#

    2/7

      public  DataTable  Consulta(string 

    strSQL, object[] objparametros)

    {

    try 

    {

    SqlDataAdapter  da = new 

    SqlDataAdapter();

    da.SelectCommand = new 

    SqlCommand();da.SelectCommand.CommandText =

    strSQL;

    //Realizo el recorrido de

    algunos parametros 

    foreach(SqlParameter  param in 

    objparametros)

    {

    da.SelectCommand.Parameters.Add(( SqlParameter)

    param);

    }

    da.SelectCommand.Connection =

    cnn;

    DataSet datos = new DataSet();

    da.Fill(datos);

    return datos.Tables[0];

    }

    catch (Exception ex)

    {

    throw  new  Exception("Ha

    ocurriod un error al Consultar"+"\n\nDetalles

    del Error."+ex.Message );

    }}

    public  DataTable 

    Consulta_StoreProcedure(string 

    strNombreProcedure, object[]objParametros)

    {

    try {

    SqlDataAdapter  da = new 

    SqlDataAdapter(strNombreProcedure, cnn);

    da.SelectCommand.CommandType =CommandType.StoredProcedure;

    foreach(SqlParameter  param in 

    objParametros)

    {

    param.IsNullable = true;

    da.SelectCommand.Parameters.Add(( SqlParameter)

    param);

    }

    DataSet datos = new DataSet();

    da.Fill(datos);

    return datos.Tables[0];

    }

    catch (Exception ex)

    {throw  new  Exception("Ha

    ocurrido un error de Consulta Store

    Procedure"+"\n\nDetalles del

    error."+ex.Message);

    }

    }

    //Funcion: Funcion que contenga una

    consulta para ejecutar una operacion de la base

    de datos. 

    public  int  EjecutarOperacion(string 

    strSQL)

    {

    try 

    {

    SqlCommand  cmd = new 

    SqlCommand();

    cmd.Connection = cnn;

    return cmd.ExecuteNonQuery();

    }

    catch (Exception ex){

    throw  new  Exception("Ha

    ocurrido un error al Ejecutar la operacionde

    consulta"  + "\n\nDetalles del error"  +

    ex.Message);

    }

    }

    //Funcion: Es la que nos ralizar una

    operacion pero con parametros parecido a la

    consulta anterior pero con uso 

    //de parametros. 

    public  int  EjecutarOperacion(string 

    strSQL, object[] objParametros)

    {

    try 

    {

    SqlCommand  cmd = new 

    SqlCommand(strSQL);

    foreach(SqlParameter  param in 

    objParametros )

    {

    cmd.Parameters.Add((SqlParameter)param);

    }

    cmd.Connection = cnn;

    return cmd.ExecuteNonQuery();

    }catch(Exception ex)

    {

    throw  new  Exception("Ha

    ocurrido un error en EjecutarOperacion"+strSQL+"\n\nDetalles del

    error"+ex.Message );

    }

    }

    public  int 

    EjecutarOperacion_StoreProcedure( string 

    strNombreProcedureAlm, object[] objParametros)

    {

    try 

    {

    SqlCommand  cmd = new 

    SqlCommand(strNombreProcedureAlm, cnn);

    cmd.CommandType =

    CommandType.StoredProcedure;

    foreach  (SqlParameter  param in 

    objParametros)

    {

    cmd.Parameters.Add((SqlParameter )param);

    }

    return cmd.ExecuteNonQuery();

    }

    catch (Exception ex)

  • 8/18/2019 Conexion 3 Capas C#

    3/7

      {

    throw  new  Exception("Ha

    Ocurrido un error en Ejecutar Operacion

    "+"\n\nDetalles del Error"+ex.Message);

    }

    }

    #endregion 

    }}

    Conexión satica.csusing System.Data.SqlClient;using System.Data;using System.Threading.Tasks;

    namespace Clase_Datos{

    public class ConectionSatitc {

    private  SqlConnection  conn =new  SqlConnection(@"Data

    Source=AMILKAR-PC\AMILKAR;InitialCatalog=Banco_Online;IntegratedSecurity=True");

    public bool Conectar(){

    try {

    conn.Open();return true;

    }catch (Exception){

    return false;}

    }

    public void Desconectar(){

    conn.Close();

    }public  DataTable 

    EjecutarConsultaXxX(string  sentencia,params SqlParameter[] parametros)

    {//Modo Desconectado 

    SqlDataAdapter  adaptador =new SqlDataAdapter();

    adaptador.SelectCommand =new SqlCommand();

    adaptador.SelectCommand.Connection =conn;

    adaptador.SelectCommand.CommandText =sentencia;

    foreach  (SqlParameter  itemin parametros)

    {

    adaptador.SelectCommand.Parameters.Add(item);

    }

    DataSet  resultado = new DataSet();

    adaptador.Fill(resultado);

    return resultado.Tables[0];}

    Transacción de la capaDatos

    using System.Data.SqlClient;using Clase_Objetos;namespace Clase_Datos{

    public class TransCuentaH {

    //La Cadena de Conexion Paso porDefault que me servira dentro de lafuncion 

    //Que es lo me dara el Web.config 

    private string strCadenaConexion= string.Empty;

    //Creo el Contructor de la ClaseTransCuentaH 

    public  TransCuentaH(string strCadenaConexion)

    {this.strCadenaConexion =

    strCadenaConexion;}

    public  DataTable LlenarCombo(Cuenta_habiente 

    objCuentaHabiente){

    try 

    { //Instancio la conexionque contiene el Acceso a Datos. 

    Conexion  objAccesoDatos= new Conexion(strCadenaConexion);

    objAccesoDatos.Conectado();

  • 8/18/2019 Conexion 3 Capas C#

    4/7

      return objAccesoDatos.Consulta_StoreProcedure("Mante_cuentaHabiente",

    new object []{

    new SqlParameter 

    ("@cod_cliente",objCuentaHabiente.cod_cliente !=0 ?(object)objCuentaHabiente.cod_cliente :DBNull.Value),

    new SqlParameter ("@cui",(object)objCuentaHabiente.cui??DBNull.Value ),

    new SqlParameter ("@dpi",(object)objCuentaHabiente.dpi?? DBNull.Value ),

    new SqlParameter 

    ("@nit",(object)objCuentaHabiente.nit??DBNull.Value ),

    new 

    SqlParameter ("@nombres",(object)objCuentaHabiente.

    nombres??DBNull.Value),new 

    SqlParameter ("@apellidos",(object)objCuentaHabiente .apellidos ??DBNull .Value),

    new SqlParameter ("@direccion",(object)objCuentaHabiente.direccion??DBNull.Value ),

    new SqlParameter ("@telefono",(object)objCuentaHabiente.telefono??DBNull.Value),

    new SqlParameter ("@email",(object)objCuentaHabiente.email ??DBNull.Value ),

    new SqlParameter  ("@fecha_registro",DBNull.Value),//DE LO CONTRARIO MDESPLIEGA DATOS DE FECHA INCORRECTO Y

    //NO M REEALIZALA OPERACION DEL COMBO, EXCELENTE. 

    new SqlParameter ("@p_opcion","COMBO")

    });}catch(Exception ex){

    throw  new  Exception("Haocurrido un error en la Operacion delCombo"  + "\n\nDetales de error:\n"  +ex.Message);

    }}public  int 

    InsertarCuentaHabiente(Cuenta_habiente objCuentaHabiente)

    {try 

    {Conexion  objAccesoDatos

    = new Conexion(strCadenaConexion);

    objAccesoDatos.Conectado();int  resultado =

    objAccesoDatos.EjecutarOperacion_StoreProcedure("Mante_cuentaHabiente",

    new object[]{

    new SqlParameter("@cod_cliente",DBNull.Value),

    new SqlParameter("@cui",objCuentaHabiente.cui),

    new SqlParameter("@dpi",objCuentaHabiente.

    dpi),new 

    SqlParameter("@nit",objCuentaHabiente.nit),

    new SqlParameter("@nombres",objCuentaHabiente.nombres),

    new SqlParameter("@apellidos",objCuentaHab

    iente.apellidos), new SqlParameter("@direccion",objCuentaHabiente.direccion),

    new SqlParameter("@telefono",objCuentaHabiente.telefono),

    new SqlParameter("@email",objCuentaHabiente .email),

    new SqlParameter("@fecha_registro",objCuentaHabiente .fecha_registro),

    new 

    SqlParameter("@p_opcion","INSERT")});

    objAccesoDatos.Desconectado();return resultado;

    }catch(Exception){

    throw;}

  • 8/18/2019 Conexion 3 Capas C#

    5/7

      }public  int 

    UpdateCuentaHabiente(Cuenta_habiente objCuentaHabiente)

    {try {

    Conexion  objAccesoDatos= new Conexion(strCadenaConexion);

    objAccesoDatos.Conectado();int  resultado =

    objAccesoDatos.EjecutarOperacion_StoreProcedure("Mante_cuentaHabiente",

    new object[]{

    new SqlParameter("@cod_cliente",objCuentaHabiente.cod_cliente),

    new 

    SqlParameter("@cui",objCuentaHabiente.cui),

    new 

    SqlParameter("@dpi",objCuentaHabiente.dpi),

    new SqlParameter("@nit",objCuentaHabiente.nit),

    new SqlParameter("@nombres",objCuentaHabiente .nombres),

    new SqlParameter("@apellidos",objCuentaHabiente.apellidos),

    new SqlParameter("@direccion",objCuentaHabiente.direccion),

    new SqlParameter("@telefono",objCuentaHabiente.telefono),

    new SqlParameter("@email",objCuentaHabiente .email),

    new SqlParameter("@fecha_registro",objCuentaHabiente.fecha_registro),

    new SqlParameter("@p_opcion","UPDATE")

    });

    objAccesoDatos.Desconectado();return resultado;

    }catch (Exception){

    throw;}

    }

    public  int EliminarCuentaHabiente(Cuenta_habiente objCuentaHabiente)

    {try {

    Conexion  objAccesoDatos

    = new Conexion(strCadenaConexion);

    objAccesoDatos.Conectado();int  resultado =

    objAccesoDatos.EjecutarOperacion_StoreProcedure("Mante_cuentaHabiente",

    new object[]{

    new SqlParameter("@cod_cliente",objCuentaHabiente.cod_cliente),

    new SqlParameter("@cui",objCuentaHabiente.

    cui),new 

    SqlParameter("@dpi",objCuentaHabiente.

    dpi),new 

    SqlParameter("@nit",objCuentaHabiente.nit),

    new SqlParameter("@nombres",objCuentaHabiente .nombres),

    new SqlParameter("@apellidos",objCuentaHabiente.apellidos),

    new 

    SqlParameter("@direccion",objCuentaHabiente.direccion),new 

    SqlParameter("@telefono",objCuentaHabiente.telefono),

    new SqlParameter("@email",objCuentaHabiente .email),

    new SqlParameter("@fecha_registro",objCuentaHabiente.fecha_registro),

    new SqlParameter("@p_opcion","ELIMINAR")

    });

    objAccesoDatos.Desconectado();return resultado;

    }catch(Exception ex){

    throw  new  Exception("Haocurrido un error en Eliminar alCliente." + "\n\nDetalles del error.\n" + ex.Message);

  • 8/18/2019 Conexion 3 Capas C#

    6/7

      }}

    }}

    Clase Funciones

    OperaCuentaH.cs

    using System.Data.SqlClient;using Clase_Objetos;using Clase_Datos;

    namespace Clase_Funciones{

    public class OperaCuentaH {

    //Devolvemos un cadena que este

    vacia de la conexion pq el q asegure queno este 

    //vacia esl Web.config 

    private  string strCadenaConexion = string.Empty;

    public  OperaCuentaH(string strCadenaConexion)

    {

    this.strCadenaConexion=strCadenaConexion;

    }

    public  DataTable LlenarCombo(Cuenta_habiente objCuentaHabiente)

    {try {TransCuentaH  objTrans=new 

    TransCuentaH(strCadenaConexion);return 

    objTrans.LlenarCombo(objCuentaHabiente);

    }catch(Exception){

    throw;}

    }

    public  static ListConsultaCuentaHabientesTipo(int cod_cliente)

    {try {

    return TransCuentaH.ConsultaCuentaHabientesTipo(cod_cliente);

    }catch {

    throw;}}

    public  int 

    InsertarCuentaHabiente(Cuenta_habiente objCuentaHabientes)

    {try {

    TransCuentaH objTranCuentaH = new TransCuentaH(strCadenaConexion);

    return objTranCuentaH.InsertarCuentaHabiente(objCuentaHabientes);

    }catch (Exception )

    {throw;

    }

    }public  int 

    UpdateCuentaHabiente(Cuenta_habiente objCuentaHabientes)

    {try {

    TransCuentaH objTranCuentaH = new TransCuentaH(strCadenaConexion);

    return 

    objTranCuentaH.UpdateCuentaHabiente(objCuentaHabientes);

    }catch (Exception){

    throw;}

    }public  int 

    EliminarCuentaHabiente(Cuenta_habiente objCuentaHabiente)

    {try 

    {TransCuentaH 

    objTranCuentaH = new TransCuentaH(strCadenaConexion);

    return objTranCuentaH.EliminarCuentaHabiente(objCuentaHabiente);

    }catch (Exception){

  • 8/18/2019 Conexion 3 Capas C#

    7/7

      throw;}

    }}

    }

    Clase Objetos

    Cuenta_Habiente.cs

    using System.Linq;using System.Text;using System.Threading.Tasks;

    namespace Clase_Objetos{

    public class Cuenta_habiente {

    public  int  cod_cliente { get;

    set; }public int cui { get; set; }

    public string dpi { get; set; }public string nit { get; set; }public  string  nombres { get;

    set; }public  string 

    apellidos{get;set;}public string direccion { get;

    set; }public  string 

    telefono{get;set;}public string email { get; set;

    }public  DateTime fecha_registro

    { get; set; }

    }}