ASP.NET Login module using session variables | Server-side state management technique in ASP.NET

Needed Stored Procedure

create procedure sp_CheckUserWithCredentials
         @e varchar(20),
         @p varchar(10)
as
begin
       select CandName from tabCandRegistration 
       where EmailID=@e and Password=@p

end

create procedure sp_GetAllCandidateRecords
as
begin
       select CandName,EmailID,DateOfBirth as DOB,Age,JoinDate 
       from tabCandRegistration
end

web.config file

<?xml version="1.0" encoding="utf-8"?>

<!-- For more information on how to configure your ASP.NET application, please visit https://go.microsoft.com/fwlink/?LinkId=169433
  -->

<configuration>
  <connectionStrings>
    <add name="SampleDBConStr" 
         connectionString="Data Source=PC377553;
          Initial Catalog=SampleDB;
          Integrated Security=True;"/>
  </connectionStrings>
  <appSettings>
   <add key="ValidationSettings:UnobtrusiveValidationMode" value="None" />
  </appSettings>

  <system.web>
    <compilation debug="true" targetFramework="4.5.2"/>
    <httpRuntime targetFramework="4.5.2"/>
  </system.web>
  <system.codedom>
    <compilers>
    </compilers>
  </system.codedom>
</configuration>


index.aspx


using System;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace WebDemo01
{
    public partial class index : System.Web.UI.Page
    {
        protected void btnLogin_Click(object sender, EventArgs e)
        {
            //Step1 (Connection estab)
            string conStr = ConfigurationManager
                  .ConnectionStrings["SampleDBConStr"].ConnectionString;
            SqlConnection con = new SqlConnection(conStr);
            con.Open();
            //step2 (Initialize command object with query and parameters)
            SqlCommand cmd = new SqlCommand
                            ("sp_CheckUserWithCredentials", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@e", txtEmailID.Text);
            cmd.Parameters.AddWithValue("@p", txtPassword.Text);
            //Step3 check the database hit occured or not?
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                    string candName = dr["CandName"].ToString();
                    lblMsg.Text = "Welcome...." + candName;

                    //Create Session
                    Session["username"] = candName;

                    //Delayed redirection
                    Response.AppendHeader
                              ("Refresh", "3;url=RecordDisplay.aspx");

                    //or Instant redirection
                    //Response.Redirect("RecordDisplay.aspx");
            }
            else
            {
                lblMsg.Text = "User not found....";
            }
            //closer steps
            cmd.Dispose();
            con.Close();
        }

        protected void btnReset_Click(object sender, EventArgs e)
        {
            txtEmailID.Text = "";
            txtPassword.Text = "";
            lblMsg.Text = "Enter user credentials.";
            txtEmailID.Focus();
        }
    }

}

RecordDisplay.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="RecordDisplay.aspx.cs" Inherits="WebDemo01.RecordDisplay" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <table>
                <tr>
                    <td>
                        <h3>Candidate Records</h3>
                    </td>
                    <td style="width:200px;">
                        <asp:Label ID="lblStatus" runat="server" Text="Hello user...">                                 </asp:Label>
                    </td>
                    <td>
                        <asp:LinkButton ID="lnkbtnSignOut" runat="server"                                                     OnClick="lnkbtnSignOut_Click">Sign Out</asp:LinkButton>
                    </td>
                </tr>
                <tr>
                    <td colspan="3">
                        <asp:GridView ID="GridView1" runat="server" Width="600px">
                        </asp:GridView>
                    </td>
                </tr>
            </table>
        </div>
    </form>
</body>
</html>


RecordDisplay.aspx.cs


using System;

//Added...
using System.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace WebDemo01
{
    public partial class RecordDisplay : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(Session["username"]!=null)
            {
                DisplayCandidateRecords();
                lblStatus.Text = "Welcome " +                                                                  Session["username"].ToString();
            }
            else
            {
                lblStatus.Text = "You have not logged in...";
            }
        }

        private void DisplayCandidateRecords()
        {
            //Step1 (Connection estab)
            string conStr = ConfigurationManager
               .ConnectionStrings["SampleDBConStr"].ConnectionString;
            SqlConnection con = new SqlConnection(conStr);
            con.Open();

            //step2 (Initialize command object with a query)
            SqlCommand cmd = new SqlCommand
                         ("sp_GetAllCandidateRecords", con);
            cmd.CommandType = CommandType.StoredProcedure;

            //Step3 (Initialize adapter with cmd object)
            SqlDataAdapter da = new SqlDataAdapter(cmd);

            //Step4: Fill dataset
            DataSet ds = new DataSet();
            da.Fill(ds);

            // Step5: Populate GridView with records...
            GridView1.DataSource = ds;
            GridView1.DataBind();
        }

        protected void lnkbtnSignOut_Click(object sender, EventArgs e)
        {
            Session.Abandon();
            lblStatus.Text = "You are Logged out";
            Response.AppendHeader("Refresh", "3;url=index.aspx");
        }
    }
}

No comments:

Post a Comment