941,498 Members | Top Members by Rank

Ad:
  • ASP.NET Discussion Thread
  • Marked Solved
  • Views: 276853
  • ASP.NET RSS
You are currently viewing page 1 of this multi-page discussion thread
May 14th, 2004
1

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

Expand Post »
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:

ASP.NET Syntax (Toggle Plain Text)
  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:
ASP.NET Syntax (Toggle Plain Text)
  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.:
ASP.NET Syntax (Toggle Plain Text)
  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:
ASP.NET Syntax (Toggle Plain Text)
  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):
ASP.NET Syntax (Toggle Plain Text)
  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:
ASP.NET Syntax (Toggle Plain Text)
  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 :
ASP.NET Syntax (Toggle Plain Text)
  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.  

ASP.NET Syntax (Toggle Plain Text)
  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 :
ASP.NET Syntax (Toggle Plain Text)
  1. SELECT Count(*) as Num_of_Users FROM tblUsers WHERE u_Name = @UserName AND u_Password = @Password;

Continue in DBConnection Subroutine :
ASP.NET Syntax (Toggle Plain Text)
  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:
Similar Threads
Team Colleague
Reputation Points: 211
Solved Threads: 27
Master Poster
Paladine is offline Offline
793 posts
since Feb 2003
May 16th, 2004
0

Good job

Once again Paladine buddy, you've done a great job. Congrats man, good code.
Reputation Points: 115
Solved Threads: 7
Practically a Master Poster
Slade is offline Offline
633 posts
since Mar 2004
May 16th, 2004
0

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

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.
Team Colleague
Reputation Points: 211
Solved Threads: 27
Master Poster
Paladine is offline Offline
793 posts
since Feb 2003
May 19th, 2004
0

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

Just a reminder to the new ASP.NET Programmers: your web.config file is case-sensitive, so be careful copying the text .
Moderator
Reputation Points: 322
Solved Threads: 28
The C# Man, Myth, Legend
Tekmaven is offline Offline
914 posts
since Feb 2002
Jul 12th, 2004
0

Re: Attempts

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 !
Team Colleague
Reputation Points: 211
Solved Threads: 27
Master Poster
Paladine is offline Offline
793 posts
since Feb 2003
Jul 16th, 2004
0

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

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,
Reputation Points: 13
Solved Threads: 1
Newbie Poster
JasonRCS is offline Offline
13 posts
since Jul 2004
Jul 16th, 2004
0

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

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.

ASP.NET Syntax (Toggle Plain Text)
  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.
Team Colleague
Reputation Points: 211
Solved Threads: 27
Master Poster
Paladine is offline Offline
793 posts
since Feb 2003
Sep 15th, 2004
0

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

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.
Reputation Points: 10
Solved Threads: 1
Newbie Poster
curiosity5 is offline Offline
4 posts
since Sep 2004
Sep 17th, 2004
0

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

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, 1608 views)
File Type: txt web.txt (480 Bytes, 966 views)
Reputation Points: 10
Solved Threads: 1
Newbie Poster
curiosity5 is offline Offline
4 posts
since Sep 2004
Sep 17th, 2004
0

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

oh wait, i know what i did wrong. Let me try this again.
Reputation Points: 10
Solved Threads: 1
Newbie Poster
curiosity5 is offline Offline
4 posts
since Sep 2004

This thread is solved

Either the thread starter or a moderator has marked this thread as solved. You can most likely trust the responses and answers given. There is most likely no reason for any further responses to be posted here. If you have a related question, please start a new thread in this forum instead.

This thread is more than three months old

No one has posted to this discussion for at least three months. Please let old threads die and do not reply to them unless you feel you have something new and valuable to contribute that absolutely must be added to make the discussion complete. Otherwise, please start a new thread in this forum instead.
This thread is currently closed and is not accepting any new replies.
Previous Thread in ASP.NET Forum Timeline: ASP.Net Directory Problems
Next Thread in ASP.NET Forum Timeline: Ready to take up a challenge





About Us | Contact Us | Advertise | Acceptable Use Policy
Forum Index | Build Custom RSS Feed


Follow us on Twitter


© 2011 DaniWeb® LLC