Build Your Own ASP.NET 3.5 Website Using C# & VB (34 page)

Read Build Your Own ASP.NET 3.5 Website Using C# & VB Online

Authors: Cristian Darie,Zak Ruvalcaba,Wyatt Barnett

Tags: #C♯ (Computer program language), #Active server pages, #Programming Languages, #C#, #Web Page Design, #Computers, #Web site development, #internet programming, #General, #C? (Computer program language), #Internet, #Visual BASIC, #Microsoft Visual BASIC, #Application Development, #Microsoft .NET Framework

BOOK: Build Your Own ASP.NET 3.5 Website Using C# & VB
13.27Mb size Format: txt, pdf, ePub

Licensed to [email protected]

180

Build Your Own ASP.NET 3.5 Web Site Using C# & VB

C#

Application.RemoveAll();

It’s important to be cautious when using application variables. Objects remain in

application state until you remove them using the Remove or RemoveAll methods,

or shut down the application in IIS. If you continue to save objects into the application state without removing them, you can place a heavy demand on server resources and dramatically decrease the performance of your applications. Let’s take a look at application state in action. Application state is very commonly

used to maintain hit counters, so our first task in this example will be to build one!

Let’s modify the
Default.aspx
page that Visual Web Developer created for us. Doubleclick
Default.aspx
in Solution Explorer, and add a Label control inside the form element. You could drag the control from the Toolbox (in either Design view or

Source view) and modify the generated code, or you could simply enter the new

code by hand. We’ll also add a bit of text to the page, and change the Label’s ID to

myLabel, as shown below (the VB and C# versions are identical):

Dorknozzle\VB\02_Default.aspx
(excerpt)




The page has been requested


times!




In Design view
, you should see your label appear inside the text, as shown in Fig-

ure 5.18.

Now, let’s modify the code-behind file to use an application variable that will keep

track of the number of hits our page receives. As we mentioned in
the section called

“Writing Your First ASP.NET Page” in Chapter 1, if your site uses, C# the
Page_Load method is already present in the code-behind file. If you site uses VB, double-click

in any empty space on your form; Visual Web Developer will create a Page_Load

Licensed to [email protected]

Building Web Applications

181

Figure 5.18. The new label appearing in Design view

method automatically, and display it in the code editor. The method will look like

this:

Visual Basic

Dorknozzle\VB\03_Default.aspx.vb
(excerpt)

Partial Class _Default

Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object,

➥ ByVal e As System.EventArgs) Handles Me.Load

End Sub

End Class

C#

Dorknozzle\CS\03_Default.aspx.cs
(excerpt)


public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

}

}

Now, let’s modify the automatically generated method by adding the code that we

want to run every time the page is loaded. Modify Page_Load as shown below:

Licensed to [email protected]

182

Build Your Own ASP.NET 3.5 Web Site Using C# & VB

Visual Basic

Dorknozzle\VB\04_Default.aspx.vb
(excerpt)

Protected Sub Page_Load(ByVal sender As Object,

➥ ByVal e As System.EventArgs) Handles Me.Load

If Application("PageCounter") >= 10 Then

Application.Remove("PageCounter")

End If

If Application("PageCounter") Is Nothing Then

Application("PageCounter") = 1

Else

Application("PageCounter") += 1

End If

myLabel.Text = Application("PageCounter")

End Sub

C#

Dorknozzle\CS\04_Default.aspx.cs
(excerpt)

protected void Page_Load(object sender, EventArgs e)

{

if (Application["PageCounter"] != null &&

(int)Application["PageCounter"] >= 10)

{

Application.Remove("PageCounter");

}

if (Application["PageCounter"] == null)

{

Application["PageCounter"] = 1;

}

else

{

Application["PageCounter"] =

(int)Application["PageCounter"] + 1;

}

myLabel.Text = Convert.ToString(Application["PageCounter"]);

}

Before analyzing the code, press
F5
to run the site and ensure that everything works

properly. Every time you refresh the page, the hit counter should increase by one

until it reaches ten, when it starts over. Now, shut down your browser altogether,

and open the page in another browser. We’ve stored the value within application

state, so when you restart the application, the page hit counter will remember the

value it reached in the original browser, as
Figure 5.19
shows.

Licensed to [email protected]

Building Web Applications

183

Figure 5.19. Using the Application object

If you play with the page, reloading it over and over again, you’ll see that the code

increments PageCounter every time the page is loaded. First, though, the code

verifies that the counter hasn’t reached or exceeded ten requests. If it has, the counter

variable is removed from the application state:

Visual Basic

Dorknozzle\VB\04_Default.aspx.vb
(excerpt)

If Application("PageCounter") >= 10 Then

Application.Remove("PageCounter")

End If

C#

Dorknozzle\CS\04_Default.aspx.cs
(excerpt)

if (Application["PageCounter"] != null &&

(int)Application["PageCounter"] >= 10)

{

Application.Remove("PageCounter");

}

Notice that the C# code has to do a little more work than the VB code. You may re
member from Chapter 3 that C# is more strict than VB when it comes to variable

types. As everything in application state is stored as an Object, C# requires that we

cast the value to an integer, by using (int), before we make use of it. This conversion

won’t work if PageCounter hasn’t been added to application state, so we also need

to check that it’s not equal to null.

Next, we try to increase the hit counter. First of all, we need verify that the counter

variable exists in the application state. If it doesn’t, we set it to 1, reflecting that the

page is being loaded. To verify that an element exists in VB, we use Is Nothing:

Licensed to [email protected]

184

Build Your Own ASP.NET 3.5 Web Site Using C# & VB

Visual Basic

Dorknozzle\VB\04_Default.aspx.vb
(excerpt)

If Application("PageCounter") Is Nothing Then

Application("PageCounter") = 1

Else

Application("PageCounter") += 1

End If

As we’ve already seen, we compare the value to null in C#:

C#

Dorknozzle\CS\04_Default.aspx.cs
(excerpt)

if (Application["PageCounter"] == null)

{

Application["PageCounter"] = 1;

}

else

{

Application["PageCounter"] =

(int)Application["PageCounter"] + 1;

}

The last piece of code simply displays the hit counter value in the Label.

There’s one small problem with our code: if two people were to open the page

simultaneously, the value could increment only by one, rather than two. The reason

for this has to do with the code that increments the counter:

C#

Dorknozzle\CS\04_Default.aspx.cs
(excerpt)

Application["PageCounter"] =

(int)Application["PageCounter"] + 1;

The expression to the right of the = operator is evaluated first; to do this, the server

must read the value of the PageCounter value stored in the application. It adds one

to this value, then stores the updated value in application state.

Now, let’s imagine that two users visit this page at the same time, and that the web

server processes the first user’s request a fraction of a second before the other request.

The web form that’s loaded for the first user might read PageCounter from applicaLicensed to [email protected]

Building Web Applications

185

tion state and obtain a value of 5, to which it would add 1 to obtain 6. However,

before the web form had a chance to store this new value into application state,

another copy of the web form, running for the second user, might read PageCounter

and also obtain the value 6. Both copies of the page will have read the same value,

and both will store an updated value of 6! This tricky situation is illustrated in

Figure 5.20.

Figure 5.20. Two users updating application state simultaneously

To avoid this kind of confusion, we should develop the application so that each

user locks application state, updates the value, and then unlocks application state

so that other users can do the same thing. This process is depicted in
Figure 5.21
. Licensed to [email protected]

186

Build Your Own ASP.NET 3.5 Web Site Using C# & VB

Figure 5.21. Two users updating application state with locks

Let’s modify our code slightly to create these locks:

Visual Basic

Dorknozzle\CS\05_Default.aspx.vb
(excerpt)


If Application("PageCounter") Is Nothing Then

Application("PageCounter") = 1

Else

Application.Lock()

Application("PageCounter") += 1

Application.UnLock()

End If


Licensed to [email protected]

Building Web Applications

187

C#

Dorknozzle\CS\05_Default.aspx.cs
(excerpt)

Other books

Fair Game by Alan Durant
Love on Loch Ness by Aubrie Dionne
A Sprite's Tale (novella) by Couper, Lexxie
The Reluctant Marquess by Maggi Andersen
Bad Day (Hard Rock Roots) by Stunich, C.M.
Cat Deck the Halls by Shirley Rousseau Murphy
Alector's Choice by L. E. Modesitt
Vampirates 1.5:Dead Deep by Justin Somper
Corpse in a Gilded Cage by Robert Barnard