Search content within the blog

Wednesday, April 29, 2009

Difference between application and Session object

Place the following code in your project and run the application under two different browsers but with the same instance of the IIS.The application object is common for entire application irrespective of the user but the session object is for a particular user only.

click both the buttons on different browers and the difference will be clear.

The code is self explanatory....

ASPX Page Code

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Stateobjects.aspx.cs" Inherits="Statemanagement_Stateobjects" Title="State Objects" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="frmStateObjects" runat="server">
<div>
Differenc between application, session
<br />
<br />
click the session button once and application button once by placing the paga on
different browsers<br />
<br />
<br />
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Application" />
<asp:Button ID="Button2" runat="server" OnClick="Button2_Click" Text="Session" /></div>
</form>
</body>
</html>


ASPX.cs Code

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class Statemanagement_Stateobjects : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button2_Click(object sender, EventArgs e)
{
int cnt=0;
try
{
cnt = Convert.ToInt32(Session["HitCounter"].ToString());
}
catch
{
//Session["HitCounter"] = "0";
}
finally
{
Session["HitCounter"] = cnt + 1;
}
Response.Write("Session counter: " + Session["HitCounter"].ToString()+"<br>");
if (Application["HitCounter"]!=null)
Response.Write("Application counter: " + Application["HitCounter"].ToString());
}
protected void Button1_Click(object sender, EventArgs e)
{
int cnt=0;
try
{
cnt = Convert.ToInt32(Application["HitCounter"].ToString());
}
catch
{
//Application["HitCounter"] = "0";
}
finally
{
Application["HitCounter"] = cnt + 1;
}
Response.Write("Application counter: " + Application["HitCounter"].ToString());
if (Session["HitCounter"] != null)
Response.Write("Session counter: " + Session["HitCounter"].ToString());
}
}

No comments:

Post a Comment