Step: 1 First of
all we will create the file Global.asax and write below code as:
<%@
Application Language="C#" %>
<%@
Import Namespace="System.IO" %>
<%@
Import Namespace="System.Collections" %>
<script runat="server">
void
Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup declare your initial value
Application["LoggedInUser"] = 0;
}
void
Application_End(object sender, EventArgs e)
{
// Code that runs on application
shutdown
}
void
Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs, this code will helps
you to catch the exception when occured
Exception ex = Server.GetLastError().GetBaseException();
string exPage = HttpContext.Current.Request.Path;
System.IO.StreamWriter file = File.AppendText(Server.MapPath("~/Error.txt")); //Append files with new data..
file.WriteLine("Error Occured on " + System.DateTime.Now.ToString());
file.WriteLine("-------------------************************-------------------------------");
file.WriteLine("Exception is as " + ex.Message);
file.WriteLine("Exception page is " + exPage);
file.WriteLine("-------------------************************-------------------------------");
file.Dispose();
file.Close();
}
void
Session_Start(object sender, EventArgs e)
{
//
Code that runs when a new session is started, when application starts it will
check logged in User in application and increment the counter
if
(Application["LoggedInUser"] != null)
{
Application.Lock();
Application["LoggedInUser"] =
((int)Application["LoggedInUser"])
+ 1;
Application.UnLock();
}
}
void
Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
if (Application["LoggedInUser"]
!= null)
{
Application.Lock();
Application["LoggedInUser"] =
((int)Application["LoggedInUser"])
- 1;
Application.UnLock();
}
}
</script>
Step: 2
Write Below code in your page I.e. Header or Footer on page
load
protected
void Page_Load(object
sender, EventArgs e)
{
if (!IsPostBack)
{
//Check whether User Loged in on website and decrement the
counter
if (Application["LoggedInUser"]
!= null)
{
int LogedInUsers = ((int)Application["LoggedInUser"]);
ltUserLogedInCount.Text = "There are
" + LogedInUsers + " User(s) Loged
In";
}
}
}
Declare one Literal Control to get user count on .aspx page
Step: 3
Change Setting to Catch Exception in web.config to
CustomErrors
<customErrors mode="On" defaultRedirect="Index.aspx">
</customErrors>
I hope you will enjoy the code.
Comments