[DebuggerVisualizer(GetType(Customer.CustomerVisualizer))]
public class Customer
{
...
public class CustomerVisualizer : DialogDebuggerVisualizer
summary .
869
{
protected override void Show(
IDialogVisualizerService windowService,
IVisualizerObjectProvider objectProvider)
{
Customer c = (Customer)objectProvider.GetObject();
CustomerForm cf = new CustomerForm(c);
if (windowService.ShowDialog(cf) ==
System.Windows.Forms.DialogResult.OK)
objectProvider.ReplaceObject(cf.ModifiedCustomer);
}
}
}
An alternate method would be to use data binding for all of the Customer fields
on the form with a BindingSource object. This BindingSource object could be
exposed with a public modifier, thereby making it accessible from the visualizer
class. All that is needed then is to set the Customer object as the DataSource
of this BindingSource object by the visualizer class, and it will automatically
synchronize changes back to the original Customer object.
suMMary
Debugging applications is one of the most time-consuming and frustrating activities in the
development cycle. In this chapter, you learned how you can take charge of Visual Studio 2010 by
customizing the debugging experience.
Using debugging proxy types and visualizers, you can control how information is presented to you
while you are debugging your application. This means that you can easily determine when your
application is not functioning correctly and be able to trace the source of the issue.
42
Debugging Web applications
what’s in this chaPter?
.
Using Visual Studio to debug both server-side ASP NET code and
client-side JavaScript running in a web browser
.
Enabling and viewing ASP NET trace logs for an individual web
page or the entire application
.
Configuring Health Monitoring so that you are notifi ed as soon as a
problem occurs in an ASP NET application
With Visual Studio 2010, debugging solutions for the Web is just as straightforward as doing the
same for Windows-based applications. You can use most of the same debugging windows already
discussed in previous chapters, as well as deal with errors through the Exception Assistant.
However, there are some differences and additional features specific to web applications that you
can use to target your debugging practices more closely to the web paradigm.
In addition to the standard debugging techniques, ASP.NET also provides you with a
comprehensive tracing capability, and even the capability to perform health monitoring on
your system to ensure it is running in the manner you expect, and exposing problematic
scenarios when it doesn’t.
If you are using Windows Vista or Windows 7 with UAC, and you use IIS rather
than the built-in web development server for debugging, then you must launch
Visual Studio with administrator rights. Right-click the Visual Studio 2010
shortcut and select Run as Administrator. To always launch as administrator,
right-click the shortcut and select Properties, and then select the Compatibility
tab and check the Run This Program as an Administrator checkbox.
872 .
chaPter 42 debugging Web ApplicATionS
debuGGinG serVer- side asP net code
Before you can perform any level of debugging in a web application, you first need to ensure that
ASP.NET debugging is enabled in your web-application or web site project. For web application
projects, enable debugging options by right-clicking the project entry in the Solution Explorer and
selecting Properties. Select the Web tab option page and ensure that the ASP.NET debugger option
is checked, as illustrated in Figure 42-1.
fiGure 42-1
If you want to be able to include unmanaged code, stored procedures, or Silverlight in
your debugging of the web applications, you can activate the Native Code, SQL Server, and
Silverlight debuggers here. Native code and SQL Server debugging are explained in the next
chapter and Silverlight debugging is discussed later in this chapter.
Enabling debugging in other web application projects, such as ASP.NET Web
Service or ASP.NET MVC applications, is exactly the same as for standard
ASP.NET web applications. In fact, from a debugging perspective, there are
really no differences between any of these project types.
Because web site projects do not have a project file, you must use a slightly different procedure to
enable debugging. Enable debugging in web site projects by right-clicking the project entry in the
Solution Explorer and selecting Property Pages from the context menu. When the Property Pages
dialog is displayed, navigate to the Start Options page, and ensure that the ASP.NET debugger
option is checked, as shown in Figure 42-2.
Debugging server-side asP.neT Code .
873
fiGure 42-2
As with web application projects, you can also customize how a web site project is to be started,
including not opening any specific page, but running the server so it listens for a request from
another application.
In addition to enabling the ASP.NET debugger in the property pages, you must enable the compiler
debug option in the web.config file. Locate the compilation node within system.web and set the
debug attribute to true. The following code shows a minimal web.config file with the debug
option enabled, ready for hooking the debugger to the application:
< ?xml version="1.0"? >
< configuration >
< system.web >
< compilation debug="true" targetFramework="4.0" / >
< /system.web >
< system.webServer >
< modules runAllManagedModulesForAllRequests="true" / >
< /system.webServer >
< /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 the web.config file. It also provides an option for Visual Studio to
automatically change this attribute for you.
You should never deploy an ASP.NET application into production with the
debug=”true” option set within the web.config file. Doing so will cause your
application to run slower, use more memory, and prevent some items from
being cached.
874 .
chaPter 42 debugging Web ApplicATionS
web application exceptions
By default, when your web application encounters an exception it displays the ASP.NET server error
page, as shown in Figure 42-3. Colloquially called the Yellow Screen of Death, this page displays the
exception details including the stack trace.
fiGure 42-3
The server error page is generated under both debug and normal execution. Although it is useful
to have this information during development, it is not something that you should be displaying to
your end users. Fortunately, there is an easy way to configure redirections for exceptions, including
standard HTTP errors, by editing the customErrors section in the web.config file.
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:
<?xml version="1.0"?>
<configuration>
<system.web>
<compilation debug="true" targetFramework="4.0" />
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<error statusCode="403" redirect="AccessDenied.html" />
<error statusCode="404" redirect="PageNotFound.html" />
</customErrors>
Debugging server-side asP.neT Code .
875
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
</configuration>
The mode attribute of the customErrors section defines three options for displaying a custom error
page instead of the default server error page. These are:
.
On: The custom error page will always be displayed.
.
Off: The server error page will always be displayed.
.
RemoteOnly: The server error page will be displayed if the browser request is coming from
the local computer; otherwise, the custom error page will be displayed.
The server error page is useful in production
scenarios where you cannot run the
application in Debug mode. However, when
debugging, it is much more useful to break
execution as soon as an exception occurs. You
can do this by enabling the Break When an
Exception Is Thrown option for the Common
Language Runtime. Figure 42-4 shows how
this option is set in the Exceptions dialog
under the Debug . Exceptions menu item.
Once you have enabled this option, when
an exception occurs, Visual Studio 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 42-5, web errors are fully
detailed and include information about which part of the statement is in error.
fiGure 42-4
fiGure 42-5
876 .
chaPter 42 debugging Web ApplicATionS
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.
edit and continue
Edit and Continue, which enables you to modify code when the application is paused in a debug
session, is disabled by default in ASP.NET web applications. This useful feature can be enabled by
right-clicking the project entry in the Solution Explorer and selecting Properties. Under the Web
tab option page, check the Enable Edit and Continue option. This is only supported for the built-in
Visual Studio development web server.
Web site projects do not support Edit and Continue, however, because they naturally support a very
iterative style of development; it is not such a useful feature for those projects. Edit and Continue is
explained in more detail in Chapter 40.
error handling
Although debugging your applications is indeed easy with the tools Visual Studio 2010 provides, it
is always best to try to avoid error situations proactively. You can do this in web applications with
structured Try-Catch exception handling, but you will also want to make your solutions more solid
by including code to handle any errors that fall outside any Catch conditions.
Notice we are using the term error handling and not exception handling here.
This is because it is broader than trapping program exceptions and also covers
HTML errors, such as Page Not Found and Authentication Required.
You can catch errors on two levels — on an individual page you can intercept unexpected errors
and produce a custom-built error, or you can catch errors on an application-wide 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:
c#
void Page_Error(object sender, EventArgs e)
{
Response.Write("An unexpected error has occurred.");
Server.ClearError();
}
Debugging Client-side Javascript .
877
Vb
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
As discussed previously, you can also set custom redirections for standard HTTP error codes in the
web.config file, so you should use this method only 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 2010 web projects do not include this file, so you’ll first need to add it to the
project through the Add New Item dialog. 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:
c#
protected void Session_End(object sender, EventArgs e)
{
Server.Transfer("UnexpectedError.aspx");
}
Vb
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.
debuGGinG client- side JaVascriPt
One of the most useful features of Visual Studio 2010 for front-end web developers is the excellent
support for debugging client-side JavaScript code. Combined with the IntelliSense support for
JavaScript, this significantly eases the difficulty of developing JavaScript code.
JavaScript debugging works only if you are using Internet Explorer as your web
browser during the debug session.
878 .
chaPter 42 debugging Web ApplicATionS
setting breakpoints in Javascript code
Setting breakpoints for JavaScript code is no different from setting any other breakpoint. Within the
editor window, any breakpoints in JavaScript code are displayed with a white circle in the center, as
shown in Figure 42-6.
JavaScript debugging will be disabled if the Silverlight debugger is enabled.