Vous êtes sur la page 1sur 20

UNIVERSIDAD ALAS PERUANAS

ESCUELA ACADEMICO PROFESIONAL DE


INGENIERIA DE SISTEMAS

Ing. DIAZ LEYVA, Teodoro


Desarrollo Rpido de Aplicaciones para Internet

Sesiones
El diseo del formulario se realiza en archivo frm_pedido utilizando un objeto MultiView y dos vistas (View)
la primara para visualizar el pedido a realizar y la segunda vista para seleccionar los productos a pedir.
Se sugiere mejorar el proyecto utilizado AJAX para evitar la recarga de la pagina.

En el View1 agregar:

3 objetos TextBox para el nmero de pedido , fecha de pedido y total del pedido

2 DropDonwListBox para listar los clientes y empleados (tablas customers y employees


respectivamente de la base de datos Northwind).

Un GriddView para mostrar los productos pedidos.

2 Button para nuevo y grabar pedido.

En el View2 agregar:

Un TextBox y Button para buscar un producto

Un GridView para mostrar todos los productos de la base de datos Nothwind.

Pgina 1 de 20

El funcionamiento de la pgina es el siguiente:

Se ingresa una fecha del de pedido.

Se selecciona un cliente y vendedor

Presionar sobre el botn Agregar Producto que le permitir seleccionar los productos de la base de
datos Northwind.

Tener en cuenta que el cuadro de texto Id Pedido y fecha estn desactivados.

Pgina 2 de 20

Despus de realizar el diseo de la pgina procedemos a codificar:

1. Crear los siguientes procedimientos almacenados para insertar un pedido( tabla Orders) y detalles del
pedido(tabla OrderDetails) en la base de datos Northwind

create PROCEDURE spu_PedidosInsert


(
@CustomerID varchar(5),
@EmployeeID int,
@OrderDate datetime,
@total decimal(9,2),
@numero int output --parametro de salida
)
AS
set @numero=(select top 1 OrderID+1 from Orders order by OrderID desc)
INSERT INTO Orders
(
CustomerID,
EmployeeID,
OrderDate,
total
)
VALUES
( @CustomerID,
@EmployeeID ,
@OrderDate ,
@total
)

Pgina 3 de 20

CREATE PROCEDURE sp_detallePedidosInsert


(
@OrderID int ,
@ProductID int,
@UnitPrice decimal,
@Quantity INT,
@subtotal decimal(9,2)
)
as
INSERT INTO dbo.OrderDetails(
OrderID ,
ProductID ,
UnitPrice ,
Quantity ,
subtotal
) VALUES(
@OrderID ,
@ProductID ,
@UnitPrice ,
@Quantity ,
@subtotal
)

Pgina 4 de 20

2. Clear una solucin Proyecto y en ella una librera App.Datos para acceder a los datos y una
App.Entidades para encapsular datos de las tablas respetivas de la base de datos Northwind y Sitio
Web AppWeb:

Pgina 5 de 20

3. En la clase Producto de la librera App.Entidades crear las siguientes propiedades y mtodos, estos
datos representa a la estructura de la tabla de la base de datos Northwind.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace App.Entidades
{
public class Producto
{
private int idproducto;
public int Idproducto
{
get { return idproducto; }
set { idproducto = value; }
}
private string nombre;
public string Nombre
{
get { return nombre; }
set { nombre = value; }
}
private int idcategoria;
public int Idcategoria
{
get { return idcategoria; }
set { idcategoria = value; }
}
private string cantidadporunidad;
public string Cantidadporunidad
{
get { return cantidadporunidad; }
set { cantidadporunidad = value; }
}
private decimal preciounitario;
public decimal Preciounitario
{
get { return preciounitario; }
set { preciounitario = value; }
}
private int stock;
public int Stock
{
get { return stock; }
set { stock = value; }
}
private bool disc;
public bool Disc
{
get { return disc; }
set { disc = value; }
}
}
}
Pgina 6 de 20

4. En la libreia App.Datos crea las siguientes clases:


Clase Conexin
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;
System.Data;
System.Data.SqlClient;
System.Configuration;

namespace App.Datos
{
public class Conexion
{
private static SqlConnection cn = new
SqlConnection(ConfigurationManager.ConnectionStrings["sqlconexion"].ConnectionStr
ing);
public static SqlConnection Abrir()
{
try
{
cn.Open();
return cn;
}
catch (Exception)
{
throw new Exception("Error en la conexin");
}
}
public static void Cerrar()
{
cn.Close();
}
}
}

Pgina 7 de 20

Clase ProductoDAO :
using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Text;
App.Entidades;
System.Data.SqlClient;
System.Data;

namespace App.Datos
{
public class ProductoDAO
{
public static void agregar(Producto prod) {
try
{
//objeto command para ejecutar procedimiento almacenado
SqlCommand cmd = new SqlCommand("sp_insertProducto",
Conexion.Abrir());
//asignar valor a los parametros del procedimiento almacenado
cmd.Parameters.AddWithValue("@ProductName", prod.Nombre);
cmd.Parameters.AddWithValue("@CategoryID", prod.Idcategoria);
cmd.Parameters.AddWithValue("@QuantityPerUnit",
prod.Cantidadporunidad);
cmd.Parameters.AddWithValue("@UnitPrice", prod.Preciounitario);
cmd.Parameters.AddWithValue("@UnitsInStock", prod.Stock);
cmd.Parameters.AddWithValue("@Discontinued", prod.Disc);
//tipo de comando
cmd.CommandType = CommandType.StoredProcedure;
//ejecutar objeto command
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw new Exception("error al grabar producto");
}
finally {
Conexion.Cerrar();
}
}
// creando mtodo para que aparesca el ltimo dato en la lista de guardar
public static DataTable selectTop()
{ //datatable para retornar los datos de la tabla alumno
try
{
string Sql=("select TOP 1 ProductID,
ProductName,CategoryID,QuantityPerUnit,UnitPrice,UnitsInStock,Discontinued from
Products order by ProductID desc");
SqlDataAdapter ad = new SqlDataAdapter(Sql, Conexion.Abrir());
//objeto tabla para cargar los datos
DataTable dt = new DataTable();
//llenar los datos en dt
ad.Fill(dt);
return dt;
}
catch (Exception ex)
{

Pgina 8 de 20

throw ex;
}
finally
{
Conexion.Cerrar();
}
}
//-----------------------------------------public static List<Producto> list() {
try
{
//arreglo cuyos elementos son objetos tipo producto
List<Producto> lista = new List<Producto>();
//variable tipo producto
Producto pro;
//instruccion sql para seleccionar todos los productos
string sql = "Select
ProductID,ProductName,CategoryID,QuantityPerUnit,UnitPrice,UnitsInStock,Discontin
ued from products";
SqlDataAdapter adp = new SqlDataAdapter(sql, Conexion.Abrir());
DataTable dt = new DataTable();
adp.Fill(dt);
foreach (DataRow fila in dt.Rows)
{
//crear objeto tipo producto
pro = new Producto();
//encapsulamineto de datos en el objeto pro
pro.Idproducto = int.Parse(fila["ProductID"].ToString());
pro.Nombre = fila["ProductName"].ToString();
pro.Idcategoria = int.Parse(fila["CategoryID"].ToString());
pro.Cantidadporunidad = fila["QuantityPerUnit"].ToString();
pro.Preciounitario =
decimal.Parse(fila["UnitPrice"].ToString());
pro.Stock = int.Parse(fila["UnitsInStock"].ToString());
pro.Disc = bool.Parse(fila["Discontinued"].ToString());
//agreagr objeto pro a la lista
lista.Add(pro);
}
//retornar la lista de objetos tipo producto
return lista;
}
catch (Exception ex)
{
throw new Exception("Error en la lista:" + ex);
}
finally { Conexion.Cerrar(); }
}
//------------------------------------public static Producto getProducto(int codigo) {
try
{
Producto pro = null;
string sql = "Select ProductID,ProductName,CategoryID," +
"QuantityPerUnit,UnitPrice,UnitsInStock,Discontinued from
products where ProductID='"+codigo+"'";
SqlDataAdapter adp = new SqlDataAdapter(sql, Conexion.Abrir());
DataTable dt = new DataTable();
adp.Fill(dt);
DataRow fila = dt.Rows[0];
Pgina 9 de 20

//crear objeto tipo producto


pro = new Producto();
//encapsulamineto de datos en el objeto pro
pro.Idproducto = int.Parse(fila["ProductID"].ToString());
pro.Nombre = fila["ProductName"].ToString();
pro.Idcategoria = int.Parse(fila["CategoryID"].ToString());
pro.Cantidadporunidad = fila["QuantityPerUnit"].ToString();
pro.Preciounitario =
decimal.Parse(fila["UnitPrice"].ToString());
pro.Stock = int.Parse(fila["UnitsInStock"].ToString());
pro.Disc = bool.Parse(fila["Discontinued"].ToString());
return pro;
}
catch (Exception)
{
throw;
}
finally { Conexion.Cerrar(); }
}
//-----------------------------------------------------public static void update(Producto prod)
{
try
{ //objeto command para ejecutar procedimiento almacenado
SqlCommand cmd = new SqlCommand("sp_updateProducto",
Conexion.Abrir());
//asignar valor a los parametros del procedimiento almacenado
cmd.Parameters.AddWithValue("@ProductID", prod.Idproducto);
cmd.Parameters.AddWithValue("@ProductName", prod.Nombre);
cmd.Parameters.AddWithValue("@CategoryID", prod.Idcategoria);
cmd.Parameters.AddWithValue("@QuantityPerUnit",
prod.Cantidadporunidad);
cmd.Parameters.AddWithValue("@UnitPrice", prod.Preciounitario);
cmd.Parameters.AddWithValue("@UnitsInStock", prod.Stock);
cmd.Parameters.AddWithValue("@Discontinued", prod.Disc);
//tipo de comando
cmd.CommandType = CommandType.StoredProcedure;
//ejecutar objeto command
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw new Exception("error al modificar producto");
}
finally
{
Conexion.Cerrar();
}
}

Pgina 10 de 20

public static void delete(int codigo) {


try
{
SqlCommand cmd = new SqlCommand("delete from products where
productID='" + codigo + "'", Conexion.Abrir());
//tipo de comando texto, dado que no existe procedimiento
//almacenado
cmd.CommandType = CommandType.Text;
//ejecutar objeto cmd
cmd.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally { Conexion.Cerrar(); }
}
}
}

Clase CategoriaDAO :

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace App.Datos
{
public class CategoriaDAO
{
public static DataTable listar() {
try
{
string sql = "select * from categories";
SqlDataAdapter ad = new SqlDataAdapter(sql, Conexion.Abrir());
DataTable dt = new DataTable();
ad.Fill(dt);
return dt;
}
catch (Exception ex)
{
throw new Exception("Error en lista:" + ex);
}
finally { Conexion.Cerrar(); }
}
}

Pgina 11 de 20

Clase ClienteDAO
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace App.Datos
{
public class ClienteDAO
{
public static DataTable listar() {
try
{
string sql = "select *from Customers";
SqlDataAdapter ad = new SqlDataAdapter(sql, Conexion.Abrir());
DataTable dt = new DataTable();
ad.Fill(dt);
return dt;
}
catch (Exception)
{
throw;
}
finally { Conexion.Cerrar(); }
}
}
}

Pgina 12 de 20

Clase PedidoDAO
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;
using System.Data;
using System.Transactions;
namespace App.Datos
{
public class PedidoDAO
{
public static int InsertarPedido(string idcliente, int idempleado,
DateTime FechaPedido,decimal total)
{
try
{
SqlCommand cmd = new SqlCommand("spu_pedidosInsert",
Conexion.Abrir());
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("@CustomerID", idcliente);
cmd.Parameters.AddWithValue("@EmployeeID", idempleado);
cmd.Parameters.AddWithValue("@OrderDate", FechaPedido);
cmd.Parameters.AddWithValue("@total", total);
//parametro de salida
cmd.Parameters.Add(new SqlParameter("@numero", DbType.String));
cmd.Parameters["@numero"].Direction =
ParameterDirection.InputOutput;
//ejecutar objeto cmd
cmd.ExecuteNonQuery();
return Convert.ToUInt16(cmd.Parameters["@numero"].Value);
}
catch (Exception ex)
{
throw ex;
}
finally {
Conexion.Cerrar();
}
}
//------------------------------------------------------------------public static void insertarDetallePedido(int idpedido, int idproducto,
decimal precio, int cantidad, decimal subtotal)
{
try
{
SqlCommand cmd = new SqlCommand("sp_detallePedidosInsert",
Conexion.Abrir());
//tipo de comanddo
cmd.CommandType = CommandType.StoredProcedure;
//asignar valor a los parametros del procedmiento almacenado
cmd.Parameters.AddWithValue("@OrderID", idpedido);
cmd.Parameters.AddWithValue("@ProductID", idproducto);
cmd.Parameters.AddWithValue("@UnitPrice", precio);
cmd.Parameters.AddWithValue("@Quantity", cantidad);
Pgina 13 de 20

cmd.Parameters.AddWithValue("@subtotal", subtotal);
//ejecurar objeto cmd
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally { Conexion.Cerrar(); }
}
//-----------------------------------------------------------------------public static string grabarPedido( string idcliente,int
idempleado,DateTime fecha,decimal total, DataTable detalle)
{
int numeropedido; ;
//transacion para que insertar pedido y detalle de pedido sea como una sola
operacion
using (TransactionScope ts = new TransactionScope())
{
//insertar datos a la tabla pedido de l base de datos
numeropedido = PedidoDAO.InsertarPedido(idcliente, idempleado, fecha,
total);
//insertar datos a la tabla detallePedido de la base de datos
foreach(DataRow fila in detalle.Rows ){
PedidoDAO.insertarDetallePedido(numeropedido,
Convert.ToUInt16(fila["IdProducto"]), Convert.ToDecimal(fila["Precio"]),
Convert.ToInt16(fila["Cantidad"]), Convert.ToDecimal(fila["SubTotal"]));
}
ts.Complete();
}
return numeropedido.ToString();
}
}
}

Pgina 14 de 20

5. En el sitio web AppWeb, cree una clase util( podra tener cualquier nombre) que ser utilizada en
cualquier parte del proyecto:

En esta clase Util, cree los siguientes mtodos:


using
using
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Data;
System.Web.UI.WebControls;

/// <summary>
/// Descripcin breve de Util
/// </summary>
public class Util
{
public Util()
{
//
// TODO: Agregar aqu la lgica del constructor
//
}
public static DataTable crearCarrito() {
//objeto carro tipo datatable
DataTable carro = new DataTable();
//columnas del objeto carro
carro.Columns.Add("IdProducto", System.Type.GetType("System.Int16"));
carro.Columns.Add("Producto", System.Type.GetType("System.String"));
carro.Columns.Add("Cantidad", System.Type.GetType("System.Int16"));
carro.Columns.Add("Precio", System.Type.GetType("System.Decimal"));
carro.Columns.Add("SubTotal", System.Type.GetType("System.Decimal"),
"Cantidad*Precio");
return carro;
}
Pgina 15 de 20

public static void agregarProducto(int codigo,string producto, int


cantidad,decimal precio, DataTable carro) {
//objeto fila que tiene las mismas columnas del objeto carro
DataRow fila = carro.NewRow();
//asignar valores a las coulnas de la fila
fila["IdProducto"] = codigo;
fila["Producto"] = producto;
fila["Cantidad"] = cantidad;
fila["Precio"] = precio;
//agregar fila al objeto carro
carro.Rows.Add(fila);
}
//-----------------------------------public struct totalPedido{
public decimal monto;
}
//-----------------------------------public static totalPedido totalColumna(int columna, GridView grv)
{
decimal total = 0;
//recorrer filas del gridview
foreach( GridViewRow fila in grv.Rows){
total = total + Decimal.Parse(fila.Cells[columna].Text);
}
//crear objeto de la estructura
totalPedido resultado = new totalPedido();
//asignar total de la columna del gridview a la variable monto
//de la estructura
resultado.monto = total;
return resultado;
}
}

Pgina 16 de 20

6.

Codificar en el formulario frm_pedido:

using
using
using
using
using
using
using

System;
System.Collections.Generic;
System.Linq;
System.Web;
System.Web.UI;
System.Web.UI.WebControls;
System.Data;

public partial class Mantenimiento_frm_pedido : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
MultiView1.ActiveViewIndex = 0;
//invocar al metodo
todosProductos();
//--------------if (Page.IsPostBack == false)
{
agregarClientes();
agregarEmpleados();
}
//fecha actual
txtfechapedido.Text = DateTime.Now.ToString("dd/MM/yyyy");
}

Pgina 17 de 20

protected void btnagregarproducto_Click(object sender, EventArgs e)


{
MultiView1.ActiveViewIndex = 1;
}

public void todosProductos()


{
GridView2.DataSource = App.Datos.ProductoDAO.list();
GridView2.DataBind();
}
public void agregarClientes()
{
cbocliente.DataSource = App.Datos.ClienteDAO.listar();
cbocliente.DataTextField = "CompanyName";
cbocliente.DataValueField = "CustomerID";
cbocliente.DataBind();
}
public void agregarEmpleados()
{
cbovendedor.DataSource = App.Datos.EmpleadoDAO.listar();
cbovendedor.DataTextField = "LastName";
cbovendedor.DataValueField = "EmployeeID";
cbovendedor.DataBind();
}
protected void GridView2_SelectedIndexChanged(object sender, EventArgs e)
{
//si la variable de sesion carrito no tiene contenido,se creala varible
//carrito
if (Session["carrito"] == null)
{
Session["carrito"] = Util.crearCarrito();
}
//invocar al metodo agrgarProducto
Util.agregarProducto(Convert.ToInt16(GridView2.SelectedRow.Cells[1].Text),
GridView2.SelectedRow.Cells[2].Text, 1,
Convert.ToDecimal(GridView2.SelectedRow.Cells[5].Text),
(DataTable)Session["carrito"]);
//asignar contedido de carrito al gridview1
GridView1.DataSource = Session["carrito"];
GridView1.DataBind();
//invocar al metodo totalpedido
totalPedido();
}

protected void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs


e)
{
//indice del elemento seleccionado
int i = e.RowIndex;
//objeto tipo tabla
DataTable car = new DataTable();
//asignar contenido de carrito a car
Pgina 18 de 20

car = (DataTable)Session["carrito"];
//eliminar producto del indice seleccionado
car.Rows[i].Delete();
//actualizar gridview
GridView1.DataSource = car;
GridView1.DataBind();
//invocar al metodo totalPedido
totalPedido();
}
//--------------------------------------------------public void totalPedido() {
Util.totalPedido total=Util.totalColumna(5,GridView1);
txttotal.Text = Convert.ToString(total.monto);
}
protected void btnnuevo_Click(object sender, EventArgs e)
{
Session.Clear();
GridView1.DataSource = Session["carrito"];
GridView1.DataBind();
txttotal.Text = "";
}
protected void btngrabar_Click(object sender, EventArgs e)
{
txtnumeropedido.Text =
App.Datos.PedidoDAO.grabarPedido(Convert.ToString(cbocliente.SelectedValue),
Convert.ToUInt16(cbovendedor.SelectedValue),
Convert.ToDateTime(txtfechapedido.Text), Convert.ToDecimal(txttotal.Text),
(DataTable)Session["carrito"]);
if (txtnumeropedido.Text != "")
{
Response.Write("<script type='text/javascript'>");
Response.Write("alert('Pedido fue grabado con xito...!')");
Response.Write("</script>");
}
}
}

Pgina 19 de 20

//******************************EJECUCIN DEL PROYECTO******************************

Agregando productos y luego grabar:

Pgina 20 de 20

Vous aimerez peut-être aussi