14.3. Using the Application Object

Just as you can use the Session object, you are able to use the Application object within your ASP.NET applications. The Application object is a shared container for managing state within your applications. This object enables you to store variables or object references that are available to all the visitors to the Web site for the life of the application. Unlike the Session object, the Application object can only run in-process, meaning that it can only run in the same process as ASP.NET. This means that if the ASP.NET is shut down for any reason, all Application data is lost.

Even though there are some limitations when compared to Session objects, you will find many benefits to using Application objects within your ASP.NET applications. Next, this chapter takes a quick look at how to use an Application objects within your code.

Very much like working with sessions, working with an Application object is easy. First, to create an Application instance, you just assign a value to the Application object as shown here:

Application["City"] = "Helsinki";

It is also just as easy to assign a variable the value of the Application object as shown in the following code:

string ProgramCity = Application["City"];

You probably noticed that this syntax is the same as the syntax you use with sessions. There is, however, a big difference between the two that you should always be aware of. Because the Application object is an application-wide object that is accessible by all users of your Web application, two users could simultaneously attempt to update the same Application object. To resolve such possible conflicts, ASP.NET has provided two methods — Lock() and UnLock().

The idea is to lock down the Application object while the first user is updating it. This prevents a second user from changing any information before the first user has had the chance to make his changes. After the first user is finished making the update to the Application object, the Application object is unlocked, thereby allowing the second user to make his own changes. See how this is done in Listing 14-5.

To show the differences between Session and Application, build an ASP.NET page that uses both to keep track of the number of times that the page is accessed. Keep in mind that the Session is per user and that the Application is for the Web application as a whole and will continue to keep on counting the numbers of hits regardless of the number of different users or applications that are hitting the page.

Example 14-5. Working with the Application object
<%@ Page Language="C#" %>

<script runat="server">

    protected void Page_Load(object sender, EventArgs e)
    {
        int appHits = ApplicationHits();
        int userHits = SessionHits();

Label1.Text = userHits.ToString();
        Label2.Text = appHits.ToString();
    }

    public int ApplicationHits()
    {
        if (Application["ApplicationHitsCount"] == null)
        {
            Application.Lock();
            Application["ApplicationHitsCount"] = 1;
            Application.UnLock();
        }
        else
        {
            Application.Lock();
            Application["ApplicationHitsCount"] =
        ((int)Application["ApplicationHitsCount"]) + 1;
            Application.UnLock();
        }
        return (int)Application["ApplicationHitsCount"];
    }

    public int SessionHits()
    {
        if (Session["SessionHitsCount"] == null)
        {
            Session["SessionHitsCount"] = 1;
        }
        else
        {
            Session["SessionHitsCount"] =
           ((int)Session["SessionHitsCount"]) + 1;
        }
        return (int)Session["SessionHitsCount"];
    }

</script>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Working with the Application Object</title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        Session object count:
        <asp:Label ID="Label1" runat="server"></asp:Label><br /><br />
        Application object count:
        <asp:Label ID="Label2" runat="server"></asp:Label>
    </div>
    </form>
</body>
</html>

After you have you typed all the code, press F5 to build and start your Web application, it will invoke the two available methods. The first is the SessionHits() method. This method is counting the number of times that you, as a user, have accessed this method.

Now it is time to construct the other method, ApplicationHits(), counts the number of times that you, as a generic user, has accessed the page. If you keep hitting the refresh button both numbers will increment together as presented here in Figure 14-4.

Figure 14-4. Figure 14-4

To see the differences between Application and Session objects, close the browser instance that is opened and, within Visual Studio 2008, deploy the Web application again by pressing F5 a second time. This time you are a second user, according to ASP.NET.

Now the ApplicationHits() and the SessionHits() methods are invoked again. This time notice that you are given the number 1 in the Session object because this is the first time that you have accessed this method as this particular user.

Now you will also notice that you will get a higher count through the Application object. This object has kept record of the total number of hits to the method regardless of the user (as shown here in Figure 14-5). It is a global variable that is saved for any user who can access it and saved for the lifetime of the Web application.

Figure 14-5. Figure 14-5

Now, change something in the web.config and recompile or refresh your page. This causes the old Web application to be killed and a new one to be put into its place, thereby creating a new Web application. If you go back to the page, you will notice that the count has once again started at the beginning.

One thing to note is that you should lock your Application object before you make a change to it to avoid concurrency issues. You do this with the Lock() method that is available with the Application object. After you are done making the necessary changes, you use the UnLock() method to open it up to any other users. If you do not use the UnLock() method, the .NET Framework does the unlock for you when the request completes, when the request times out, or when an unhandled error occurs during request execution and causes the request to fail. This automatic unlocking prevents the application from deadlocking.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset