SIGN UP MEMBER LOGIN:    
ARTICLE

Simple Login Project in ASP.Net

Posted by Abhimanyu Kumar Vatsa Articles | ASP.NET Programming June 17, 2010
This article will explain you how to create simple login project without using any login controls.
Reader Level:
 

Introduction

As we know on internet world without security we can not expect any thing. At least on every website we use to face such like to create account but as far we concern to learn how to create it then without any good guidelines we can't. Let's take a look on this article to create such project.

Perquisite

This article expect something from you as

  1. You should know MS-SQL Server
  2. You should have the basic knowledge of ASP.Net controls

Creating Database

To store the user's credentials for future login, we should have database. So, let's create it.

Database Name: myDb.mdf

Table Name: myTb

Column Names:

Column Name Data Type Required or Not
name varchar(50) Not Checked
username varchar(50) Not Checked
password varchar(50) Not Checked
emailed varchar(100) Not Checked

login1.gif

Creating Database Configuration in web.config file

To create database configuration in web.config file, simply drag the 'myTb' table from Database Explorer on any form and now delete the dragged item from web page, it will create the configuration settings for your database in web.config file automatically.

login2.gif

Here is your configuration in web.config file

<connectionStrings>
  <
add name="myDbConnectionString1" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\myDb.mdf;Integrated Security=True;User Instance=True"
   providerName="System.Data.SqlClient" />
 </connectionStrings>

Create User Form Designing

To create or register new user we should have a form as given below. You can ignore the side links, top banner and footer texts because they are occurring from master page.

login3.gif

 
Control Name ID Other
TextBox name  
TextBox username  
TextBox password Textmode=password
TextBox emailed  
Button create Text=Create User

To call for the database configuration setting from web.config file I have used a function

    public string GetConnectionString()
    {
        return System.Configuration.ConfigurationManager.ConnectionStrings["myDbConnectionString1"].ConnectionString;
    }

I have used a execute named function in code behind to perform the insertion task when 'Create User' named button clicked

private void execution(string name, string username, string password, string emailid)
    {
        SqlConnection conn = new SqlConnection(GetConnectionString());
        string sql = "INSERT INTO myTb (name, username, password, emailid) VALUES "
        + " (@name, @username, @password, @emailid)";
        try
        {
            conn.Open();
           
           
SqlCommand cmd = new SqlCommand(sql, conn);
            SqlParameter[] pram = new SqlParameter[4];

            pram[0] = new SqlParameter("@name", SqlDbType.VarChar, 50);
            pram[1] = new SqlParameter("@username", SqlDbType.VarChar, 50);
            pram[2] = new SqlParameter("@password", SqlDbType.VarChar, 50);
            pram[3] = new SqlParameter("@emailid", SqlDbType.Char, 10);

            pram[0].Value = name;
            pram[1].Value = username;
            pram[2].Value = password;
            pram[3].Value = emailid;

            for (int i = 0; i < pram.Length; i++)
            {
                cmd.Parameters.Add(pram[i]);
            }
            cmd.CommandType = CommandType.Text;
            cmd.ExecuteNonQuery();
        }
        catch (System.Data.SqlClient.SqlException ex_msg)
        {
            string msg = "Error occured while inserting";
            msg += ex_msg.Message;
            throw new Exception(msg);
        }
        finally
        {
            conn.Close();
        }
    }

Finally I have used to following code in 'Create User' button click event. In this event we have to check the database for the duplication. Because in login project duplications are never assumed even. If there is no any duplication found in code behind will create a new account. Here it is

protected void create_Click(object sender, EventArgs e)
    {
        SqlDataSource sds = new SqlDataSource();
        sds.ConnectionString = ConfigurationManager.ConnectionStrings["myDbConnectionString1"].ToString();

        sds.SelectParameters.Add("name", TypeCode.String, this.name.Text);
        sds.SelectParameters.Add("username", TypeCode.String, this.username.Text);
        sds.SelectParameters.Add("password", TypeCode.String, this.password.Text);
        sds.SelectParameters.Add("emailid", TypeCode.String, this.emailid.Text);

        sds.SelectCommand = "SELECT * FROM [myTb] WHERE [username] = @username";

        DataView dv = (DataView)sds.Select(DataSourceSelectArguments.Empty);

        if (dv.Count != 0)
        {
            this.lblinfo.ForeColor = System.Drawing.Color.Red;
            this.lblinfo.Text = "The user already Exist!";
            return;
        }
        else
        {  
            execution(name.Text,username.Text,password.Text,emailid.Text);
            this.lblinfo.Text = "New User Profile has been created you can login now";
this.name.Text = "";
            this.username.Text = "";
            this.password.Text = "";
            this.emailid.Text = "";
        }
    }

Login User Form Designing

To create or register new user we have created a form but still we don't have any login form. So let's create the login form.
 

Control Name ID Other
TextBox username  
TextBox password  
Button log Text=Login

login4.gif

Now we have to write some codes which will select the values from database @ values in textboxes. And if any values are not being selected (retrieved) in code behind then show the error message like 'Invalid username or password!'. And if it matches any record then will redirect to the secure page. Here one more big concept arises, is know as 'membership'. But his is out of this article. Let's take a look at code behind of login form.

protected void log_Click(object sender, EventArgs e)
    {
        SqlDataSource sds = new SqlDataSource();
        sds.ConnectionString = ConfigurationManager.ConnectionStrings["myDbConnectionString1"].ToString();

        sds.SelectParameters.Add("username", TypeCode.String, this.username.Text);
        sds.SelectParameters.Add("password", TypeCode.String, this.password.Text);

        sds.SelectCommand = "SELECT * FROM [myTb] WHERE [username] = @username AND [password] = @password";

        DataView dv = (DataView)sds.Select(DataSourceSelectArguments.Empty);

        if (dv.Count == 0)
        {
            this.lblinfo.ForeColor = System.Drawing.Color.Red;
            this.lblinfo.Text = "Invalid username and password!";
            return;
        }
        else
        {
            this.Session["username"] = dv[0].Row["username"].ToString();
            Response.Redirect("securepage/SecurePage.aspx");
        }
    }

Almost we have done everything but still we are missing a major thing. If you run your project at this time will open the SecurePage.aspx without login also. But if you want to redirect the user for login and then with authentication can access the SecurePage.aspx we have to deny the access in SecurePage.aspx page or directly in particular directory. And also when user enters credentials then session variables remember it until user close his browser or click on logout button or link (generally we prefer to click on logout).

So let's take a look to deny the access:

:::::::::::
  :::::::::::
  <
location path="securepage">
    <system.web>
      <
authorization>
        <
deny users="?"/>
      </authorization>
    </
system.web>
  </
location>

</configuration>

And we also have to change the authentication mode to "Forms" like:

::::::::::::::
<
system.web>
    <
authentication mode="Forms">
      <forms loginUrl="Login.aspx" />
    </authentication>
            <
compilation debug="true"/>
</system.web>
::::::::::::::

Conclusion

We can also place our logins to MasterPage so that can be visible entirely in website.

HAVE A GOOD CODING!
 

Login to add your contents and source code to this article
share this article :
post comment
 

Hello Rahul, I try to log in but the proggram not connected in UserDetails page.When put to Log In Button all it does refresh the log in page

Posted by John Liamiras May 11, 2012

Buddy, the project I have attached here is fully tested by many guys, i can't think that has any error. I'll recommend you to check the coding or come with the error msg in forum section here. Thanks.

Posted by Abhimanyu Kumar Vatsa Mar 14, 2012

When I execute the Default.aspx page on Visual Studio 2010 it gives me this error "This page contains the following errors: error on line 1 at column 2: StartTag: invalid element name Below is a rendering of the page up to the first error." How do I fix it?

Posted by Shrisha S Bhat Mar 14, 2012

thanks very much

Posted by Dungxk Nov 08, 2011

check out the microsoft website [http://www.microsoft.com/visualstudio/en-us/products/2010-editions/express] and download any express edition

Posted by Abhimanyu Kumar Vatsa Sep 01, 2011
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor
PREMIUM SPONSORS
  • Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
6 Months Free & No Setup Fees ASP.NET Hosting!
Become a Sponsor