Download as pdf or txt
Download as pdf or txt
You are on page 1of 9

Hands-On Lab

Lab Manual
DEV-HOL19: Introduction to ASP.NET caching,
tracing and state management

Release Date: June 2003


Please do not remove this manual from the lab
The lab manual will be available from CommNet

Information in this document is subject to change without notice. The example companies,
organizations, products, people, and events depicted herein are fictitious. No association with
any real company, organization, product, person or event is intended or should be inferred.
Complying with all applicable copyright laws is the responsibility of the user. Without limiting the
rights under copyright, no part of this document may be reproduced, stored in or introduced into
a retrieval system, or transmitted in any form or by any means (electronic, mechanical,
photocopying, recording, or otherwise), or for any purpose, without the express written
permission of Microsoft Corporation.

Microsoft may have patents, patent applications, trademarked, copyrights, or other intellectual
property rights covering subject matter in this document. Except as expressly provided in any
written license agreement from Microsoft, the furnishing of this document does not give you any
license to these patents, trademarks, copyrights, or other intellectual property.

2003 Microsoft Corporation. All rights reserved.

Microsoft, MS-DOS, MS, Windows, Windows NT, MSDN, Active Directory, BizTalk, SQL
Server, SharePoint, Outlook, PowerPoint, FrontPage, Visual Basic, Visual C++, Visual J++,
Visual InterDev, Visual SourceSafe, Visual C#, Visual J#, and Visual Studio are either
registered trademarks or trademarks of Microsoft Corporation in the U.S.A. and/or other
countries.

Other product and company names herein may be the trademarks of their respective owners.

Release Date: June 2003


Contents

Exercise #1: ASP.NET Session State ...............................................................................................................4


Exercise 2: ASP.NET Tracing............................................................................................................................5
Exercise 3: ASP.NET Page Output Caching .....................................................................................................7

2
This lab provides a simple introduction to some of the great new features of ASP.NET simplify web
application development.

Estimated time to complete this lab: 45 minutes

Objectives
After completing this lab, you will be able to:

 Use ASP.NET caching in your Web applications


 Use different state management options provided by ASP.NET
 Use ASP.NET tracing to debug your applications

The solution for this lab is located in the following folders:

C:\HandsOnLabs\ASP.NET\VB

Exercises
Exercise 1: ASP.NET Session State
ASP.NET introduces several new ways to store session state which allow you to build more robust and
fault tolerant applications than ever before. This lab provides an overview of the three state management
options offered by ASP.NET.

Exercise 2: ASP.NET Tracing


ASP.NET Tracing provides detailed information about what is happening behind the scenes when a web
application executes. This lab provides an overview of how page tracing can be used to better understand
and debug your application.

Exercise 3: ASP.NET Page Output Caching


Output caching can increase the performance of your application significantly as it reduces the need to
generate dynamic pages on the fly. ASP.NET Page Output Caching provides a powerful yet simple to use
method to implementing caching in your applications. This lab will provide an overview of simple Page
Output caching in ASP.NET.

3
Exercise #1: ASP.NET Session State
In this exercise, you will create a new ASP.NET web application in Visual Studio .NET, and experiement
with some different session state configuration options, and learn about cookieless session state.

X Part 1: Setting Up and Exploring Session State


Note: As you perform this task, you can ignore the Start page.
… Click Start->Programs->Microsoft Visual Studio .NET->Microsoft Visual Studio .NET.
… Click File->New->Project.
… In the Project Types pane, click Visual Basic Projects.
… In the Templates pane, click ASP.NET Web Application.
… Type http://localhost/SessionStateVB in the Location field.
… Click OK.
… Navigate to the WebForm1.aspx file, right-click and select View Code
… In the Page_Load function, type the following:
Response.Write(“Last accessed “ + Session(“lastAccess”) + “<p>”)
Session(“lastAccess”) = DateTime.Now.ToLongTimeString()
Response.Write("Time is now " + Session("lastAccess"))
… Compile and run the application by pressing Ctrl+F5 (Note: Visual Studio .NET might take a few
moments to compile the application)
… Visual Studio .NET will bring up a Web browser which points to your application on the local web server
… Now refresh the page a few times by clicking Refresh in the Web browser. Wait a few seconds
between each refresh. Note that the time of the last access is stored in the session state object
between refreshes.
… Now let’s see what happens to the session state information when the Web server is restarted. Click
Start->Run and type iisreset.
… Click OK.
… Now go back to the Web browser and click Refresh again. (Note: the page might take a few moments
to refresh this time).
… Note that the “Last accessed” time is blank. We have lost our session data because of the Web server
reset.
… Close the Web browser

X Part 2: Using Out-Of-Process Session State


… So far we’ve been using in-process session state, whereby session state data is stored in the same
process as ASP.NET (this is why we lost our session state when we reset the web server). We will now
start experimenting with other settings.
… In the SessionStateVB project we create in Part, 1 navigate to the Solution Explorer window (in the
top, right hand corner of Visual Studio .NET)
… Open the file named web.config. This file contains all the configuration settings for our application.
… Locate the <SessionState> tag
… The value of the mode attribute is now “InProc”. Change this to “StateServer” as shown in the following
code. This is the only change necessary to ensure that session state is not lost when the web server is
restarted.
<sessionState
mode="StateServer"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=sa;password="
cookieless="false"
timeout="20"
/>

4
… Before testing, you need to start the ASP.NET State Service (which will store the session state data).
Click Start->Run and type net start ASPNET_STATE.
… Press Ctrl+F5 to compile and run the page.
… Refresh the page a few times by clicking Refresh in the Web browser. Wait a few seconds between
each refresh. Note that the time of the last access is stored in the session state object between
refreshes.
… Restart the web server. Click Start->Run and type iisreset.
… Click OK.
… Now go back to the Web browser and click Refresh again.
… Note that the ”Last accessed” time is still available. We have no lost our session state data.
… Close the Web browser
Note 1: If you wish to share state between different web servers (in a web farm scenario for instance), you can
run the ASP.NET State Service on a remote machine. Your application can be directed to this remote
machine using the StateConnectionString attribute of the <SessionState> tag in web.config. Simply
set the value of StateConnectionString to the IP address of the machine running the ASP.NET State
Service.
Note 2: You may also store state information in a SQLServer database. To do this change the mode attribute
of the <SessionState> tag to “SQLServer”.

X Part 3: Using Cookieless Session State


… In web.config, change the mode attribute of the <SessionState> tag back to “InProc”.
… Now change the cookieless attribute of the <SessionState> tag to “true”. This attribute controls
whether cookies should be sent to the client when a session is initiated. If this attribute is set to true,
ASP.NET will not user cookies. Instead, the session id is sent as part of the URL.
… Your <SessionState> tag should now look like the following:
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=sa;password="
cookieless="true"
timeout="20"
/>
… Press Ctrl+F5 to compile and run the application
… Note that the URL of your application gets modified to include the session id, looking something like the
following:
http://localhost/SessionStateVB/(hgyyz5vjzxztxv55h4cai045)/WebForm1.aspx
… Close the web browser

Note; You may be asking when cookieless sessions are applicable. One case is when a corporate policy
prevent usage of cookies, any Intranet applications then need to use a different way to associate a client
with data on the server. There are alternatives to using session data, e.g. hidden fields containing data,
but nothing is as easy to use as normal session data.

Exercise 2: ASP.NET Tracing


In this exercise you will add tracing data to the application built in Exercise 1. You’ll learn how a single line
of code will enable us to see what’s really happening behind the scenes in our application.

X Part 1: Getting Started


… Navigate to the SessionStateVB project which you used in Exercise 1.
… Make sure that the <sessionState> tag in the web.config file is identical to the following:

5
<sessionState
mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="data source=127.0.0.1;user id=sa;password="
cookieless="false"
timeout="20"
/>

… Locate the <trace> tag in the web.config file.


… Enable ASP.NET tracing by changing the enabled attribute to “true”. Also change the pageOutput
attribute to “true”. The <trace> tag should now look like the following:
<trace enabled="true" requestLimit="10" pageOutput="true" traceMode="SortByTime"
localOnly="true" />

… Press Ctrl+F5 to run the application and observe the result.


Note:

The attributes available for the <trace> tag are:


• enabled: Set to true | false, indicates whether Tracing is enabled for the application (default is false).
• pageOutput: Set to true | false, indicates whether trace information should be rendered at the end of
each page - or only accessible via the trace.axd utility (default is false).
• requestLimit: Number of trace requests to store on the server (default is 10).
• traceMode: Set to SortByTime | SortByCategory, indicates the display order for Trace messages
(default is SortByTime).
• localOnly: Set to true | false, indicates whether Tracing is enabled for localhost users or for all users
(default is true).

At the top your page will be displayed. Below your page is a number of informational elements that is
useful for understanding how the page was created and which settings were available at the time.

The information listed are, in order:


• Request Details
• Trace Information: Trace of event that happens during page rendering. Later we will see how you can
write information here yourself.
• Control Tree
• Session State (list all session variables)
• Cookie Collection
• Header Collection
• Server Variables

After having looked at the basic trace information let’s insert some trace statements of your own. The
Trace class statement comes in two flavors: Write and Warn. They both take the same arguments. The
only difference between them is the color they trace in, Write uses black and Warn uses red.

X Part 2: Inserting Statements into the Page Trace


… Navigate to the WebForm1.aspx file, right-click and select View Code
… In the Page_Load function, type the following below the code you entered in Exercise 1:
Trace.Write("This is a Trace.Write message")
Trace.Warn("This is a Trace.Warn message")

6
… Press Ctrl+F5 to compile the application. Observe the resulting trace information on the page. Each
event is shown as well as the execution time between each event.
… Close the web browser.

Note: ASP.NET introduces an event-based programming model to web development. MSDN


(msdn.microsoft.com) contains many helpful articles which explain this model in detail and how to take
advantage of this model in your applications.

X Part 3: Using trace.axd


Another way to view the trace information is to use the special page trace.axd. This page provides a
summary of recent traces and allows you to click on one of them to see the same details you have just
seen above. With this approach only the trace information itself is displayed, the page is not rendered
above it.
… Press Ctrl+F5 to compile and run your application.
… Access the trace.axd file for your application by entering the following URL in the web browser:
http://localhost/SessionStateVB/trace.axd
… You should now see a series of application traces from the past few requests to you application.
… Close the web browser.

Exercise 3: ASP.NET Page Output Caching


X Part 1: Simple Output Caching
Note: As you perform this task, you can ignore the Start page.
… Close Visual Studio .NET if it it open. Do not save any change to existing projects.
… Click Start->Programs->Microsoft Visual Studio .NET->Microsoft Visual Studio .NET.
… Click File->New->Project.
… In the Project Types pane, click Visual Basic Projects.
… In the Templates pane, click ASP.NET Web Application.
… Type http://localhost/OutputCachingVB in the Location field.
… Click OK.
… Navigate to the WebForm1.aspx file, right-click and select View Code
… Enter the following code in the Page_Load function:
Response.Write(“This page was created on:” + DateTime.Now.ToLongTimeString())
… Press Ctrl+F5 to run the project.
… Refresh the page several times to see that the page creation time is updated each time you refresh.
… Close the web browser.
… Navigate to the WebForm1.aspx file.
… Right click on the WebForm1.aspx design surface and select View HTML Source
… At the top of the page, enter the following code:
<%@ OutputCache Duration="10" VaryByParam="none"%>

… Press Ctrl+F5 to run the project.


… Refresh the page several times. Note that the page is now only updated every 10 seconds. The page is
beign compiled once every ten seconds and place in the cache. Subsequent requests for this page are
being served from the cache.

7
… This is the simplest for of caching. As many pages have slightly different contents depending on a
simple parameter in the query string this simple form of caching can be extended. You will now utilize
the VaryByParam argument in the OutputCache directive above.

X Part 2: Caching depending on a parameter


… We will now modify the OutputCache directive to vary by “something”, and cache the page for a longer
time. Right click on WebForm1.aspx and select View Code
… Add the following to the Page_Load function above the code you entered in part 1
Response.Write(Request.QueryString.Item("something"))
Response.Write("<p>")
… Navigate back to WebForm1.aspx. Right-click and select View HTML Source
… Modify the OutputCache directive to look like the following:
<%@ OutputCache Duration="30" VaryByParam="fruit"%>
… You have just created a page that cache a version of itself depending on the value of a query string
parameter called “fruit”. Each version of this page writes out the value of “fruit” to help you keep track of
the version.
… Press Ctrl+F5 to run the application.
… Try calling passing different parameters to the application by entering the following URLs in the web
browser:
http://localhost/OutputCachingVB/WebForm1.aspx?fruit=Apple
http://localhost/OutputCachingVB/WebForm1.aspx?fruit=Pear
http://localhost/OutputCachingVB/WebForm1.aspx?fruit=Orange
… Note that the page is only updated when you enter a new value for the “fruit” parameter. There is an
independent cached version of the page in memory for each value of “fruit” you submit. All of these
pages are recompiled every 30 seconds (as we requested in the OutputCache directive).

Note: ASP.NET provides several very flexbile and easy to use caching options which makes it much simpler
for you to build high performance applications. We did not highlight it here, but ASP.NET also allows
you to cache fragments of pages, instead of the entire page. For more information on page fragment
caching please refer to the PAG lab series (also on this machine) or MSDN (msdn.microsoft.com).

You might also like