Tuesday 14 May 2013

Login Form in ASP.Net with C#


Login Form in ASP.Net with C#



Login Form in ASP.Net with C#


Here, I’m going to describe Login web Form in ASP.Net. This article’s beauties are, it provide login for Admin and User both from single tableaccording define role.  This demo is having proper validation and Stay login. Steps are given below:
Step 1:- Create a table and fill records
CREATE TABLE LoginAuthentication
(
      [id] [varchar](50) Primary Key,
      [pass] [varchar](50) NOT NULL,
      [role] [int] NOT NULL
)

Login Form in ASP.Net with C#
Note:- Here role 1 means Admin Login and 0 means User Login
Step 2: Take three web pages namely “Login.aspx”, “Admin.aspx” and “User.aspx
Step 3:- Add Connection String in web.config file
<configuration>
                <connectionStrings>
                                 <add name="dbconnection" providerName="System.Data.SqlClient"
                                    connectionString="Data Source=.;Initial Catalog=avi;User Id=avisqlserver;        password=123456" />
                </connectionStrings>
</configuration>

Step 4:- Login.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        .style1
        {
            width75px;
        }
        .style2
        {
            width417px;
        }
    </style>
    <script type="text/javascript">
        window.history.forward();
        function noBack() { window.history.forward(1); }
    </script>
    <%--RequerFeildValidater--%>
    <script type="text/javascript">
        function ValidateFeild() {
            var txtId = document.getElementById("txtId").value;
            var txtPass = document.getElementById("txtPassword").value;
            if (txtId === "") {
                document.getElementById("lblId").innerHTML = "*";
                document.getElementById("lblId").title = "Enter email id";
                return false;
            }
            else {
                document.getElementById("lblId").innerHTML = "";
            }

            if (txtPass === "") {
                document.getElementById("lblPass").innerHTML = "*";
                document.getElementById("lblPass").title = "Enter password";
                return false;
            }
            else {
                document.getElementById("lblPass").innerHTML = "";
            }

            if (txtId !== "") {
                var RegExEmail = /^(?:\w+\.?)*\w+@(?:\w+\.)+\w+$/;

                if (!RegExEmail.test(txtId)) {
                    document.getElementById("lblEmailValid").innerHTML = "*";
                    document.getElementById("lblEmailValid").title = "Email formate incorrect";
                    return false;
                }
                else {
                    document.getElementById("lblEmailValid").innerHTML = "";
                }
            }

        }
    </script>
    
</head>
<body onload="noBack();" onpageshow="if (event.persisted) noBack();" onunload="">
    <form id="form1" runat="server">
    <div style="height: 426px">
        <fieldset style="width: 236px; background-image: url(images/legendback.png);" />
        <legend></legend>
        <table cellpadding="0" cellspacing="0" style="height: 197px">
            <tr style="padding: 0px;">
                <td style="border-bottom: 1px solid black; padding: 0px">
                Sign in
                </td>
                <td style="border-bottom: 1px solid black;">
                   
                </td>
            </tr>
        
            <tr>
                <td class="style1">
                    Email Id
                </td>
                <td class="style2">
                    <asp:TextBox ID="txtId" runat="server" Width="130px"meta:resourcekey="txtIdResource1" OnFocus="this.style.borderColor='blue'"OnBlur="this.style.borderColor=''" ></asp:TextBox>
                    <asp:Label ID="lblId" runat="server" ForeColor="#FF3300"></asp:Label>
                    <asp:Label ID="lblEmailValid" runat="server" ForeColor="#FF3300"></asp:Label>
                </td>
            </tr>
            <tr>
                <td class="style1">
                    <asp:Label ID="lblPassword" runat="server" Text="Password"meta:resourcekey="lblPasswordResource1"></asp:Label>
                </td>
                <td class="style2">
                    <asp:TextBox ID="txtPassword" runat="server" Width="130px"meta:resourcekey="txtPasswordResource1" OnFocus="this.style.borderColor='blue'"OnBlur="this.style.borderColor=''"
                        TextMode="Password"></asp:TextBox>
                    <asp:Label ID="lblPass" runat="server" ForeColor="#FF3300"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                </td>
                <td class="style2">
                    <asp:Label ID="lblErrorMsg" runat="server" ForeColor="#FF3300"Visible="False" meta:resourcekey="lblErrorMsgResource1"></asp:Label>
                </td>
            </tr>
            <tr>
                <td>
                </td>
                <td>
                    <asp:CheckBox ID="chkRemember" runat="server" Text="Stay signed in" />
                </td>
            </tr>
            <tr>
                <td class="style1">
                </td>
                <td class="style2">
                    <asp:Button ID="btnLogin" runat="server" Text="Sign In"OnClientClick="return ValidateFeild(this)"
                        OnClick="btnLogin_Click1" meta:resourcekey="btnLoginResource1" />
                </td>
            </tr>
        </table>
        </fieldset>
    </div>
    </form>
</body>
</html>


Output
Login Form in ASP.Net with C#
Step 5:- Login.aspx.cs
using System;
using System.Data;
using System.Data.SqlClient;

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

    readonly string cnString = System.Configuration.ConfigurationManager.ConnectionStrings["dbconnection"].ConnectionString;


    public void login(string id, string pass)
    {
        if (id.Length > 0 && pass.Length > 0)
        {
            try
            {
                SqlConnection con = new SqlConnection(cnString);
                SqlCommand cmd = new SqlCommand(String.Format("select * from LoginAuthentication where id = '{0}'", id), con);
                if (con.State == ConnectionState.Closed)
                    con.Open();

                using (SqlDataReader rd = cmd.ExecuteReader())
                {
                    if (rd.Read())
                    {
                        if (rd["pass"].ToString() == pass)
                        {
                            lblErrorMsg.Visible = false;
                            if (chkRemember.Checked == true)
                            {
                                Response.Cookies["IdCookie"].Value = txtId.Text.Trim();
                                Response.Cookies["IdCookie"].Expires =DateTime.Now.AddDays(30);
                                Response.Cookies["PassCookie"].Value = txtPassword.Text.Trim();
                                Response.Cookies["PassCookie"].Expires =DateTime.Now.AddDays(30);
                            }
                            if (Convert.ToInt32(rd["role"]) == 1)
                            {
                                Session.Add("AdminSession", id);
                                Response.Redirect("Admin.aspx");
                            }
                            else
                            {
                                Session.Add("UserSession", id);
                                Response.Redirect("User.aspx");
                            }
                        }
                        else
                        {
                            lblErrorMsg.Text = "password incorrect";
                            lblErrorMsg.Visible = true;
                        }
                    }
                    else
                    {
                        lblErrorMsg.Text = "email id incorrect ";
                        lblErrorMsg.Visible = true;
                    }
                }
                if (con.State == ConnectionState.Open)
                    con.Close();
            }
            catch
            {
               
            }
        }
       
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Request.Cookies["IdCookie"] != null && Request.Cookies["PassCookie"] != null)
                 login(Request.Cookies["IdCookie"].Value, Request.Cookies["PassCookie"].Value);
        }
    }

    protected void btnLogin_Click1(object sender, EventArgs e)
    {
        login(txtId.Text.Trim(),txtPassword.Text.Trim());
    }
   
}


Step 6:- Admin.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
     <script type="text/javascript">
         window.history.forward();
         function noBack() { window.history.forward(1); }
</script>
</head>
<body onload="noBack();" onpageshow="if (event.persisted) noBack();" onunload="">
    <form id="form1" runat="server">
    <div>
    Welcome Admin Panel
        <asp:LinkButton ID="LinkButton1" runat="server"
            style="float: right; margin:0px 40px 0px 0px" onclick="LinkButton1_Click">Sign Out</asp:LinkButton>
    </div>
    </form>
</body>
</html>

Step 7:- Admin.aspx.cs
using System;

public partial class Admin : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Convert.ToString(Session["AdminSession"]) == "")          
            Response.Redirect("Login.aspx");
    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Session.Abandon();
        Response.Cookies["IdCookie"].Value = null;
        Response.Cookies["PassCookie"].Value = null;
        Response.Redirect("Login.aspx");    
    }
}

Step 8:- User.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        window.history.forward();
        function noBack() { window.history.forward(1); }
</script>
</head>
<body onload="noBack();" onpageshow="if (event.persisted) noBack();" onunload="">
    <form id="form1" runat="server">
    <div>
    Welcome User Panel
    <asp:LinkButton ID="LinkButton1" runat="server"
            style="float: right; margin:0px 40px 0px 0px" onclick="LinkButton1_Click">Sign Out</asp:LinkButton>
    </div>
    </form>
</body>
</html>

Step 9:- User.aspx.cs
using System;

public partial class User : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Convert.ToString(Session["UserSession"]) == "")
            Response.Redirect("Login.aspx");
    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Session.Abandon();
        Response.Cookies["IdCookie"].Value = null;
        Response.Cookies["PassCookie"].Value = null;
        Response.Redirect("Login.aspx");
       
    }
}

Step 10:- compile the program and run the application
Note- If you not properly Sing Out web form then, when will be open Login web formautomatic previous Logged web form open, becausecookies are set on Admin and User web form’s Page_Load event.

No comments:

Post a Comment