Powered by Blogger.

Monday, July 19, 2010

How to Write a Simple login page in Asp.net

Yesterday I stumbled across a post that was posted on our forum. I was very busy with other things, when Sheo started a conversation based on that post. I was looking at it until he updated the untagged code that was posted. By looking at the Stored Procedure I could see that the poster was lost and his Stored Procedure approach failed him. In this Article am going to explain how to write a simple login in Asp.net.


sing the code
We are going to user C# as our language.
Start
Open Visual Studio and Create a New Website. Automatically you will have an empty page defined for you like this 
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 id="Head1" runat="server">

<title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    </div>

    </form>

</body>

</html>  
 Go to Design View and you will notice there is nothing on your page. Now open your Toolbox and add a buttons and some textbox and depicted in the following.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 id="Head1" runat="server">

<title></title>

</head>

<body>

    <form id="form1" runat="server">

    <div>

    <asp:Label ID="lblUsername" runat="server" Text="Username"></asp:Label>

    &nbsp;&nbsp;&nbsp;&nbsp;

    <asp:TextBox ID="txtUsername" runat="server"></asp:TextBox>

    <br />

    <br />

    <asp:Label ID="lblPassword" runat="server" Text="Password"></asp:Label>

    &nbsp;&nbsp;&nbsp;&nbsp;

    <asp:TextBox ID="txtPassword" runat="server" TextMode="Password"></asp:TextBox>

    <br />

    <br />

    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

    <asp:Button ID="btnlogin" runat="server" Text="Login" onclick="btnlogin_Click"

    Width="47px" />

    &nbsp;

    <asp:Button ID="btnCancel" runat="server" Text="Cancel"

    onclick="btnCancel_Click" />

    <br />

    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;

    <asp:Label ID="lblMessage" runat="server" Text=""></asp:Label>

    </div>

    </form>

</body>

</html>
And your Design should look like this

Now as you can see our login page is created, Let us see how we can validate the login and what is needed to have a proper login. Open your Sql management Studio and Create a New Database, but if you already have it you will just follow the Step 2 where we add a table.
Step 1: Create a Database 
Create Database FORUM
Step 2: Create a Table
CREATE TABLE [dbo].[Log_Users]
(
 [Logid] [int] IDENTITY(100,1)PRIMARY KEY NOT NULL,
 [Username] [varchar](55) NOT NULL,
 [PASSWORD][varchar](55),
 [Time_Logged_in] [datetime] NOT NULL,
 [Time_Logged_Out] [datetime] NOT NULL,
 [Status] [int] NOT NULL,
 [Date_Logged_in] [datetime] NOT NULL,
 [E_MAIL] [varchar](55) NOT NULL
 )

Step 3: Let us Add Sample Data 

insert into dbo.Log_Users
values('Vuyiswamb','wowididit',GETDATE(),'02/07/2010',1,GETDATE(),'Vuyiswa@wow.com')
insert into dbo.Log_Users
values('SheoNarayan','Oops?',GETDATE(),'02/09/2010',1,GETDATE(),'Sheo@wowMail.com')
Now that we have our sample Data. Please note that you can use any other field but the username and Password fields are the most important. Now let us create our stored Procedure.
Step 4: Create a Stored Prcedure that will validate and return a valid Integer.
Create Proc [dbo].[prcLoginv]
 (
 @Username VarChar(50), 
 @UPassword varChar(50),
 @OutRes int OUTPUT
 )
 AS
set @OutRes = (SELECT count(*) FROM [dbo].Log_Users 
WHERE Username = @Username And [Password] = @UPassword)
select case @OutRes
when 1 then 1 --Login is Correct
else
0  --Bad login
end 
In the above Stored Procedure we count the Records that have matched the Records and if there is one record found then it is a good login else it is a bad login. But how will you use this in your asp.net Page. First we have to create a Function that will access the stored procedure and call that function in click event of the button. Create a Function as show below in your page not inside your page load because you will get an Error.
public int Validate_Login(String Username, String Password)
{
SqlConnection con = new SqlConnection(@"User id=sa;Password=Dotnetfunda;Server=VUYISWA\VUYISWA;Database=Forum"); SqlCommand cmdselect = new SqlCommand(); cmdselect.CommandType = CommandType.StoredProcedure; cmdselect.CommandText = "[dbo].[prcLoginv]"; cmdselect.Parameters.Add("@Username", SqlDbType.VarChar, 50).Value = Username; cmdselect.Parameters.Add("@UPassword", SqlDbType.VarChar, 50).Value = Password; cmdselect.Parameters.Add("@OutRes", SqlDbType.Int, 4); cmdselect.Parameters["@OutRes"].Direction = ParameterDirection.Output; cmdselect.Connection = con;int Results = 0; try {
con.Open(); cmdselect.ExecuteNonQuery();Results = (int)cmdselect.Parameters["@OutRes"].Value;
}catch (SqlException ex) {
lblMessage.Text = ex.Message;
}
finally {
cmdselect.Dispose();if (con != null) { con.Close(); }
}return Results;
}
As you can see this Function return an Integer, as we said before this will return either a 1 which is equal to “Good” and other numbers will be “Bad”. The login Data should be clean, no Duplicates should be there because this will break your functionality. It might return the duplicates and the count might not match the if statement that you will see later in this article. Double click you Button and add the following code in the Click event of the Button.
protected void btnlogin_Click(object sender, EventArgs e)
{
int Results = 0; if (txtUsername.Text != "" && txtPassword.Text != "") {
Results = Validate_Login(txtUsername.Text, txtPassword.Text);
}
else {
lblMessage.Text = "Please make sure that the username and the password is Correct";
} if (Results == 1) {
lblMessage.Text = "Login is Good, Send the User to another page or enable controls";
}else {
lblMessage.Text = "Invalid Login"; lblMessage.ForeColor = System.Drawing.Color.Red; //Dont Give too much information this might tell a hacker what is wrong in the login
}
}
Now our code is ready for testing. Run your Application and enter an incorrect password deliberately and see what message you see and when you enter the correct login you will receive a message that says
Login is Good, Send the User to another page or enable controls
In your application you can redirect the user to another page and store the Session that you will use through out your application And abondon when the user exit your application. Please note that for some application it is good to enable and disable Controls based on the Session value, meaning that you can check if the user is logged in , and display the benefits that logged in user can get in the same page. I will not explain more on that because it is beyong the scope of this article.
Conclusion

There are a lot of ways to do a login control in asp.net, but I thought it will be important to point the basic one to our users.

Thank you for visiting DotnetFunda
Vuyiswa Maseko

2 comments:

  1. Thanks!!! it really help me alot!!! god bless...

    ReplyDelete
  2. S1061: 'ASP.default_aspx' does not contain a definition for 'btnCancel_Click' and no extension method 'btnCancel_Click' accepting a first argument of type 'ASP.default_aspx' could be found (are you missing a using directive or an assembly reference?)


    string is have no definiton for empty and the same for trim too (are you missing a using directive or an assembly reference?)


    Reply me!!

    ReplyDelete

  ©Template by Dicas Blogger.

TOPO