Vous êtes sur la page 1sur 46

Sistema de gestin de login y usuarios en ASP.NET 2.0 y VB.net Por Alvaro 04/03/2009 Enviar esta pagina a un amigo.

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 adems crearemos una carpeta ordinaria llamada Users. Dentro de la carpeta Users, aadiremos las pginas 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 botn derecho, podremos aadirlos en el men aadir nuevo elemento. Y para finalizar vamos a crear la base de datos y la tabla que usaremos para almacenar toda la informacin de los usuarios. Pulsamos con el botn 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 botn 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 usis el SQL Express, y usis el SQL Management Studio, o el SQL Server 2005, tambin podris crear la tabla con este cdigo ejecutndolo 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

Sistema de gestin de login y usuarios en ASP.NET 2.0 y VB.net (2) Por Alvaro 05/03/2009 Enviar esta pagina a un amigo. Nos centraremos ahora en el cdigo 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 botn derecho y damos a crear procedimiento almacenado nuevo. En la ventana que nos sale pegamos el cdigo que se encuentra a continuacin, y le damos a grabar o salvar, tan simple como eso. Aqu tenis. 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 Sistema de gestin de login y usuarios en ASP.NET 2.0 y VB.net (3) Por Alvaro 06/03/2009 Enviar esta pagina a un amigo. Vamos con la tercera parte. Los archivos, delete.aspx, login.aspx, modify.aspx, newuser.aspx y profile.aspx, llevaran el cdigo html que vera el usuario. Y Los archivos, delete.vb, login.vb, modify.vb, newuser.vb y profile.vb, llevarn el cdigo 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 aadido en el nuevo .NET 2.0 que nos hacen la vida mas fcil 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="Aadir" /> <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" FontNames="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>

Sistema de gestin de login y usuarios en ASP.NET 2.0 y VB.net (4) Por Alvaro 09/03/2009 Enviar esta pagina a un amigo. 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 momentneamente 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

Librera de acceso a bases de datos con ADO.NET 2.0 Por Alvaro 02/03/2009 Enviar esta pagina a un amigo. Con esta librera podrs acceder a Access, Sql Server, MySQL sin esfuerzo. Es sencilla e intuitiva, y te ahorrar muchas lneas de cdigo y tiempo evitando tener que tratar todo el cdigo ADO.NET. As que si no lo entiendes, no te apetece aprenderlo, o simplemente quieres un atajo, esta librera puede ayudarte. Puedes mandar consultas, SQL, llamar a procedimientos almacenados, usar transacciones, TODO! :) Esta en versin BETA y, aunque yo la uso siempre, si tienes algn problema, sugerencia, la quieres mejorar, o comentario que hacer, no dudes en contactarme en mi pagina de contacto. Imports System.Data Imports System.Data.Odbc Imports System.Data.OleDb Imports System.Data.SqlClient 'Imports MySql.Data.MySqlClient Imports System.IO Imports System.Web.UI.WebControls Public Class dllData Dim cPath As String Dim cOriginData As Double = 0 Dim cSqlDataSource As String = "localhost" Dim cSqlDatabase As String Dim cSqlUserID As String = "root" Dim cSqlPassword As String Dim cDataConnectionOle As OleDbConnection Dim cDataCommandOle As OleDbCommand Dim cDataConnectionODBC As OdbcConnection Dim cDataCommandODBC As OdbcCommand Dim cDataConnectionSQL As SqlConnection Dim cDataCommandSQL As SqlCommand 'Dim cDataConnectionMySQL As MySqlConnection 'Dim cDataCommandMySQL As MySqlCommand Dim cDataOleDB As OleDbDataReader Dim cDataODBC As OdbcDataReader

Dim cDataSQL As SqlDataReader 'Dim cDataMySQL As MySqlDataReader Dim cDataTransOle As OleDbTransaction Dim cDataTransODBC As OdbcTransaction Dim cDataTransSQL As SqlTransaction 'Dim cDataTransMySQL As MySqlTransaction Dim cDataDataAdapter As Object Dim cRowsAffected As Long Dim _Return_Val As Object Dim cErrors As String Public ReadOnly Property Errors() As String Get Errors = cErrors 'ClearErrors() End Get End Property Public Sub ErrorsClear() cErrors = "" End Sub Public Property Path() As String Get Path = cPath End Get Set(ByVal Value As String) cPath = Value End Set End Property Public Property Return_Val() As String Get Return_Val = _Return_Val End Get Set(ByVal Value As String) _Return_Val = Value End Set End Property Public Property SQLDataSource() As String Get

SQLDataSource = cSqlDataSource End Get Set(ByVal Value As String) cSqlDataSource = Value End Set End Property Public Property SQLDatabase() As String Get SQLDatabase = cSqlDatabase End Get Set(ByVal Value As String) cSqlDatabase = Value End Set End Property Public Property SQLUserID() As String Get SQLUserID = cSqlUserID End Get Set(ByVal Value As String) cSqlUserID = Value End Set End Property Public Property SQLPassword() As String Get SQLPassword = cSqlPassword End Get Set(ByVal Value As String) cSqlPassword = Value End Set End Property Public Property OriginData() As Double Get OriginData = cOriginData End Get Set(ByVal Value As Double) cOriginData = Value 'cOriginData = 0 ' OleDb 'cOriginData = 1 ' ODBC 'cOriginData = 2 ' SQLServer 'cOriginData = 3 ' MySQL End Set End Property Public ReadOnly Property RowsAffected() As Long

Get RowsAffected = cRowsAffected End Get End Property Public Function Connect() As Boolean Dim strConn As String Try Select Case cOriginData Case 0, 0.1 If cOriginData = 0 Then strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & cPath & ";" ElseIf cOriginData = 0.1 Then strConn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & cPath & ";" Else Throw New Exception("Provider not accepted.") End If cDataConnectionOle = New OleDbConnection(strConn) cDataConnectionOle.Open() cOriginData = 0 Case 1, 1.1 If cOriginData = 1 Then strConn = "DSN=" & cPath ElseIf cOriginData = 1.1 Then strConn = "Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" & cPath & ";" Else Throw New Exception("Provider not accepted.") End If cDataConnectionODBC = New OdbcConnection(strConn) cDataConnectionODBC.Open() cOriginData = 1 Case 2 strConn = cPath cDataConnectionSQL = New SqlConnection(strConn) cDataConnectionSQL.Open() Case 3 ''strConn = "Persist Security Info=False;Data Source=" & cSqlDataSource ''strConn += ";Database=" & cSqlDatabase ''strConn += ";User ID=" & cSqlUserID & ";Password=" & cSqlPassword 'strConn = cPath 'cDataConnectionMySQL = New MySqlConnection(strConn) 'cDataConnectionMySQL.Open() End Select Catch e As Exception cErrors += " " & e.Message Exit Function

End Try Return True End Function Public Function State() As Boolean Try Select Case cOriginData Case 0 If cDataConnectionOle.State = ConnectionState.Open Then Return True Case 1 If cDataConnectionODBC.State = ConnectionState.Open Then Return True Case 2 If cDataConnectionSQL.State = ConnectionState.Open Then Return True Case 3 'If cDataConnectionMySQL.State = ConnectionState.Open Then Return True End Select Catch e As Exception cErrors += " " & e.Message Exit Function End Try Return True End Function Public Function Refresh() As Boolean Select Case cOriginData Case 0 If cDataConnectionOle.State = ConnectionState.Open Then If Disconnect() Then Return Connect() End If Case 1 If cDataConnectionODBC.State = ConnectionState.Open Then If Disconnect() Then Return Connect() End If Case 2 If cDataConnectionSQL.State = ConnectionState.Open Then If Disconnect() Then Return Connect() End If Case 3 'If cDataConnectionMySQL.State = ConnectionState.Open Then ' If Disconnect() Then Return Connect() 'End If End Select End Function Public Function Disconnect() As Boolean Select Case cOriginData

Case 0 If Not cDataConnectionOle Is Nothing Then cDataConnectionOle.Close() Case 1 If Not cDataConnectionODBC Is Nothing Then cDataConnectionODBC.Close() Case 2 If Not cDataConnectionSQL Is Nothing Then cDataConnectionSQL.Close() Case 3 'cDataConnectionMySQL.Close() End Select Return True End Function Public Function ReadReturn() As Object Try If cOriginData = 0 Then Return cDataOleDB ElseIf cOriginData = 1 Then Return cDataODBC ElseIf cOriginData = 2 Then Return cDataSQL ElseIf cOriginData = 3 Then 'Return cDataMySQL End If Catch ex As Exception cErrors += " " & ex.Message End Try End Function Public Function ReadNext() As Boolean Try If cOriginData = 0 Then Return cDataOleDB.Read ElseIf cOriginData = 1 Then Return cDataODBC.Read ElseIf cOriginData = 2 Then Return cDataSQL.Read ElseIf cOriginData = 3 Then 'Return cDataMySQL.Read End If Catch ex As Exception cErrors += " " & ex.Message End Try End Function Public Function ReadClose() As Boolean Try

If cOriginData = 0 Then cDataOleDB.Close() ElseIf cOriginData = 1 Then cDataODBC.Close() ElseIf cOriginData = 2 Then cDataSQL.Close() ElseIf cOriginData = 3 Then 'cDataMySQL.Close() End If Return True Catch ex As Exception cErrors += " " & ex.Message Return False End Try End Function Public Function ReadHaveData() As Boolean Try If cOriginData = 0 Then Return cDataOleDB.HasRows() ElseIf cOriginData = 1 Then Return cDataODBC.HasRows() ElseIf cOriginData = 2 Then Return cDataSQL.HasRows() ElseIf cOriginData = 3 Then 'Return cDataMySQL.HasRows End If Catch ex As Exception cErrors += " " & ex.Message Return False End Try End Function Public Function Read(ByVal Value As String) As Object Try If cOriginData = 0 Then If Not cDataOleDB(Value) Is DBNull.Value Then Return cDataOleDB(Value) Else Return "" End If ElseIf cOriginData = 1 Then If Not cDataODBC(Value) Is DBNull.Value Then Return cDataODBC(Value) Else Return "" End If

ElseIf cOriginData = 2 Then If Not cDataSQL(Value) Is DBNull.Value Then Return cDataSQL(Value) Else Return "" End If ElseIf cOriginData = 3 Then 'If Not cDataMySQL(Value) Is DBNull.Value Then ' Return cDataMySQL(Value) 'Else ' Return "" 'End If End If Catch ex As Exception cErrors += " " & ex.Message End Try End Function Public Function Read(ByVal Value As Integer) As Object Try If cOriginData = 0 Then If Not cDataOleDB(Value) Is DBNull.Value Then Return cDataOleDB(Value).name Else Return "" End If ElseIf cOriginData = 1 Then If Not cDataODBC(Value) Is DBNull.Value Then Return cDataODBC(Value).name Else Return "" End If ElseIf cOriginData = 2 Then If Not cDataSQL(Value) Is DBNull.Value Then Return cDataSQL(Value).name Else Return "" End If ElseIf cOriginData = 3 Then 'If Not cDataMySQL(Value) Is DBNull.Value Then ' Return cDataMySQL(Value) 'Else ' Return "" 'End If End If Catch ex As Exception cErrors += " " & ex.Message

End Try End Function Public Function ReadDate(ByVal Value As String) As Date Try If cOriginData = 0 Then If Not cDataOleDB(Value) Is DBNull.Value Then Return cDataOleDB(Value) Else Return "1/1/1" End If ElseIf cOriginData = 1 Then If Not cDataODBC(Value) Is DBNull.Value Then Return cDataODBC(Value) Else Return "1/1/1" End If ElseIf cOriginData = 2 Then If Not cDataSQL(Value) Is DBNull.Value Then Return cDataSQL(Value) Else Return "1/1/1" End If ElseIf cOriginData = 3 Then 'If Not cDataMySQL(Value) Is DBNull.Value Then ' Return cDataMySQL(Value) 'Else ' Return "1/1/1" 'End If End If Catch ex As Exception cErrors += " " & ex.Message End Try End Function Public Function ReadString(ByVal Value As String) As String Try If cOriginData = 0 Then If Not cDataOleDB(Value) Is DBNull.Value Then Return cDataOleDB(Value) Else Return 0 End If ElseIf cOriginData = 1 Then If Not cDataODBC(Value) Is DBNull.Value Then Return cDataODBC(Value) Else Return 0

End If ElseIf cOriginData = 2 Then If Not cDataSQL(Value) Is DBNull.Value Then Return cDataSQL(Value) Else Return 0 End If ElseIf cOriginData = 3 Then 'If Not cDataMySQL(Value) Is DBNull.Value Then ' Return cDataMySQL(Value) 'Else ' Return 0 'End If End If Catch ex As Exception cErrors += " " & ex.Message End Try End Function Public Function ReadLong(ByVal Value As String) As Long Try If cOriginData = 0 Then If Not cDataOleDB(Value) Is DBNull.Value Then Return cDataOleDB(Value) Else Return 0 End If ElseIf cOriginData = 1 Then If Not cDataODBC(Value) Is DBNull.Value Then Return cDataODBC(Value) Else Return 0 End If ElseIf cOriginData = 2 Then If Not cDataSQL(Value) Is DBNull.Value Then Return cDataSQL(Value) Else Return 0 End If ElseIf cOriginData = 3 Then 'If Not cDataMySQL(Value) Is DBNull.Value Then ' Return cDataMySQL(Value) 'Else ' Return 0 'End If End If Catch ex As Exception

cErrors += " " & ex.Message End Try End Function Public Function ReadBoolean(ByVal Value As String) As Boolean Try If cOriginData = 0 Then If Not cDataOleDB(Value) Is DBNull.Value Then Return cDataOleDB(Value) Else Return False End If ElseIf cOriginData = 1 Then If Not cDataODBC(Value) Is DBNull.Value Then Return cDataODBC(Value) Else Return False End If ElseIf cOriginData = 2 Then If Not cDataSQL(Value) Is DBNull.Value Then Return cDataSQL(Value) Else Return False End If ElseIf cOriginData = 3 Then 'If Not cDataMySQL(Value) Is DBNull.Value Then ' Return cDataMySQL(Value) 'Else ' Return 0 'End If End If Catch ex As Exception cErrors += " " & ex.Message End Try End Function Public Function ReadDouble(ByVal Value As String) As Double Try If cOriginData = 0 Then If Not cDataOleDB(Value) Is DBNull.Value Then Return cDataOleDB(Value) Else Return 0 End If ElseIf cOriginData = 1 Then If Not cDataODBC(Value) Is DBNull.Value Then Return cDataODBC(Value) Else

Return 0 End If ElseIf cOriginData = 2 Then If Not cDataSQL(Value) Is DBNull.Value Then Return cDataSQL(Value) Else Return 0 End If ElseIf cOriginData = 3 Then 'If Not cDataMySQL(Value) Is DBNull.Value Then ' Return cDataMySQL(Value) 'Else ' Return 0 'End If End If Catch ex As Exception cErrors += " " & ex.Message End Try End Function Public Function ReadInteger(ByVal Value As String) As Integer Try If cOriginData = 0 Then If Not cDataOleDB(Value) Is DBNull.Value Then Return cDataOleDB(Value) Else Return 0 End If ElseIf cOriginData = 1 Then If Not cDataODBC(Value) Is DBNull.Value Then Return cDataODBC(Value) Else Return 0 End If ElseIf cOriginData = 2 Then If Not cDataSQL(Value) Is DBNull.Value Then Return cDataSQL(Value) Else Return 0 End If ElseIf cOriginData = 3 Then 'If Not cDataMySQL(Value) Is DBNull.Value Then ' Return cDataMySQL(Value) 'Else ' Return 0 'End If End If

Catch ex As Exception cErrors += " " & ex.Message End Try End Function Public Function ReadSP(ByVal value As String) As Object Try Return cDataSQL(value) Catch ex As Exception cErrors += " " & ex.Message End Try End Function Private Sub ReadDataStoreProcPrepareAux(ByVal SP As String) cDataCommandSQL = New SqlCommand(SP, cDataConnectionSQL) cDataCommandSQL.CommandType = CommandType.StoredProcedure cDataDataAdapter = New SqlDataAdapter(cDataCommandSQL) End Sub Public Function ReadDataStoreProcPrepare(ByVal SP As String, ByVal Parameters() As String, ByVal ParametersValue() As String) As Boolean Try ReadDataStoreProcPrepareAux(SP) For i As Integer = 0 To Parameters.GetUpperBound(0) cDataCommandSQL.Parameters.Add(New SqlParameter(Parameters(i), SqlDbType.NVarChar)) Next For i As Integer = 0 To Parameters.GetUpperBound(0) cDataDataAdapter.SelectCommand.Parameters(Parameters(i)).Value = ParametersValue(i) Next 'cDataSQL = cDataCommandSQL.ExecuteReader() ReadDataStoreProcPrepare = True Catch ex As Exception cErrors += " " & ex.Message ReadDataStoreProcPrepare = False End Try End Function Public Function ReadDataStoreProcPrepareExecute() As Boolean Try cDataSQL = cDataCommandSQL.ExecuteReader() ReadDataStoreProcPrepareExecute = True Catch ex As Exception cErrors += " " & ex.Message ReadDataStoreProcPrepareExecute = False End Try End Function Public Function ReadDataStoreProcPrepare(ByVal SP As String) As Boolean

Try ReadDataStoreProcPrepareAux(SP) ReadDataStoreProcPrepare = True Catch ex As Exception cErrors += " " & ex.Message ReadDataStoreProcPrepare = False End Try End Function Public Function ReadDataStoreProcPrepare(ByVal SP As String, ByVal Read As Boolean) As Boolean Try ReadDataStoreProcPrepareAux(SP) If Read And cOriginData = 2 Then cDataSQL = cDataCommandSQL.ExecuteReader() End If ReadDataStoreProcPrepare = True Catch ex As Exception cErrors += " " & ex.Message ReadDataStoreProcPrepare = False End Try End Function Public Function ReadDataStoreProcExecute(ByVal SP As String) As Boolean Try cDataCommandSQL = New SqlCommand(SP, cDataConnectionSQL) cDataCommandSQL.CommandType = CommandType.StoredProcedure cDataCommandSQL.ExecuteNonQuery() ReadDataStoreProcExecute = True Catch ex As Exception cErrors += " " & ex.Message ReadDataStoreProcExecute = False End Try End Function Public Function ReadDataStoreProcExecute(ByVal SP As String, ByVal Parameters() As Object, ByVal ParametersValue() As Object) As Boolean Try Select Case cOriginData Case 2 cDataCommandSQL = New SqlCommand(SP, cDataConnectionSQL) cDataCommandSQL.CommandType = CommandType.StoredProcedure For i As Integer = 0 To Parameters.GetUpperBound(0) If IsDate(ParametersValue(i)) Then Dim Aux As Date = ParametersValue(i) cDataCommandSQL.Parameters.AddWithValue(Parameters(i), Aux) Else cDataCommandSQL.Parameters.Add(Parameters(i), ParametersValue(i)) End If

Next Dim ReturnValueParam As SqlParameter = cDataCommandSQL.Parameters.Add("@RETURN_VALUE", SqlDbType.NVarChar, 100) ReturnValueParam.Direction = ParameterDirection.ReturnValue cDataCommandSQL.ExecuteNonQuery() _Return_Val = cDataCommandSQL.Parameters("@RETURN_VALUE").Value.ToString Case 3 'cDataCommandMySQL = New MySqlCommand(SP, cDataConnectionMySQL) 'cDataCommandMySQL.CommandType = CommandType.StoredProcedure 'For i As Integer = 0 To Parameters.GetUpperBound(0) ' System.Diagnostics.Debug.Print(Parameters(i)) ' cDataCommandMySQL.Parameters.Add(Parameters(i), ParametersValue(i)) 'Next 'cDataCommandMySQL.ExecuteNonQuery() End Select ReadDataStoreProcExecute = True Catch ex As Exception cErrors += " " & ex.Message ReadDataStoreProcExecute = False End Try End Function Public Function ReadDataStoreProcExecute(ByVal SP As String, ByVal Parameters() As Object, ByVal ParametersValue() As Object, ByVal ParametersOUT() As Object, ByRef ParametersOUTValue() As Object) As Boolean Try Select Case cOriginData Case 2 cDataCommandSQL = New SqlCommand(SP, cDataConnectionSQL) cDataCommandSQL.CommandType = CommandType.StoredProcedure For i As Integer = 0 To Parameters.GetUpperBound(0) cDataCommandSQL.Parameters.Add(Parameters(i), ParametersValue(i)) Next For i As Integer = 0 To ParametersOUT.GetUpperBound(0) Dim ReturnValueParam As SqlParameter = cDataCommandSQL.Parameters.Add(ParametersOUT(i), SqlDbType.NVarChar, 50) ReturnValueParam.Direction = ParameterDirection.Output Next Dim ReturnValueParamx As SqlParameter = New SqlParameter("@Return_Value", DbType.Int32) ReturnValueParamx.Direction = ParameterDirection.ReturnValue cDataCommandSQL.Parameters.Add(ReturnValueParamx) cDataCommandSQL.ExecuteNonQuery() ReDim ParametersOUTValue(ParametersOUT.GetUpperBound(0)) For i As Integer = 0 To ParametersOUT.GetUpperBound(0)

ParametersOUTValue(i) = cDataCommandSQL.Parameters(ParametersOUT(i)).Value.ToString Next _Return_Val = cDataCommandSQL.Parameters("@Return_Value").Value.ToString Case 3 'cDataCommandMySQL = New MySqlCommand(SP, cDataConnectionMySQL) 'cDataCommandMySQL.CommandType = CommandType.StoredProcedure 'For i As Integer = 0 To Parameters.GetUpperBound(0) ' System.Diagnostics.Debug.Print(Parameters(i)) ' cDataCommandMySQL.Parameters.Add(Parameters(i), ParametersValue(i)) 'Next 'cDataCommandMySQL.ExecuteNonQuery() End Select ReadDataStoreProcExecute = True Catch ex As Exception cErrors += " " & ex.Message ReadDataStoreProcExecute = False End Try End Function Public Function ReadDataStoreProc() As DataSet Dim cDataDataSet As New DataSet If cOriginData = 2 Then cDataDataAdapter.Fill(cDataDataSet) Return cDataDataSet End Function Public Function ReadDataStoreProcExecute() As Boolean Try If cOriginData = 2 Then cDataCommandSQL.ExecuteNonQuery() ReadDataStoreProcExecute = True Catch ex As System.Exception cErrors += " " & ex.Message ReadDataStoreProcExecute = False End Try End Function Public Function ReadDataStoreProcClose() As Boolean Try If Not cDataDataAdapter.SelectCommand Is Nothing Then If Not cDataDataAdapter.SelectCommand.Connection Is Nothing Then cDataDataAdapter.SelectCommand.Connection.Dispose() End If cDataDataAdapter.SelectCommand.Dispose() End If cDataDataAdapter.Dispose() ReadDataStoreProcClose = True Catch ex As Exception cErrors += " " & ex.Message ReadDataStoreProcClose = False

End Try End Function Public Function ReadData(ByVal Sql As String, Optional ByVal Read As Boolean = True, Optional ByVal Trans As Boolean = False) As Object Try If cOriginData = 0 Then cDataCommandOle = New OleDbCommand(Sql, cDataConnectionOle) If Trans Then cDataCommandOle.Transaction = cDataTransOle If Read Then cDataOleDB = cDataCommandOle.ExecuteReader() Return True Else Return cDataCommandOle.ExecuteReader() End If ElseIf cOriginData = 1 Then cDataCommandODBC = New OdbcCommand(Sql, cDataConnectionODBC) If Trans Then cDataCommandODBC.Transaction = cDataTransODBC If Read Then cDataODBC = cDataCommandODBC.ExecuteReader() Return True Else Return cDataCommandODBC.ExecuteReader() End If ElseIf cOriginData = 2 Then cDataCommandSQL = New SqlCommand(Sql, cDataConnectionSQL) If Trans Then cDataCommandSQL.Transaction = cDataTransSQL If Read Then cDataSQL = cDataCommandSQL.ExecuteReader() Return True Else Return cDataCommandSQL.ExecuteReader() End If ElseIf cOriginData = 3 Then 'cDataCommandMySQL = New MySqlCommand(Sql, cDataConnectionMySQL) 'If Trans Then cDataCommandMySQL.Transaction = cDataTransMySQL 'If Read Then ' cDataMySQL = cDataCommandMySQL.ExecuteReader() ' Return True 'Else ' Return cDataCommandMySQL.ExecuteReader() 'End If End If Catch ex As Exception cErrors += " " & ex.Message End Try End Function

Public Function ReadData(ByVal Sql As String, ByVal NombreConsulta As String) As DataSet Dim cDataDataAdapter As Object Dim cDataDataSet As New DataSet Try If cOriginData = 0 Then cDataCommandOle = New OleDbCommand(Sql, cDataConnectionOle) cDataDataAdapter = New OleDbDataAdapter(cDataCommandOle) ElseIf cOriginData = 1 Then cDataCommandODBC = New OdbcCommand(Sql, cDataConnectionODBC) cDataDataAdapter = New OdbcDataAdapter(cDataCommandODBC) ElseIf cOriginData = 2 Then cDataCommandSQL = New SqlCommand(Sql, cDataConnectionSQL) cDataDataAdapter = New SqlDataAdapter(cDataCommandSQL) ElseIf cOriginData = 3 Then 'cDataCommandMySQL = New MySqlCommand(Sql, cDataConnectionMySQL) 'cDataDataAdapter = New MySqlDataAdapter(cDataCommandMySQL) End If cDataDataAdapter.Fill(cDataDataSet, NombreConsulta) Catch ex As System.Exception cErrors += " " & ex.Message End Try Return cDataDataSet End Function Public Function Execute(ByVal Sql As String, Optional ByVal Trans As Boolean = False) As Boolean 'Give back the number of the affected rows Try If cOriginData = 0 Then cDataCommandOle = New OleDbCommand(Sql, cDataConnectionOle) If Trans Then cDataCommandOle.Transaction = cDataTransOle cRowsAffected = cDataCommandOle.ExecuteNonQuery() ElseIf cOriginData = 1 Then cDataCommandODBC = New OdbcCommand(Sql, cDataConnectionODBC) If Trans Then cDataCommandODBC.Transaction = cDataTransODBC cRowsAffected = cDataCommandODBC.ExecuteNonQuery() ElseIf cOriginData = 2 Then cDataCommandSQL = New SqlCommand(Sql, cDataConnectionSQL) If Trans Then cDataCommandSQL.Transaction = cDataTransSQL cRowsAffected = cDataCommandSQL.ExecuteNonQuery() ElseIf cOriginData = 3 Then 'cDataCommandMySQL = New MySqlCommand(Sql, cDataConnectionMySQL) 'If Trans Then cDataCommandMySQL.Transaction = cDataTransMySQL 'cRowsAffected = cDataCommandMySQL.ExecuteNonQuery() End If

Catch ex As System.Exception cErrors += " " & ex.Message Return False End Try If cRowsAffected > 0 Then Return True End Function '***************************Transactions********************************** *********** Public Function Transaccion() As Boolean Return Transaccion(0) End Function Public Function Transaccion(ByVal Value As Integer) As Boolean Try If cOriginData = 0 Then Select Case Value Case -1 cDataTransOle.Rollback() Case 0 cDataTransOle = cDataConnectionOle.BeginTransaction 'cDataCommand.Transaction = cDataTrans Case 1 cDataTransOle.Commit() End Select ElseIf cOriginData = 1 Then Select Case Value Case -1 cDataTransODBC.Rollback() Case 0 cDataTransODBC = cDataConnectionODBC.BeginTransaction Case 1 cDataTransODBC.Commit() End Select ElseIf cOriginData = 2 Then Select Case Value Case -1 cDataTransSQL.Rollback() Case 0 cDataTransSQL = cDataConnectionSQL.BeginTransaction Case 1 cDataTransSQL.Commit() End Select ElseIf cOriginData = 3 Then 'Select Case Value ' Case -1 ' cDataTransMySQL.Rollback()

' Case 0 ' cDataTransMySQL = cDataConnectionMySQL.BeginTransaction ' Case 1 ' cDataTransMySQL.Commit() 'End Select End If Return True Catch ex As Exception cErrors += " " & ex.Message End Try End Function Protected Overrides Sub Finalize() cDataConnectionOle = Nothing cDataCommandOle = Nothing cDataConnectionODBC = Nothing cDataCommandODBC = Nothing cDataConnectionSQL = Nothing cDataCommandSQL = Nothing 'cDataConnectionMySQL = Nothing 'cDataCommandMySQL = Nothing cDataOleDB = Nothing cDataODBC = Nothing cDataSQL = Nothing 'cDataMySQL = Nothing cDataTransOle = Nothing cDataTransODBC = Nothing cDataTransSQL = Nothing 'cDataTransMySQL = Nothing MyBase.Finalize() End Sub End Class

Vous aimerez peut-être aussi