16
PROGRAMACIÓN 5 – L13 – CSharp.NET PRACTICA PROGRAMACION 4 CAPAS 1. Creamos una solución llamada slnCuatroCapas. 2. Una vez guardado la solución: procedemos a crear las capas y las clases. a. Agregamos un proyecto de Biblioteca de Clases que se llamara Capa4_entidades. i. Agregamos una Clase que se llamara clsCliente. b. Agregamos un proyecto de Biblioteca de Clases que se llamara Capa3_Datos. i. Agregamos una Clase que se llamara clsConexion. ii. Agregamos una Clase que se llamara clsClienteDAL. c. Agregamos un proyecto de Biblioteca de Clases que se llamara Capa2_Logica. i. Agregamos una Clase que se llamara clsClienteBLL. d. Agregamos un proyecto de Windows Form que se llamara Capa1_Presentacion. i. Agregamos un formulario que se llamara frmCliente. e. Declare las regiones en cada clase y acomode el código correspondiente de cada región.. f. Una vez finalizada la actividad el explorador de soluciones quedara de la siguiente manera: g.

C# - Sem13-02sdsd

Embed Size (px)

DESCRIPTION

sdsdsdsd

Citation preview

  • PROGRAMACIN 5 L13 CSharp.NET

    PRACTICA PROGRAMACION 4 CAPAS

    1. Creamos una solucin llamada slnCuatroCapas.

    2. Una vez guardado la solucin: procedemos a crear las capas y las clases.

    a. Agregamos un proyecto de Biblioteca de Clases que se llamara Capa4_entidades.

    i. Agregamos una Clase que se llamara clsCliente.

    b. Agregamos un proyecto de Biblioteca de Clases que se llamara Capa3_Datos.

    i. Agregamos una Clase que se llamara clsConexion.

    ii. Agregamos una Clase que se llamara clsClienteDAL.

    c. Agregamos un proyecto de Biblioteca de Clases que se llamara Capa2_Logica.

    i. Agregamos una Clase que se llamara clsClienteBLL.

    d. Agregamos un proyecto de Windows Form que se llamara Capa1_Presentacion.

    i. Agregamos un formulario que se llamara frmCliente.

    e. Declare las regiones en cada clase y acomode el cdigo correspondiente de cada

    regin..

    f. Una vez finalizada la actividad el explorador de soluciones quedara de la siguiente

    manera:

    g.

  • PROGRAMACIN 5 L13 CSharp.NET

    3. Agreguen las correspondientes referencias e imports a las clases de acuerdo al siguiente

    diagrama.

    4. En el SQLSERVER restaure la base de datos suministrada por el profesor para dicho fin.

  • PROGRAMACIN 5 L13 CSharp.NET

    5. En la Capa4_Entidades en la clase clsCliente agregue las propiedades de todos los campos

    de la tabla cliente.

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Capa4_entidades { public class clsCliente { #region "Variables Globales, Campos o Atributos" private int _idCliente; private string _NombreCliente; private string _ApellidoCliente; private string _DireccionCliente; private string _DNICliente; private string _TelefonoCliente; private string _RUCCliente; private Boolean _EstadoCliente; #endregion #region "Propiedades" public int pIdCliente { get {return _idCliente;} set {_idCliente = value;} } public string pNombreCliente { get { return _NombreCliente; } set { _NombreCliente = value; } } public string pApellidoCliente { get { return _ApellidoCliente; } set { _ApellidoCliente = value; } } public string pDireccionCliente { get { return _DireccionCliente; } set { _DireccionCliente = value; } } public string pDNICliente { get { return _DNICliente; } set { _DNICliente = value; } } public string pTelefonoCliente { get { return _TelefonoCliente; } set { _TelefonoCliente = value; } } public string pRUCCliente { get { return _RUCCliente; } set { _RUCCliente = value; } }

    public bool pEstadoCliente

  • PROGRAMACIN 5 L13 CSharp.NET

    { get { return _EstadoCliente; } set { _EstadoCliente = value; } } #endregion #region "Constructores" public clsCliente() { //SUB NEW VACIO } public clsCliente(int idCliente, string NombreCliente, string ApellidoCliente, string DireccionCliente, string DNICliente, string TelefonoCliente, string RUCCliente, bool EstadoCliente) { ValidaData(idCliente, NombreCliente, ApellidoCliente, DireccionCliente, DNICliente,

    TelefonoCliente, RUCCliente, EstadoCliente);

    SetData(idCliente, NombreCliente, ApellidoCliente, DireccionCliente, DNICliente, TelefonoCliente, RUCCliente, EstadoCliente);

    } #endregion #region "Metodos" /// /// Valida los datos del objeto /// /// /// /// /// /// /// /// /// public void ValidaData(int idCliente, string NombreCliente, string ApellidoCliente, string DireccionCliente, string DNICliente, string TelefonoCliente, string RUCCliente, bool EstadoCliente) { if (idCliente

  • PROGRAMACIN 5 L13 CSharp.NET

    throw new System.ArgumentException("El valor del Apellido del Cliente

    debe ser indicado", "Apellido Cliente"); } if (String.IsNullOrEmpty(DireccionCliente) ||

    String.IsNullOrWhiteSpace(DireccionCliente)) { throw new System.ArgumentException("El valor de la Direccin del Cliente

    debe ser indicado", "Direccin Cliente"); } if (String.IsNullOrEmpty(DNICliente) ||

    String.IsNullOrWhiteSpace(DNICliente)) { throw new System.ArgumentException("El valor del DNI del Cliente debe

    ser indicado", "DNI Cliente"); } if (String.IsNullOrEmpty(TelefonoCliente) ||

    String.IsNullOrWhiteSpace(TelefonoCliente)) { throw new System.ArgumentException("El valor del Telefono del Cliente

    debe ser indicado","Telefono Cliente"); } if (String.IsNullOrEmpty(RUCCliente) ||

    String.IsNullOrWhiteSpace(RUCCliente)) { throw new System.ArgumentException("El valor del RUC del Cliente debe

    ser indicado", "RUC Cliente"); } bool H; string value = EstadoCliente.ToString(); if (Boolean.TryParse(value ,out H)) { // si se puede convertir no hace nada de lo contrario dara el error } else { throw new System.ArgumentException("El valor del Estado del Cliente no

    es un valor Booleano", "Estado Cliente"); } } /// /// Establece los datos del objeto /// /// /// /// /// /// /// /// /// public void SetData(int idCliente, string NombreCliente, string ApellidoCliente, string DireccionCliente, string DNICliente, string TelefonoCliente, string RUCCliente, bool EstadoCliente) { _idCliente = idCliente; _NombreCliente = NombreCliente; _ApellidoCliente = ApellidoCliente; _DireccionCliente = DireccionCliente; _DNICliente = DNICliente;

  • PROGRAMACIN 5 L13 CSharp.NET

    _TelefonoCliente = TelefonoCliente; _RUCCliente = RUCCliente; _EstadoCliente = EstadoCliente; } #endregion #region "Eventos" #endregion } }

    6. En la Capa3_Datos en la clase clsConexion agregue el siguiente cdigo.

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace Capa3_Datos { public class clsConexion { #region "Variables Globales, Campos o Atributos" //private SqlConnection conexion; string cadena = "Data Source=CFALLASD_UTC;Initial Catalog=01-SISTEMAFACTURACION;Integrated Security=True"; #endregion #region "Propiedades" #endregion #region "Constructores" #endregion #region "Metodos" public SqlConnection obtenerConeccion() { SqlConnection conexion = new SqlConnection(cadena); if (conexion.State == System.Data.ConnectionState.Open) { conexion.Close(); } else { conexion.Open(); } return conexion; } #endregion #region "Eventos" #endregion } }

  • PROGRAMACIN 5 L13 CSharp.NET

  • PROGRAMACIN 5 L13 CSharp.NET

    7. En la Capa3_Datos en la clase clsClienteDAL agregue el siguiente cdigo.

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Capa4_entidades; using System.Data.SqlClient; using System.Data; namespace Capa3_Datos { public class clsClienteDAL { #region "Variables" //SqlDataAdapter daCliente; SqlCommand cmdCliente = new SqlCommand(); //DataSet dsCliente; //SqlDataReader drCliente; clsConexion objConexion = new clsConexion(); #endregion #region "Propiedades" #endregion #region "Constructores" #endregion #region "Metodos" public string AgregarCliente(clsCliente objClienteE) { string mensaje = string.Empty; cmdCliente.CommandType = CommandType.StoredProcedure; cmdCliente.CommandText = "SP_Insertar_Cliente"; cmdCliente.Connection = objConexion.obtenerConeccion(); cmdCliente.Parameters.Add("@idCliente", SqlDbType.Int).Value =

    objClienteE.pIdCliente; cmdCliente.Parameters.Add("@nomCliente", SqlDbType.VarChar).Value =

    objClienteE.pNombreCliente; cmdCliente.Parameters.Add("@apeCliente", SqlDbType.VarChar).Value =

    objClienteE.pApellidoCliente; cmdCliente.Parameters.Add("@dniCliente", SqlDbType.VarChar).Value =

    objClienteE.pDNICliente; cmdCliente.Parameters.Add("@rucCliente", SqlDbType.VarChar).Value =

    objClienteE.pRUCCliente; cmdCliente.Parameters.Add("@telCliente", SqlDbType.VarChar).Value =

    objClienteE.pTelefonoCliente; cmdCliente.Parameters.Add("@dirCliente", SqlDbType.VarChar).Value =

    objClienteE.pDireccionCliente; int registros; registros = cmdCliente.ExecuteNonQuery(); if (registros == 1) { mensaje = "Registro guardado correctamente"; } else { mensaje = "Error en la transaccion"; } cmdCliente.Parameters.Clear(); objConexion.obtenerConeccion().Close(); return mensaje;

  • PROGRAMACIN 5 L13 CSharp.NET

    } public string ActualizarCliente(clsCliente objClienteE) { string mensaje; cmdCliente.CommandType = CommandType.StoredProcedure; cmdCliente.CommandText = "SP_Actualizar_Cliente"; cmdCliente.Connection = objConexion.obtenerConeccion(); cmdCliente.Parameters.Add("@idCliente", SqlDbType.Int).Value =

    objClienteE.pIdCliente; cmdCliente.Parameters.Add("@nomCliente", SqlDbType.VarChar).Value =

    objClienteE.pNombreCliente; cmdCliente.Parameters.Add("@apeCliente", SqlDbType.VarChar).Value =

    objClienteE.pApellidoCliente; cmdCliente.Parameters.Add("@dniCliente", SqlDbType.VarChar).Value =

    objClienteE.pDNICliente; cmdCliente.Parameters.Add("@rucCliente", SqlDbType.VarChar).Value =

    objClienteE.pRUCCliente; cmdCliente.Parameters.Add("@telCliente", SqlDbType.VarChar).Value =

    objClienteE.pTelefonoCliente; cmdCliente.Parameters.Add("@dirCliente", SqlDbType.VarChar).Value =

    objClienteE.pDireccionCliente; int registros; registros = cmdCliente.ExecuteNonQuery(); if (registros == 1) { mensaje = "Registro Actualizado correctamente"; } else { mensaje = "Error en la transaccion"; } cmdCliente.Parameters.Clear(); objConexion.obtenerConeccion().Close(); return mensaje; } public List ListarClientes() { List lista = new List(); SqlDataReader dr; cmdCliente.CommandType = CommandType.StoredProcedure; cmdCliente.CommandText = "SP_Listar_Clientes"; cmdCliente.Connection = objConexion.obtenerConeccion(); dr = cmdCliente.ExecuteReader(); while (dr.Read()) { clsCliente objCliente = new clsCliente(); objCliente.pIdCliente = Convert.ToInt16(dr.GetValue(0)); objCliente.pNombreCliente =Convert.ToString(dr.GetValue(1)); objCliente.pApellidoCliente = Convert.ToString(dr.GetValue(2)); objCliente.pDireccionCliente = Convert.ToString(dr.GetValue(6)); objCliente.pDNICliente = Convert.ToString(dr.GetValue(3)); objCliente.pTelefonoCliente = Convert.ToString(dr.GetValue(5)); objCliente.pRUCCliente = Convert.ToString(dr.GetValue(4)); lista.Add(objCliente); } return lista; } public List BuscarCliente(int codigo) { List lista = new List(); SqlDataReader dr; cmdCliente.CommandType = CommandType.StoredProcedure; cmdCliente.CommandText = "Sp_BuscarCliente"; cmdCliente.Connection = objConexion.obtenerConeccion(); cmdCliente.Parameters.Add("@idCliente", SqlDbType.Int).Value = codigo;

  • PROGRAMACIN 5 L13 CSharp.NET

    dr = cmdCliente.ExecuteReader(); while (dr.Read()) { clsCliente objCliente = new clsCliente(); objCliente.pIdCliente = Convert.ToInt16(dr.GetValue(0)); objCliente.pNombreCliente = Convert.ToString(dr.GetValue(1)); objCliente.pApellidoCliente = Convert.ToString(dr.GetValue(2)); objCliente.pDireccionCliente = Convert.ToString(dr.GetValue(6)); objCliente.pDNICliente = Convert.ToString(dr.GetValue(3)); objCliente.pTelefonoCliente = Convert.ToString(dr.GetValue(5)); objCliente.pRUCCliente = Convert.ToString(dr.GetValue(4)); lista.Add(objCliente); } return lista; } public int codCliente() { int codigo=0; SqlDataReader dr; cmdCliente.CommandType = CommandType.StoredProcedure; cmdCliente.CommandText = "SP_Generar_Cod_Cliente"; cmdCliente.Connection = objConexion.obtenerConeccion(); dr = cmdCliente.ExecuteReader(); while (dr.Read()) { codigo = Convert.ToInt16(dr.GetValue(0)); } return codigo; } #endregion #region "Eventos" #endregion } }

  • PROGRAMACIN 5 L13 CSharp.NET

    8. En la Capa2_Logica en la clase clsClienteBLL agregue el siguiente cdigo.

    using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Capa3_Datos; using Capa4_entidades; namespace Capa2_Logica { public class clsClienteBLL { #region "Variables Globales, Campos o Atributos" private clsClienteDAL objClienteDAO = new clsClienteDAL (); #endregion #region "Propiedades" #endregion #region "Constructores" #endregion #region "Metodos" public String AgregarCliente(clsCliente objClienteE) { return objClienteDAO.AgregarCliente(objClienteE); } public string ActualizarCliente(clsCliente objClienteE) { return objClienteDAO.ActualizarCliente(objClienteE); } public int CodCliente() { return objClienteDAO.codCliente(); } public List listarClientes() { return objClienteDAO.ListarClientes(); } public List ListarCliente(int codigo) { return objClienteDAO.BuscarCliente(codigo); } #endregion #region "Eventos" #endregion } }

  • PROGRAMACIN 5 L13 CSharp.NET

    9. En la Capa1_Presentacion el formulario frmCliente contendr la siguiente forma.

    10. En la Capa1_Presentacion en el formularo frmCliente agregue el siguiente cdigo.

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using Capa2_Logica; using Capa4_entidades; namespace Capa1_Presentacion { public partial class frmCliente : Form { #region "Variables Globales, Campos o Atributos" #endregion #region "Propiedades" #endregion #region "Constructores" public frmCliente() { InitializeComponent(); } #endregion #region "Metodos" void NuevoCliente() { //Crea Objeto sin validacion clsCliente objClienteE = new clsCliente (); objClienteE.pIdCliente = Convert.ToInt16 (txtCodCliente.Text);

  • PROGRAMACIN 5 L13 CSharp.NET

    objClienteE.pNombreCliente = txtNomCliente.Text; objClienteE.pApellidoCliente = txtApeCliente.Text; objClienteE.pDireccionCliente = txtDirrCliente.Text; objClienteE.pDNICliente = txtDNICliente.Text; objClienteE.pTelefonoCliente = txtTelfCliente.Text; objClienteE.pRUCCliente = txtRUC.Text; //Crea Objeto con validacion try { objClienteE = new clsCliente(Convert.ToInt16 (txtCodCliente.Text), txtNomCliente.Text, txtApeCliente.Text, txtDirrCliente.Text, txtDNICliente.Text, txtTelfCliente.Text, txtRUC.Text, false); clsClienteBLL objClienteNE = new clsClienteBLL(); string salida = objClienteNE.AgregarCliente(objClienteE); MessageBox.Show(salida); dgvCliente.DataSource = objClienteNE.listarClientes(); habilitarBotones(true, false, false, false); HabilitarCajas(false); } catch (Exception ex) { MessageBox.Show(ex.Message); } } void LimpiarCajas() { txtCodCliente.Clear(); txtNomCliente.Clear(); txtApeCliente.Clear(); txtDirrCliente.Clear(); txtDNICliente.Clear(); txtTelfCliente.Clear(); txtRUC.Clear(); } void HabilitarCajas(bool estado) { txtCodCliente.Enabled = false; txtNomCliente.Enabled = estado; txtApeCliente.Enabled = estado; txtDirrCliente.Enabled = estado; txtDNICliente.Enabled = estado; txtTelfCliente.Enabled = estado; txtRUC.Enabled = estado; txtNomCliente.Focus(); } void ConfigurarDataGrid() { dgvCliente.RowsDefaultCellStyle.BackColor = Color.LightYellow; dgvCliente.AlternatingRowsDefaultCellStyle.BackColor = Color.LightGreen; } void habilitarBotones(bool Nuevo, bool Agregar, bool Actualizar, bool Cancelar) { btnNuevo.Enabled = Nuevo; btnGrabar.Enabled = Agregar; btnActualizar.Enabled = Actualizar; btnCancelar.Enabled = Cancelar; } void BuscarClientes(int codigo) {

  • PROGRAMACIN 5 L13 CSharp.NET

    clsClienteBLL objClienteNE = new clsClienteBLL(); List objClienteE = new List(); int idCliente; idCliente = objClienteNE.CodCliente() - 1; if (codigo > idCliente) { MessageBox.Show("Registros no encontrado"); } else { objClienteE = objClienteNE.ListarCliente(codigo); txtCodCliente.Text = objClienteE[0].pIdCliente.ToString(); txtNomCliente.Text = objClienteE[0].pNombreCliente.ToString(); txtApeCliente.Text = objClienteE[0].pApellidoCliente.ToString(); txtDirrCliente.Text = objClienteE[0].pDireccionCliente.ToString(); txtDNICliente.Text = objClienteE[0].pDNICliente.ToString(); txtTelfCliente.Text = objClienteE[0].pTelefonoCliente.ToString(); txtRUC.Text = objClienteE[0].pRUCCliente.ToString(); } habilitarBotones(false, false, true, true); HabilitarCajas(true); } void actualizarClientes() { if (txtCodCliente.Text != "") { clsCliente objClienteE = new clsCliente(); clsClienteBLL objClienteNE = new clsClienteBLL(); objClienteE.pIdCliente = Convert.ToInt16 (txtCodCliente.Text); objClienteE.pNombreCliente = txtNomCliente.Text; objClienteE.pApellidoCliente = txtApeCliente.Text; objClienteE.pDireccionCliente = txtDirrCliente.Text; objClienteE.pDNICliente = txtDNICliente.Text; objClienteE.pTelefonoCliente = txtTelfCliente.Text; objClienteE.pRUCCliente = txtRUC.Text; string salida = objClienteNE.ActualizarCliente(objClienteE); MessageBox.Show(salida); dgvCliente.DataSource = objClienteNE.listarClientes(); } else { MessageBox.Show("Ingrese los datos para actualizar"); } habilitarBotones(true, false, false, false); HabilitarCajas(false); } static DialogResult InputBox(string title, string promptText, ref int codigo) { Form form = new Form(); Label label = new Label(); TextBox textBox = new TextBox(); Button buttonOk = new Button(); Button buttonCancel = new Button(); form.Text = title; label.Text = promptText; textBox.Text = codigo.ToString() ; buttonOk.Text = "OK"; buttonCancel.Text = "Cancel"; buttonOk.DialogResult = DialogResult.OK; buttonCancel.DialogResult = DialogResult.Cancel; label.SetBounds(9, 20, 372, 13);

  • PROGRAMACIN 5 L13 CSharp.NET

    textBox.SetBounds(12, 36, 372, 20); buttonOk.SetBounds(228, 72, 75, 23); buttonCancel.SetBounds(309, 72, 75, 23); label.AutoSize = true; textBox.Anchor = textBox.Anchor | AnchorStyles.Right; buttonOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right; form.ClientSize = new Size(396, 107); form.Controls.AddRange(new Control[] { label, textBox, buttonOk, buttonCancel }); form.ClientSize = new Size(Math.Max(300, label.Right + 10), form.ClientSize.Height); form.FormBorderStyle = FormBorderStyle.FixedDialog; form.StartPosition = FormStartPosition.CenterScreen; form.MinimizeBox = false; form.MaximizeBox = false; form.AcceptButton = buttonOk; form.CancelButton = buttonCancel; DialogResult dialogResult = form.ShowDialog(); codigo = Convert.ToInt16(textBox.Text); return dialogResult; } #endregion #region "Eventos" private void frmCliente_Load(object sender, EventArgs e) { clsClienteBLL objClienteNE1; objClienteNE1 = new clsClienteBLL(); dgvCliente.DataSource = objClienteNE1.listarClientes(); ConfigurarDataGrid(); BuscarClientes(1); HabilitarCajas(false); habilitarBotones(true, false, false, false); } private void btnNuevo_Click(object sender, EventArgs e) { HabilitarCajas(true); LimpiarCajas(); habilitarBotones(false, true, false, true); clsClienteBLL objClienteNE = new clsClienteBLL(); txtCodCliente.Text = objClienteNE.CodCliente().ToString(); } private void btnBuscar_Click(object sender, EventArgs e) { try { clsClienteBLL objClienteNE = new clsClienteBLL(); clsCliente objClienteE = new clsCliente();

    int codigo = 0; int Busca = Convert.ToInt16(InputBox("Ingrese Cdigo Cliente", "Dgite el cdigo

    a buscar", ref codigo )); BuscarClientes(codigo); } catch (Exception ex) { MessageBox.Show(ex.Message); } } private void btnCancelar_Click(object sender, EventArgs e) { BuscarClientes(1); HabilitarCajas(false); habilitarBotones(true, false, false, false);

  • PROGRAMACIN 5 L13 CSharp.NET

    } private void btnActualizar_Click(object sender, EventArgs e) { actualizarClientes(); } private void btnGrabar_Click(object sender, EventArgs e) { NuevoCliente(); } private void dgvCliente_CellClick(object sender, DataGridViewCellEventArgs e) { if (dgvCliente.Rows.Count > 0) { DataGridViewRow dgvFila = dgvCliente.CurrentRow; txtCodCliente.Text = dgvFila.Cells[0].Value.ToString(); txtNomCliente.Text = dgvFila.Cells[1].Value.ToString(); txtApeCliente.Text = dgvFila.Cells[2].Value.ToString(); txtDirrCliente.Text = dgvFila.Cells[3].Value.ToString(); txtDNICliente.Text = dgvFila.Cells[4].Value.ToString(); txtTelfCliente.Text = dgvFila.Cells[5].Value.ToString(); txtRUC.Text = dgvFila.Cells[6].Value.ToString(); } else { MessageBox.Show("No hay ningun registro seleccionado"); } habilitarBotones(false, false, true, true); HabilitarCajas(true); } #endregion } }

    11. Ejecute la aplicacin.