Documentos de Académico
Documentos de Profesional
Documentos de Cultura
[reportes] [bit] NOT NULL, [administrar] [bit] NOT NULL, [fecha_registro] [datetime] NOT NULL, CONSTRAINT [PK_users] PRIMARY KEY CLUSTERED ( [user_login] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS [PRIMARY] ) ON [PRIMARY] GO /****** Object: Table [dbo].[unidad_medida] Script Date: 09/08/2011 17:27:43 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE TABLE [dbo].[unidad_medida]( [id_unidad_medida] [smallint] NOT NULL, [unidad_medida] [nvarchar](150) NULL, CONSTRAINT [PK_unidad_medida] PRIMARY KEY CLUSTERED ( [id_unidad_medida] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS [PRIMARY] ) ON [PRIMARY] GO /****** 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 = ON, ALLOW_PAGE_LOCKS = ON) ON
= ON, ALLOW_PAGE_LOCKS
= ON) ON
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS [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 [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 [PRIMARY] ) ON [PRIMARY] GO /****** Object: Table [dbo].[venta_detalle] Script Date: 09/08/2011 17:27:43 ******/ SET ANSI_NULLS ON GO
= ON, ALLOW_PAGE_LOCKS
= ON) ON
= ON, ALLOW_PAGE_LOCKS
= ON) ON
= ON, ALLOW_PAGE_LOCKS
= ON) ON
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)
<!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>Punto de Venta Web</title> </head> <body> <form id="frmMain" runat="server"> <h1>SISTEMA PUNTO DE VENTA</h1> <div style=" width:800px;"> <div id="menuh"> <ul> <li><a href="default.aspx">Inicio</a></li> <asp:Label ID="lblOpciones" runat="server" Text=""></asp:Label> <li><asp:LinkButton ID="btnCerrarSesion" runat="server" onclick="btnCerrarSesion_Click">Cerrar Sesin</asp:LinkButton></li> </ul> </div> <br /> <asp:ContentPlaceHolder id="cphMain" runat="server"> </asp:ContentPlaceHolder> <h4>DESARROLLADO POR TYRODEVELOPER</h4> </div> </form> </body> </html>
Para ejecutar nuestro sistema, nos vamos presionamos la combinacin de teclas Windows + R, y se muestra la siguiente pantalla:
margin: 0; padding: 0; } #menuh li { float: left; } #menuh a { text-decoration: none; color: #3366CC; background: #F0F7FC; display: block; padding: 3px 10px; text-align: center; border: 1px solid #ACCFE8; border-width: 1px 1px 1px 0; }
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
if (drLogin.Read()) { Session.Add("USER_NAME", drLogin["nombre"].ToString()); _return = true; } else{ lblMensaje.Text = "Nombre de usuario o contrasea incorrectos"; _return = false; } drLogin.Close(); cnnLogin.Close(); return (_return); } catch (Exception ex) { lblMensaje.Text = ex.Message; return (false); } } protected void btnSubmit_Click(object sender, EventArgs e) { lblMensaje.Text = ""; if (fnLogin(txtUSER_LOGIN.Text,txtPASSWORD.Text)) { //correcto FormsAuthentication. RedirectFromLoginPage(txtUSER_LOGIN.Text, chkPersist.Checked); } }
Hasta aqu todo debe ir bien, solamente que es necesario agregar cdigo adicional. Luego, agregamos la carpeta App_Code, de la siguiente manera:
/// <summary> /// Clase Main /// </summary> public class clsMain { public clsMain(){} /// <summary> /// Regresa la cadena de conexin /// </summary> public static string CnnStr { get { return (ConfigurationManager. ConnectionStrings["dbCnnStr"]. ConnectionString); } } /// <summary> /// 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 (""); } } }
namespace ISODates{ public class Dates{ /// <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 10:25 a.m.= 19800410 10:25:00</example> public static string SQLServerDate(DateTime prmDate){ string varYear = "1900"; string varMonth = "01"; string varDay = "01"; string varHour = "00"; string varMin = "00"; string varSec = "00"; 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; } varHour = prmDate.Hour.ToString(); if (varHour.Length == 1){ varHour = "0" + varHour; } varMin = prmDate.Minute.ToString(); if (varMin.Length == 1){ varMin = "0" + varMin; } varSec = prmDate.Second.ToString(); if (varSec.Length == 1){ varSec = "0" + varSec; } return (varYear + varMonth + varDay + " " + varHour + ":" + varMin + ":" + varSec); } /// <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 00:00:00</example> 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; }
<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.
<% @ Page Language = "C #" AutoEventWireup = "true" CodeFile = "ventas.aspx.cs" Inherits = "Ventas" %> <DOCTYPE HTML PUBLIC! "- / / W3C / / DTD XHTML 1.0 Transitional / / EN" transitional.dtd" > "http://www.w3.org/TR/xhtml1/DTD/xhtml1-
<HTML xmlns = "http://www.w3.org/1999/xhtml" > <Cabeza runat = "server" > <title> Punto de Venta Web </ title> <Link href = "stylesheet.css" rel = "stylesheet" type = "text / css" /> <Script type = "text / javascript" > / / NO SALIR of this Pantalla
window.history.forward (1); / / Solo numeros var nav4 = window.event? verdad : false ; funcin acceptNum (evt) { / / NOTA: '.' Retroceso = 8, Enter = 13, '0 '= 48, '9' = 57, = 46 var key = nav4? evt.which: evt.keyCode; retorno (tecla <= 13 | | (tecla> = 48 && tecla <= 57) | | key == 46); } </ Script> </ Head> <body> <Forma id = "frmVentas" runat = "server" > <Div style = "min-height: 300px; ancho: 580px;" > <Div style = "position: absolute; top: 40px; background-color: # ADD8E6, ancho: 150px; izquierda: 400px; text-align: right; altura: 50px; font-size: 20pt; inferior: 480px; vertical align: middle; " > <asp: Label ID = "" lblTOTAL runat = "" servidor Texto = "$ 0.00" > </ asp: Label> </ div> <Style fieldset = "min-height: 300px;" > <legend> Ventas </ legend> <Estilo de tabla = "margen: 10px;" > <tr> <td> Clave: </ td> <td> CANTIDAD: </ td> <Td rowspan = "2" > <Asp: Button </ Td> </ Tr> <tr> <td> <Asp: TextBox ID = "txtID_PRODUCTO" MaxLength = "50" runat = "server" > </ asp: TextBox> <Asp: RequiredFieldValidator </ Td> <td> <Asp: TextBox ID = "txtCANTIDAD" MaxLength = "10" Ancho = "90" runat = "server" > </ asp: TextBox> <Asp: RequiredFieldValidator </ Td> </ Tr> </ Table> <Asp: GridView <Columns> <Asp: BoundField HeaderText = "Clave" DataField = "id_producto" > <ItemStyle HorizontalAlign = "izquierda" />
<HeaderStyle HorizontalAlign = "izquierda" /> </ Asp: BoundField> <Asp: BoundField HeaderText = "Description" DataField = "Producto" > <ItemStyle HorizontalAlign = "izquierda" /> <HeaderStyle HorizontalAlign = "izquierda" /> </ Asp: BoundField> <Asp: BoundField HeaderText = "CANTIDAD" DataField = "CANTIDAD" HtmlEncode = "False" DataFormatString = "{0: N0}" > <ItemStyle HorizontalAlign = "derecha" /> <HeaderStyle HorizontalAlign = "derecha" /> </ Asp: BoundField> <Asp: BoundField HeaderText = "Precio" DataField = "p_venta" HtmlEncode = "False" DataFormatString = "{0: C}" > <ItemStyle HorizontalAlign = "derecha" /> <HeaderStyle HorizontalAlign = "derecha" /> </ Asp: BoundField> <Asp: BoundField HeaderText = "Total" DataField = "TOTAL" HtmlEncode = "False" DataFormatString = "{0: C}" > <ItemStyle HorizontalAlign = "derecha" /> <HeaderStyle HorizontalAlign = "derecha" /> </ Asp: BoundField> </ Columns> <EmptyDataTemplate> <h2> No Hay Registros. </ h2> <br /> <b> INSTRUCCIONES prr agregar articulos: </ b> <br /> <br /> 1. Proporcione la clave del articulo <br /> 2. Proporcione la CANTIDAD <br /> 3. PRESIONE "persona que buscas?" </ EmptyDataTemplate> </ Asp: GridView> <Estilo de tabla = "width: 100%" > <tr> <Td style = "text-align: center;" > <Asp: Button ID = "btnGrabar" OnClick = "btnGrabar_Click" ancho = "100" Altura = "50" runat = "server" texto = "Grabar" /> <Asp: Button ID = "btnCancelar" OnClick = "btnCancelar_Click" ancho = "100" Altura = "50" runat = "server" texto = "Cancelar" /> </ Td> </ Tr> </ Table>
<Asp: Label ID = "lblMessage" runat = "server" text = ""> </ asp: Label> </ Fieldset> </ Div> </ Form> </ Body> </ Html>
CREATE PROCEDURE [dbo]. [proc_LISTA_TEMP_VENTAS] @ USER_LOGIN NVARCHAR (50) COMO SELECCIONAR T.id_venta_detalle_tmp, P.id_producto, P.producto, T.cantidad, T.p_venta, (T.cantidad * T.p_venta) COMO TOTALES DE Productos P JOIN venta_detalle_tmp T EN P.id_producto = T.id_producto JOIN unidad_medida M EN P.id_unidad_medida = M.id_unidad_medida DONDE T.user_login = @ USER_LOGIN GO USO [pventa] GO / ****** Objeto:. StoredProcedure [dbo] [proc_TEMP_VENTAS] Guin Fecha: 09/08/2011 17:14:49 ****** / SET ANSI_NULLS ON GO SET GO QUOTED_IDENTIFIER EN
CREATE
@ USER_LOGIN NVARCHAR (50), @ ID_PRODUCTO NVARCHAR (50), @ CANTIDAD FLOAT COMO / * GRABAR TMEP_VENTAS * / COMENZAR TRANSACCIN tVTA DECLARE @ PRECIO FLOAT , @ IVA FLOAT , @ EXISTENCIA FLOAT , @ CANT FLOAT , @ PRECIO = = = CANTIDAD + @ CANTIDAD DONDE user_login =
IF @ @ ERROR <> 0 GOTO ERROR COMMIT TRANSACCIN tVTA RETURN ERROR: RAISERROR ( 'No Se Puede agregar el Registro, 16,1) ROLLBACK TRANSACCIN tVTA GOTO FIN RETURN ERROR_A: RAISERROR ( 'El articulo no EXISTE, 16,1) ROLLBACK TRANSACCIN tVTA GOTO FIN RETURN ERROR_EXIST: RAISERROR ( 'No Hay suficientes existencias, 16,1) ROLLBACK TRANSACCIN tVTA GOTO FIN
RETURN FIN: GO USO [pventa] GO 09/08/2011 17:14:58 ****** /: / ****** Objeto:. StoredProcedure [dbo] [proc_VENTA] Guin Fecha SET ANSI_NULLS ON GO SET GO CREAR QUOTED_IDENTIFIER EN
PROCEDIMIENTO [dbo]. [proc_VENTA]) GOTO NOOPER - GRABAMOS LA VENTA INSERT EN VENTA (user_login, fecha_registro) VALORES (@ USER_LOGIN, GETDATE ()) - OBTENEMOS EL FOLIO DE LA VENTA SELECT @ FOLIO_VENTA = @ @ IDENTITY - INSERTAMOS EL DETALLE DE LA LAS EXISTENCIAS GENERALES ACTUALIZACIN Productos SET productos.EXISTENCIA =
productos.EXISTENCIA-venta_detalle_tmp. [CANTIDAD] DE venta_detalle_tmp DONDE productos.ID_PRODUCTO = venta_detalle_tmp.ID_PRODUCTO Y venta_detalle_tmp.user_login = @ USER_LOGIN - BORRAMOS LA TABLA TEMPORAL BORRAR DE venta_detalle_tmp DONDE user_login = @ user_login IF @ @ ERROR <> 0 GOTO ERROR SELECT @ FOLIO_VENTA COMMIT INTERCAMBIO tVTAs DEVUELTO
ERROR: RAISERROR ( 'No Se Puede grabar La Venta, 16,1) ROLLBACK TRANSACCIN tVTAs GOTO FIN RETURN NOOPER: RAISERROR ( 'No Hay Registros en La Lista de Ventas, 16,1) ROLLBACK TRANSACCIN tVTAs GOTO FIN RETURN FIN: GO
da.Fill (ds, "DATOS" ); grdVentas.DataSource = ds.Tables [ "DATOS" ]; grdVentas.DataBind (); ds.Dispose (); cmdReadData.Dispose (); cnnReadData.Close (); cnnReadData.Dispose (); } captura (Exception ex) { lblMessage.Text = ex.Message; } } bool Temp_Ventas ( string prmUSER_LOGIN, cadena prmID_PRODUCTO, doble prmCANTIDAD) { / / Para CARGAR La Venta TEMPORAL try { CnnTempVentas SqlConnection = nueva SqlConnection (clsMain.CnnStr); cnnTempVentas.Open (); SqlCommand cmdTempVentas = nuevo SqlCommand (); cmdTempVentas.Connection = cnnTempVentas; cmdTempVentas.CommandText = "EJECUTAR [proc_TEMP_VENTAS] '" + prmUSER_LOGIN + "','" + prmID_PRODUCTO + "'," + prmCANTIDAD + ""; cmdTempVentas.ExecuteNonQuery (); cnnTempVentas.Close (); cmdTempVentas.Dispose (); cnnTempVentas.Dispose (); txtID_PRODUCTO.Text = ""; txtCANTIDAD.Text = "1" ; regreso ( verdadero ); } captura (Exception ex) { lblMessage.Text = ex.Message; volver ( false ); } } protegidos void grdVentas_RowDataBound ( objeto emisor, GridViewRowEventArgs e) { si (== e.Row.RowType DataControlRowType.DataRow) { / / aadir el UnitPrice y QuantityTotal a las variables corrientes totales varTOTAL + = Convert.ToDouble (DataBinder.Eval (e. Row.DataItem, "TOTAL" )); }
ms
si (== e.Row.RowType DataControlRowType.Footer) { e.Row.Cells [3] = Texto. "TOTAL" ; e.Row.Cells [3] = HorizontalAlign HorizontalAlign.Right.; e.Row.Cells [3] = VerticalAlign VerticalAlign.Top.; / / Para el pie de pgina, mostrar los totales acumulados e.Row.Cells [4] = Texto varTOTAL.ToString (. "C" ); e.Row.Cells [4] HorizontalAlign = HorizontalAlign.Right.; e.Row.Cells [4] VerticalAlign = VerticalAlign.Top.; e.Row.Font.Bold = cierto ; lblTOTAL.Text = varTOTAL.ToString ( "C" ); / / establecemos en Blanco Las Celdas Que No Tienen dato
} } protegida void btnAgregar_Click ( objeto sender, EventArgs e) { intento { si (Temp_Ventas (User.Identity.Name, txtID_PRODUCTO.Text, Convert.ToDouble (txtCANTIDAD.Text))) { ReadData (User.Identity.Name); } } captura (Exception ex) { lblMessage.Text = ex.Message; } } privada { int RealizaVenta ( string prmUSER_LOGIN)
tratar { int varTICKET = 0; SqlConnection cnnGrabar = nueva SqlConnection (clsMain.CnnStr); cnnGrabar.Open (); SqlCommand cmdGrabar = nuevo SqlCommand (); cmdGrabar.Connection = cnnGrabar; cmdGrabar.CommandText = "EJECUTAR [proc_VENTA] '" + prmUSER_LOGIN + "'" ; varTICKET = Convert.ToInt32 (cmdGrabar.ExecuteScalar ()); / / LIBERAMOS LOS RECUSROS cnnGrabar.Close ();
cnnGrabar.Dispose (); cmdGrabar.Dispose (); La informacin / / mostramos regreso (varTICKET); } captura (Exception ex) { lblMessage.Text = ex.Message; regreso (0); } } privada bool CancelarVenta ( string prmUSER_LOGIN) { trate { CnnCancelar SqlConnection = nueva SqlConnection (clsMain.CnnStr); cnnCancelar.Open (); SqlCommand cmdCancelar = nuevo SqlCommand ( "DELETE FROM venta_detalle_tmp DONDE user_login = '" + prmUSER_LOGIN + "'" , cnnCancelar); cmdCancelar.ExecuteNonQuery (); cnnCancelar.Close (); cnnCancelar.Dispose (); cmdCancelar.Dispose (); volver ( verdadero ); } captura (Exception ex) { lblMessage.Text = ex.Message; volver ( false ); } } protegida void btnGrabar_Click ( objeto sender, EventArgs e) { try { int varTICKET = RealizaVenta (User.Identity.Name), si (varTICKET = 0) { Response.Redirect ( "default.aspx" ); } } captura (Exception ex) { lblMessage.Text = ex.Message; } } protegida void btnCancelar_Click ( objeto sender, EventArgs e) { intento {
Antes de Continuar, entremos ala de base de Datos y agreguemos Unidades de Medida y articulos. Asi s he Nuestro Formulario con articulos:
Reporte de Ventas Hasta aqui ya hicimos la parte mas complicada de todo, sin embargo, lo anterior no tiene ningun sentido si no podemos sacar reportes. Esa ser nuestra tarea ahora, obtener el reporte de Ventas. Agregamos una nueva pgina llamada reportes.aspx, marcar la opcin "Select master page" y seleccionen man.master:
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; verticalalign: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-ventas-ver.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>
>
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=\"ContentType\" 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(); }
GO CREATE PROCEDURE [dbo].[proc_RPT_VENTAS] @FECHA_INI DATETIME, @FECHA_FIN DATETIME AS SELECT V.id_venta,V.fecha_registro, P.id_producto,P.producto, D.cantidad,D.p_venta, D.cantidad*D.p_venta AS TOTAL FROM venta V JOIN venta_detalle D ON V.id_venta=V.id_venta JOIN productos P ON D.id_producto=P.id_producto WHERE V.fecha_registro BETWEEN @FECHA_INI AND @FECHA_FIN GO
<itemtemplate> <a %="" href="http://www.blogger.com/user.aspx?id=<%#Eval(" user_login?)="">">Editar</a> </itemtemplate> <itemstyle width="16"> <headertemplate> Editar </headertemplate> </itemstyle></asp:templatefield> <asp:boundfield datafield="user_login" headertext="Usuario"> <headerstyle horizontalalign="Left"> <itemstyle horizontalalign="Left"> </itemstyle></headerstyle></asp:boundfield> <asp:boundfield datafield="nombre" headertext="Nombre completo"> <headerstyle horizontalalign="Left"> <itemstyle horizontalalign="Left"> </itemstyle></headerstyle></asp:boundfield> </columns> </asp:gridview> </td> </tr> </tbody></table> </asp:content>
grdLista.DataSource = ds.Tables["USERS"]; grdLista.DataBind(); cnn.Close(); cnn.Dispose(); ds.Dispose(); da.Dispose(); } catch (Exception ex){ lblMessage.Text = ex.Message; } }
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-right-width: 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>
if (!Page.IsPostBack){ if (!Context.User.Identity.IsAuthenticated){ FormsAuthentication.RedirectToLoginPage("login.aspx"); } else{ if (Request.Params["id"].ToString() == "0"){ //Nuevo btnGrabar.Enabled = true; } else{ //editar txtUSER_LOGIN.Enabled = false; ReadData(Request.Params["id"].ToString()); } } } } catch (Exception ex){ 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; } }
@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