Simple ASP.Net Login Page (Using VB.Net)

Please support our ASP.NET advertiser: Intel Parallel Studio Home
Thread Solved

Join Date: Feb 2003
Posts: 793
Reputation: Paladine has a spectacular aura about Paladine has a spectacular aura about Paladine has a spectacular aura about 
Solved Threads: 26
Team Colleague
Paladine's Avatar
Paladine Paladine is offline Offline
Master Poster

Simple ASP.Net Login Page (Using VB.Net)

 
0
  #1
May 14th, 2004
This is sample code for a ASP.Net Login page (using Visual Basic.Net code behind) with OleDB connection to an Access Database using ADO.Net.

The datebase used is the Access Northwind Database. With the connection string being placed in the web.config file.

1. Web Config File code:

  1. <?xml version="1.0" encoding="utf-8" ?>
  2. <configuration>
  3. <!-- ||||| Application Settings ||||| -->
  4. <appSettings>
  5. <add key="strConn" value="Provider = Microsoft.Jet.OLEDB.4.0;Data Source=C:\Inetpub\wwwroot\Northwind.mdb;User ID=Admin;Password=;" />
  6. </appSettings>
  7. <system.web>
  8. ....
  9. ...

Authentication will be conducted by "forms" authentication set in the web.config file:
  1. ....
  2. ....
  3. <!-- AUTHENTICATION
  4. This section sets the authentication policies of the application. Possible modes are "Windows",
  5. "Forms", "Passport" and "None"
  6.  
  7. "None" No authentication is performed.
  8. "Windows" IIS performs authentication (Basic, Digest, or Integrated Windows) according to
  9. its settings for the application. Anonymous access must be disabled in IIS.
  10. "Forms" You provide a custom form (Web page) for users to enter their credentials, and then
  11. you authenticate them in your application. A user credential token is stored in a cookie.
  12. "Passport" Authentication is performed via a centralized authentication service provided
  13. by Microsoft that offers a single logon and core profile services for member sites.
  14. -->
  15. <!-- ||||| MY Authentication Setup ||||| -->
  16. <authentication mode="Forms">
  17. <forms name="NWLogin" loginUrl="Login.aspx" />
  18. </authentication>
  19.  
  20. <!-- AUTHORIZATION


3. Login Page Creationg (HTML Side), with form validation controls, using a summary display for an controls not passing validation.:
  1. <%@ Page Language="vb" AutoEventWireup="false" Codebehind="Login.aspx.vb" Inherits="NorthLogin.WebForm1"%>
  2. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
  3. <html>
  4. <head>
  5. <title>Northwind Database Login</title>
  6. <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR">
  7. <meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE">
  8. <meta content="JavaScript" name="vs_defaultClientScript">
  9. <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema">
  10. </head>
  11. <body>
  12. <!-- ||||| Login Form ||||| -->
  13. <form id="frmlogin" method="post" runat="server">
  14. <asp:label id="lblMessage" runat="server" width="288px" font-bold="True" font-italic="True"
  15. font-size="Medium" forecolor="#C00000"></asp:label>
  16. <table id="mainTable" style="POSITION: absolute; TOP: 30%">
  17. <tr>
  18. <td>
  19. <table cellspacing="15" id="loginTable" style="BORDER-RIGHT: #6699cc solid; BORDER-TOP: #6699cc solid; FONT-WEIGHT: bold; LEFT: 30%; BORDER-LEFT: #6699cc solid; BORDER-BOTTOM: #6699cc solid; FONT-FAMILY: Sans-Serif; BACKGROUND-COLOR: lightgrey">
  20. <tr>
  21. <td><b>Login: </b>
  22. </td>
  23. <td>
  24. <asp:textbox id="txtUserName" runat="server" width="160px"></asp:textbox>
  25. <asp:requiredfieldvalidator runat="server" id="rvUserValidator" controltovalidate="txtUserName" errormessage="You must supply a Username!"
  26. display="None" />
  27. </td>
  28. </tr>
  29. <tr>
  30. <td><b>Password: </b>
  31. </td>
  32. <td>
  33. <asp:textbox id="txtPassword" runat="server" textmode="Password" width="160px"></asp:textbox>
  34. <asp:requiredfieldvalidator runat="server" id="rvPasswordValidator" controltovalidate="txtPassword" errormessage="Empty Passwords not accepted"
  35. display="None" />
  36. </td>
  37. </tr>
  38. <tr>
  39. <td align="center" colspan="2"><asp:button id="cmdSubmit" text="Submit" runat="server" borderstyle="Solid"></asp:button></td>
  40. </tr>
  41. </table>
  42. </td>
  43. </tr>
  44. <tr>
  45. <td>
  46. <table id="messageDisplay">
  47. <tr>
  48. <td><asp:validationsummary runat="server" displaymode="BulletList" id="Validationsummary1" width="472px" />
  49. </td>
  50. </tr>
  51. </table>
  52. </td>
  53. </tr>
  54. </table>
  55. </form>
  56. <!-- ||||| End of Form ||||| -->
  57. </body>
  58. </html>

4. The Code behind (in visual basic.net)

a. Imports:
  1. Imports System.Web.Security ' ||||| Required Class for Authentication
  2. Imports System.Data ' ||||| DB Accessing Import
  3. Imports System.Data.OleDb ' |||||| Access Database Required Import!
  4. Imports System.Configuration ' |||||| Required for Web.Config appSettings |||||
  5.  
  6. ' ||||| Connection String - XML coded in Web.Config
  7. ' ||||| Remember to set the Security Settings in Windows on the MDB file for IUSR

b. Add the code for the button click event (in this case cmdSubmit button):
  1. Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
  2. ' ||||| Put user code to initialize the page here
  3. End Sub
  4.  
  5. Private Sub cmdSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSubmit.Click
  6. If Page.IsValid Then
  7. ' ||||| Connect to Database for User Validation |||||
  8. If DBConnection(txtUserName.Text, txtPassword.Text) Then
  9. FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, False) ' ||||| default.aspx Page!
  10.  
  11. Else
  12. ' ||||| Credentials are Invalid
  13. lblMessage.Text = "Invalid Login!"
  14. End If
  15. End If
  16. End Sub

c. Write the code for the DBConnection Subroutine - Beginning with variable creation, and obtaining the connection string from web.config:
  1. ' ||||| Declare Required Variables
  2. ' ||||| Access appSettings of Web.Config for Connection String (Constant)
  3. Dim LoginSQL As String
  4. Dim MyConn As OleDbConnection = New OleDbConnection(ConfigurationSettings.AppSettings("strConn"))
d. Withing DBConnection Subroutine :
  1. ' ||||| Create a OleDb Command Object
  2. ' ||||| Pass in the SQL String and Connection Object related to SQL String.
  3. ' ||||| Passing in SQL string and Connection Obj to the OleDbCommand Constructor
  4.  

  1. ' ||||| Pass in Stored procedure
  2. ' ||||| Set CommandType to Stored Procedure
  3. Dim MyCmd As New OleDbCommand("sp_ValidateUser", MyConn)
  4. MyCmd.CommandType = CommandType.StoredProcedure
  5.  
  6. ' ||||| Create Parameter Objects for values passed in
  7. Dim objParam1, objParam2 As OleDbParameter
  8.  

***Note*** The SQL Stored Procedure in Access is :
  1. SELECT Count(*) as Num_of_Users FROM tblUsers WHERE u_Name = @UserName AND u_Password = @Password;

Continue in DBConnection Subroutine :
  1. ' ||||| Add the parameters to the parameters collection of the
  2. ' ||||| command object, and set their datatypes (OleDbType in this case)
  3. objParam1 = MyCmd.Parameters.Add("@UserName", OleDbType.Char)
  4. objParam2 = MyCmd.Parameters.Add("@Password", OleDbType.Char)
  5. ' ||||| Set the direction of the parameters...input, output, etc
  6. objParam1.Direction = ParameterDirection.Input
  7. objParam2.Direction = ParameterDirection.Input
  8. ' ||||| Set the value(s) of the parameters to the respective source controls
  9. objParam1.Value = txtUserName.Text
  10. objParam2.Value = txtPassword.Text
  11.  
  12. ' ||||| Try, catch block!
  13. Try
  14. ' ||||| Check if Connection to DB is already open, if not, then open a connection
  15. If MyConn.State = ConnectionState.Closed Then
  16. ' ||||| DB not already Open...so open it
  17. MyConn.Open()
  18. End If
  19.  
  20. ' ||||| Create OleDb Data Reader
  21. Dim objReader As OleDbDataReader
  22. objReader = MyCmd.ExecuteReader(CommandBehavior.CloseConnection)
  23. ' ||||| Close the Reader and the Connection Closes with it
  24.  
  25. While objReader.Read()
  26. If CStr(objReader.GetValue(0)) <> "1" Then
  27. lblMessage.Text = "Invalid Login!"
  28. Else
  29. objReader.Close() ' ||||| Close the Connections & Reader
  30. Return True
  31. End If
  32.  
  33. End While
  34. Catch ex As Exception
  35. lblMessage.Text = "Error Connecting to Database!"
  36. End Try
  37.  
  38.  
  39. End Function

Voila, compile and run. Hopefully the comments in and outside of the code give you enough of an idea on how to customize this code for your needs.

Happy coding folks! :lol:
Assistant Manager, Pharmacy Informatics
Wordpress Learning Blog
Updated : ASP.Net Login Code
Quick reply to this message  
Join Date: Mar 2004
Posts: 634
Reputation: Slade has a spectacular aura about Slade has a spectacular aura about 
Solved Threads: 7
Slade's Avatar
Slade Slade is offline Offline
Practically a Master Poster

Good job

 
0
  #2
May 16th, 2004
Once again Paladine buddy, you've done a great job. Congrats man, good code.
Formerly known as Slade.
Quick reply to this message  
Join Date: Feb 2003
Posts: 793
Reputation: Paladine has a spectacular aura about Paladine has a spectacular aura about Paladine has a spectacular aura about 
Solved Threads: 26
Team Colleague
Paladine's Avatar
Paladine Paladine is offline Offline
Master Poster

Re: Simple ASP.Net Login Page (Using VB.Net)

 
0
  #3
May 16th, 2004
Thanks Slade. I just hope someone can put the code to good use.

I plan to upgrade this code to a moderate level of knowledge, by creating a Login User Customizable control that can be dropped into any page where it is needed. But that won't be a few weeks at least.
Assistant Manager, Pharmacy Informatics
Wordpress Learning Blog
Updated : ASP.Net Login Code
Quick reply to this message  
Join Date: Feb 2002
Posts: 898
Reputation: Tekmaven is a glorious beacon of light Tekmaven is a glorious beacon of light Tekmaven is a glorious beacon of light Tekmaven is a glorious beacon of light Tekmaven is a glorious beacon of light 
Solved Threads: 28
Moderator
Tekmaven's Avatar
Tekmaven Tekmaven is offline Offline
The C# Man, Myth, Legend

Re: Simple ASP.Net Login Page (Using VB.Net)

 
0
  #4
May 19th, 2004
Just a reminder to the new ASP.NET Programmers: your web.config file is case-sensitive, so be careful copying the text .
-Ryan Hoffman

.NET Specialist / Webmaster, Extended64.com.
Please do not email or PM me with support questions. Please direct them to the forums instead.
Quick reply to this message  
Join Date: Feb 2003
Posts: 793
Reputation: Paladine has a spectacular aura about Paladine has a spectacular aura about Paladine has a spectacular aura about 
Solved Threads: 26
Team Colleague
Paladine's Avatar
Paladine Paladine is offline Offline
Master Poster

Re: Attempts

 
0
  #5
Jul 12th, 2004
A small addition to this code, which will allow the application to monitor the number of attempts at a login before granting or denying access.

a. Modify the Global.asax Session_Start method:
Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)
        '<summary>
        '   |Fires when the session is started
        '   |Administrator will only be allowed a certain number of login attempts
        '</summary>
        Session("Num_of_Tries") = 3
        Session("LoginCount") = 0

        '   |Track whether they're logged in or not
        Session("Logged_IN") = "No"
End Sub

b. Add the code for the button click event (in this case cmdSubmit button): - Revised!
Private Sub cmdSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSubmit.Click
        If Page.IsValid Then    '   ||||| Meaning the Control Validation was successful!
            '   |||||   Connect to Database for User Validation |||||
            Dim intMaxLoginAttempts = CInt(Session("Num_of_Tries"))

            If DBConnection(txtUserName.Text.Trim(), txtPassword.Text.Trim()) Then
                Session("Logged_IN") = "Yes"    '   |||||   Use to Validate on other pages in the application
                FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, False)  '   |||||   default.aspx Page!
            Else
                '   |||||   Credentials are Invalid
                lblMessage.Text = "Invalid Login!"
                '   |||||   Increment the LoginCount (attempts)
                Session("LoginCount") = CInt(Session("LoginCount")) + 1
                '   |||||   Determine the Number of Tries
                If Session("LoginCount").Equals(intMaxLoginAttempts) Then
                    Response.Redirect("Denied.aspx")
                End If

            End If
        End If
End Sub

c. Validate login on other pages in the application - Add to Page_Load Event
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        '   <summary>
        '   |||||   Authenicate user for accces to pages within application
        '   |||||   Enusre the page can't be navigated to without
        '   |||||   user's being online and logged in.
        '   |||||   **Note: Logged_IN session object is created in Session_Start 
        '   |||||   of the Global.asax file **
        '   </summary>

        '   |Do not allow caching of page
        Response.Cache.SetCacheability(HttpCacheability.NoCache)
        If Session("Logged_IN").Equals("No") Then
            Response.Redirect("Login.aspx")
        End If

Happy coding !
Assistant Manager, Pharmacy Informatics
Wordpress Learning Blog
Updated : ASP.Net Login Code
Quick reply to this message  
Join Date: Jul 2004
Posts: 13
Reputation: JasonRCS is an unknown quantity at this point 
Solved Threads: 1
JasonRCS's Avatar
JasonRCS JasonRCS is offline Offline
Newbie Poster

Re: Simple ASP.Net Login Page (Using VB.Net)

 
0
  #6
Jul 16th, 2004
I am new to stored procedures in Access, infact I have been told that it could not be done. I have tried to create a query in sql view and named it sp_Check User, but I get an error that my app can not access the table or querry.

How do I create a stored procedure in Access?

Thanks,
JasonRCS

Always a work in progress...
Quick reply to this message  
Join Date: Feb 2003
Posts: 793
Reputation: Paladine has a spectacular aura about Paladine has a spectacular aura about Paladine has a spectacular aura about 
Solved Threads: 26
Team Colleague
Paladine's Avatar
Paladine Paladine is offline Offline
Master Poster

Re: Simple ASP.Net Login Page (Using VB.Net)

 
0
  #7
Jul 16th, 2004
Hi JasonRCS, I think I can help. Whom ever told you that Stored Procedures can not be done in access was completely wrong...well ok, maybe just a little wrong. Granted they look nothing like those done on SQL server, but they do function the same way.

In the above exercise this is the stored "procedure" I used.

  1. SELECT COUNT(*) AS Num_of_User
  2. FROM tblUser
  3. WHERE (((tblUser.U_Name)=[@UserName]) AND ((tblUser.U_Password)=[@Password]));

That is exactly how it appears in the SQL view in Access. See here is why the person who said it wasn't possible was partly right. As you don't really use the Create Procedure syntax as you would in SQL Server. But the principle is still the same.

Hope this helps.
Assistant Manager, Pharmacy Informatics
Wordpress Learning Blog
Updated : ASP.Net Login Code
Quick reply to this message  
Join Date: Sep 2004
Posts: 4
Reputation: curiosity5 is an unknown quantity at this point 
Solved Threads: 1
curiosity5 curiosity5 is offline Offline
Newbie Poster

Re: Simple ASP.Net Login Page (Using VB.Net)

 
0
  #8
Sep 15th, 2004
I'm a newbie. I have 8 years of access experience and had enough of it.
Can anyone put this code together in a folder in the correct files for me or at least tell me which codes go into which files? I just couldn't get it working.
Thanks in advance.
Quick reply to this message  
Join Date: Sep 2004
Posts: 4
Reputation: curiosity5 is an unknown quantity at this point 
Solved Threads: 1
curiosity5 curiosity5 is offline Offline
Newbie Poster

Re: Simple ASP.Net Login Page (Using VB.Net)

 
0
  #9
Sep 17th, 2004
I attached the two files.
I just renamed them to .txt for attachment.
I have login.aspx and web.config in a folder. It stopped at
Line 1: <%@ Page Language="vb" AutoEventWireup="false" Codebehind="Login.aspx.vb" Inherits="NorthLogin.WebForm1"%>

Please help!!
Attached Files
File Type: txt login.txt (5.8 KB, 299 views)
File Type: txt web.txt (480 Bytes, 178 views)
Quick reply to this message  
Join Date: Sep 2004
Posts: 4
Reputation: curiosity5 is an unknown quantity at this point 
Solved Threads: 1
curiosity5 curiosity5 is offline Offline
Newbie Poster

Re: Simple ASP.Net Login Page (Using VB.Net)

 
0
  #10
Sep 17th, 2004
oh wait, i know what i did wrong. Let me try this again.
Quick reply to this message  
Closed Thread

This thread has been marked solved.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the ASP.NET Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC