clase 1 asp

45
UNAC Ing.Osmart Morales Chalco UNIVERSIDAD NACIONAL DEL CALLAO FACULTAD DE INGENIERIA DE SISTEMAS LENGUAJE DE PROGRAMACION III EJEMPLO 1

Upload: sebastian-carbajal

Post on 24-Oct-2014

53 views

Category:

Documents


8 download

TRANSCRIPT

Page 1: clase 1 asp

UNAC Ing.Osmart Morales Chalco

UNIVERSIDAD NACIONAL DEL CALLAOFACULTAD DE INGENIERIA DE SISTEMAS

LENGUAJE DE PROGRAMACION IIIEJEMPLO 1

Page 2: clase 1 asp

UNAC Ing.Osmart Morales Chalco

Partial Class Alumno Inherits System.Web.UI.Page

Protected Sub btnCalcular_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCalcular.Click Dim N1, N2, N3, Prom As Single N1 = Single.Parse(txtN1.Text) N2 = Single.Parse(txtN2.Text) N3 = Single.Parse(txtN3.Text) Prom = (N1 + N2 + N3 * 2) / 4 Me.txtPromedio.Text = Prom.ToString If Prom >= 14 Then lblMensaje.Text = "Aprobado" ElseIf Prom > 11 Then lblMensaje.Text = "Sustitutorio" Else lblMensaje.Text = "Llevar de nuevo" End If End Sub

Protected Sub btnNuevo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnNuevo.Click txtCodigo.Text = "" txtNombre.Text = "" txtCurso.Text = "" txtN1.Text = "" txtN2.Text = "" txtN3.Text = "" txtPromedio.Text = "" lblMensaje.Text = "" txtCodigo.Focus()

End SubEnd Class

Page 3: clase 1 asp

UNAC Ing.Osmart Morales Chalco

EJEMPLO 2

RepeatDirection = Horizontal (esta propiedad sale un solo radiobutton, pero al incrementar

Se incrementa para la derecha)

Items = colección (esta propiedad hace que se incrementen los radiobutton)

Se coloca los nombres en text=masculino y value=masculino

Page 4: clase 1 asp

UNAC Ing.Osmart Morales Chalco

Partial Class Empleado Inherits System.Web.UI.Page

Protected Sub Calcular(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click Dim Tot, Imp1, Imp2 As Single Select Case lstCargo.SelectedIndex Case 0 : Tot = 4000 Case 1 : Tot = 3000 Case 2 : Tot = 1200 Case 3 : Tot = 1000 End Select Select Case ddlEstado.SelectedIndex Case 0 : Tot+ = 0 Case 1 : Tot+ = 50 Case 2 : Tot+ = 30 Case 3 : Tot+ = 70 End Select If rbnSexo.Items(0).Selected Then Tot += 80 ElseIf rbnSexo.Items(1).Selected Then Tot += 70 End If If chkRenta.Items(0).Selected Then Imp1 = Tot * 0.1 Else Imp1 = 0 End If If chkRenta.Items(1).Selected Then Imp2 = Tot * 0.02 Else Imp2 = 0 End If txtTotal.Text = (Tot - (Imp1 + Imp2)).ToString("n2")

End SubEnd Class

Page 5: clase 1 asp

UNAC Ing.Osmart Morales Chalco

EJEMPLO3

Imports System.DataImports System.Data.SqlClientPartial Class _Default Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim Cnx As New SqlConnection("uid=sa;server=.;database=Northwind") Dim Dap As New SqlDataAdapter("Select ProductId,ProductName,UnitPrice,UnitsInStock From Products", Cnx) Dim Dst As New DataSet Dap.Fill(Dst, "Productos") grdproducto.DataSource = Dst.Tables("productos") grdProducto.DataBind() End Sub

En la propiedad AllowPaging =true para que salga por paginas y pagisize=9 (se muestra 9 registros por pagina)

Page 6: clase 1 asp

UNAC Ing.Osmart Morales Chalco

Protected Sub grdproducto_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles grdproducto.PageIndexChanging grdproducto.PageIndex = e.NewPageIndex grdproducto.DataBind() End Sub

Hacer dobleclic en GridView y luego buscar el evento PageIndexChanging para controlar el uso de las paginas

Esta opcion

Es para darle un

Formato al GridView

Alinear el texto a la izquierda en el

GridView –propiedades

Font-HorizontalAlign-

Page 7: clase 1 asp

UNAC Ing.Osmart Morales Chalco

Ejemplo 4: mostrar todos los productos por categoria

Imports System.Data

Imports System.Data.SqlClient

Partial Class _Default Inherits System.Web.UI.Page

Private Cnx As New SqlConnection("uid=sa;server=localhost;database=Northwind") Private Dap As New SqlDataAdapter("Select * From Categories", Cnx) Private dst As New DataSet Private vista As New DataView

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) H… Dap.Fill(dst, "Categorias") If Not Page.IsPostBack Then With ddlCategoria .DataSource = dst.Tables("Categorias") .DataTextField = "CategoryName" .DataValueField = "CategoryID" .DataBind() End With End If Dap.SelectCommand.CommandText = "Select ProductId,ProductName,CategoryId,UnitPrice,UnitsInStock From Products" Dap.Fill(dst, "Productos") vista = dst.Tables("Productos").DefaultView Vista.RowFilter = "CategoryID=" & ddlCategoria.SelectedItem.Value grdproducto.DataSource = Vista grdProducto.DataBind() 'en el combo ddlCategoria cambiar la propiedad autopostback=true para poder hacer el filtroEnd Sub

End Class

Page 8: clase 1 asp

UNAC Ing.Osmart Morales Chalco

EJEMPLO 4: Plantillas en Asp.Net

1.- crear un nuevo proyecto web

2.- Agregamos un nuevo elemento Llamado pagina principal o un Masterpage

3.- Me ubico dentro de la plantilla Masterpage

- DISENO - INSERTAR TABLA - PLANTILLA

El masterpage cuando se ejecuta ( F5 ) no carga por ser una plantilla, tengo que crear un formulario y a añadirlo al masterpage para verlo

Plantilla= Encabezado y pie de Pagina ……. Puedo escoger el formato deseado

Page 9: clase 1 asp

UNAC Ing.Osmart Morales Chalco

4.- Después De Crear Mi Plantilla Dentro De Mi Masterpage , elaboro mi diseño ( banner, menú, cuerpo), creo un Nuevo elemento llamado CONTROL DE USUARIO

Después Le Agrego Este Código, Que Se Encuentra En Archivo De Texto A Mi Archivo Headerweb.Ascx. Este archivo se encuentra solo con una línea de código

Si notan hay algunos errores porque falta la carpeta imágenes con sus fotos. Para solucionar hay que arrastras la carpeta images dentro del proyecto

Page 10: clase 1 asp

UNAC Ing.Osmart Morales Chalco

5.- El Siguiente Paso Lo Hago Con El Archivo Footerweb.Aspx - LO CREO FooterWeb - LE INSERTO EL CODIGO - LO ARRASTRO Y ME QUEDA ASI.........

Después de pasar la carpeta images, el elemento Headerweb.Ascx que se encuentra en el explorador de soluciones lo arrastro hacia el banner de la página (ver imagen) pero el banner queda en el centro le doy en la propiedad de la tabla valingn=top para ajustarlo en la parte

Page 11: clase 1 asp

UNAC Ing.Osmart Morales Chalco

6.- El Siguiente Paso Nos Faltaría Agregar El Menú Vertical Categoría Y Productos

ME VOY ME DIRIJO A MASTERPAGE Y LE AGREGO EL SIGUIENTE CODIGO

- LO CREO MenuHTM.ascx - LE INSERTO EL CODIGO - LO ARRASTRO Y ME QUEDA ASI.........

El elemento Footerweb.Aspx que se encuentra en el explorador de soluciones lo arrastro hacia el banner de la página (ver imagen)

Page 12: clase 1 asp

UNAC Ing.Osmart Morales Chalco

7.- Para mejorar el diseño de la página(es para que se vea mejor el texto, color de fondo), pasar el siguiente estilo qsstyle.css al explorador de soluciones y luego arrastrarlo hacia la plantilla.

valingn=top

Para ajustar el menú hacia la parte de arriba

Page 13: clase 1 asp

UNAC Ing.Osmart Morales Chalco

8.- SI LO EJECUTO NO VEO NADA, QUE FALTA CREAR UN FORMULARIO WEB, COLOCAR EL NOMBRE DEL FORM SELECCIONA LA OPCION SELECCCIONAR PAGINA PRINCIPAL y ESCOGE EL MASTERPAGE QUE QUIERAS

Page 14: clase 1 asp

UNAC Ing.Osmart Morales Chalco

10.- LO ULTIMO ES ME UBICO EN EL MATERWEB Y LO DIRECCION A MIS NUEVOS FORMULARIOS

Page 15: clase 1 asp

UNAC Ing.Osmart Morales Chalco

EJEMPLO 5: Plantillas en Asp.Net

1.- crear un nuevo proyecto web

2.- Agregamos un nuevo elemento Llamado pagina principal o un Masterpage

3.- creamos una tabla de filas=4 columnas =4

El masterpage cuando se ejecuta ( F5 ) no carga por ser una plantilla, tengo que crear un formulario y a añadirlo al masterpage para verlo

Page 16: clase 1 asp

UNAC Ing.Osmart Morales Chalco

4.- insertamos en el banner 4 imágenes

5.- insertar el menú.

En la propiedad=Imageurl inserta la imagen

Propiedades: Menu

Orientación=Horizontal, BackColor=Amarillo, ForeColor=Rojo

Page 17: clase 1 asp

UNAC Ing.Osmart Morales Chalco

Para editar el menu, nos ubicamos en el borde de menu y le damos editar elementos del menu y agregamos los elementos en las propiedades text=Quienes Somos

También para agregar elementos en el menú …… propiedades:

Page 18: clase 1 asp

UNAC Ing.Osmart Morales Chalco

6.- Insertar los siguientes objetos ( label y TreeView)

7. Lista la plantilla para enlazarla con los otros formularios web

Propiedades: TreeView

Nodes=(colección)…agregar elementos ImageSet=Contacts….agrega los símbolos como el Messenger, Height=152 px….

Page 19: clase 1 asp

UNAC Ing.Osmart Morales Chalco

EJEMPLO 6: CONTROLES DE VALIDACION

Este grupo de controles nos permite validar la entrada dada por el usuario a traves de los controles de un WebForm, esta validación se puede realizar en el cliente y en el servidor, ASP.NET, nos ofrece 6 controles de Validación1 - Requiredfieldvalidator : Este control valida que se ha rellenado un campo con un valor, es decir valida, los campos requeridos2 - CustomValidator : Se Utilizara para realizar Validaciones personalizadas, este control llamara a una función definida por el usuario que será la que realice la validación. propiedades:

Protected Sub cuvtxtnombre_ServerValidate(ByVal source As Object, ByVal args…uvtxtnombre.ServerValidate If args.Value.Length < 5 Then args.IsValid = False Else args.IsValid = True End IfEnd Sub

1.-ClientValidationFunction Indicaremos el nombre de la función del lado del cliente, en este caso la función será desarrollada en un lenguaje Script. 2.-OnServerValidate Debemos la función del servidor que se va a encargar de la validación correspondiente, esta función se ejecutara cuando se produzca el evento ServerValidate

RequiredfieldvalidatorID=rfvnombre : Controltovalidate=txtnombreErrormessage=El nombre es ObligatorioText=*

CustomValidatorID= CuvnombreControltovalidate=txtnombreErrormessage=El nombre es demasiado cortoText=*Nota: doble click para programarlo

Page 20: clase 1 asp

UNAC Ing.Osmart Morales Chalco

3 - RangeValidator : Este control se utilizara cuando deseamos comprobar si un valor de entrada de un control Web se encuentra comprendido en un rango determinado

4 - CompareValidator : Este control lo utilizaremos para comparar el valor que contiene un control WEB con un valor especifico, que puede ser un valor determinado como una constante o bien un valor de otro control web

RangeValidator ID=rvedad : Controltovalidate=txtedadErrormessage=Entre 18 y 100 Text=*Type=IntegerMaximunValue=100MinimunValue=18

CompareValidator ID= CvfechaControltovalidate=txtfechaErrormessage=Fecha incorrectaOperator=DataTypeCheckType=DateText=*Nota: doble click para

Propiedades:ValueToCompare - Se utiliza cuando deseamos comparar el valor del control WEb con un valor constante, esta propiedad tendra el valor constanteControlToCompare - cuando deseamos comparar el control WEB con otro control WEBType - Indica el tipo de dato de los valores que se van a comparar, esta propiedad puede ser Currency, Date, Double, Integer y String Operator:Equal(igual) GreaterThan(Mayor)GreaterThanEqual(mayor o Igual)LessThan(Menor) LessThanEqual(menor o igual) NotEqual(distinto)DataTypeCheck(Validacion Tipo)

Page 21: clase 1 asp

UNAC Ing.Osmart Morales Chalco

5 - RegularExpressionValidator : este control de validación es utilizado para comparar el valor del control correspondiente con una expresión regular. Este control debe hacer uso de la propiedad RegularExpressionValidator para indicar la expresión regular con la que se va a comparar el valor indicado en el control Web.

6 - ValidationSummary : Este control difiere del resto, ya que en realidad no va a realizar un tipo de validacion determinada, sino que contiene todos los mensajes de error que se han producido y muestra una lista de ellos en la pagina(los cuales hallan fallado)Propeidades : * HeaderText - Contendra el texto que va a mostrarse como cabecera a modo de descripcion de errores * ShowSummary - que puede tener los valores true o false,. Indicara si deseamos mostrar o no el resumen de validacion de la pagina * DisplayMode - La forma en la que se va a mostrar las distintas descripciones de cada uno de los errores de validacion encontrados en la pagina, pueden ser : BulletList(una lista con puntos), List(una LIsta) y SingleParagraph(un unico parrafo)

RegularExpressionValidator ID=revemail : Controltovalidate=txttemailErrormessage=incorrecto Text=*ValidationExpression=

RegularExpressionValidator ID=revtelefono : Controltovalidate=txttelefonoErrormessage=incorrecto Text=*ValidationExpression=

\d{2}-\d{3}-\d{4}

CompareValidator ID=cvpasswordControltovalidate=txtpasswordControltocompare=txtconfirmarOperator=equalType=StringErrormessage=el password no coincide Text=*Nota: en la caja de texto modificar la propiedadTextmode= Password

Page 22: clase 1 asp

UNAC Ing.Osmart Morales Chalco

EJEMPLO 6:

Imports System.DataImports System.Data.SqlClientPartial Class cliente Inherits System.Web.UI.Page Private Cnx As New SqlConnection("Data Source=.;Initial Catalog=dbsistemas;Integrated Security=True") Private Dap As New SqlDataAdapter("usp_cliente_Listar", Cnx) Private dst As New DataSet

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load mostrar() End Sub

create database dbsistemas

create table clientes

(codigo int primary key identity(1,1) not null,

nombre varchar(25),

apellidos varchar(25),

direccion varchar(60),

clave char(5))

Txtcodigo , Txtnombre, Txtapellido, Txtdireccion, txtclave btnLimpiar, btnAgregar, btneliminar, btnModificar

CREATE PROCEDURE usp_cliente_Listar ASSELECT codigo, nombre, apellidos, direccion, claveFROM clientes

Page 23: clase 1 asp

UNAC Ing.Osmart Morales Chalco

Protected Sub btnlimpiar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnlimpiar.Click limpiar() End Sub

Private Sub limpiar() txtcodigo.Text = "" : txtapellido.Text = "" txtnombre.Text = "" : txtclave.Text = "" txtdireccion.Text = "" End Sub

Private Sub mostrar() dst.Clear() Dap.Fill(dst, "cliente") grdcliente.DataSource = dst.Tables("cliente") grdcliente.DataBind() End Sub

Protected Sub btnagregar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnagregar.Click Dim cmd As New SqlCommand("usp_cliente_Adicionar", Cnx) With cmd .CommandType = CommandType.StoredProcedure .Parameters.Add("nombre", txtnombre.Text) .Parameters.Add("apellidos", txtapellido.Text) .Parameters.Add("direccion", txtdireccion.Text) .Parameters.Add("clave", txtclave.Text) End With Try Cnx.Open() cmd.ExecuteNonQuery() Catch ex As Exception lblerror.Text = "Error" & ex.Message Finally Cnx.Close() limpiar() : mostrar() End Try End Sub

CREATE PROCEDURE usp_cliente_Adicionar @nombre varchar(25),@apellidos VARCHAR(25),@direccion varchar(60),@clave CHAR(5)

ASINSERT INTO clientes(nombre,apellidos,direccion,clave)VALUES (@nombre,@apellidos,@direccion,@clave)

Page 24: clase 1 asp

UNAC Ing.Osmart Morales Chalco

Private Sub llenardesdedrid() With dst.Tables("cliente").Rows(grdcliente.SelectedIndex.ToString) txtcodigo.Text = .ItemArray(0) txtnombre.Text = .ItemArray(1) txtapellido.Text = .ItemArray(2) txtdireccion.Text = .ItemArray(3) txtclave.Text = .ItemArray(4)

End With End Sub

Protected Sub grdcliente_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles grdcliente.SelectedIndexChanged llenardesdedrid() End Sub

Page 25: clase 1 asp

UNAC Ing.Osmart Morales Chalco

Protected Sub Btneliminar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Btneliminar.Click Dim cmd As New SqlCommand("usp_cliente_eliminar", Cnx) With cmd .CommandType = CommandType.StoredProcedure .Parameters.Add("codigo", txtcodigo.Text) End With Try Cnx.Open() cmd.ExecuteNonQuery() Catch ex As Exception lblerror.Text = "Error" & ex.Message Finally Cnx.Close() limpiar() : mostrar() End Try End Sub Protected Sub btnmodificar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnmodificar.Click Dim cmd As New SqlCommand("usp_cliente_Actualizar", Cnx) With cmd .CommandType = CommandType.StoredProcedure .Parameters.Add("codigo", txtcodigo.Text) .Parameters.Add("nombre", txtnombre.Text) .Parameters.Add("apellidos", txtapellido.Text) .Parameters.Add("direccion", txtdireccion.Text) End With Try Cnx.Open() cmd.ExecuteNonQuery() Catch ex As Exception lblerror.Text = "Error" & ex.Message Finally Cnx.Close() limpiar() : mostrar() End Try End SubEnd Class

CREATE PROCEDURE usp_cliente_eliminar@codigo intASDELETE FROM clientes where codigo=@codigo

CREATE PROCEDURE usp_cliente_actualizar @codigo int, @nombre varchar(25),@apellidos VARCHAR(25),@direccion varchar(60)ASUPDATE clientes SET nombre=@nombre,apellidos=@apellidos, direccion=@direccionwhere codigo=@codigo

Page 26: clase 1 asp

UNAC Ing.Osmart Morales Chalco

EJEMPLO 7: Control: DetailsView

Fieldheaderstyle(Alinear a la izquierda horizontal=left

Page 27: clase 1 asp

UNAC Ing.Osmart Morales Chalco

EJEMPLO 8: Se muestra primero el listado del personal, cada vez que selecciono un empleado por código, pasa al siguiente formulario de mantenimiento Proyecto General Osmart.Net

Nota: Normalmente siempre hacemos la conexión de esta manera

Dim cn As New SqlConnection("database=northwind;Server=.;User ID=sa"), pero esta manera va ser diferente

Lo vamos ha realisar en el web.config……..veamoslo.

Forma Normal: <configuration>

<appSettings/><connectionStrings/><system.web>

Ejemplo 6

<configuration><appSettings>

<add key="Conexion" value="uid=sa;server=.;database=northwind"/></appSettings><connectionStrings/><system.web>

Web_Form ListaEmpleados.aspx

Partial Class ListaEmpleados Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load Dim objX As New ClsEmpleado grdEmpleado.DataSource = objX.EmpleadoListar grdEmpleado.DataBind() End SubEnd Class

Donde primero se tiene que programar en el Proyecto General en el web.config, para que en la clase no se ponga la ruta de la base de

Es el primer formulario donde se muestra el

Page 28: clase 1 asp

UNAC Ing.Osmart Morales Chalco

Propiedad Columns=(colección) para darle los nombres de los títulos ó campos del GridView1 como Código, Apellido, Nombre y Cargo, además hay que configurar los campos para que cuando haga un click en campo del código se habrá una nuevo formulario donde se va poder agregar a los nuevos empleados

Page 29: clase 1 asp

UNAC Ing.Osmart Morales Chalco

HyperLink: Apariencia: HearderText=Codigo Datos DataNav…... =Employeeid DataNav…… =DatosEmpleado.aspx?cod={0} DataTextFields=Employeeid..

BoundField: Apariencia: HearderText=Apellido Datos DataTextFields=LastName

El primer campo es de tipo HyperLink: porque va acceder al nuevo formulario de

Quitar el CHECK

Page 30: clase 1 asp

UNAC Ing.Osmart Morales Chalco

Web_Clase clsempleado.vb

Imports system.DataImports System.Data.SqlClient

Public Class ClsEmpleado

Public Function EmpleadoListar() As DataTable

Dim Cnx As New SqlConnection(ConfigurationManager.AppSettings.Get("conexion")) Dim Dap As New SqlDataAdapter("usp_Empleado_Listar", Cnx) Dim dst As New DataSet Dap.Fill(dst, "Empleados") Return dst.Tables("Empleados")

End Function

Public Function EmpleadoDatos(ByVal vEmployeeid As Integer) As SqlDataReader

Dim Cnx As New SqlConnection(ConfigurationManager.AppSettings.Get("Conexion")) Dim cmd As New SqlCommand("usp_Empleado_Datos", Cnx) With cmd

.CommandType = CommandType.StoredProcedure .Parameters.Add("@Employeeid", SqlDbType.Int).Value = vEmployeeid

End With Cnx.Open() Dim dr As SqlDataReader = cmd.ExecuteReader(CommandBehavior.SingleRow) Return dr

End Function

CREATE PROCEDURE usp_Empleado_Listar ASSELECT EmployeeID, LastName, FirstName, TitleFROM Employees

Create PROCEDURE usp_Empleado_Datos @Employeeid intASSELECT EmployeeID, LastName, FirstName, TitleFROM Employees WHERE EmployeeID=@Employeeid

Page 31: clase 1 asp

UNAC Ing.Osmart Morales Chalco

Public Sub EmpleadoAdicionar(ByVal vLastname As String, ByVal vFirstname As String, ByVal vTitle As String) Dim Cnx As New SqlConnection(ConfigurationManager.AppSettings.Get("Conexion")) Dim cmd As New SqlCommand("usp_Empleado_Adicionar", Cnx) With cmd .CommandType = CommandType.StoredProcedure .Parameters.Add("@Lastname", SqlDbType.VarChar, 20).Value = vLastname .Parameters.Add("@Firstname", SqlDbType.VarChar, 10).Value = vFirstname .Parameters.Add("@Title", SqlDbType.VarChar, 50).Value = vTitle End With Try Cnx.Open() cmd.ExecuteNonQuery() Cnx.Close() Catch ex As Exception Throw ex End Try End Sub

Public Sub EmpleadoActualizar(ByVal vEmployeeid As Integer, ByVal vLastname As String, ByVal vFirstname As String, ByVal vTitle As String) Dim Cnx As New SqlConnection(ConfigurationManager.AppSettings.Get("Conexion")) Dim cmd As New SqlCommand("usp_Empleado_Actualizar", Cnx) With cmd .CommandType = CommandType.StoredProcedure .Parameters.Add("@Employeeid", SqlDbType.Int).Value = vEmployeeid .Parameters.Add("@Lastname", SqlDbType.VarChar, 20).Value = vLastname .Parameters.Add("@Firstname", SqlDbType.VarChar, 10).Value = vFirstname .Parameters.Add("@Title", SqlDbType.VarChar, 50).Value = vTitle End With Try Cnx.Open() cmd.ExecuteNonQuery() Cnx.Close() Catch ex As Exception Throw ex End Try End Sub

CREATE PROCEDURE usp_Empleado_Adicionar @Lastname varchar(20),@Firstname VARCHAR(10),@Title varchar(50)ASInsert into Employees(Lastname,Firstname,Title)values(@Lastname,@Firstname,@Title)

Create PROCEDURE usp_Empleado_Actualizar @Employeeid int,@Lastname varchar(20),@Firstname VARCHAR(10),@Title varchar(50)ASUpdate Employees set Lastname=@Lastname,Firstname=@Firstname, Title=@TitleWhere Employeeid=@Employeeid

Page 32: clase 1 asp

UNAC Ing.Osmart Morales Chalco

Public Sub EmpleadoEliminar(ByVal vEmployeeid As Integer) Dim Cnx As New SqlConnection(ConfigurationManager.AppSettings.Get("Conexion")) Dim cmd As New SqlCommand("usp_Empleado_Eliminar", Cnx) With cmd .CommandType = CommandType.StoredProcedure .Parameters.Add("@Employeeid", SqlDbType.Int).Value = vEmployeeid End With Try Cnx.Open() cmd.ExecuteNonQuery() Cnx.Close() Catch ex As Exception Throw ex End Try End SubEnd Class

CREATE PROCEDURE usp_Empleado_Eliminar @Employeeid intASDelete from Employees Where Employeeid=@Employeeid

Nos falta programar dentro de nuestro formulario… DatosEmpleado.aspx

Txtcodigo , Txtapellido, Txtnombre, Txtcargo

btnAdicionar, btnactualizar, btneliminar, btnnuevo

Page 33: clase 1 asp

UNAC Ing.Osmart Morales Chalco

Web_Form DatosEmpleado.aspx(Formulario 2)

Imports System.Data.SqlClient

Partial Class DatosEmpleado

Inherits System.Web.UI.Page

Private objX As New ClsEmpleado

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

If Not Page.IsPostBack Then Dim Codigo As String = Request.QueryString("cod") Dim dr As SqlDataReader = objX.EmpleadoDatos(Integer.Parse(Codigo)) dr.Read() txtcodigo.Text = dr(0) txtapellido.Text = dr(1) txtnombre.Text = dr(2) txtcargo.Text = dr(3) dr.Close() End If

End Sub

Protected Sub btnAdicionar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdicionar.Click Try objX.EmpleadoAdicionar(txtapellido.Text, txtnombre.Text, txtcargo.Text) Server.Transfer("ListaEmpleados.aspx") Catch ex As Exception lblerror.Text = ex.Message End Try End Sub

Llamar a la clase ClsEmpleado

Page 34: clase 1 asp

UNAC Ing.Osmart Morales Chalco

Protected Sub btnactualizar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnactualizar.Click Try objX.EmpleadoActualizar(Integer.Parse(txtcodigo.Text), txtapellido.Text, txtnombre.Text, txtcargo.Text) Server.Transfer("ListaEmpleados.aspx") Catch ex As Exception lblerror.Text = ex.Message End Try End Sub

Protected Sub btneliminar_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btneliminar.Click Try objX.EmpleadoEliminar(Integer.Parse(txtcodigo.Text)) Server.Transfer("ListaEmpleados.aspx") Catch ex As Exception lblerror.Text = ex.Message End Try End Sub

Protected Sub btnnuevo_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnnuevo.Click txtcodigo.Text = "" txtapellido.Text = "" txtnombre.Text = "" txtcargo.Text = "" End SubEnd Class

Page 35: clase 1 asp

Imports System.DataImports System.Data.SqlClientPublic Class validaruser Public Shared Function validarusuario(ByVal xuser As String, ByVal xpass As String) As Boolean Dim Cnx As New SqlConnection("Data Source=.;Initial Catalog=neptuno;Integrated Security=True") Dim Dap As New SqlDataAdapter("select * from Empleados where nombre='" & xuser & "' and extensión='" & xpass & "'", Cnx) Dim dst As New DataSet Dap.Fill(dst, "usuario") If dst.Tables("usuario").Rows.Count > 0 Then Return True Else Return False End If End FunctionEnd Class

Partial Class iniciouser Inherits System.Web.UI.Page Protected Sub Login1_Authenticate(ByVal sender As Object, ByVal e As …ntArgs) Handles Login1.Authenticate If validaruser.validarusuario(Login1.UserName, Login1.Password) Then Server.Transfer("cliente.aspx") Else Login1.FailureText = "Acceso Denegado" End If End SubEnd Class

UNAC Ing.Osmart Morales Chalco

EJEMPLOS 9: CONTROL : LOGIN

Insertamos una tabla de uno x uno para luego insertar el control login

Page 36: clase 1 asp

UNAC Ing.Osmart Morales Chalco

SERVICIOS WEB

Marcar Servicio Web

Direccionar una ruta

Eliminamos el archivo Service.vb y service.asmx para crearlos otra vez con el nombre northwind.asmx

Después de crear nuestro servicio web comenzamos a programar

Page 37: clase 1 asp

UNAC Ing.Osmart Morales Chalco

Servicio Web Northwind

Imports System.WebImports System.Web.ServicesImports System.Web.Services.ProtocolsImports System.DataImports System.Data.SqlClient

<WebService(Namespace:="http://tempuri.org/", Description:="Administracion de datos de la BD Northwind")> _<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _Public Class Northwind Inherits System.Web.Services.WebService

<WebMethod(Description:="Lista de Empleados")> _ Public Function ListaEmpleados() As DataSet Dim cnx As New SqlConnection("Data Source=.;Initial Catalog=Northwind;Integrated Security=True") Dim dap As New SqlDataAdapter("SELECT EmployeeID, LastName, FirstName, Title FROM dbo.Employees", cnx) Dim dst As New DataSet dap.Fill(dst, "Empleados") Return dst ' los sw no devuelve tabla sino dataset End Function

End Class

Servicio Web Poblacion

http://www.abundanttech.com/WebServices/Population/population.asmx

Este serbio Web seda directamente desde internet

Page 38: clase 1 asp

UNAC Ing.Osmart Morales Chalco

Partial Class _Default Inherits System.Web.UI.Page

Private obj As New poblacion.PopulationWS

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load If Not Page.IsPostBack Then Dim objsw As New proxy.Northwind Me.GridView1.DataSource = objsw.ListaEmpleados.Tables("empleados") GridView1.DataBind() Dim pais() As String = obj.getCountries For Each x As String In pais DropDownList1.Items.Add(x) Next End If

TextBox1.Text = obj.getPopulation(DropDownList1.Text).Pop End Sub : End Class

GridView1

DropDownList1

TextBox1

Click derecho Agregar Referencia Web

Nombre de referencia Web se va a llamar Proxy que se encuentra en forma local y cuando se encuentra en un dominio en internet se va a llamar

Codigo dentro del formulario Web

Ruta del Servicio Web : http://localhost:49205/ServicioWEbUrl/Northwind.asmx http://www.abundanttech.com/WebServices/Population/population.asmx