Sie sind auf Seite 1von 20

Sistema de gestión de login y usuarios en ASP.NET 2.

0 y
VB.net
Vamos a crear un sistema con ASP.NET y VB.NET 2.0 en el que gestionaremos los usuarios de
nuestra web, la seguridad, y el permiso de acceso a la web mediante un sistema de login. Este
caso vamos a crear la estructura de ficheros y de base de datos.
Usaremos Visual Studio 2005 y SQL Server Express.

En la estructura de nuestro proyecto web, crearemos las carpetas de sistema ASP.NET, que serian
App_Code, y App_Data, y además crearemos una carpeta ordinaria llamada Users.

Dentro de la carpeta Users, añadiremos las páginas web, delete.aspx, login.aspx, modify.aspx,
newuser.aspx y profile.aspx.

Luego en cuando a ficheros, crearemos los archivos, MasterPage.master (Pagina maestra, Page
Master), Web.sitemap (Site map, Mapa del sitio). Estos archivos al hacer clic con el botón derecho,
podremos añadirlos en el menú añadir nuevo elemento.

Y para finalizar vamos a crear la base de datos y la tabla que usaremos para almacenar toda la
información de los usuarios. Pulsamos con el botón derecho en la carpeta ya creada App_Data, y
pinchamos en crear un nuevo elemento, que en este caso, solo nos mostrara una base de datos.
Le dejamos su nombre Database.mdf, y salvamos.

Vamos al Explorador de Servidores, y allí veremos Conexiones de datos y Servidores. Dentro de


Conexiones de datos, podremos ver nuestra base de datos sobre la que vamos a pulsar para
abrirla. En la carpeta Tablas vamos a clicar con el botón derecho y vamos a crear una nueva con
estos campos o columnas y que tengan estos tipos de datos:

Nombre del campo Tipo de dato Acepta Nulos


ID bigint No
UserName nvarchar(50) No
Password nvarchar(50) No
Active bit No
Comments varchar(MAX) Si
Date_In datetime No
Date_Out datetime No
Admin bit Si
Sobre el campo ID dentro de sus propiedades lo haremos lo que en Access se llamaba campo
autonumerico, es decir, en la jerga del nuevo SQL Server, se llama que es identidad, y lo
cambiaremos de no, a SI.

Si no usáis el SQL Express, y usáis el SQL Management Studio, o el SQL Server 2005, también
podréis crear la tabla con este código ejecutándolo como un procedimiento almacenado.

CREATE TABLE [dbo].[tblUsers](


[ID] [bigint] IDENTITY(1,1) NOT NULL,
[UserName] [nvarchar](50) NULL,
[Password] [nvarchar](50) NULL,
[Active] [bit] NULL,
[Comments] [varchar](max) NOT NULL,
[Date_In] [datetime] NULL,
[Date_Out] [datetime] NULL,
[Admin] [bit] NOT NULL,
CONSTRAINT [PK_Table_1] PRIMARY KEY CLUSTERED
(
[ID] 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
SET ANSI_PADDING OFF

Nos centraremos ahora en el código de los procedimientos almacenados.


Vamos a crearlos dentro de nuestra base de datos, bien mediante el explorador de servidores en
nuestro visual studio o bien desde sql management studio, pero recomendamos el visual studio
por su simplicidad.
Entramos en la base de datos y dentro de la carpeta de los procedimientos almacenados, hacemos
clic con el botón derecho y damos a crear procedimiento almacenado nuevo. En la ventana que
nos sale pegamos el código que se encuentra a continuación, y le damos a grabar o salvar, tan
simple como eso.

Aquí tenéis.

ALTER PROCEDURE dbo.UserRead


(
@ID bigint
)

AS

SELECT ID, UserName, Password, Active, Comments, Date_In, Date_Out


FROM tblUsers
WHERE Admin = 0 and ID = @ID

RETURN

ALTER PROCEDURE dbo.UserModify


(
@ID bigint,
@UserName nvarchar(50),
@Password nvarchar(50),
@Comments varchar(MAX),
@Active bit,
@Date_Out datetime
)
AS

UPDATE tblUsers SET


UserName = @UserName ,
Password = @Password ,
Active = @Active,
Comments = @Comments,
Date_Out = @Date_Out
WHERE ID = @ID
RETURN 0

ALTER PROCEDURE dbo.UserLogin


(
@UserName nvarchar(50),
@Password nvarchar(50)
)
AS

if (Select admin From tblUsers Where UserName = @UserName and Password = @Password) = 1
BEGIN
Select * From tblUsers Where UserName = @UserName and Password = @Password
END
ELSE
BEGIN

Select * From tblUsers Where UserName = @UserName and Password = @Password and Active =
1 and Date_out > GETDATE()
END

RETURN

ALTER PROCEDURE dbo.UserDelete


(
@ID bigint
)
AS

DECLARE @userexists nvarchar(50)

SET @userexists = (SELECT COUNT(*) FROM tblUsers Where ID = @ID)

IF @userexists = 0
BEGIN
RETURN 0
END

ELSE

BEGIN

DELETE FROM tblUsers WHERE ID = @ID


SET @userexists = (SELECT COUNT(*) FROM tblUsers Where ID = @ID)

IF @userexists = 0
BEGIN
RETURN 0
END
ELSE
BEGIN
RETURN -1
END
END

ALTER PROCEDURE dbo.UserAdd


(
@UserName nvarchar(50),
@Password nvarchar(50),
@Active bit,
@Comments varchar(MAX)
)
AS

DECLARE @userexists nvarchar(50)

SET @userexists = (SELECT COUNT(*) FROM tblUsers Where UserName = @UserName)

IF @userexists > 0
BEGIN
RETURN -1--User Exists
END

ELSE

BEGIN

INSERT INTO tblUsers


(
UserName,
Password,
Active,
Comments,
Date_In,
Date_Out,
admin
)

Values
(
@UserName,
@Password,
@Active,
@Comments,
GETDATE(),
GETDATE() + 365,
0
)
RETURN 0
END

ALTER PROCEDURE dbo.GetUsers

AS

SELECT tblUsers.ID, tblUsers.UserName, Password, Active, Comments, Date_In,


Date_Out
FROM tblUsers
WHERE tblUsers.Admin= 0

RETURN
Los archivos, delete.aspx, login.aspx, modify.aspx, newuser.aspx y profile.aspx, llevaran el código
html que vera el usuario. Y Los archivos, delete.vb, login.vb, modify.vb, newuser.vb y profile.vb,
llevarán el código fuente que se ejecutara en el servidor.

Luego, MasterPage.master (Pagina maestra, Page Master), Web.config, Web.sitemap (Site map,
Mapa del sitio), son los algunos de archivos que se han añadido en el nuevo .NET 2.0 que nos
hacen la vida mas fácil a los programadores.

web.config:

<?xml version="1.0"?>
<configuration>
<appSettings/>
<connectionStrings>
<remove name="DataBase"/>
<add name="DataBase" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|
DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True"/>
</connectionStrings>
<system.web>
<compilation debug="true">
<assemblies>
<add assembly="System.Windows.Forms, Version=2.0.0.0, Culture=neutral,
PublicKeyToken=B77A5C561934E089"/>
</assemblies>
</compilation>
<authentication mode="Forms">
<forms name="form_Auth" path="/" loginUrl="users/login.aspx" protection="All"
timeout="10"/>
</authentication>
<authorization>
<allow users="*"/>
</authorization>
</system.web>
<location path="users">
<system.web>
<authorization>
<deny users="?"/>
</authorization>
</system.web>
</location>
</configuration>

MasterPage.master:

<%@ Master Language="VB" CodeFile="MasterPage.master.vb" Inherits="MasterPage" %>

<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<asp:LoginView ID="LoginView1" runat="server">
<AnonymousTemplate>
No estas conectado.
</AnonymousTemplate>
<LoggedInTemplate>
<asp:Menu ID="Menu1" runat="server" DataSourceID="SiteMapDataSource1"
Orientation="Horizontal"
MaximumDynamicDisplayLevels="0" StaticDisplayLevels="2" />
<asp:SiteMapPath ID="SiteMapPath1" runat="server" />
</LoggedInTemplate>
</asp:LoginView>
|
<asp:LoginStatus ID="lsUser" LogoutPageUrl="~/Default.aspx" runat="server"
LoginText="Conectarse" LogoutText="Desconectarse" />
<hr />
<asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
</asp:ContentPlaceHolder>
<asp:SiteMapDataSource ID="SiteMapDataSource1" runat="server" />
</form>
</body>
</html>

Web.sitemap:

<?xml version="1.0" encoding="utf-8" ?>


<siteMap>
<siteMapNode title="Principal" description="Principal" url="~/users/profile.aspx">
</siteMapNode>
</siteMap>

Default.aspx:

<%@ Page Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false"


CodeFile="Default.aspx.vb" Inherits="_Default" title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
Hola a todos!<br />
<br />
</asp:Content>

Y dentro de la carpeta users tenemos:


users/newuser.aspx:

<%@ Page Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false"


CodeFile="newuser.aspx.vb" Inherits="newuser" title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<table border="0" cellpadding="1" cellspacing="1">
<tr>
<td style="width: 100px">
<asp:Label ID="Label1" runat="server" Text="Nombre Usuario:"></asp:Label></td>
<td style="width: 125px">
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox><asp:RequiredFieldValidator
ID="RequiredFieldValidator1" runat="server" ControlToValidate="txtUserName"
ErrorMessage="Nombre Usuario requerido">*</asp:RequiredFieldValidator></td>
</tr>
<tr>
<td style="width: 100px">
<asp:Label ID="Label2" runat="server" Text="Password:"></asp:Label></td>
<td style="width: 125px">
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox><asp:RequiredFieldValidator
ID="RequiredFieldValidator2" runat="server" ControlToValidate="txtPassword"
ErrorMessage="Password requerido">*</asp:RequiredFieldValidator></td>
</tr>
<tr>
<td style="width: 100px">
<asp:Label ID="Label6" runat="server" Text="Activo:"></asp:Label></td>
<td style="width: 125px">
<asp:CheckBox ID="chkActive" runat="server" Checked="True" /></td>
</tr>
<tr>
<td style="width: 100px; height: 74px">
<asp:Label ID="Label5" runat="server" Text="Comentarios:"></asp:Label></td>
<td style="width: 125px; height: 74px">
<asp:TextBox ID="txtComments" runat="server" Height="121px"
Width="269px"></asp:TextBox></td>
</tr>
</table>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" HeaderText="Tienes que
poner un valor en los siguientes campos:"
ShowMessageBox="True" ShowSummary="False" />
<br />
<asp:Button ID="btnAdd" runat="server" Text="Añadir" />
<asp:Label ID="lblTextReturn" runat="server"></asp:Label>
</asp:Content>

users/modify.aspx:

<%@ Page Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false"


CodeFile="modify.aspx.vb" Inherits="users_modify" title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<table border="0">
<tr>
<td style="width: 100px">
<asp:Label ID="Label1" runat="server" Text="Nombre Usuario:"></asp:Label></td>
<td style="width: 141px">
<asp:TextBox ID="txtUserName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server"
ControlToValidate="txtUserName"
ErrorMessage="Nombre de usuario requerido.">*</asp:RequiredFieldValidator></td>
<td style="width: 100px">
</td>
<td rowspan="5" style="width: 149px" valign="top">
<asp:Calendar ID="clDateOut" runat="server" Visible="False" BackColor="White"
BorderColor="#999999" CellPadding="4" DayNameFormat="Shortest" Font-Names="Verdana"
Font-Size="8pt" ForeColor="Black" Height="180px" Width="200px">
<SelectedDayStyle BackColor="#666666" Font-Bold="True" ForeColor="White" />
<SelectorStyle BackColor="#CCCCCC" />
<WeekendDayStyle BackColor="#FFFFCC" />
<TodayDayStyle BackColor="#CCCCCC" ForeColor="Black" />
<OtherMonthDayStyle ForeColor="#808080" />
<NextPrevStyle VerticalAlign="Bottom" />
<DayHeaderStyle BackColor="#CCCCCC" Font-Bold="True" Font-Size="7pt" />
<TitleStyle BackColor="#999999" BorderColor="Black" Font-Bold="True" />
</asp:Calendar>
</td>
</tr>
<tr>
<td style="width: 100px">
<asp:Label ID="Label2" runat="server" Text="Password:"></asp:Label></td>
<td style="width: 141px">
<asp:TextBox ID="txtPassword" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="RequiredFieldValidator2" runat="server"
ControlToValidate="txtPassword"
ErrorMessage="Password requerido.">*</asp:RequiredFieldValidator></td>
<td style="width: 100px">
</td>
</tr>
<tr>
<td style="width: 100px">
<asp:Label ID="Label7" runat="server" Text="Activo:"></asp:Label></td>
<td style="width: 141px">
<asp:CheckBox ID="chkActive" runat="server" /></td>
<td style="width: 100px">
</td>
</tr>
<tr>
<td style="width: 100px">
<asp:Label ID="Label5" runat="server" Text="Fecha Baja:"></asp:Label></td>
<td style="width: 141px">
<asp:TextBox ID="txtFechaBaja" runat="server"></asp:TextBox><br />
<asp:RequiredFieldValidator ID="RequiredFieldValidator4" runat="server"
ControlToValidate="txtFechaBaja"
ErrorMessage="Fecha de baja
requerida.">*</asp:RequiredFieldValidator><asp:CustomValidator
ID="CustomValidator1" runat="server" ControlToValidate="txtFechaBaja" ValidateEmptyText
=true
OnServerValidate="ServerValidation" ErrorMessage="La fecha no tiene un formato valido o
es pasada.">*</asp:CustomValidator></td>
<td style="width: 100px">
&nbsp;<asp:Button CausesValidation=false ID="btnCal" runat="server" Text="Calendario"
/></td>
</tr>
<tr>
<td style="width: 100px">
<asp:Label ID="Label6" runat="server" Text="Comentarios:"></asp:Label></td>
<td style="width: 141px">
<asp:TextBox ID="txtComments" runat="server" Height="96px"
TextMode="MultiLine"></asp:TextBox></td>
<td style="width: 100px">
<asp:Button ID="btnModify" runat="server" Text="Modificar" /></td>
</tr>
</table>
<asp:ValidationSummary ID="ValidationSummary1" runat="server" HeaderText="Tienes que
poner un valor en los siguientes campos:"
ShowMessageBox="False" ShowSummary="true" />
<br />
<asp:Label ID="lblMessages" runat="server"></asp:Label>
&nbsp;
&nbsp; &nbsp;&nbsp;
</asp:Content>

users/login.aspx:

<%@ Page Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false"


CodeFile="login.aspx.vb" Inherits="users_login" Title="Untitled Page" %>

<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">


<asp:Login ID="lgLogin" runat="server" DestinationPageUrl="~/users/profile.aspx"
DisplayRememberMe="True" FailureText="Login no valido, intentelo otra vez."
LoginButtonText="Enviar" PasswordRequiredErrorMessage="El Password es requerido."
RememberMeText="Recordarme la proxima vez." TitleText="Conectarse a Gestmobil"
UserNameLabelText="Usuario:" UserNameRequiredErrorMessage="El nombre de usuario es
requerido.">
</asp:Login>
</asp:Content>

users/profile.aspx:

<%@ Page Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false"


CodeFile="profile.aspx.vb" Inherits="profile" title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Button ID="btnAddUser" runat="server" Text="Nuevo Usuario" />
<br />
<asp:GridView ID="gvUsers" runat="server" Caption="Usuarios" GridLines="Horizontal"
AutoGenerateColumns="False">
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" Visible="False" />
<asp:BoundField DataField="UserName" HeaderText="Usuario" />
<asp:BoundField DataField="Password" HeaderText="Password" />
<asp:BoundField HeaderText="Fecha Entrada" DataField="Date_In" DataFormatString="{0:dd-
MMM-yyyy}" />
<asp:BoundField HeaderText="Fecha Salida" DataField="Date_Out" DataFormatString="{0:dd-
MMM-yyyy}" />
<asp:BoundField HeaderText="Activo" DataField="Active" />
<asp:HyperLinkField DataNavigateUrlFields="ID" DataNavigateUrlFormatString="modify.aspx?
id={0}"
DataTextField="ID" DataTextFormatString="Modificar" HeaderText="Modificar" />
<asp:HyperLinkField DataNavigateUrlFields="ID" DataNavigateUrlFormatString="delete.aspx?
id={0}"
DataTextField="ID" DataTextFormatString="Borrar" HeaderText="Borrar" />
</Columns>
</asp:GridView>
<asp:Label ID="lblMessages" runat="server"></asp:Label><br />
</asp:Content>

users/delete.aspx:

<%@ Page Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false"


CodeFile="delete.aspx.vb" Inherits="users_delete" title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Label ID="lblUserNumber" runat="server"></asp:Label><br />
<asp:Button ID="btnDelete" runat="server" Text="Borrar" />
</asp:Content>

Y terminamos la coleccion de documentos sobre el registro en la web con este documento.

Y terminamos con el codigo de las paginas correspondientes. Recordaros que todas nuestras
clases usan nuestra propia libreria de acceso a datos.

profile.vb:

Partial Class profile


Inherits System.Web.UI.Page

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


Me.Load
If Not Page.IsPostBack Then
Dim User As New dllUser
Try
gvUsers.DataSource = User.GetUsers
gvUsers.DataBind()

Catch ex As Exception
lblMessages.Text = User.Errors
End Try
User = Nothing
End If
End Sub

Protected Sub btnAddUser_Click(ByVal sender As Object, ByVal e As System.EventArgs)


Handles btnAddUser.Click
Response.Redirect("newuser.aspx")
End Sub

End Class

newuser.vb:

Partial Class newuser


Inherits System.Web.UI.Page

Protected Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles


btnAdd.Click
Dim User As New dllUser()

User.UserName = txtUserName.Text
User.Password = txtPassword.Text
User.Comments = txtComments.Text
User.Active = chkActive.Checked

If User.UserAdd Then

lblTextReturn.Text = "Hecho"

txtUserName.Text = ""
txtPassword.Text = ""
txtComments.Text = ""
chkActive.Checked = False

Else
lblTextReturn.Text = User.ErrorsUser
End If
User = Nothing

End Sub

End Class

modify.vb:

Partial Class users_modify


Inherits System.Web.UI.Page

Sub ServerValidation(ByVal source As Object, ByVal arguments As ServerValidateEventArgs)

'Dim num As Integer = Integer.Parse(arguments.Value)


'arguments.IsValid = ((num Mod 2) = 0)
arguments.IsValid = IsDate(arguments.Value) AndAlso arguments.Value > Now
End Sub

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


Me.Load
If Not Page.IsPostBack Then
If Request("ID").Trim.Length > 0 Then
Dim User As New dllUser
If User.UserRead(Request("ID")) Then
txtPassword.Text = User.Password
txtUserName.Text = User.UserName
chkActive.Checked = User.Active
If User.Date_Out <> #1/1/1900# Then
txtFechaBaja.Text = User.Date_Out
Else
txtFechaBaja.Text = ""
End If
txtComments.Text = User.Comments
Else
lblMessages.Text = User.ErrorsUser
End If
User = Nothing
Else
lblMessages.Text = "Debe especificar un usuario."
End If
End If
End Sub

Protected Sub btnModify_Click(ByVal sender As Object, ByVal e As System.EventArgs)


Handles btnModify.Click
If Request("ID").Trim.Length > 0 Then
If Page.IsValid Then
Try
Dim User As New dllUser
User.UserName = txtUserName.Text
User.Password = txtPassword.Text
User.Comments = txtComments.Text
If txtFechaBaja.Text.Trim.Length > 0 Then
User.Date_Out = txtFechaBaja.Text
End If
User.Active = chkActive.Checked

If User.UserModify(Request("ID")) Then
lblMessages.Text = "Usuario modificado correctamente."
Else
lblMessages.Text = User.ErrorsUser
End If
User = Nothing
Catch ex As Exception
lblMessages.Text = ex.Message
End Try
Else
lblMessages.Text = "Hay elementos no validos en la pagina."
End If
Else
lblMessages.Text = "Debe especificar un usuario."
End If
End Sub

Protected Sub btnCal_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles


btnCal.Click
clDateOut.Visible = True
End Sub

Protected Sub clDateOut_SelectionChanged(ByVal sender As Object, ByVal e As


System.EventArgs) Handles clDateOut.SelectionChanged
txtFechaBaja.Text = clDateOut.SelectedDate
If clDateOut.SelectedDate < Now Then
chkActive.Checked = False
End If
End Sub

End Class

login.vb:

Partial Class users_login


Inherits System.Web.UI.Page

Private Function ValidateUser(ByVal User As String, ByVal Pass As String) As Boolean


Dim UserLogin As New dllUser()
If UserLogin.Login(User, Pass) Then
Return True
End If
UserLogin = Nothing
End Function

Protected Sub lgLogin_Authenticate(ByVal sender As Object, ByVal e As


System.Web.UI.WebControls.AuthenticateEventArgs) Handles lgLogin.Authenticate
If ValidateUser(lgLogin.UserName, lgLogin.Password) Then
e.Authenticated = True
End If
End Sub

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


Me.Load
lgLogin.Focus()
End Sub
End Class

delete.vb:

Partial Class users_delete


Inherits System.Web.UI.Page

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


Me.Load
If Not Page.IsPostBack Then
lblUserNumber.Text = " Desea borrar al usuario " & Request("ID") & "?"
End If
End Sub

Protected Sub btnDelete_Click(ByVal sender As Object, ByVal e As System.EventArgs)


Handles btnDelete.Click
Dim User As New dllUser()
If User.UserDelete(Request("ID")) Then
lblUserNumber.Text = "Borrado"
btnDelete.Visible = False
Else
lblUserNumber.Text = User.ErrorsUser
End If
User = Nothing
End Sub
End Class

dlluser.vb:

Public Class dllUser


Inherits dllBase

Private _UserName As String


Private _Password As String
Private _Active As Boolean 'Desactivará momentáneamente la descarga para esa tienda.
Private _Date_In As Date
Private _Date_Out As Date 'Esto permitirá que el aplicativo ya no se pueda usar por una
tienda.
Private _Comments As String

Private _Return_Value As Integer


Private _Errors As String

Public ReadOnly Property ErrorsUser() As String


Get
ErrorsUser = _Errors
End Get
End Property

Public Sub New()


MyBase.New()
End Sub
Protected Overrides Sub Finalize()
MyBase.Finalize()
End Sub

Public Property UserName() As String


Get
UserName = _UserName
End Get
Set(ByVal value As String)
_UserName = value
End Set
End Property
Public Property Password() As String
Get
Password = _Password
End Get
Set(ByVal value As String)
_Password = value
End Set
End Property
Public Property Active() As Boolean
Get
Active = _Active
End Get
Set(ByVal value As Boolean)
_Active = value
End Set
End Property
Public Property Date_New() As Date
Get
Date_New = _Date_In
End Get
Set(ByVal value As Date)
_Date_In = value
End Set
End Property
Public Property Date_Out() As Date
Get
Date_Out = _Date_Out
End Get
Set(ByVal value As Date)
_Date_Out = value
End Set
End Property
Public Property Comments() As String
Get
Comments = _Comments
End Get
Set(ByVal value As String)
_Comments = value
End Set
End Property
Public Property Return_Value() As Integer
Get
Return_Value = _Return_Value
End Get
Set(ByVal value As Integer)
_Return_Value = value
End Set
End Property

Public Function Login(ByVal UserName As String, ByVal Password As String) As Boolean


Dim Parameters(1) As String, ParametersValue(1) As String

Parameters(0) = "@UserName"
ParametersValue(0) = UserName
Parameters(1) = "@Password"
ParametersValue(1) = Password

Try
If cData.Connect() Then
cData.ErrorsClear()
If Not cData.ReadDataStoreProcPrepare("UserLogin", Parameters, ParametersValue) Then
_Errors = cData.Errors
Login = False
Else
cData.ReadDataStoreProcPrepareExecute()
If cData.ReadHaveData Then Login = True
End If
cData.ReadDataStoreProcClose()
cData.Disconnect()
Else
Login = False
_Errors = "No se pudo conectar con la base de datos."
End If
Catch ex As Exception
Login = False
_Errors = ex.Message
End Try

End Function

Public Function GetPassword() As String


Dim Parameters(0) As String, ParametersValue(0) As String

Parameters(0) = "@Email"
ParametersValue(0) = My.User.Name

If cData.Connect() Then
cData.ReadDataStoreProcPrepare("UserGetPassword", Parameters, ParametersValue)
Dim a As Data.DataSet = cData.ReadDataStoreProc
GetPassword = cData.ReadSP("Password")
'GetPassword = a.Tables(0).Rows(0).Item("Password")
cData.ReadDataStoreProcClose()
cData.Disconnect()
End If
End Function

Public Function ChangePassword(ByVal NewP As String) As Boolean


Dim Parameters(1) As String, ParametersValue(1) As String

Parameters(0) = "@Email"
ParametersValue(0) = My.User.Name
Parameters(1) = "@Password"
ParametersValue(1) = NewP

If cData.Connect() Then
If Not cData.ReadDataStoreProcExecute("UserChangePassword", Parameters, ParametersValue)
Then
ChangePassword = False
Else
ChangePassword = True
End If
cData.ReadDataStoreProcClose()
cData.Disconnect()
End If
End Function

Public Function UserDelete(ByVal ID As Integer) As Boolean


Dim Parameters(0) As String, ParametersValue(0) As String

Parameters(0) = "@ID"
ParametersValue(0) = ID

Try
If cData.Connect() Then
cData.ErrorsClear()
If cData.ReadDataStoreProcExecute("UserDelete", Parameters, ParametersValue) Then
If cData.Return_Val = 0 Then
UserDelete = True
Else
_Errors = "Usuario no existia."
End If
Else
_Errors = cData.Errors
UserDelete = False
End If
cData.ReadDataStoreProcClose()
cData.Disconnect()
Else
_Errors = "No se pudo conectar con la base de datos."
UserDelete = False
End If
Catch ex As Exception
_Errors = ex.Message
End Try
End Function

Public Function UserAdd() As Boolean

Dim Parameters(3) As String, ParametersValue(3) As String

Parameters(0) = "@UserName"
Parameters(1) = "@Password"
Parameters(2) = "@Comments"
Parameters(3) = "@Active"

ParametersValue(0) = _UserName
ParametersValue(1) = _Password
ParametersValue(2) = _Comments
ParametersValue(3) = _Active

If cData.Connect() Then
cData.ErrorsClear()
If Not cData.ReadDataStoreProcExecute("UserAdd", Parameters, ParametersValue) Then
_Errors = cData.Errors
Else
If cData.Return_Val = "-1" Then
_Errors = "El nombre de usuario ya existe."
ElseIf cData.Return_Val = 0 Then
UserAdd = True
End If
End If
cData.ReadDataStoreProcClose()
cData.Disconnect()
Else
_Errors = "No se pudo conectar con la base de datos."
UserAdd = False
End If

End Function

Public Function UserModify(ByVal ID As Long) As Boolean

Dim Parameters(5) As String, ParametersValue(5) As String

Parameters(0) = "@ID"
Parameters(1) = "@UserName"
Parameters(2) = "@Password"
Parameters(3) = "@Comments"
Parameters(4) = "@Active"
Parameters(5) = "@Date_Out"

ParametersValue(0) = ID
ParametersValue(1) = _UserName
ParametersValue(2) = _Password
ParametersValue(3) = _Comments
ParametersValue(4) = _Active
ParametersValue(5) = _Date_Out

Try
If cData.Connect() Then
cData.ErrorsClear()
If Not cData.ReadDataStoreProcExecute("UserModify", Parameters, ParametersValue) Then
_Errors = cData.Errors
Else
If cData.Return_Val = 0 Then
UserModify = True
End If
End If
cData.ReadDataStoreProcClose()
cData.Disconnect()
Else
_Errors = "No se pudo conectar con la base de datos."
UserModify = False
End If
Catch ex As Exception
_Errors = ex.Message
End Try
End Function

Public Function GetMessages() As Data.DataSet


Dim Parameters(0) As String, ParametersValue(0) As String

Parameters(0) = "@Email"
ParametersValue(0) = My.User.Name

If cData.Connect() Then
If cData.ReadDataStoreProcPrepare("UserGetMessages", Parameters, ParametersValue) Then
GetMessages = cData.ReadDataStoreProc()
cData.ReadDataStoreProcClose()
cData.Disconnect()
Else
_Errors = "Can't read the messages."
End If
Else
_Errors = "Cant connect with the database."
End If
End Function

Public Function GetMessagesByMonth(ByVal Month As Integer) As Data.DataSet


Dim Parameters(1) As String, ParametersValue(1) As String

Parameters(0) = "@Email"
ParametersValue(0) = My.User.Name
Parameters(1) = "@Month"
ParametersValue(1) = Month

If cData.Connect() Then
If cData.ReadDataStoreProcPrepare("UserGetMessagesByMonth", Parameters, ParametersValue)
Then
GetMessagesByMonth = cData.ReadDataStoreProc()
cData.ReadDataStoreProcClose()
cData.Disconnect()
Else
_Errors = "Can't read the messages."
End If
Else
_Errors = "Cant connect with the database."
End If
End Function

Public Function GetMessagesSearch(ByVal Str As String) As Data.DataSet


Dim Parameters(1) As String, ParametersValue(1) As String

Parameters(0) = "@Email"
ParametersValue(0) = My.User.Name
Parameters(1) = "@String"
ParametersValue(1) = Str

If cData.Connect() Then
If cData.ReadDataStoreProcPrepare("UserGetMessagesSearch", Parameters, ParametersValue)
Then
GetMessagesSearch = cData.ReadDataStoreProc()
cData.ReadDataStoreProcClose()
cData.Disconnect()
Else
_Errors = "Can't read the messages."
End If
Else
_Errors = "Cant connect with the database."
End If
End Function

Public Function UserRead(ByVal ID As Long) As Boolean


Dim Parameters(0) As String, ParametersValue(0) As String
Dim DS As New Data.DataSet

If ID > 0 Then
Try
Parameters(0) = "@ID"
ParametersValue(0) = ID

If cData.Connect() Then
cData.ErrorsClear()
If cData.ReadDataStoreProcPrepare("UserRead", Parameters, ParametersValue) Then
DS = cData.ReadDataStoreProc()
'_Nombre_Tienda = cData.ReadSP("Nombre_Tienda")
With DS.Tables(0).Rows(0)
_Password = .Item("Password")
_UserName = .Item("UserName")
_Active = .Item("Active")
_Date_Out = IIf(.Item("Date_Out") Is DBNull.Value, "#12:00:00 AM#", .Item("Date_Out"))
_Date_In = .Item("Date_In")
_Comments = .Item("Comments")
End With
UserRead = True
Else
_Errors = cData.Errors
End If
cData.ReadDataStoreProcClose()
cData.Disconnect()
Else
_Errors = "Cant connect with the database."
End If

Catch ex As Exception
_Errors = ex.Message
End Try
Else
_Errors = "User not provided."
End If
End Function

Public Function GetUsers() As Data.DataSet


If cData.Connect() Then
cData.ErrorsClear()
If cData.ReadDataStoreProcPrepare("GetUsers") Then
GetUsers = cData.ReadDataStoreProc()
cData.ReadDataStoreProcClose()
cData.Disconnect()
Else
_Errors = cData.Errors
End If
Else
_Errors = "Cant connect with the database."
End If
End Function

End Class

dllbase.vb:

Imports System.Configuration.ConfigurationManager
Imports GBData

Public Class dllBase

Friend _ID As String


Private ConnectionPath As String = ConnectionStrings("DataBase").ConnectionString

Friend cData As dllData

Public Function Errors() As String


Errors = cData.Errors
End Function

Friend Sub New()


cData = New dllData
cData.OriginData = 2
cData.Path = ConnectionPath
End Sub
Protected Overrides Sub Finalize()
cData = Nothing
MyBase.Finalize()
End Sub

Public Property ID() As String


Get
ID = _ID
End Get
Set(ByVal value As String)
_ID = value
End Set
End Property

End Class