Download Source Code : 1408_LoginPage.zip
We will see in this article that how we can create a Login page in ASP.NET.
I have written an article on DevASP.NET about how to create a signup or register page in ASP.NET. When you have created a register page then you need to create login page as well. I will create a simple login page using the same database which I have used for signup page. This SQL Server database (SampleApplicationDatabase) has a table (Account). Table (Account) has six columns (AccountID, FirstName, LastName, Email, Password, ConfirmPassword and CreateDate). I will use Email and Password fields for login purposes and I will check both values from database when user will try to login. For this purpose I have written a stored procedure to check valid user. Of course, I have also implemented client side validation by using RequiredFieldValidator controls and RegularExpressionValidator for Email.
Let’s see how we can create a login page. You can download source code.
- Open Visual Studio 2010
- File > New > Web Site
- Visual C# or Visual Basic > ASP.NET Empty Web Site > Click Ok
- Website > Add New Item > Web Form > Click Add (Default.aspx)
- Website > Add New Item > Web Form > Click Add (Rename as Register.aspx)
- Website > Add New Item > Web Form > Click Add (Rename as UserPage.aspx
- Add code below in Default.aspx
<table>
<tr>
<td colspan="3" style="height: 21px; text-align: center">
<span style="font-size: 16pt">Please login if you have account</span></td>
</tr>
<tr>
<td colspan="3" style="height: 21px; text-align: center">
</td>
</tr>
<tr>
<td colspan="2" style="text-align: center; height: 21px;">
<span style="font-size: 24pt">
Login</span>
</td>
</tr>
<tr>
<td style="width: 71px" valign="top">
<asp:Label ID="lblEmail" runat="server" Text="Email:"></asp:Label></td>
<td style="width: 178px; text-align: right;" valign="top">
<asp:TextBox ID="txtEmail" runat="server" ></asp:TextBox></td>
<td style="width: 37px" valign="top">
<asp:RequiredFieldValidator ID="EmailRequiredFieldValidator" runat="server" ControlToValidate="txtEmail"
Display="Dynamic" ErrorMessage="Email Required" SetFocusOnError="True">*</asp:RequiredFieldValidator>
<asp:RegularExpressionValidator ID="EmailRegularExpressionValidator" runat="server"
ControlToValidate="txtEmail" Display="Dynamic" ErrorMessage="Provide Valid Email Address"
ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">*</asp:RegularExpressionValidator></td>
</tr>
<tr>
<td style="width: 71px; height: 26px;">
<asp:Label ID="lblPassword" runat="server" Text="Password:"></asp:Label></td>
<td style="width: 178px; height: 26px; text-align: right;">
<asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox></td><
<td style="width: 37px; height: 26px">
<asp:RequiredFieldValidator ID="PasswordRequiredFieldValidator" runat="server" ControlToValidate="txtPassword"
Display="Dynamic" ErrorMessage="Password Required">*</asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td colspan="2" style="text-align: right">
</td>
<td colspan="1" style="width: 37px; text-align: right">
</td>
</tr>
<tr>
<td style="width: 71px; height: 27px;"> </td>
<td style="width: 178px; text-align: right; height: 27px;">
<asp:Button ID="btnLogin" runat="server" Style="position: relative"
Text="Login" onclick="btnLogin_Click" /></td>
<td style="width: 37px; height: 27px; text-align: right">
</td>
</tr>
<tr>
<td style="width: 71px; text-align: right; height: 27px;">
</td>
<td style="width: 178px; text-align: right; height: 27px;">
<asp:Label ID="lblNewUser" runat="server" Text="New User?"></asp:Label>
<asp:HyperLink ID="RegisterHyperLink" runat="server" Font-Bold="False" Font-Names="Georgia"
NavigateUrl="~/Register.aspx" Style="position: relative">Register</asp:HyperLink>
</td>
<td style="width: 37px; height: 27px; text-align: right">
</td>
</tr>
<tr>
<td colspan="3" style="height: 27px; text-align: center">
<asp:ValidationSummary ID="LoginValidationSummary" runat="server" />
</td>
</tr>
</table>
<br />
<asp:Label ID="lblMessage" runat="server"></asp:Label>I have used RequiredFieldValidator for both email and password and I have also used a RegularExpressionValidator for email. I have displayed a HyperLink control to direct the user to register or Signup page. - Write below stored procedure in SQL Server database to verify user.CREATE PROCEDURE dbo.VerifyAccount@Email Varchar(100),@Password NVarchar(50),@Verify BIT OUTPUTASBEGINDECLARE @RecordCount INTSELECT @RecordCount = Count(*) FROM Account WHERE Email = @Email AND Password = @PasswordIF @RecordCount = 1BEGINSET @Verify = 1ENDELSEBEGINSET @Verify = 0ENDENDdbo.VerifyAccount stored procedure checks in Account table for any account against email and password.
- Open code behind file and include following namespace.C#using System.Data;using System.Data.SqlClient;VB.NET
Imports System.DataImports System.Data.SqlClient
- Write two functions in code behind file to verify user and to get user name.Function to verify userC#
public bool VerifyAccount(string email, string password){bool result;string connstring = "Data Source=Local;Initial Catalog=SampleApplicationDatabase;Integrated Security=True";SqlConnection conn = new SqlConnection(connstring);SqlCommand cmd = new SqlCommand("VerifyAccount", conn);cmd.CommandType = CommandType.StoredProcedure;cmd.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = email;cmd.Parameters.Add("@Password", SqlDbType.NVarChar, 50).Value = password;SqlParameter pVerify = new SqlParameter("@Verify", SqlDbType.Bit);pVerify.Direction = ParameterDirection.InputOutput;pVerify.Value = DBNull.Value;cmd.Parameters.Add(pVerify);try{conn.Open();cmd.ExecuteNonQuery();if ((bool)pVerify.Value == true){result = true;}else{result = false;}}catch (Exception ex){result = false;}conn.Close();return result;}VB.NET
Public Function VerifyAccount(email As String, password As String) As BooleanDim result As BooleanDim connstring As String = "Data Source=Local;Initial Catalog=SampleApplicationDatabase;Integrated Security=True"Dim conn As New SqlConnection(connstring)Dim cmd As New SqlCommand("VerifyAccount", conn)cmd.CommandType = CommandType.StoredProcedurecmd.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = emailcmd.Parameters.Add("@Password", SqlDbType.NVarChar, 50).Value = passwordDim pVerify As New SqlParameter("@Verify", SqlDbType.Bit)pVerify.Direction = ParameterDirection.InputOutputpVerify.Value = DBNull.Valuecmd.Parameters.Add(pVerify)Tryconn.Open()cmd.ExecuteNonQuery()If CBool(pVerify.Value) = True Thenresult = TrueElseresult = FalseEnd IfCatch ex As Exceptionresult = FalseEnd Tryconn.Close()Return resultEnd FunctionFunction to get user nameC#
public string GetUser(string email){string userName = "";string sqlQuery = "SELECT (FirstName + ' ' + LastName) AS UserName FROM Account WHERE Email = @Email";string connstring = "Data Source=Local;Initial Catalog=SampleApplicationDatabase;Integrated Security=True";SqlConnection conn = new SqlConnection(connstring);SqlCommand cmd = new SqlCommand(sqlQuery, conn);cmd.CommandType = CommandType.Text;cmd.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = email;try{conn.Open();userName = cmd.ExecuteScalar().ToString();}catch (Exception ex){}finally{conn.Close();}return userName;}VB.NET
Public Function GetUser(email As String) As StringDim userName As String = ""Dim sqlQuery As String = "SELECT (FirstName + ' ' + LastName) AS UserName FROM Account WHERE Email = @Email"Dim connstring As String = "Data Source=Local;Initial Catalog=SampleApplicationDatabase;Integrated Security=True"Dim conn As New SqlConnection(connstring)Dim cmd As New SqlCommand(sqlQuery, conn)cmd.CommandType = CommandType.Textcmd.Parameters.Add("@Email", SqlDbType.VarChar, 100).Value = emailTryconn.Open()userName = cmd.ExecuteScalar().ToString()Catch ex As ExceptionFinallyconn.Close()End TryReturn userNameEnd FunctionVerfiyAccount() function verifies that an account exists using stored procedure against entered email and password.GetUser() function retrieves full name of the user against email. For this, you have to make sure that there will be only one user for one email address. Note in SQL query, I have concatenated first and last name to get as single string. - Write code below in login button click eventC#
protected void btnLogin_Click(object sender, EventArgs e){bool result = VerifyAccount(txtEmail.Text, txtPassword.Text);if (result == true){Session["ValidUser"] = true;Session["UserName"] = GetUser(txtEmail.Text);Response.Redirect("UserPage.aspx");}else{Session["ValidUser"] = false;lblMessage.Text = "Sorry you cannot login, please provide correct Email and password";}}VB.NET
Protected Sub btnLogin_Click(sender As Object, e As EventArgs)Dim result As Boolean = VerifyAccount(txtEmail.Text, txtPassword.Text)If result = True ThenSession("ValidUser") = TrueSession("UserName") = GetUser(txtEmail.Text)Response.Redirect("UserPage.aspx")ElseSession("ValidUser") = FalselblMessage.Text = "Sorry you cannot login, please provide correct Email and password"End IfEnd SubIn Login button click event, first I have called the VerifyAccount() function. If it is true then I have set session true for that user. I have also called GetUser() method and stored string value in a session object. Then I have redirected the user to UserPage.aspx page.
- Add code below in UserPage.aspx
<asp:Label ID="lblWelcome" runat="server"></asp:Label>
<br />
<br />
<asp:Button ID="btnLogout" runat="server" Text="Logout"
onclick="btnLogout_Click" /> - Write code below in code behind fileC#protected void Page_Load(object sender, EventArgs e){if (!IsPostBack){if ((bool)Session["ValidUser"] == true){string userName = Session["UserName"].ToString();lblWelcome.Text = "Hello " + userName + ", Welcome to our website.";btnLogout.Visible = true;}else{lblWelcome.Text = "Sorry you cannot visit this page. Please Login to visit this page.";btnLogout.Visible = false;}}}protected void btnLogout_Click(object sender, EventArgs e){Session["ValidUser"] = false;Response.Redirect("Default.aspx");}VB.NET
Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.LoadIf Not IsPostBack ThenIf CBool(Session("ValidUser")) = True ThenDim userName As String = Session("UserName").ToString()lblWelcome.Text = "Hello " + userName + ", Welcome to our website."btnLogout.Visible = TrueElselblWelcome.Text = "Sorry you cannot visit this page. Please Login to visit this page."btnLogout.Visible = FalseEnd IfEnd IfEnd SubProtected Sub btnLogout_Click(sender As Object, e As System.EventArgs) Handles btnLogout.ClickSession("ValidUser") = FalseResponse.Redirect("Default.aspx")End SubIn Page Load event of the user page, I have checked session. If user session is true then I have retrieved user name from other session object and displayed a welcome message for that user.
- Set Default.aspx as start page and Press F5. Enter values in database table directly or using Signup page. Enter email and password and click Login.
No comments:
Post a Comment