Hello and Welcome,
Here I am going to discuss with you regarding Session variable in one class file to maintain it. You do not need to check it on each and every pages. Here we goes.
First we will create on class file to create and maintain Session variable. Create Class name like "Session_Class".
Session_Class objSession = new Session_Class();
Session_Class objSession = new Session_Class();
Here I am going to discuss with you regarding Session variable in one class file to maintain it. You do not need to check it on each and every pages. Here we goes.
First we will create on class file to create and maintain Session variable. Create Class name like "Session_Class".
using System;using System.Collections.Generic;using System.Linq;using System.Web;////// Summary description for clsSession///
public class Session_Class
{
public Session_Class()
{
//
// TODO: Add constructor logic here
//
}
public bool
CheckSession()
{
if (HttpContext.Current.Session["uid"] == null)
{
return false;
}
else
{
return true;
}
}
public void
CheckSession(out string
strUserName, out string
strUserID)
{
strUserName = "";
strUserID = "";
if (HttpContext.Current.Session["userName"] != null
&& HttpContext.Current.Session["uid"] != null)
{
strUserName = Convert.ToString(HttpContext.Current.Session["userName"]);
strUserID = Convert.ToString(HttpContext.Current.Session["uid"]);
}
}
public void
CreateSession(string strId, string strUserName)
{
HttpContext.Current.Session.Add("uid", strId);
HttpContext.Current.Session.Add("userName",strUserName);
}
public void
RemoveSession(string strId, string strUserName)
{
HttpContext.Current.Session.Remove("uid");
HttpContext.Current.Session.Remove("userName");
HttpContext.Current.Session.RemoveAll();
}
}
Here is .aspx page
<div><asp:LinkButton ID="lnkLogin" runat="server" OnClick="Login">Login</asp:LinkButton> <asp:LinkButton ID="lnkLogOut" runat="server" OnClick="Logout">Logout</asp:LinkButton>
<asp:LinkButton ID="lnkCheckSessionNow" runat="server"
OnClick="CheckNow">Check
Session Now</asp:LinkButton>
</div>
.aspx.cs page
protected void Login(object sender, EventArgs
e)
{
Session_Class objSession = new
Session_Class();
objSession.CreateSession("ved","vedPathak");
if (objSession.CheckSession() == true)
{
string strUserName = "";
string strUserId = "";
objSession.CheckSession(out strUserName,
out strUserId);
Response.Write("Hello" +
strUserName + " " + strUserId);
}
}
protected void
Logout(object sender, EventArgs
e)
{
objSession.RemoveSession("uid",
"userName");
}
protected void
CheckNow(object sender, EventArgs e)
{
if (objSession.CheckSession() == true)
{
Response.Write("Session is still alive
now.");
}
else
{
Response.Write("Session is Expired now.");
}
}
Comments