•
•
•
•
What is DaniWeb IT Discussion Community?
You're currently browsing the ASP.NET section within the Web Development category of DaniWeb, a massive community of 397,592 software developers, web developers, Internet marketers, and tech gurus who are all enthusiastic about making contacts, networking, and learning from each other. In fact, there are 2,867 IT professionals currently interacting right now! Registration is free, only takes a minute and lets you enjoy all of the interactive features of the site.
Please support our ASP.NET advertiser: Lunarpages ASP Web Hosting
Views: 146986 | Replies: 74 | Solved
![]() |
| |
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:
Authentication will be conducted by "forms" authentication set in the web.config file:
3. Login Page Creationg (HTML Side), with form validation controls, using a summary display for an controls not passing validation.:
4. The Code behind (in visual basic.net)
a. Imports:
b. Add the code for the button click event (in this case cmdSubmit button):
c. Write the code for the DBConnection Subroutine - Beginning with variable creation, and obtaining the connection string from web.config:
d. Withing DBConnection Subroutine :
***Note*** The SQL Stored Procedure in Access is :
Continue in DBConnection Subroutine :
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:
The datebase used is the Access Northwind Database. With the connection string being placed in the web.config file.
1. Web Config File code:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <!-- ||||| Application Settings ||||| --> <appSettings> <add key="strConn" value="Provider = Microsoft.Jet.OLEDB.4.0;Data Source=C:\Inetpub\wwwroot\Northwind.mdb;User ID=Admin;Password=;" /> </appSettings> <system.web> .... ...
Authentication will be conducted by "forms" authentication set in the web.config file:
....
....
<!-- AUTHENTICATION
This section sets the authentication policies of the application. Possible modes are "Windows",
"Forms", "Passport" and "None"
"None" No authentication is performed.
"Windows" IIS performs authentication (Basic, Digest, or Integrated Windows) according to
its settings for the application. Anonymous access must be disabled in IIS.
"Forms" You provide a custom form (Web page) for users to enter their credentials, and then
you authenticate them in your application. A user credential token is stored in a cookie.
"Passport" Authentication is performed via a centralized authentication service provided
by Microsoft that offers a single logon and core profile services for member sites.
-->
<!-- ||||| MY Authentication Setup ||||| -->
<authentication mode="Forms">
<forms name="NWLogin" loginUrl="Login.aspx" />
</authentication>
<!-- AUTHORIZATION 3. Login Page Creationg (HTML Side), with form validation controls, using a summary display for an controls not passing validation.:
<%@ Page Language="vb" AutoEventWireup="false" Codebehind="Login.aspx.vb" Inherits="NorthLogin.WebForm1"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <html> <head> <title>Northwind Database Login</title> <meta content="Microsoft Visual Studio .NET 7.1" name="GENERATOR"> <meta content="Visual Basic .NET 7.1" name="CODE_LANGUAGE"> <meta content="JavaScript" name="vs_defaultClientScript"> <meta content="http://schemas.microsoft.com/intellisense/ie5" name="vs_targetSchema"> </head> <body> <!-- ||||| Login Form ||||| --> <form id="frmlogin" method="post" runat="server"> <asp:label id="lblMessage" runat="server" width="288px" font-bold="True" font-italic="True" font-size="Medium" forecolor="#C00000"></asp:label> <table id="mainTable" style="POSITION: absolute; TOP: 30%"> <tr> <td> <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"> <tr> <td><b>Login: </b> </td> <td> <asp:textbox id="txtUserName" runat="server" width="160px"></asp:textbox> <asp:requiredfieldvalidator runat="server" id="rvUserValidator" controltovalidate="txtUserName" errormessage="You must supply a Username!" display="None" /> </td> </tr> <tr> <td><b>Password: </b> </td> <td> <asp:textbox id="txtPassword" runat="server" textmode="Password" width="160px"></asp:textbox> <asp:requiredfieldvalidator runat="server" id="rvPasswordValidator" controltovalidate="txtPassword" errormessage="Empty Passwords not accepted" display="None" /> </td> </tr> <tr> <td align="center" colspan="2"><asp:button id="cmdSubmit" text="Submit" runat="server" borderstyle="Solid"></asp:button></td> </tr> </table> </td> </tr> <tr> <td> <table id="messageDisplay"> <tr> <td><asp:validationsummary runat="server" displaymode="BulletList" id="Validationsummary1" width="472px" /> </td> </tr> </table> </td> </tr> </table> </form> <!-- ||||| End of Form ||||| --> </body> </html>
4. The Code behind (in visual basic.net)
a. Imports:
Imports System.Web.Security ' ||||| Required Class for Authentication Imports System.Data ' ||||| DB Accessing Import Imports System.Data.OleDb ' |||||| Access Database Required Import! Imports System.Configuration ' |||||| Required for Web.Config appSettings ||||| ' ||||| Connection String - XML coded in Web.Config ' ||||| 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):
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' ||||| Put user code to initialize the page here
End Sub
Private Sub cmdSubmit_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdSubmit.Click
If Page.IsValid Then
' ||||| Connect to Database for User Validation |||||
If DBConnection(txtUserName.Text, txtPassword.Text) Then
FormsAuthentication.RedirectFromLoginPage(txtUserName.Text, False) ' ||||| default.aspx Page!
Else
' ||||| Credentials are Invalid
lblMessage.Text = "Invalid Login!"
End If
End If
End Subc. Write the code for the DBConnection Subroutine - Beginning with variable creation, and obtaining the connection string from web.config:
' ||||| Declare Required Variables
' ||||| Access appSettings of Web.Config for Connection String (Constant)
Dim LoginSQL As String
Dim MyConn As OleDbConnection = New OleDbConnection(ConfigurationSettings.AppSettings("strConn"))' ||||| Create a OleDb Command Object ' ||||| Pass in the SQL String and Connection Object related to SQL String. ' ||||| Passing in SQL string and Connection Obj to the OleDbCommand Constructor
' ||||| Pass in Stored procedure
' ||||| Set CommandType to Stored Procedure
Dim MyCmd As New OleDbCommand("sp_ValidateUser", MyConn)
MyCmd.CommandType = CommandType.StoredProcedure
' ||||| Create Parameter Objects for values passed in
Dim objParam1, objParam2 As OleDbParameter***Note*** The SQL Stored Procedure in Access is :
SELECT Count(*) as Num_of_Users FROM tblUsers WHERE u_Name = @UserName AND u_Password = @Password;
Continue in DBConnection Subroutine :
' ||||| Add the parameters to the parameters collection of the
' ||||| command object, and set their datatypes (OleDbType in this case)
objParam1 = MyCmd.Parameters.Add("@UserName", OleDbType.Char)
objParam2 = MyCmd.Parameters.Add("@Password", OleDbType.Char)
' ||||| Set the direction of the parameters...input, output, etc
objParam1.Direction = ParameterDirection.Input
objParam2.Direction = ParameterDirection.Input
' ||||| Set the value(s) of the parameters to the respective source controls
objParam1.Value = txtUserName.Text
objParam2.Value = txtPassword.Text
' ||||| Try, catch block!
Try
' ||||| Check if Connection to DB is already open, if not, then open a connection
If MyConn.State = ConnectionState.Closed Then
' ||||| DB not already Open...so open it
MyConn.Open()
End If
' ||||| Create OleDb Data Reader
Dim objReader As OleDbDataReader
objReader = MyCmd.ExecuteReader(CommandBehavior.CloseConnection)
' ||||| Close the Reader and the Connection Closes with it
While objReader.Read()
If CStr(objReader.GetValue(0)) <> "1" Then
lblMessage.Text = "Invalid Login!"
Else
objReader.Close() ' ||||| Close the Connections & Reader
Return True
End If
End While
Catch ex As Exception
lblMessage.Text = "Error Connecting to Database!"
End Try
End FunctionVoila, 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, Regional Pharmacy Information Systems
TLC Services Website (Under Construction)
Updated : ASP.Net Login Code
TLC Services Website (Under Construction)
Updated : ASP.Net Login Code
Once again Paladine buddy, you've done a great job. Congrats man, good code.
Formerly known as Slade.
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.
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, Regional Pharmacy Information Systems
TLC Services Website (Under Construction)
Updated : ASP.Net Login Code
TLC Services Website (Under Construction)
Updated : ASP.Net Login Code
Just a reminder to the new ASP.NET Programmers: your web.config file is case-sensitive, so be careful copying the text
.
. -Ryan Hoffman
ASP.NET Specialist / Webmaster, Extended64.com.
Please do not email or PM me with support questions. Please direct them to the forums instead.
ASP.NET Specialist / Webmaster, Extended64.com.
Please do not email or PM me with support questions. Please direct them to the forums instead.
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:
b. Add the code for the button click event (in this case cmdSubmit button): - Revised!
c. Validate login on other pages in the application - Add to Page_Load Event
Happy coding
!
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, Regional Pharmacy Information Systems
TLC Services Website (Under Construction)
Updated : ASP.Net Login Code
TLC Services Website (Under Construction)
Updated : ASP.Net Login Code
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,
How do I create a stored procedure in Access?
Thanks,
JasonRCS
Always a work in progress...
Always a work in progress...
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.
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.
In the above exercise this is the stored "procedure" I used.
SELECT COUNT(*) AS Num_of_User FROM tblUser 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, Regional Pharmacy Information Systems
TLC Services Website (Under Construction)
Updated : ASP.Net Login Code
TLC Services Website (Under Construction)
Updated : ASP.Net Login Code
•
•
Join Date: Sep 2004
Posts: 4
Reputation:
Rep Power: 0
Solved Threads: 1
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.
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.
•
•
Join Date: Sep 2004
Posts: 4
Reputation:
Rep Power: 0
Solved Threads: 1
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!!
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!!
![]() |
•
•
•
•
Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
•
•
•
•
•
•
•
•
DaniWeb ASP.NET Marketplace
Other Threads in the ASP.NET Forum
- Previous Thread: ASP.Net Directory Problems
- Next Thread: Ready to take up a challenge

Hybrid Mode