Professional Documents
Culture Documents
/****** Object: Table [dbo].[productos] Script Date: 09/08/2011 17:27:43 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[productos]( [id_producto] [nvarchar](50) NOT NULL, [producto] [nvarchar](250) NULL, [id_unidad_medida] [smallint] NULL, [p_compra] [float] NULL, [p_venta] [float] NULL, [existencia] [float] NULL, CONSTRAINT [PK_productos] PRIMARY KEY CLUSTERED ( [id_producto] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO /****** Object: Table [dbo].[venta] Script Date: 09/08/2011 17:27:43 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[venta]( [id_venta] [int] IDENTITY(1,1) NOT NULL, [fecha_registro] [datetime] NOT NULL, [user_login] [nvarchar](50) NOT NULL, CONSTRAINT [PK_venta] PRIMARY KEY CLUSTERED ( [id_venta] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO /****** Object: Table [dbo].[venta_detalle_tmp] Script Date: 09/08/2011 17:27:43 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[venta_detalle_tmp]( [id_venta_detalle_tmp] [int] IDENTITY(1,1) NOT NULL, [id_producto] [nvarchar](50) NOT NULL, [cantidad] [float] NOT NULL, [user_login] [nvarchar](50) NOT NULL, [p_venta] [float] NOT NULL, CONSTRAINT [PK_venta_detalle_tmp] PRIMARY KEY CLUSTERED ( [id_venta_detalle_tmp] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO /****** Object: Table [dbo].[venta_detalle] Script Date: 09/08/2011 17:27:43 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[venta_detalle]( [id_venta_detalle] [int] IDENTITY(1,1) NOT NULL, [id_venta] [int] NOT NULL, [id_producto] [nvarchar](50) NOT NULL, [cantidad] [float] NOT NULL, [p_venta] [float] NOT NULL,
CONSTRAINT [PK_venta_detalle] PRIMARY KEY CLUSTERED ( [id_venta_detalle] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] GO /****** Object: Default [DF_users_fecha_registro] Script Date: 09/08/2011 17:27:43 ******/ ALTER TABLE [dbo].[users] ADD CONSTRAINT [DF_users_fecha_registro] DEFAULT (getdate()) FOR [fecha_registro] GO /****** Object: Default [DF_venta_fecha_registro] Script Date: 09/08/2011 17:27:43 ******/ ALTER TABLE [dbo].[venta] ADD CONSTRAINT [DF_venta_fecha_registro] DEFAULT (getdate()) FOR [fecha_registro] GO /****** Object: ForeignKey [FK_productos_unidad_medida] Script Date: 09/08/2011 17:27:43 ******/ ALTER TABLE [dbo].[productos] WITH CHECK ADD CONSTRAINT [FK_productos_unidad_medida] FOREIGN KEY([id_unidad_medida]) REFERENCES [dbo].[unidad_medida] ([id_unidad_medida]) GO ALTER TABLE [dbo].[productos] CHECK CONSTRAINT [FK_productos_unidad_medida] GO /****** Object: ForeignKey [FK_venta_users] Script Date: 09/08/2011 17:27:43 ******/ ALTER TABLE [dbo].[venta] WITH CHECK ADD CONSTRAINT [FK_venta_users] FOREIGN KEY([user_login]) REFERENCES [dbo].[users] ([user_login]) GO ALTER TABLE [dbo].[venta] CHECK CONSTRAINT [FK_venta_users] GO /****** Object: ForeignKey [FK_venta_detalle_productos] Script Date: 09/08/2011 17:27:43 ******/ ALTER TABLE [dbo].[venta_detalle] WITH CHECK ADD CONSTRAINT [FK_venta_detalle_productos] FOREIGN KEY([id_producto]) REFERENCES [dbo].[productos] ([id_producto]) GO ALTER TABLE [dbo].[venta_detalle] CHECK CONSTRAINT [FK_venta_detalle_productos] GO /****** Object: ForeignKey [FK_venta_detalle_venta] Script Date: 09/08/2011 17:27:43 ******/ ALTER TABLE [dbo].[venta_detalle] WITH CHECK ADD CONSTRAINT [FK_venta_detalle_venta] FOREIGN KEY([id_venta]) REFERENCES [dbo].[venta] ([id_venta]) GO ALTER TABLE [dbo].[venta_detalle] CHECK CONSTRAINT [FK_venta_detalle_venta] GO /****** Object: ForeignKey [FK_venta_detalle_tmp_productos] Script Date: 09/08/2011 17:27:43 ******/ ALTER TABLE [dbo].[venta_detalle_tmp] WITH CHECK ADD CONSTRAINT [FK_venta_detalle_tmp_productos] FOREIGN KEY([id_producto]) REFERENCES [dbo].[productos] ([id_producto]) GO ALTER TABLE [dbo].[venta_detalle_tmp] CHECK CONSTRAINT [FK_venta_detalle_tmp_productos] GO /****** Object: ForeignKey [FK_venta_detalle_tmp_users] Script Date: 09/08/2011 17:27:43 ******/ ALTER TABLE [dbo].[venta_detalle_tmp] WITH CHECK ADD CONSTRAINT [FK_venta_detalle_tmp_users] FOREIGN KEY([user_login]) REFERENCES [dbo].[users] ([user_login]) GO ALTER TABLE [dbo].[venta_detalle_tmp] CHECK CONSTRAINT [FK_venta_detalle_tmp_users] GO
Creamos elproyecto:
En la imagen se muestran las opciones que debemos seleccionar. Se mostrar el explorador de soluciones como se muestra en la imagen:
Nuestro proyecto est vaco, por ahora crearemos varios objetos que describimos a continuacin. Creacin de la Pgina Maestra (main.master)
Para ejecutar nuestro sistema, nos vamos presionamos la combinacin de teclas Windows + R, y se muestra la siguiente pantalla:
Nuestro sistema ya va agarrando fuerza. Pantalla de Inicio de Sesin (login.aspx) Ahora, tenemos que agregar un registro a la base de datos, en la tabla users:
Aqu debemos poner un poco de atencin, porque hay que empezar a programar, debemos tener abierto SQL Server Management Studio porque escribiremos procedimientos almacenados al mismo tiempo que programamos. Este es el cdigo HTML de login.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="login.aspx.cs" Inherits="login" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Iniciar Sesin</title> <link href="StyleSheet.css" rel="stylesheet" type="text/css" /> </head> <body> <form id="form1" runat="server"> <div> <table class="verde" > <tr> <td colspan="2" align="center" > <h3> Inicio de Sesin </h3> </td> </tr> <tr> <td align="left" >Usuario:</td> <td > <asp:TextBox ID="txtUSER_LOGIN" runat="server" ToolTip="Usuario" Width="150px"></asp:TextBox> <asp:RequiredFieldValidator ID="reqUSER_LOGIN" runat="server" ControlToValidate="txtUSER_LOGIN" ErrorMessage="Debe introducir un nombre de usuario">*</asp:RequiredFieldValidator> </td> </tr> <tr> <td align="left" >Contrasea:</td> <td align="left"> <asp:TextBox ID="txtPASSWORD" runat="server" TextMode="Password"
ToolTip="Contrasea" Width="150px"></asp:TextBox> </td> </tr> <tr> <td colspan="2" align="left"> <asp:CheckBox ID="chkPersist" runat="server" Text="Recordar usuario" /> </td> </tr> <tr> <td colspan="2" align="center" > <asp:Button ID="btnSubmit" runat="server" OnClick="btnSubmit_Click" Text="Entrar" Font-Bold="True" Width="100px" /> </td> </tr> </table> <asp:Label ID="lblMensaje" runat="server" Text=""></asp:Label> </div> </form> </body> </html>
Luego, en login.aspx.cs
} }
Hasta aqu todo debe ir bien, solamente que es necesario agregar cdigo adicional. Luego, agregamos la carpeta App_Code, de la siguiente manera:
/// Lee el archivo de configuracin /// </summary> /// <param name=prmKey">Llave a Leer</param>" /// <returns></returns> public static string WebConfig(string prmKey) { try { string value = ConfigurationManager.AppSettings[prmKey]; return (value); } catch { return (""); } } }
public static string SQLServerDateINI(DateTime prmDate){ string varYear = "1900"; string varMonth = "01"; string varDay = "01"; varYear = prmDate.Year.ToString(); varMonth = prmDate.Month.ToString(); if (varMonth.Length == 1){ varMonth = "0" + varMonth; } varDay = prmDate.Day.ToString(); if (varDay.Length == 1){ varDay = "0" + varDay; } return (varYear + varMonth + varDay + " 00:00:00"); } /// <summary> /// Devuelve una Fecha ISO para SQLServer /// </summary> /// <param name=prmDate">Fecha a convertir</param>" /// <returns>Fecha ISO para SQL Server</returns> /// <example>10 Abril 1980 = 19800410 23:59:59</example> public static string SQLServerDateFIN(DateTime prmDate){ string varYear = "1900"; string varMonth = "01"; string varDay = "01"; varYear = prmDate.Year.ToString(); varMonth = prmDate.Month.ToString(); if (varMonth.Length == 1){ varMonth = "0" + varMonth; } varDay = prmDate.Day.ToString(); if (varDay.Length == 1){ varDay = "0" + varDay; } return (varYear + varMonth + varDay + " 23:59:59"); } } }
--> <compilation debug="false" targetFramework="4.0"> <assemblies> <add assembly="System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B03F5F7F11D50A3A"/> <add assembly="System.Web.Extensions, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> <add assembly="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=B77A5C561934E089"/> </assemblies> </compilation> <!-La seccin <authentication> habilita la configuracin del modo de autenticacin de seguridad utilizado por ASP.NET para identificar a un usuario entrante. --> <authentication mode="Forms"> <forms name=".VENTASYS" loginUrl="login.aspx" defaultUrl="default.aspx" protection="All" timeout="20" path="/" requireSSL="false" slidingExpiration="true" cookieless="UseDeviceProfile" domain="" enableCrossAppRedirects="false"> <credentials passwordFormat="SHA1"/> </forms> </authentication> <authorization> <deny users="?"/> </authorization> <!-La seccin <customErrors> habilita la configuracin de las acciones que se deben realizar si un error no controlado tiene lugar durante la ejecucin de una solicitud. Especficamente, permite a los desarrolladores configurar pginas de error html que se mostrarn en lugar de un seguimiento de pila de errores. <customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm"> <error statusCode="403" redirect="NoAccess.htm" /> <error statusCode="404" redirect="FileNotFound.htm" /> </customErrors> --> <pages controlRenderingCompatibilityVersion="3.5" clientIDMode="AutoID"> </pages> <httpHandlers> <add path="ChartImg.axd" verb="GET,HEAD" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" validate="false"/> </httpHandlers> </system.web> <!-La seccin system.webServer es necesaria para ejecutar ASPN.NET AJAX en Internet Information Services 7.0. No es necesaria para la versin anterior de IIS. --> <system.webServer> <validation validateIntegratedModeConfiguration="false"/> <handlers> <add name="ChartImageHandler" preCondition="integratedMode" verb="GET,HEAD" path="ChartImg.axd" type="System.Web.UI.DataVisualization.Charting.ChartHttpHandler, System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/> </handlers> </system.webServer>
<appSettings> <add key="ChartImageHandler" value="Storage=file;Timeout=20;Url=~/rpt/;"/> <add key="TICKET_HEADER_01" value="VENTAS S.A DE CV"/> <add key="TICKET_HEADER_02" value="ENCABEZADO 02"/> <add key="TICKET_HEADER_03" value="ENCABEZADO 03"/> <add key="TICKET_HEADER_04" value="ENCABEZADO 04"/> <add key="TICKET_FOOTER_01" value="GRACIAS POR SU COMPRA"/> <add key="TICKET_FOOTER_02" value="PI 02"/> <add key="TICKET_FOOTER_03" value="PI 03"/> <add key="TICKET_FOOTER_04" value="PI 04"/> <add key="PROGRAMADOR_NOMBRE" value="JUAN GABRIEL CASTILLO"/> <add key="PROGRAMADOR_MAIL" value="tyrodeveloper@gmail.com"/> <add key="PROGRAMADOR_MENSAJE" value="Gracias por adquirir este sistema."/> <add key="GMAIL_USER" value=""/> <add key="GMAIL_PASSWORD" value=""/> <add key="GMAIL_HOST" value="smtp.gmail.com"/> <add key="GMAIL_PORT" value="587"/> <add key="GMAIL_URL" value="http://mail.google.com"/> <add key="DEVELOPER_URL" value=""/> </appSettings> </configuration>
Poner especial atencin a la llave ConnectionStrings ya que en esa seccin deben poner la configuracin de su SQL Server. Ahora agregaremos el cdigo para cerrar la sesin, nos vamos a la pgina main.master.cs y agregamos el siguiente cdigo:
protected void btnCerrarSesion_Click(object sender, EventArgs e) { FormsAuthentication.SignOut(); Response.Redirect("default.aspx"); }
De acuerdo a los datos que introdujimos a la tabla users Nombre de usuario: admin Contrasea: admin Luego, al introducir un nombre de usuario y contrasea correctos, veremos la siguiente pantalla:
Y al dar clic al botn Cerrar sesin el sistema nos regresa a lapantal la de Login. Lo que haremos a continuacin ser el diseo de los permisos, es decir, dependiendo de los permisos que tenga el usuario que inici sesin, sern las opciones que podr ver en el menu.
Le hemos agregado "{ventas}{reportes}{administrar}", haremos un Replace de cdigo HTML como se muestra en seguida. Ahora vamos al cdigo C# del archivo main.master.cs y escribiremos el siguiente cdigo:
void Permisos(string prmUSER_LOGIN){ try{ SqlConnection cnn = new SqlConnection(clsMain.CnnStr); cnn.Open(); SqlCommand cmd = new SqlCommand("EXECUTE [proc_USERS_PERMISOS_MOSTRAR]'" + prmUSER_LOGIN + "'", cnn); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()){ if (Convert.ToBoolean(dr["ADMINISTRAR"])){ lblOpciones.Text = lblOpciones.Text.Replace("{administrar}"," administrar.aspx\">Administrar "); } else{ lblOpciones.Text = lblOpciones.Text.Replace("{administrar}", ""); } if (Convert.ToBoolean(dr["REPORTES"])){ lblOpciones.Text = lblOpciones.Text.Replace("{reportes}", " reportes.aspx\">Reportes "); } else{ lblOpciones.Text = lblOpciones.Text.Replace("{reportes}", ""); } if (Convert.ToBoolean(dr["VENTAS"])){
lblOpciones.Text = lblOpciones.Text.Replace("{ventas}", " ventas.aspx\">Ventas "); } else { lblOpciones.Text = lblOpciones.Text.Replace("{ventas}", ""); } } dr.Close(); cmd.Dispose(); cnn.Close(); cnn.Dispose(); } catch (Exception ex){ lblOpciones.Text = ex.Message; } }
Podemos ver como se aplican los permisos. Crea varios usuarios en el SQL Server y ponles diferentes permisos para que veas el efecto que tiene en la pantalla.
<td>Cantidad:</td> <td rowspan="2"> <asp:Button ID="btnAgregar" ValidationGroup="Add" OnClick="btnAgregar_Click" Height="50" runat="server" Text="Agregar" /> </td> </tr> <tr> <td> <asp:TextBox ID="txtID_PRODUCTO" MaxLength="50" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="reqtxtID_PRODUCTO" ValidationGroup="Add" ControlToValidate="txtID_PRODUCTO" runat="server" ErrorMessage="*"></asp:RequiredFieldValidator> </td> <td> <asp:TextBox ID="txtCANTIDAD" MaxLength="10" Width="90" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="reqtxtCANTIDAD" ValidationGroup="Add" ControlToValidate="txtCANTIDAD" runat="server" ErrorMessage="*"></asp:RequiredFieldValidator> </td> </tr> </table> <asp:GridView ID="grdVentas" AutoGenerateColumns="False" OnRowDataBound="grdVentas_RowDataBound" Width="100%" ShowFooter="True" runat="server"> <Columns> <asp:BoundField HeaderText="Clave" DataField="id_producto"> <ItemStyle HorizontalAlign="Left" /> <HeaderStyle HorizontalAlign="Left" /> </asp:BoundField> <asp:BoundField HeaderText="Descripcion" DataField="producto" > <ItemStyle HorizontalAlign="Left" /> <HeaderStyle HorizontalAlign="Left" /> </asp:BoundField> <asp:BoundField HeaderText="Cantidad" DataField="cantidad" HtmlEncode="False" DataFormatString="{0:N0}" > <ItemStyle HorizontalAlign="Right" /> <HeaderStyle HorizontalAlign="Right" /> </asp:BoundField> <asp:BoundField HeaderText="Precio" DataField="p_venta" HtmlEncode="False" DataFormatString="{0:C}" > <ItemStyle HorizontalAlign="Right" /> <HeaderStyle HorizontalAlign="Right" /> </asp:BoundField> <asp:BoundField HeaderText="Total" DataField="TOTAL" HtmlEncode="False" DataFormatString="{0:C}" > <ItemStyle HorizontalAlign="Right" /> <HeaderStyle HorizontalAlign="Right" /> </asp:BoundField> </Columns> <EmptyDataTemplate> <h2>No hay registros.</h2> <br /> <b>Instrucciones para agregar articulos:</b><br /><br /> 1. Proporcione la clave del articulo<br /> 2. Proporcione la cantidad<br /> 3. Presione "Agregar" </EmptyDataTemplate> </asp:GridView> <table style="width:100%"> <tr>
<td style="text-align:center;"> <asp:Button ID="btnGrabar" OnClick="btnGrabar_Click" Width="100" Height="50" runat="server" Text="Grabar" /> <asp:Button ID="btnCancelar" OnClick="btnCancelar_Click" Width="100" Height="50" runat="server" Text="Cancelar" /> </td> </tr> </table> <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label> </fieldset> </div> </form> </body> </html>
IF EXISTS(SELECT ID_PRODUCTO FROM venta_detalle_tmp WHERE ID_PRODUCTO=@ID_PRODUCTO AND user_login=@USER_LOGIN) BEGIN --EDITAR SELECT @CANT = CANTIDAD FROM venta_detalle_tmp WHERE ID_PRODUCTO=@ID_PRODUCTO AND user_login=@USER_LOGIN IF(@CANTIDAD<=(@EXISTENCIA-@CANT)) BEGIN UPDATE venta_detalle_tmp SET CANTIDAD = CANTIDAD + @CANTIDAD WHERE user_login = @USER_LOGIN AND ID_PRODUCTO=@ID_PRODUCTO AND user_login=@USER_LOGIN END ELSE GOTO ERROR_EXIST END ELSE BEGIN --INSERTAR IF(@CANTIDAD<=@EXISTENCIA) BEGIN INSERT INTO venta_detalle_tmp(user_login,ID_PRODUCTO,CANTIDAD,p_venta) VALUES(@USER_LOGIN,@ID_PRODUCTO,@CANTIDAD,@PRECIO) END ELSE GOTO ERROR_EXIST END IF @@ERROR<> 0 GOTO ERROR COMMIT TRANSACTION tVTA RETURN ERROR: RAISERROR('No se puede agregar el registro,16,1) ROLLBACK TRANSACTION tVTA GOTO FIN RETURN ERROR_A: RAISERROR('El articulo no existe,16,1) ROLLBACK TRANSACTION tVTA GOTO FIN RETURN ERROR_EXIST: RAISERROR('No hay suficientes existencias,16,1) ROLLBACK TRANSACTION tVTA GOTO FIN RETURN FIN: GO USE [pventa] GO /****** Object: StoredProcedure [dbo].[proc_VENTA] 17:14:58 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE PROCEDURE [dbo].[proc_VENTA] @USER_LOGIN NVARCHAR(50) AS BEGIN TRANSACTION tVTAs DECLARE @FOLIO_VENTA INT Script Date: 09/08/2011
IF NOT EXISTS(SELECT ID_PRODUCTO FROM venta_detalle_tmp WHERE user_login=@USER_LOGIN ) GOTO NOOPER --GRABAMOS LA VENTA INSERT INTO VENTA(user_login,fecha_registro) VALUES(@USER_LOGIN,GETDATE()) --OBTENEMOS EL FOLIO DE LA VENTA SELECT @FOLIO_VENTA=@@IDENTITY --INSERTAMOS EL DETALLE DE LA VENTA INSERT INTO VENTA_DETALLE(id_venta,ID_PRODUCTO,CANTIDAD,P_VENTA) SELECT @FOLIO_VENTA,ID_PRODUCTO,CANTIDAD,P_VENTA FROM venta_detalle_tmp WHERE user_login=@USER_LOGIN --ACTUALIZAMOS LAS EXISTENCIAS GENERALES UPDATE productos SET productos.EXISTENCIA = productos.EXISTENCIA-venta_detalle_tmp.[CANTIDAD] FROM venta_detalle_tmp WHERE productos.ID_PRODUCTO = venta_detalle_tmp.ID_PRODUCTO AND venta_detalle_tmp.user_login= @USER_LOGIN --BORRAMOS LA TABLA TEMPORAL DELETE FROM venta_detalle_tmp WHERE user_login = @USER_LOGIN IF @@ERROR <> 0 GOTO ERROR SELECT @FOLIO_VENTA COMMIT TRANSACTION tVTAs RETURN ERROR: RAISERROR('No se puede grabar la venta,16,1) ROLLBACK TRANSACTION tVTAs GOTO FIN RETURN NOOPER: RAISERROR('No hay registros en la lista de ventas,16,1) ROLLBACK TRANSACTION tVTAs GOTO FIN RETURN FIN: GO
DataSet ds = new DataSet(); SqlDataAdapter da = new SqlDataAdapter(varSQL, cnnReadData); da.Fill(ds, "DATOS"); grdVentas.DataSource = ds.Tables["DATOS"]; grdVentas.DataBind(); ds.Dispose(); cmdReadData.Dispose(); cnnReadData.Close(); cnnReadData.Dispose(); } catch (Exception ex){ lblMessage.Text = ex.Message; } } bool Temp_Ventas(string prmUSER_LOGIN, string prmID_PRODUCTO, double prmCANTIDAD){ //Para cargar la venta TEMPORAL try{ SqlConnection cnnTempVentas = new SqlConnection(clsMain.CnnStr); cnnTempVentas.Open(); SqlCommand cmdTempVentas = new SqlCommand(); cmdTempVentas.Connection = cnnTempVentas; cmdTempVentas.CommandText = "EXECUTE [proc_TEMP_VENTAS] '" + prmUSER_LOGIN + "','" + prmID_PRODUCTO + "'," + prmCANTIDAD + ""; cmdTempVentas.ExecuteNonQuery(); cnnTempVentas.Close(); cmdTempVentas.Dispose(); cnnTempVentas.Dispose(); txtID_PRODUCTO.Text = ""; txtCANTIDAD.Text = "1"; return (true); } catch (Exception ex){ lblMessage.Text = ex.Message; return (false); } } protected void grdVentas_RowDataBound(object sender, GridViewRowEventArgs e){ if (e.Row.RowType == DataControlRowType.DataRow){ // add the UnitPrice and QuantityTotal to the running total variables varTOTAL += Convert.ToDouble(DataBinder.Eval(e.Row.DataItem, "TOTAL")); } else if (e.Row.RowType == DataControlRowType.Footer){ e.Row.Cells[3].Text = "TOTAL"; e.Row.Cells[3].HorizontalAlign = HorizontalAlign.Right; e.Row.Cells[3].VerticalAlign = VerticalAlign.Top; // for the Footer, display the running totals e.Row.Cells[4].Text = varTOTAL.ToString("C"); e.Row.Cells[4].HorizontalAlign = HorizontalAlign.Right; e.Row.Cells[4].VerticalAlign = VerticalAlign.Top; e.Row.Font.Bold = true; lblTOTAL.Text = varTOTAL.ToString("C"); //establecemos en blanco las celdas que no tienen dato } } protected void btnAgregar_Click(object sender, EventArgs e){ try { if (Temp_Ventas(User.Identity.Name,txtID_PRODUCTO.Text, Convert.ToDouble(txtCANTIDAD.Text))) { ReadData(User.Identity.Name); }
} catch (Exception ex){ lblMessage.Text = ex.Message; } } private int RealizaVenta(string prmUSER_LOGIN) { try{ int varTICKET = 0; SqlConnection cnnGrabar = new SqlConnection(clsMain.CnnStr); cnnGrabar.Open(); SqlCommand cmdGrabar = new SqlCommand(); cmdGrabar.Connection = cnnGrabar; cmdGrabar.CommandText = "EXECUTE [proc_VENTA] '" + prmUSER_LOGIN + "'"; varTICKET = Convert.ToInt32(cmdGrabar.ExecuteScalar()); //LIBERAMOS LOS RECUSROS cnnGrabar.Close(); cnnGrabar.Dispose(); cmdGrabar.Dispose(); //mostramos la info return (varTICKET); } catch (Exception ex){ lblMessage.Text =ex.Message; return (0); } } private bool CancelarVenta(string prmUSER_LOGIN){ try{ SqlConnection cnnCancelar = new SqlConnection(clsMain.CnnStr); cnnCancelar.Open(); SqlCommand cmdCancelar = new SqlCommand( "DELETE FROM venta_detalle_tmp WHERE user_login = '"+prmUSER_LOGIN +"'",cnnCancelar); cmdCancelar.ExecuteNonQuery(); cnnCancelar.Close(); cnnCancelar.Dispose(); cmdCancelar.Dispose(); return (true); } catch (Exception ex){ lblMessage.Text = ex.Message; return (false); } } protected void btnGrabar_Click(object sender, EventArgs e){ try { int varTICKET = RealizaVenta(User.Identity.Name); if (varTICKET != 0) { Response.Redirect("default.aspx"); } } catch (Exception ex) { lblMessage.Text = ex.Message; } } protected void btnCancelar_Click(object sender, EventArgs e){ try{ if (CancelarVenta(User.Identity.Name)){ Response.Redirect("default.aspx"); } } catch (Exception ex) { lblMessage.Text = ex.Message; }
Antes de continuar, entremos ala base de datos y agreguemos unidades de medida y articulos. Asi se ve nuestro formulario con articulos:
Ahora agregamos una nueva pgina llamada rpt-ventas.aspx, marcar la opcin "Select master page" y seleccionen man.master (como en el caso anterior) y el cdigo HTML ser el siguiente::
<%@ Page Title="" Language="C#" MasterPageFile="~/main.master" AutoEventWireup="true" CodeFile="rpt-ventas.aspx.cs" Inherits="rpt_ventas" %> <asp:Content ID="cntMain" ContentPlaceHolderID="cphMain" Runat="Server"> <h3>Reporte de Ventas</h3> <table style="width:100%;"> <tr> <td style=" border-right-style:dotted; border-right-color:Silver; width:200px; border-right-width:1px; vertical-align:top; text-align:left;"> <a href="javascript:" onclick="VerReporte(0);">Ver Reporte</a> <a href="javascript:" onclick="VerReporte(1);">Exportar</a> </td> <td style=" width:580px; vertical-align:top; text-align:left;"> <table > <tr> <td>Fecha inicio:</td>
<td> <asp:TextBox ID="txtFECHA_INI" Width="80" runat="server"></asp:TextBox> </td> </tr> <tr> <td>Fecha final:</td> <td> <asp:TextBox ID="txtFECHA_FIN" Width="80" runat="server"></asp:TextBox> </td> </tr> </table> </td> </tr> </table> <p>Escriba un rango de fechas y seleccione "Ver reporte" para ver en formato HTML, o seleccione "Exportar" para enviarlo a Excel</p> <script type="text/javascript"> function VerReporte(op) { objFINI = document.getElementById("ctl00_cphMain_txtFECHA_INI"); objFFIN = document.getElementById("ctl00_cphMain_txtFECHA_FIN"); if ((objFINI.value != '') && (objFFIN.value != '')) { if (op == 0) { window.open('rpt-ventas-ver.aspx?fini=' + objFINI.value + '&ffin=' + objFFIN.value + '&op=0'); } else { window.open('rpt-ventas-ver.aspx?fini=' + objFINI.value + '&ffin=' + objFFIN.value + '&op=1'); } } else { alert('Debe indicar la fecha inicial y la fecha final'); } } </script> </asp:Content>
Agregamos una nueva pgina llamada rpt-ventas-ver.aspx, pero en este caso NO SELECCIONAREMOS la master page, el cdigo HTML sera el siguiente:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="rpt-ventasver.aspx.cs" Inherits="rpt_ventas_ver" %> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>Reporte de Ventas</title> </head> <body> <form id="frmReporte" runat="server"> <div> <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>
<asp:GridView ID="grdLista" OnRowDataBound="grdLista_RowDataBound" Width="100%" ShowFooter="True" AutoGenerateColumns="False" runat="server" > <Columns> <asp:BoundField HeaderText="Id " DataField="id_venta" > <HeaderStyle HorizontalAlign="Left" /> <ItemStyle HorizontalAlign="Left" Width="40" /> </asp:BoundField> <asp:BoundField HeaderText="Fecha" DataField="fecha_registro" HtmlEncode="False" DataFormatString="{0:dd/MM/yyyy HH:mm}" > <HeaderStyle HorizontalAlign="Left" /> <ItemStyle HorizontalAlign="Left" Width="200" /> </asp:BoundField> <asp:BoundField HeaderText="Clave" DataField="id_producto" HtmlEncode="False" > <HeaderStyle HorizontalAlign="Center" /> <ItemStyle HorizontalAlign="Center" Width="70" /> </asp:BoundField> <asp:BoundField HeaderText="Descripcin" DataField="producto" > <HeaderStyle HorizontalAlign="Left" /> <ItemStyle HorizontalAlign="Left" /> </asp:BoundField> <asp:BoundField HeaderText="Precio" DataField="p_venta" HtmlEncode="False" DataFormatString="{0:C}" > <HeaderStyle HorizontalAlign="Right" /> <ItemStyle HorizontalAlign="Right" Width="70" /> </asp:BoundField> <asp:BoundField HeaderText="Cantidad" DataField="cantidad" HtmlEncode="False" DataFormatString="{0:N}" > <HeaderStyle HorizontalAlign="Right" /> <ItemStyle HorizontalAlign="Right" Width="70" /> </asp:BoundField> <asp:BoundField HeaderText="Total" DataField="TOTAL" HtmlEncode="False" DataFormatString="{0:C}" > <HeaderStyle HorizontalAlign="Right" /> <ItemStyle HorizontalAlign="Right" Width="70" /> </asp:BoundField> </Columns> <EmptyDataTemplate> <h1>No hay datos para mostrar, intente con otras fechas</h1> </EmptyDataTemplate> </asp:GridView> </div> </form> </body> </html>
protected void Page_Load(object sender, EventArgs e){ try{ if (!Page.IsPostBack){ Response.Clear(); Response.Buffer = true; if (Request.Params["op"] == "1"){ Response.ContentType = "application/vnd.ms-excel"; Response.AddHeader("Content-Disposition", "attachment;filename=RptVentas.xls"); } Response.ContentEncoding = System.Text.Encoding.Default; //Cagamos los Datos ReadData(ISODates.Dates.SQLServerDateINI(Convert.ToDateTime(Request.Params["fi ni"])), ISODates.Dates.SQLServerDateFIN(Convert.ToDateTime(Request.Params["ffin"]))); Response.Write(HTML()); //Llamada al procedimiento HTML Response.End(); } } catch (Exception ex){ lblMessage.Text = ex.Message; } } void ReadData(string prmFECHA_INI, string prmFECHA_FIN){ try { SqlConnection cnn = new SqlConnection(clsMain.CnnStr); cnn.Open(); SqlDataAdapter da = new SqlDataAdapter("EXECUTE [dbo].[proc_RPT_VENTAS] '" + prmFECHA_INI + "','" + prmFECHA_FIN + "'", cnn); DataSet ds = new DataSet(); da.Fill(ds, "DATOS"); grdLista.DataSource = ds.Tables["DATOS"]; grdLista.DataBind(); cnn.Close(); cnn.Dispose(); ds.Dispose(); da.Dispose(); } catch (Exception ex){ lblMessage.Text = ex.Message; } } protected void grdLista_RowDataBound(object sender, GridViewRowEventArgs e) { if (e.Row.RowType == DataControlRowType.DataRow){ varTotal += Convert.ToInt32(DataBinder.Eval(e.Row.DataItem, "TOTAL")); } else if (e.Row.RowType == DataControlRowType.Footer){ varTotalX = varTotal / 2; e.Row.Cells[5].Text = "TOTAL:"; e.Row.Cells[5].HorizontalAlign = HorizontalAlign.Right; e.Row.Cells[6].HorizontalAlign = HorizontalAlign.Right; e.Row.Cells[6].Text = varTotalX.ToString("C"); } } //El procedimiento HTML que se encarga de dar o mantener formatos segn corresponda: public string HTML(){ Page page1 = new Page(); HtmlForm form1 = new HtmlForm(); grdLista.EnableViewState = false; if (grdLista.DataSource != null){ grdLista.DataBind(); } grdLista.EnableViewState = false;
page1.EnableViewState = false; page1.Controls.Add(form1); form1.Controls.Add(grdLista); System.Text.StringBuilder builder1 = new System.Text.StringBuilder(); System.IO.StringWriter writer1 = new System.IO.StringWriter(builder1); HtmlTextWriter writer2 = new HtmlTextWriter(writer1); writer2.Write("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1transitional.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<title>Reporte</title>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\" />\n<style type=\"text/css\">body{font-family : Tahoma, Verdana, Arial, sansserif;}</style>\n</head>\n<body>\n"); writer2.Write("<table style=\"width:100%\"><tr><td></td>" + "<td style=\"text-align:center;\"><b>TYRODEVELOPER</b><br />SISTEMA PUNTO DE VENTA WEB<br />REPORTE DE VENTAS</td>" + "<td></td></tr></table>"); writer2.Write(String.Format("Reporte entre las fechas: {0} y {1}<br />Total: {2}", Request.Params["fini"].ToString(), Request.Params["ffin"].ToString(), varTotalX.ToString("C"))); page1.DesignerInitialize(); page1.RenderControl(writer2); writer2.Write("\n</body>\n</html>"); page1.Dispose(); page1 = null; return builder1.ToString(); }
</asp:content>
El cdigo HTML:
<asp:content contentplaceholderid="cphMain" id="cntMain" runat="Server"> <h3>
Usuarios del Sistema</h3> <table style="width: 100%;"> <tbody> <tr> <td style="border-right-color: silver; border-right-style: dotted; border-rightwidth: 1px; text-align: left; vertical-align: top; width: 200px;"><asp:linkbutton id="btnGrabar" onclick="btnGrabar_Click" runat="server" tooltip="Clic aqui para grabar">Grabar</asp:linkbutton> <a href="http://www.blogger.com/user-lista.aspx">Cancelar</a> </td> <td style="text-align: left; vertical-align: top; width: 580px;"><table> <tbody> <tr> <td>Usuario:</td> <td><asp:textbox id="txtUSER_LOGIN" maxlength="50" runat="server" width="150"></asp:textbox> </td> </tr> <tr> <td>Nombre:</td> <td><asp:textbox id="txtNOMBRE" maxlength="50" runat="server" width="150"></asp:textbox></td> </tr> <tr> <td>Contrasea:</td> <td><asp:textbox id="txtUSER_PASSWORD" maxlength="50" runat="server" width="150"></asp:textbox></td> </tr> <tr> <td>Activo:</td> <td><asp:checkbox id="chkACTIVO" runat="server"> </asp:checkbox></td> </tr> <tr> <td>Ventas:</td> <td><asp:checkbox id="chkVENTAS" runat="server"> </asp:checkbox></td> </tr> <tr> <td>Reportes:</td> <td><asp:checkbox id="chkREPORTES" runat="server"> </asp:checkbox></td> </tr> <tr> <td>Administrar:</td> <td><asp:checkbox id="chkADMINISTRAR" runat="server"> </asp:checkbox></td> </tr> </tbody></table> </td> </tr> </tbody></table> <asp:label id="lblMensaje" runat="server" text=""></asp:label> </asp:content>
lblMensaje.Text = ex.Message; } } void ReadData(string prmUSER_LOGIN){ try{ SqlConnection cnn = new SqlConnection(clsMain.CnnStr); cnn.Open(); SqlCommand cmd = new SqlCommand("SELECT * FROM users WHERE user_login ='"+ prmUSER_LOGIN +"'", cnn); SqlDataReader dr = cmd.ExecuteReader(); if (dr.Read()){ txtUSER_LOGIN.Text = dr["USER_LOGIN"].ToString(); txtUSER_PASSWORD.Text = dr["USER_PASSWORD"].ToString(); txtNOMBRE.Text = dr["NOMBRE"].ToString(); chkACTIVO.Checked = Convert.ToBoolean(dr["ACTIVO"]); chkVENTAS.Checked = Convert.ToBoolean(dr["VENTAS"]); chkREPORTES.Checked = Convert.ToBoolean(dr["REPORTES"]); chkADMINISTRAR.Checked = Convert.ToBoolean(dr["ADMINISTRAR"]); } dr.Close(); cnn.Close(); cmd.Dispose(); cnn.Dispose(); } catch (Exception ex){ lblMensaje.Text = ex.Message; } } bool fnRegistro(string prmUSER_LOGIN, string prmUSER_PASSWORD, string prmNOMBRE, int prmACTIVO, int prmREPORTES, int prmVENTAs, int prmADMINISTRAR){ try{ SqlConnection cnn = new SqlConnection(clsMain.CnnStr); cnn.Open(); string varSQL = "execute proc_USERS '" + prmUSER_LOGIN + "'," + "'" + prmUSER_PASSWORD + "','" + prmNOMBRE + "'," + prmACTIVO + "," + prmREPORTES + "," + "" + prmVENTAs + "," + prmADMINISTRAR + " "; SqlCommand cmd = new SqlCommand(varSQL, cnn); cmd.ExecuteNonQuery(); cnn.Close(); cnn.Dispose(); cmd.Dispose(); return (true); } catch (Exception ex){ lblMensaje.Text = ex.Message; return (false); } } protected void btnGrabar_Click(object sender, EventArgs e){ try{ if (fnRegistro(txtUSER_LOGIN.Text,txtUSER_PASSWORD.Text,txtNOMBRE.Text, Convert.ToInt32(chkACTIVO.Checked), Convert.ToInt32(chkREPORTES.Checked), Convert.ToInt32(chkVENTAS.Checked), Convert.ToInt32(chkADMINISTRAR.Checked))) { Response.Redirect("user-lista.aspx"); } } catch (Exception ex){ lblMensaje.Text = ex.Message; } }
CREATE PROCEDURE [dbo].[proc_USERS] @USER_LOGIN NVARCHAR(50), @USER_PASSWORD VARCHAR(8000), @NOMBRE NVARCHAR(50), @ACTIVO BIT, @REPORTES BIT, @VENTAS BIT, @ADMINISTRAR BIT AS /* USUARIOS DEL SISTEMA FECHA:24-OCT-2011 PROGRAMADOR:J. GABRIEL CASTILLO MAIL: jgcastillo@uat.edu.mx,muskin@msn.com */ BEGIN TRANSACTION tUSERS IF NOT EXISTS(SELECT 1 FROM users WHERE user_login=@USER_LOGIN) BEGIN INSERT INTO USERS(USEr_LOGIN,USER_PASSWORD,NOMBRE,activo,reportes,ventas,administrar) VALUES(@USER_LOGIN,@USER_PASSWORD,@NOMBRE,@ACTIVO,@REPORTES,@VENTAS,@ADMINISTRAR) END ELSE BEGIN UPDATE USERS SET NOMBRE=@NOMBRE, activo=@ACTIVO, reportes=@REPORTES, ADMINISTRAR=@ADMINISTRAR, VENTAS=@VENTAS WHERE user_login=@USER_LOGIN END COMMIT TRANSACTION tUSERS RETURN ERROR: RAISERROR('No se puede ejecutar la accin solicitada,16,1) ROLLBACK TRANSACTION tUSERS GOTO FIN RETURN FIN: GO