Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

Professional Visual Studio 2005 (2006) [eng]

.pdf
Скачиваний:
132
Добавлен:
16.08.2013
Размер:
21.9 Mб
Скачать

Chapter 51

Figure 51-1

An alternative method of implementing web debugging is to use the Web.config file. Locate the compilation node within system.web and set the debug attribute to true. The following listing shows a minimal Web.config file with the debug option set, ready for hooking the debugger to the application:

<configuration>

<appSettings/>

<connectionStrings/>

<system.web>

<compilation debug=”true” strict=”false” explicit=”true” /> </system.web>

</configuration>

Note that even when you activate the ASP.NET debugger in the Start Options, without setting the debug attribute to true you will be unable to debug the application. However, Visual Studio will detect this discrepancy and present you with a dialog informing you that in order to debug you will need to change Web.config. It also provides an option for Visual Studio to automatically change this attribute for you.

While you’re editing the Web.config file, you may also want to configure redirections for any normal HTTP error codes. While this doesn’t help you with debugging, it enables you to specify a nicely formatted page for your end users, explaining the problem instead of displaying a generic page potentially filled with information you don’t want the user to know. Modifying the previous Web.config file to include these redirection options for 403 (access denied) and 404 (page not found) can result in a configuration similar to the following:

<configuration>

<appSettings/>

<connectionStrings/>

<system.web>

<compilation debug=”true” strict=”false” explicit=”true” /> <customErrors mode=”RemoteOnly” defaultRedirect=”GenericErrorPage.htm”>

<error statusCode=”403” redirect=”AccessDenied.html” /> <error statusCode=”404” redirect=”PageNotFound.html” />

726

Maintaining Web Applications

</customErrors>

</system.web>

</configuration>

Breaking on Errors Automatically

When your web application encounters an error, Visual Studio 2005 drops back into the IDE and positions the workspace so the statement at issue is visible. Just like Windows-based applications, Visual Studio can aid you when errors occur by displaying the Exception Assistant. As shown in Figure 51-2, web errors are fully detailed and include information about which part of the statement is in error.

Figure 51-2

You can gather additional information on the error by clicking the View Detail link, which provides you with a comprehensive exception object visualizer that you can navigate to determine the content of the error at hand.

Debugging an Executing Web Application

Sometimes you’ll need to debug an application after it has already been deployed onto IIS and is executing. If the application was started with debugging enabled, this is not really a problem, as you can simply break it in the IDE, or even just insert breakpoints on the page you want to debug and wait until that page is used.

However, if the web application was started without debugging enabled, you can still debug the application by attaching to the process that’s handling the web site. The process you’ll need to attach to is the ASP.NET worker process, and it will either be the native process within IIS (normally named aspnet_wp

.exe) or the Visual Studio 2005 test server application WebDev.WebServer.exe, which is used for local testing and debugging.

727

Chapter 51

Either way, the method to attach to the running web application is the same. From the Debug menu in Visual Studio 2005, use the Attach to Process command. This displays the Attach to Process dialog window (see Figure 51-3) from which you can browse all active processes. Locate the ASP.NET worker process from the Available Processes list and click the Attach button.

Figure 51-3

You need to check the “Show processes from all users” option because the IIS process is usually running under the ASPNET user instead of your own.

Once you’ve finished debugging in this manner, you should always cleanly detach from the process by selecting Debug Detach All.

Error Handling

While debugging your applications is indeed easy with the tools Visual Studio 2005 provides, it is always best to try to avoid error situations proactively. You can do this in web applications with standard Try-Catch blocks, but you will also want to make your solutions more solid by including code to handle any errors that fall outside any Catch conditions.

You can debug on two levels — on an individual page you can intercept unexpected errors and produce a custom-built error, or you can debug on an applicationwide level through the implementation of a routine to handle errors in the global.asax file.

Page-Level Errors

To handle an error on an individual page, you need to implement an event handler routine that intercepts the MyBase.Error event. When this event is raised, you can then perform whatever actions you need to take place when unexpected errors occur. A typical routine might look like this:

728

Maintaining Web Applications

Private Sub Page_Error(ByVal sender As Object, ByVal e As System.EventArgs) _ Handles MyBase.Error

Response.Write(“An unexpected error has occurred.”) Server.ClearError()

End Sub

Remember that you can also set custom redirections for standard HTTP error codes in the Web.config file, so you should only use this method for errors that are not already handled and are specific to the individual page.

Application-Level Errors

At the web application level, you can also trap a series of errors through the global.asax file. By default, Visual Studio 2005 web projects do not include this file, so you’ll first need to add it to the project through the Website Add New Item menu command. Select the Global Application Class item, leave the name as Global.asax, and click Add to add the file to your project.

When this class is added to the project, the template includes stubs for the commonly encountered application events, including the error event. To handle any errors that are not catered to elsewhere in the project, add your processing code to this Application_Error routine, like so:

Sub Application_Error(ByVal sender As Object, ByVal e As EventArgs)

Server.Transfer(“UnexpectedError.aspx”)

End Sub

This sample routine simply transfers the user to an errors page that determines what to do by interrogating the Server.GetLastError property.

Tracing

In addition to actively debugging your web applications when things go wrong, you can also implement ASP.NET tracing functionality to look at the information produced in an individual page request. Using tracing enables you to add debug statements to your code that are only viewable when viewing locally; when the web application is deployed to the remote server, users see only the proper page.

Trace information can include variables and simple objects to help you determine the state of the specific request and how it was executed. Note that ASP.NET tracing is different from using the Trace class in normal Windows applications in that its output is produced on the actual ASP.NET web page or in a standalone trace viewer, rather than the output windows that Trace commands use.

Tracing has been available since the first release of ASP.NET but with Visual Studio 2005 and ASP.NET 2.0 you can now redirect the Trace commands to the ASP.NET tracing output destination as well, enabling a more comprehensive capability to follow the diagnostic information in your web site page requests. In addition, you can now perform application-level tracing much more easily than before.

Page-Level Tracing

To implement page-level tracing, you simply need to include a trace attribute in the @Page directive at the top of the page you wish to trace. A simple Visual Basic page with tracing activated might look like the following:

729

Chapter 51

<%@ Page Language=”VB” Trace=”true” AutoEventWireup=”false” CodeFile=”Default.aspx.vb” Inherits=”_Default” %>

<!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=”form1” runat=”server”> <div>

Hello!</div>

</form>

</body>

</html>

In addition, you can specify how the tracing messages associated with the page request should appear by using the TraceMode attribute. Set this to SortByTime to output the tracing messages in the order that they were produced, or SortByCategory to categorize them into different message types. Figure 51-4 shows the trace output for the sample page defined in the previous listing when sorted by category.

Figure 51-4

730

Maintaining Web Applications

Application-Level Tracing

Application-level tracing can be enabled through the Web.config file. Within the system.web node you need to include a trace node that contains the attribute enabled with a value of true. When using application-level tracing, you can control how the tracing is produced through the pageOutput attribute. When set to true, you receive the tracing information at the bottom of every page (similar to how it appears in Figure 51-4), while a value of false ensures that the tracing information never appears on the page, and is instead only accessible through the Trace Viewer (covered later in this chapter). You can also restrict the amount of information to trace with the requestLimit attribute. Including a trace node for the Web.config file you saw earlier in this chapter results in a configuration like the following:

<configuration>

<appSettings/>

<connectionStrings/>

<system.web>

<compilation debug=”true” strict=”false” explicit=”true” /> <customErrors mode=”RemoteOnly” defaultRedirect=”GenericErrorPage.htm”>

<error statusCode=”403” redirect=”AccessDenied.html” /> <error statusCode=”404” redirect=”PageNotFound.html” />

</customErrors>

<trace enabled=”true” pageOutput=”false” traceMode=”SortByCategory”/> </system.web>

</configuration>

Trace Output

Tracing output is voluminous. The simple Hello page defined earlier produces almost three full printed pages of information, including the following categories of data:

Request Details: The specific details of the current session, time of the request, what type of request it was, and the HTTP code that is returned to the browser

Trace Information: A full listing of each event as it begins and then ends, including the amount of time taken to process each event

Control Tree: A listing of all controls defined on the page, including the page object itself as well as HTML elements. Each object also has a size listed, so you can determine whether there are any abnormal object sizes affecting your application’s performance.

Session State and Application State: These two lists show the keys and their values for the individual session and the application overall.

Request Cookies Collection and Response Cookies Collection: A list of any known ASP.NET request and response cookies on the system that your application may be able to access

Headers Collection: A list of the HTTP headers included in the page

Response Headers Collection: The HTTP headers associated with the response, indicating what type of object is being returned

Form Collection: A list of any forms defined in the page

Querystring Collection: A list of any query strings used in the page request

Server Variables: A list of all server variables known to the ASP.NET server and application you’re currently executing

731

Chapter 51

As you can see, when tracing is implemented for a web page or application, you gain access to an enormous amount of information that you can then use to determine how your application is performing. You can see whether there are problems in the various collections in the way of missing or extraneous data, as well as analyze the Trace Information list to determine whether there are any abnormally long processing times for any specific events.

Trace Viewer

The Trace Viewer is a custom page included in your web application when you have application tracing activated. When tracing is being reported at the application level, you can navigate to this page and view all page tracing output as it occurs. To view the Trace Viewer, browse to the trace.axd page in the root directory of your web site.

The Trace Viewer provides a summary table of all requests made in the application, along with the time the request was made and the HTTP status code returned in the response. It also provides a link to detailed information for each request (which is the same information that you can see on a page trace discussed earlier), as shown in Figure 51-5.

Figure 51-5

Custom Trace Output

You can supplement the default trace information with your own custom-built trace messages, using the Trace.Warn and Trace.Write methods. Both have the same set of syntactical overloads, and the only real difference is that messages outputted using the Warn method are displayed in red text.

The simplest form for these commands is to include a message string like so:

Trace.Warn(“Encountered a potential issue”)

732

Maintaining Web Applications

However, you can categorize your warnings and messages by using the second and third forms of the methods, including a category and optionally an error object as well:

Trace.Warn(“MyApp Error Category”, “Encountered a potential issue”, myAppException)

Summar y

With the combination of Visual Studio 2005 and ASP.NET 2.0 server-side capabilities, you have a wide array of tools to help you look after your web solutions. These features enhance the already impressive feature set available with normal Windows application debugging, with web-specific features such as pageand application-level error handling, and the capability to keep track of your application as it runs on the server.

In addition, by adding tracing code, which you can view through the Trace Viewer, you can monitor the way issues are produced in your web applications without stopping the execution for your end-users.

733

Other Debugging Techniques

As you’ve seen throughout the last several chapters, Visual Studio 2005 comes with a great variety of ways to debug and run through your applications, including catching errors and displaying them to you for action before the code executes too far, a number of tool windows specifically dealing with the area of testing, and other features such as breakpoints and visualizing errors.

However, there is still more functionality to be found in the Visual Studio IDE that you can use to customize your experience with debugging projects, databases, and even macros, and that’s what this chapter is all about. In it you’ll find a summary of the additional options you have at your disposal for testing and debugging your projects regardless of language or technology.

Debugging Options Pages

There is a whole group of options pages dedicated to the area of debugging. You can use these pages to customize the way debugging occurs in the application, controlling when and how debug messages are displayed, as well as implementing specific features that cater to different workflow methodologies, such as Edit and Continue.

To access these options, use the Tools Options menu command and then navigate to the Debugging group, expanding it to show the individual pages if necessary. Selecting the root node of Debugging displays the General debugging options page automatically, so you may not need to expand the node if your customization will take place in that page alone.

General Options

The General options page contains more than twenty settings that tweak the way you can experience debugging projects (see Figure 52-1). Be aware that Visual Studio will choose a different set of default properties depending on the environment setup you selected, with the Visual Basic