You are on page 1of 19

Enrique Gmez Jimenez, 2013. Programacin en Visual C# 2012.

I Parte. Creacin de la base de dats dbUpacp.


La base de datos dbUpacoop:
Lo primero que vamos a realizar para nuestro proyecto es crear la base de datos que servir como repositorio de datos a dicho proyecto. La base de datos consiste en 2 tablas lgicamente relacionadas entre s mediante el campo comn AsociadoID, tal como se muestra en la imagen siguiente:

Esta base de datos adems del diseo de las tablas y su relacin deber contar con un procedimiento almacenado que se indica en el siguiente prrafo:

Enrique Gmez Jimenez, 2013. Programacin en Visual C# 2012.


CREATE PROCEDURE validarAsociado (@pAsociadoID char(10), @pClave char(15)) AS Select *From tbAsociados Where (AsociadoID = @pAsociadoID And Clave = @pClave)

II Parte. Creacin del servici web wsGestinDats.


Servicio web wsGestionDatos:
Una vez que se disea la base de datos debe crearse un procedimiento almacenado, en este caso denominado wsGestionDato. Inicialmente deber establecer la propiedad connectionString en el archivo web.config, tal como se muestra en el siguiente prrafo de cdigo:

Enrique Gmez Jimenez, 2013. Programacin en Visual C# 2012.


Una vez configurado el web.config, debemos programar los mtodos web que utilizar nuestro servicio web. Este cdigo es el siguiente:
1. using System; 2. using System.Collections.Generic; 3. using System.Linq; 4. using System.Web; 5. using System.Web.Services; 6. using System.Data.SqlClient; 7. using System.Configuration; 8. [WebService(Namespace = "http://tempuri.org/")] 9. [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] 10. // Para permitir que se llame a este servicio web desde un script, usando ASP.NET AJAX, quite la marca de comentario de la lnea siguiente. 11. // [System.Web.Script.Services.ScriptService] 12. public class Service : System.Web.Services.WebService 13. { 14. public Service () { 15. //Elimine la marca de comentario de la lnea siguiente si utiliza los componentes diseados 16. //InitializeComponent(); 17. } 18. static private string strConn = ConfigurationManager.ConnectionStrings["dbConn"].ConnectionString; 19. private SqlConnection objConn = new SqlConnection(strConn); 20. [WebMethod] 21. public void obtenerDatos(ref String mensaje, string cSQL, ref System.Data.DataSet ds) 22. { 23. try 24. { 25. SqlDataAdapter da = new SqlDataAdapter(cSQL, objConn); 26. da.Fill(ds); 27. } 28. catch (Exception ex) 29. { 30. mensaje = ex.Message; 31. } 32. } 33. [WebMethod]

Enrique Gmez Jimenez, 2013. Programacin en Visual C# 2012.


34. public Boolean actualizarDatos(String cSQL, ref String Mensaje) 35. { 36. try 37. { 38. SqlCommand cmd = new SqlCommand(cSQL, objConn); 39. if (objConn.State == System.Data.ConnectionState.Closed) objConn.Open(); 40. cmd.ExecuteNonQuery(); 41. if (objConn.State == System.Data.ConnectionState.Open) objConn.Close(); 42. return true; 43. } 44. catch (Exception ex) 45. { 46. Mensaje = ex.Message; 47. return false; 48. } 49. } 50. [WebMethod] 51. public void validaUsuario(string usuario, string clave, ref System.Data.DataSet ds) 52. { 53. SqlCommand cmd = new SqlCommand(); 54. SqlParameter prmUsuario = new SqlParameter(); 55. SqlParameter prmClave = new SqlParameter(); 56. cmd = new SqlCommand("validarAsociado", objConn); 57. cmd.CommandType = System.Data.CommandType.StoredProcedure; 58. prmUsuario = cmd.Parameters.Add("@pAsociadoId", System.Data.SqlDbType.Char); 59. prmClave = cmd.Parameters.Add("@pClave", System.Data.SqlDbType.Char); 60. prmUsuario.Value = usuario; 61. prmClave.Value = clave; 62. prmUsuario.Direction = System.Data.ParameterDirection.Input; 63. prmClave.Direction = System.Data.ParameterDirection.Input; 64. SqlDataAdapter dA = new SqlDataAdapter(cmd); 65. dA.Fill(ds); 66. } 67. }

Una vez creado este servicio web podemos ver su ejecucin en el navegador. La siguiente imagen muestra dicha ejecucin.

Enrique Gmez Jimenez, 2013. Programacin en Visual C# 2012.

Con la ejecucin del servicio web, podemos darnos cuenta que la funcionalidad del mismo ya est establecida. Por tanto, debemos compilar dicho servicio web y proceder a generar dicho sitio web.

Enrique Gmez Jimenez, 2013. Programacin en Visual C# 2012.

III Parte. Creacin de la aplicacin web webCperativa.


Creacin de la clase Formato para la aplicacin:
Vamos a crear una clase para esta aplicacin que permita utilizar una ventana de mensaje y la limpieza de texto en objetos TextBox. Esta clase se crea en esta aplicacin para efectos de ilustracin de cmo utilizar clases en una aplicacin web ASP .NET. El cdigo es el siguiente:
1. using System; 2. using System.Collections.Generic; 3. using System.Linq; 4. using System.Web; 5. using System.Web.UI; 6. using System.Web.UI.WebControls; 7. using System.Collections; 8. /// <summary> 9. /// Descripcin breve de Formato 10. /// </summary> 11. public class Formato 12. { 13. public Formato() 14. { 15. } 16. public void MessageBox(String msg, System.Web.UI.Control Page) 17. { 18. Label lbl = new Label(); 19. lbl.Text = "<script language='javascript'>" + 20. Environment.NewLine + "window.alert('" + msg + "')</script>"; 21. Page.Controls.Add(lbl); 22. }

Enrique Gmez Jimenez, 2013. Programacin en Visual C# 2012.


23. public void LimpiartextBoxes(Control parent) 24. { 25. foreach (Control c in parent.Controls) 26. { 27. if ((c.GetType() == typeof(TextBox))) 28. { 29. ((TextBox)(c)).Text = ""; 30. } 31. if (c.HasControls()) 32. { 33. LimpiartextBoxes(c); 34. } 35. } 36. } 37. }

Pantalla inicial webLogin.aspx:


Una vez creada la clase formato vamos a iniciar con la creacin del formulario inicial de la aplicacin web. La interface de este formulario es:

Enrique Gmez Jimenez, 2013. Programacin en Visual C# 2012.


En el formulario anterior observe el uso de tablas (an no estamos utilizando CSS) y coloque los objetos tal y como se observan en la imagen. El cdigo para este formulario es el siguiente:
1. using System; 2. using System.Collections.Generic; 3. using System.Linq; 4. using System.Web; 5. using System.Web.UI; 6. using System.Web.UI.WebControls; 7. public partial class webLogin : System.Web.UI.Page 8. { 9. protected void Page_Load(object sender, EventArgs e) 10. { 11. } 12. protected void btnAceptar_Click(object sender, EventArgs e) 13. { 14. GestionDatos.Service owsGD = new GestionDatos.Service(); 15. System.Data.DataSet dsUsuarios = new System.Data.DataSet(); 16. Formato oVentana = new Formato(); 17. owsGD.validaUsuario(txtUsuario.Text, txtClave.Text, ref dsUsuarios); 18. if (dsUsuarios.Tables[0].Rows.Count > 0) 19. { 20. Session["IdCliente"] = dsUsuarios.Tables[0].Rows[0][0].ToString(); 21. Session["nomCliente"] = dsUsuarios.Tables[0].Rows[0][2].ToString()+ 22. " " + dsUsuarios.Tables[0].Rows[0][1].ToString(); 23. Response.Redirect("webMenu.aspx"); 24. } 25. else 26. oVentana.MessageBox("Usuario No existe....", this); 27. } 28. }

Una vez listo este formulario podemos observar su ejecucin en el navegador. La siguiente imagen lo muestra:

Enrique Gmez Jimenez, 2013. Programacin en Visual C# 2012.

Si el usuario no existe se mostrar una ventana indicando tal situacin, de lo contrario se direccionar hacia la pgina webMenu.aspx, tal y como se indica en el cdigo de este formulario web.

Pantalla men webMenu.aspx:


El siguiente formulario constituye el men principal de nuestra aplicacin web.

Enrique Gmez Jimenez, 2013. Programacin en Visual C# 2012.

Ejecutado este men se vera tal como se muestra en la imagen siguiente:

10

Enrique Gmez Jimenez, 2013. Programacin en Visual C# 2012.

Pantalla men webMantAsociados.aspx:


El siguiente formulario permite el mantenimiento de la tabla Asociados. La interface es la siguiente:
11

Enrique Gmez Jimenez, 2013. Programacin en Visual C# 2012.

Y el cdigo de este formulario es:

1. using System; 2. using System.Collections.Generic; 3. using System.Linq; 4. using System.Web; 5. using System.Web.UI; 6. using System.Web.UI.WebControls; 7. public partial class webMantAsociados : System.Web.UI.Page 8. { 9. String SQL,mssg; 10. GestionDatos.Service aux = new GestionDatos.Service();

12

Enrique Gmez Jimenez, 2013. Programacin en Visual C# 2012.


11. System.Data.DataSet dst = new System.Data.DataSet(); 12. private void habilitarExiste() 13. { 14. btnAgregar.Enabled = false; 15. btnModificar.Enabled = true; 16. btnEliminar.Enabled= true; 17. } 18. private void habilitarNuevo() 19. { 20. btnAgregar.Enabled = true; 21. btnModificar.Enabled = false; 22. btnEliminar.Enabled= false; 23. } 24. private void deshabilitarBotones() 25. { 26. btnAgregar.Enabled = false; 27. btnModificar.Enabled = false; 28. btnEliminar.Enabled = false; 29. ventana.LimpiartextBoxes(this); 30. } 31. Formato ventana = new Formato(); 32. protected void ImageButton1_Click(object sender, ImageClickEventArgs e) 33. { 34. try 35. { 36. SQL = "Select *From tbAsociados Where AsociadoID = '" + txtID.Text + "'"; 37. aux.obtenerDatos(ref mssg, SQL, ref dst); 38. if (dst.Tables[0].Rows.Count > 0) 39. { 40. txtNombre.Text = dst.Tables[0].Rows[0][2].ToString(); 41. txtApellidos.Text = dst.Tables[0].Rows[0][1].ToString(); 42. txtDireccion.Text = dst.Tables[0].Rows[0][3].ToString(); 43. txtTelefono.Text = dst.Tables[0].Rows[0][4].ToString(); 44. txtEmail.Text = dst.Tables[0].Rows[0][5].ToString(); 45. DatePicker1.SelectedDate = Convert.ToDateTime(dst.Tables[0].Rows[0][6].ToString()); 46. habilitarExiste(); 47. } 48. else

13

Enrique Gmez Jimenez, 2013. Programacin en Visual C# 2012.


49. { 50. ventana.MessageBox("Registro no encontrado!", this); 51. habilitarNuevo(); 52. Session["ID"] = txtID.Text; 53. ventana.LimpiartextBoxes(this); 54. txtID.Text = Session["ID"].ToString(); 55. } 56. } 57. catch (Exception ex) 58. { 59. ventana.MessageBox(ex.Message, this); 60. } 61. } 62. protected void btnEliminar_Click(object sender, EventArgs e) 63. { 64. try 65. { 66. SQL = "Delete from tbAsociados Where AsociadoID= '" + txtID.Text + "'"; 67. aux.actualizarDatos(SQL, ref mssg); 68. ventana.MessageBox("Registro eliminado", this); 69. deshabilitarBotones(); 70. } 71. catch (Exception ex) 72. { 73. ventana.MessageBox(ex.Message, this); 74. } 75. } 76. protected void btnAgregar_Click(object sender, EventArgs e) 77. { 78. try 79. { 80. String fecha = DatePicker1.SelectedDate.ToString(); 81. SQL = "Insert into tbAsociados(AsociadoID,Apellidos,Nombre,Direccion,Telefono,Email,Fecha_Ingreso,Capital_Social,Clave)"; 82. SQL += " Values('" + txtID.Text + "','" + txtApellidos.Text + "','" + txtNombre.Text + "','"; 83. SQL += txtDireccion.Text + "','" + txtTelefono.Text + "','" + txtEmail.Text + "','"; 84. SQL += fecha + "',0,'123')"; 85. aux.actualizarDatos(SQL, ref mssg); 86. ventana.MessageBox("Registro ingresado exitosamente!", this);

14

Enrique Gmez Jimenez, 2013. Programacin en Visual C# 2012.


87. deshabilitarBotones(); 88. } 89. catch (Exception ex) 90. { 91. ventana.MessageBox(ex.Message, this); 92. } 93. } 94. protected void btnModificar_Click(object sender, EventArgs e) 95. { 96. try 97. { 98. String fecha = DatePicker1.SelectedDate.ToString(); 99. SQL = "Update tbAsociados set Apellidos='" + txtApellidos.Text +"'"; 100. SQL += ",Nombre = '" + txtNombre.Text + "'"; 101. SQL += ",Direccion = '" + txtDireccion.Text + "'"; 102. SQL += ",Telefono= '" + txtTelefono.Text + "'"; 103. SQL += ",Email= '" + txtEmail.Text + "'"; 104. SQL += ",Fecha_Ingreso= '" + fecha + "'"; 105. SQL += " Where AsociadoID= '" + txtID.Text + "'"; 106. Response.Write(SQL); 107. aux.actualizarDatos(SQL, ref mssg); 108. ventana.MessageBox("Registro modificado", this); 109. deshabilitarBotones(); 110. } 111. catch (Exception ex) 112. { 113. ventana.MessageBox(ex.Message, this); 114. } 115. } 116. }

Y la ejecucin de este formulario se muestra en la imagen siguiente:

15

Enrique Gmez Jimenez, 2013. Programacin en Visual C# 2012.

Pantalla men webConsultaGeneral.aspx:


El siguiente formulario permite la consulta general de las cuotas del asociado tbCuotas. La interface es la siguiente:

16

Enrique Gmez Jimenez, 2013. Programacin en Visual C# 2012.

El cdigo respectivo a este formulario es:


1. using System; 2. using System.Collections.Generic; 3. using System.Linq; 4. using System.Web; 5. using System.Web.UI; 6. using System.Web.UI.WebControls; 7. using System.Data; 8. public partial class webConsultaGeneral : System.Web.UI.Page 9. { 10. GestionDatos.Service aux = new GestionDatos.Service(); 11. System.Data.DataSet ds = new System.Data.DataSet(); 12. String SQL,Id;

17

Enrique Gmez Jimenez, 2013. Programacin en Visual C# 2012.


13. String messa = ""; 14. void cargarGrid(System.Data.DataSet dsTabla) 15. { 16. GridView1.DataSource = dsTabla.Tables[0].DefaultView; 17. GridView1.DataBind(); 18. } 19. void cargarCuotas() 20. { 21. SQL = "Select Fecha_Cuota, Monto_Cuota As Cuota,"; 22. SQL += "Descripcion From tbCuotas Where AsociadoID = '" + Id.Trim() +"'"; 23. aux.obtenerDatos(ref messa, SQL, ref ds); 24. cargarGrid(ds); 25. } 26. protected void Page_Load(object sender, EventArgs e) 27. { 28. Id = (String)Session["IdCliente"]; 29. cargarCuotas(); 30. } 31. protected void btnConsultar_Click(object sender, EventArgs e) 32. { 33. String Fecha1, Fecha2; 34. Fecha1 = DatePicker1.SelectedDate.ToString(); 35. Fecha2 = DatePicker2.SelectedDate.ToString(); 36. //DatePicker1.PickerFormat = "MM/dd/yyyy"; 37. SQL = "Select Fecha_Cuota As Fecha, Monto_Cuota As Cuota,"; 38. SQL += "Descripcion From tbCuotas Where AsociadoID = '" + Id.Trim() + "'"; 39. SQL += " And Fecha_Cuota >='" + Fecha1 + "' And Fecha_Cuota <='" + Fecha2 + "'"; 40. ds.Clear(); 41. aux.obtenerDatos(ref messa, SQL, ref ds); 42. cargarGrid(ds); 43. } 44. protected void GridView1_SelectedIndexChanged(object sender, EventArgs e) 45. { 46. int fila = Convert.ToInt32(GridView1.SelectedIndex); 47. Label1.Text = GridView1.Rows[fila].Cells[1].Text; 48. Label2.Text = GridView1.Rows[fila].Cells[2].Text; 49. Label3.Text = GridView1.Rows[fila].Cells[3].Text; 50. }

18

Enrique Gmez Jimenez, 2013. Programacin en Visual C# 2012.


51. } Y la ejecucin de este formulario es:

19

You might also like