Blue Theme Orange Theme Green Theme Red Theme
 
Nevron Chart
Home | Forums | Videos | Advertise | Certifications | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
Discover the top 5 tips for understanding .NET Interop
Search :       Advanced Search »
Home » Learn .NET » Login Control in ASP.NET 3.5

Login Control in ASP.NET 3.5

In this step by step tutorial, I am going to discuss the Login control available in ASP.NET 3.5.

Author Rank :
Page Views : 129016
Downloads : 3723
Rating :
 Rate it
Level : Beginner
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
Download Files:
LoginControl.zip
 
 
Nevron Chart
Become a Sponsor
 Tag Cloud
 Latest Jobs
More ... 
 Latest Interview Questions
More ... 

The ASP.NET login controls provide a robust login solution for ASP.NET Web applications without requiring programming. By default, login controls integrate with ASP.NET membership and forms authentication to help automate user authentication for a Web site. It provides you with a ready-to-use user interface that queries the user name and password from the user and offers a Log In button for login. It validate user credentials against the membership API and encapsulating the basic froms authentication functionality like redirecting back to the original requested page in a restricted area of you application after the successful login.

The Login control displays a user interface for user authentication. The Login control contains text boxes for the user name and password and a check box that allows users to indicate whether they want the server to store their identity using ASP.NET membership and automatically be authenticated the next time they visit the site.

The Login control has properties for customized display, for customized messages, and for links to other pages where users can change their password or recover a forgotten password. The Login control can be used as a standalone control on a main or home page, or you can use it on a dedicated login page. If you use the Login control with ASP.NET membership, you do not need to write code to perform authentication. However, if you want to create your own authentication logic, you can handle the Login control's Authenticate event and add custom authentication code.

Note - Login controls might not function correctly if the Method of the ASP.NET Web page is changed from POST (the default) to GET.

Ø  Start Microsoft Visual Studio 2008

Ø  Create a new ASP.NET WebSite, Like this:


Ø 
Drang and drop Login control on page from ToolBox.

 

 

Figure 1.

Whenever user hits the Log In button, the control automatically validates the user name and password using the membership API function Membership.ValidateUse() and then calls FormAuthentication.redirectFromLoginPage() if the validation was successful. All options on the UI of the LoginControl affect the input delivered by the control to these methods. For Example, if you click the "Remember me next time" check box, it passes the value true to the createPresistentCookie parameter of the RedirectFromLoginPage() method. Therefore, the FormAuthenticateModule creates a persistent cookie.

There are three Login Tasks by default.

·         Auto Format - you can select default schemes.

·         Convert To Template - You can edit content of Login Control.

·         Administer Website - You can configure Web Site Administration Tools, Like Security, Application, Provider.

 

Figure 2. 

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

<div>

<asp:Login ID="Login1" runat="server" BackColor="#F7F7DE" BorderColor="#CCCC99" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana" Font-Size="10pt">

<TitleTextStyle BackColor="#6B696B" Font-Bold="True" ForeColor="#FFFFFF" />

</asp:Login>

    </div>

    </form>

You can change styles of LoginControl using css too,  Like this:

.LoginControl

{

      background-color:#F7F7DE;

      border-color:#CCCC99;

      border-style:solid;

    border-width:1px;

    font-family:Verdana;

    font-size:10px;    

}

And now apply css to control:

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Login Control</title>

    <link href="StyleSheet.css" type="text/css" rel="Stylesheet" />

</head>

<body>

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

    <div>

        <asp:Login ID="Login1" runat="server" CssClass="LoginControl">

            <TitleTextStyle BackColor="#6B696B" Font-Bold="True" ForeColor="#FFFFFF" />

        </asp:Login>

    </div>

    </form>

</body>

</html>

 

If you running the page and if the CSS file is placed in a directory where anonymous access is denied, the add the following configuration for the CSS file to you web.config file.

<location path="StyleSheet.css">

<system.web>

<authorization>

<allow users="*"/>

</authorization>

</system.web>

</location>

 

You can add several hyperlinks to your Login control, such as hyperlink to a help text page, or a hyperlink to to a registration page.

 

<asp:Login ID="Login1" runat="server" CssClass="LoginControl"

CreateUserText="Register"

CreateUserUrl="~/Register.aspx"

HelpPageText="Additional Help" HelpPageUrl="~/Help.aspx"

InstructionText="Please enter your user name and password for login.">

<TitleTextStyle BackColor="#6B696B" Font-Bold="True" ForeColor="#FFFFFF" />

</asp:Login>

Looks like this :

Here is .CS Code:

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data.SqlClient;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

        if (!this.IsPostBack)

            ViewState["LoginErrors"] = 0;

    }

 

   protected void Login1_Authenticate(object sender, AuthenticateEventArgs e)

    {

        if (YourValidationFunction(Login1.UserName, Login1.Password))

        {

           // e.Authenticated = true;

            Login1.Visible = false;

            MessageLabel.Text = "Successfully Logged In";

        }

        else

        {

            e.Authenticated = false;

        }

    }

   

  

 protected void Login1_LoginError(object sender, EventArgs e)

    {

        if (ViewState["LoginErrors"] == null)

            ViewState["LoginErrors"] = 0;

 

        int ErrorCount = (int)ViewState["LoginErrors"] + 1;

        ViewState["LoginErrors"] = ErrorCount;

 

        if ((ErrorCount > 3) && (Login1.PasswordRecoveryUrl != string.Empty))

            Response.Redirect(Login1.PasswordRecoveryUrl);

    }

 

 private bool YourValidationFunction(string UserName, string Password)

    {

        bool boolReturnValue = false;       

        string strConnection = "server=.;database=Vendor;uid=sa;pwd=wintellect;";

        SqlConnection sqlConnection = new SqlConnection(strConnection);

        String SQLQuery = "SELECT UserName, Password FROM Login";

        SqlCommand command = new SqlCommand(SQLQuery, sqlConnection);

        SqlDataReader Dr;

        sqlConnection.Open();

        Dr = command.ExecuteReader();

        while (Dr.Read())

        {

            if ((UserName == Dr["UserName"].ToString()) & (Password == Dr["Password"].ToString()))

            {

                boolReturnValue = true;

            }

            Dr.Close();

            return boolReturnValue;

        }

        return boolReturnValue;

    }

}

 

If you insert wrong username and password then message will show like this:

If you insert right usename, password then redirect your page whereever you want or you can show message in ErrorLabel, Like this:

I am attaching my database with application in App_Data folder, if u want use my database then attach my .MDF file.

Any question and queries ask me any time.

Comment Request!
Thank you for reading this post. Please post your feedback, question, or comments about this post Here.
Login to add your contents and source code to this article
 Article Extensions
Contents added by Ganesh on Feb 05, 2010
but how to configure website administration tool and how to strore username and password in login folder of pur database?
 [Top] Rate this article
 
 About the author
 
Raj Kumar

Raj Kumar is a Microsoft MVP and Senior Software Engineer with lots of hands on experience using ASP.NET 2.0/3.5, AJAX, MVC, C#, Visual Basic .NET, SQL Server 2005/2008, Oracle, WPF, WCF, XAML and Silverlight. He has over 6 years of IT experience working most on Microsoft technologies. He holds Master's degree in Computer Science. When he is not writing code, he likes to write articles and play cricket.

Reach him at raj2511984@gmail.com 

 

Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
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.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Discover the Top 5 .NET Memory Management Fundamentals
To write the best .NET code, you need to know exactly how the .NET framework really manages memory. Ricky Leeks presents the Top 5 fundamental facts of .NET memory management. Learn more.
Nevron Chart for .NET 2010.1 Now Available
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.
ASP.NET 4 Hosting
Get 2 Months Free of ASP.NET Hosting for Only $4.95/month! Receive FREE MS SQL and MySQL Databases Including ASP.NET 4/3.5, MVC 3.0, Silverlight 4, Windows 2008/IIS 7.0 Plus FREE IIS 7 Modules. Host UNLIMITED ASP.NET Web Sites – Click Here!
 
 Post a Feedback, Comment, or Question about this article
Subject:
Comment:
DevExpress Free UI Controls
Become a Sponsor
 Comments
Doubt in asp.net website administration tool by Ambika On September 23, 2008
Hi, Nice example. Could you please explain detail on asp.net website administration tool? which options to be clicked how to get asp_net.mdf db? Regards, Ambika
Reply | Email | Modify 
Re: Doubt in asp.net website administration tool by Raj On October 4, 2008
Just click on ASP.NET configuration link under Website tab. and in security tab click enable roles. that will automatically add ASPNETDB.MDF in App_Data folder.
Reply | Email | Modify 
Re: Doubt in asp.net website administration tool by Raj On February 20, 2011
The ASP.NET Web Site Administration Tool is a utility provided along with Microsoft Visual Studio which assists in the configuration and administration of a website created using Microsoft Visual Studio 2005 and later versions Accessing the Tool the Web Site Administration Tool could be accessed by clicking ASP.NET Configuration from the Website menu. It can also be accessed by clicking on the ASP.NET Configuration icon in the Solution Explorer window. Features The ASP.NET Web Site Administration tool is a multi-tabbed utility which has the following features: Web Site Administration Tool Security Tab Web Site Administration Tool Application Tab Web Site Administration Tool Provider Tab Web Site Administration Tool Internals asp_net.mdf is auto generated database which is stored in App_Data asp.net folder in application.
Reply | Email | Modify 
Try To Copy Completely....... by Qais On October 6, 2008
Your example is not working.............
Reply | Email | Modify 
Problem Using ASP.NET Web Site Administration Tool by Pedro On April 14, 2009
I am trying to set up a login page and have to use the ASP.NET Web Site Administration Tool in the process. I am running Visual Studio as an administrator. I got the following error message when I clicked to the Security tab in the Administration Tool: There is a problem with your selected data store. This can be caused by an invalid server name or credentials, or by insufficient permission. It can also be caused by the role manager feature not being enabled. Click the button below to be redirected to a page where you can choose a new data store. The following message may help in diagnosing the problem: Unable to connect to SQL Server database. Any ideas what is going on? Peter
Reply | Email | Modify 
Need Remember me Next time with login control by MONIA On July 8, 2009
Hi

Thank u for the post. I am new to .NET and ur post really helped me a lot. can u please post the code for remember me next time option?

Thanks in Advance
Viki
Reply | Email | Modify 
thanks for ur login post by mohamed On September 9, 2009
thanks
Reply | Email | Modify 
Thank you by Pubudini On October 26, 2009
Your article is very clear to understand. Thank you so much.
Reply | Email | Modify 
very good by doam minh On December 12, 2009
thanks you
Reply | Email | Modify 
Thanks by ankit On February 24, 2010
Hey thanks alot ..you saved me alot of time...this was awesome..thanks alot !!
Reply | Email | Modify 
Oracle in administration tool by saeed On June 10, 2010
At first thanks for this topic and how can i use oracle provider in web sit administration tool(Figure 2.) because i have one provider (AspNetSqlMembershipProvider) i want (OracleProvider ) how can it be apear ? 
Reply | Email | Modify 
Re: Oracle in administration tool by Raj On February 20, 2011
first you must change provider for membership and roles from sql server to oracle as above secand you must configration new provider like scand code. but but in your mind you must add references for Oracle.DataAccess.Client and oracle.web thired you must create schema in oracle database and give this user above privilages Change notification Create job Create procedure Create public synonym Create role Create session Create table Create view Drop public synonym Grant access to and allocate space in an Oracle tablespace also for your information ODP.Net have tools for oracle database you can run sql script you can find it in (odp_home)/ASP.NET\SQL you must first with InstallOracleASPNETCommon.sql and run all scripts start with install then you can configuation from admin tools web site 1.<remove name="OraAspNetConString"/> 2. <add name="DORKNOZZLE" connectionString="oracle connection" providerName="Oracle.DataAccess.Client" />
Reply | Email | Modify 
Login Control Comment by durga On September 15, 2010
hi Raj,


     This example is not working. i am trying to solve that problem. but no answer.
     If i gave username,password ,then brower running without answer like  "login successfully". It showed time expired error.



Reply | Email | Modify 
plz tell how do i rectify this error by ghafran On December 25, 2010
"A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)" waiting for yours reply
Reply | Email | Modify 
Re: plz tell how do i rectify this error by Raj On February 20, 2011
connection string is not working properly. check your connection string.
Reply | Email | Modify 
thanks by satish On January 20, 2011
best of luck in future.....
Reply | Email | Modify 
Re: thanks by Raj On February 20, 2011
Thanks
Reply | Email | Modify 
Login Control by Rajendra On February 7, 2011
All articles of Raj Kumar are greate.
Reply | Email | Modify 
while loop error by Malek On February 13, 2011
the while loop should be like this -------------------------------------------------- while (Dr.Read()) { if ((username == Dr["username"].ToString()) & (password == Dr["password"].ToString())) { boolReturnValue = true; break; } } Dr.Close(); return boolReturnValue; -------------------------------------------------- other wise, it's just going to check the first username in the database.
Reply | Email | Modify 
Re: while loop error by Raj On February 20, 2011
you are right malek thanks.
Reply | Email | Modify 
Feed back by Sunita On February 17, 2011
Information is worhit.
Reply | Email | Modify 
log out page by rajeev On March 25, 2011
sir can you please instruct me to design logout page using master page I'm a fresher to .net so please help me out
Reply | Email | Modify 
admin panel by jasbir On May 12, 2011
how to make admin panel in asp.net with .cs
Reply | Email | Modify 
login control by sathya On July 10, 2011
This working only in the current page. How to make to work login status and login name for all the page. Regards, Sathya
Reply | Email | Modify 
ASPNETDB.mdf and web.config by Hassan On July 11, 2011
How to deploy ASPNETDB.mdf to remote server (from local PC to Internet) and what changes that required to be done on web.config file? Thank you - Hassan Shaqhan - ShaqhanHA@yahoo.com
Reply | Email | Modify 
Re: ASPNETDB.mdf and web.config by EMMANUEL On July 26, 2011
No reconoce a login1 Error 2 El nombre 'Login1' no existe en el contexto actual C:\Users\Emmanuel\Documents\Visual Studio 2010\Projects\WebApplication3\WebApplication3\Default.aspx.cs 36 36 WebApplication3 n
Reply | Email | Modify 
Re: ASPNETDB.mdf and web.config by Raj On September 5, 2011
From Visual Studio, in your Server Explorer tab, you'll notice all of the tables created by default. As well, there are Views, Stored Procedures, etc. First, we want to create a SQL script to recreate all of those objects. So right click the database and select Publish To Provider.This will bring up the Database Publishing Wizard. Select the button to continue.You will be presented with a list of your databases and asked to select your database. There is a checkbox to Script all objects in the database. Select it. Select Next to continue.Now you are given the option to script to a file. It presents a default path, I changed mine.In the next window you will be offered several options. In my case, I needed to change the target database to SQL Server 2008. Select the target you need, then Select to continue. As per Chris Rivera's comment below this blog, if 2008 doesn't show as an option, make sure you download and install SP1.Next you may review the options selected.Click Finish to complete the Wizard. You'll see the progress.Now you have a fancy script generated for you. This script will select, alter, drop, update, insert, etc. etc., all needed values. Now to get this to your database server. Mine happens to be on the same network as my webserver, but not on the same network as my development box, so I created a folder within my project and placed the script in there. When I updated my project, this sql script was then copied to my web server. From my database server, I then copied it via the network to my SQL Server 2008 Web Edition desktop. I opened my Microsoft SQL Server Management Studio and created my new blank database. Just right click Databases, and select New Database. Give it a name and select OK. Then with this new database selected, click the sql file on your desktop and it will open up in your screen. Again, with the new database selected, right click in the script and select "Execute." This will execute the script on the selected database and create all the objects needed.
Reply | Email | Modify 
PasswordRecoveryUrl by Yogesh On August 9, 2011
Hello My dear i have implemented in my local server but still there is a problem with my Login1.PasswordRecoveryUrl not working well while i have typed password wrong more than three times. . . Please revert me back Thanks in advance Yogesh chandra upreti
Reply | Email | Modify 
Discover the top 5 tips for understanding .NET Interop
 © 2012  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.