25 June 2012

What is an application object and where we use application object in asp.net ?


What is an application object?

Application object is used to store the information and access variables from any page in application. Application object is same as session object only the difference is session object is used to maintain the session for particular user. 
If one user enters in to the application then session id will create for that particular user if he leaves from the application then the session id will deleted. If they again enter in to the application they will get different session id but application object is same for all users once application object is created that application object is used throughout the application regardless of user. The information stored in application object accessed throughout all the pages in application (like database connection information) and we can change the application object in one place those changes automatically reflected in all the pages.

You can create application objects in Global.asax file and access those variables throughout the application. To know about how to add Global.asax file check the post here

Add following code in Global.asax file like this


<%@ Application Language="C#" %>
<script runat="server">
void Application_Start(object sender, EventArgs e)
{
// Code that runs on application startup
Application["UserID"] = "RojaSamala";
}
</script>
After completion of writing code global.asax file write the following code in aspx page


<html>
<head>
<title>Application Object Sample</title>
</head>
<body>
<form id="form1" runat="server">
<asp:Label id="lblText" runat="server"></asp:Label>
</form>
</body>
</html>
After that write the following code in code behind like this

public void Page_Load(object sender, EventArgs e)
{
this.lblText.Text =  "UserName: " + Application["UserID"] + "<br>";
}

Now run your application you will see the application object value in your page. I hope it helps you.