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

C# ПІДРУЧНИКИ / c# / Hungry Minds - ASP.NET Bible VB.NET & C#

.pdf
Скачиваний:
128
Добавлен:
12.02.2016
Размер:
7.64 Mб
Скачать

Table 7-1: Debug options

Option

Description

margin of the line where you want to set a breakpoint.

Note

The Step Into and Step Over options perform the same operation

 

until the code reaches a calling statement to call a procedure. The

 

Step Into option causes you to enter the called procedure and run

 

through it, whereas the Step Over option causes you to skip any

 

called procedure.

Let us look at a step-by-step approach to debug an ASP.NET Web page. Consider a simple Web page that provides users with the functionality of adding two numbers. The code of this Web page is given as follows:

<%@ Page Language="vb"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">

<HTML>

<HEAD>

<TITLE></TITLE>

</HEAD>

<Script runat="server">

Sub DoArithmetic(Src As Object, E As EventArgs)

lblResult.Text = txtNum1.Text + txtNum2.Text

End Sub

</Script>

<Body>

<Form id="Form1" method="post" runat="server">

<P>

<asp:Label id="lblNumber1" runat="server">Number 1</asp:Label>

<asp:TextBox id="txtNum1" runat="server"></asp:TextBox>

</P>

<P>

<asp:Label id="lblNumber2" runat="server">Number 2</asp:Label>

<asp:TextBox id="txtNum2" runat="server"></asp:TextBox>

</P>

<P>

<asp:Button id="cmdCalculate" runat="server" Text="Calculate" onclick="DoArithmetic" />

</P>

<P>

<asp:Label id="lblResult" runat="server" Width="270px" Height="31px"></asp:Label>

</P>

</Form>

</Body>

</HTML>

When you browse this Web page in Internet Explorer, and enter two numbers, say 5 and 5, in the two text boxes, and then click the Calculate button, you'll notice that the result that is displayed is 55 instead of 10.

Let us see how you can use the Visual Studio .NET debugger to debug the preceding code. Before browsing the page in Internet Explorer, the first thing that you need to do is to set a breakpoint on the line from where debugging should start. Typically, the line on which the debugger should break will be the one that the developer suspects as a source of malfunctioning. In our case, the breakpoint should be on the Sub procedure named DoArithmetic. Note that a breakpoint can also be conditional; the debugger will break on the breakpoint only if a given condition evaluates to True or False as defined on the breakpoint. Figure 7-1 shows the New Breakpoint dialog box.

Figure 7-1: The New Breakpoint dialog box

Note You can also add a breakpoint by clicking the left margin of the line on which you need to set the breakpoint or by pressing the F9 key while the cursor is on the line. Then, to remove a breakpoint, press F9 or click the left margin of the line at which the breakpoint was set.

To debug the current page, you need to mark the page as the startup page of the project. This can be done by right-clicking the ASPX file in the Solution Explorer window and choosing the Set As Start Page option from the context menu.

After you have set the breakpoint and set the Web page as the startup page of the project, you can start debugging your page. To start debugging the page, select Start from the Debug menu. This will start a new instance of Internet Explorer, and load the current page in it.

When you enter numbers in the Number1 and Number2 text boxes, say 5 and 5, respectively, and click the Calculate button, the debugger enters Break mode. In this

mode, you can see the line at which you set the breakpoint being highlighted. You can check the values of the various variables and controls for correctness in Break mode. You'll now run through the procedure in a stepwise manner to identify the source of the problem. To do so, select Debug Step Into. You'll notice that the next line (this is the only code line in the procedure) gets highlighted. Select Debug Step Into once more to execute this line of code. At this stage, the next line (End Sub) gets highlighted. This is the time when you should check the value in each text box and thus conclude the source of the problem. The Immediate window can be used for ad-hoc querying of variable and control property values. You can open the Immediate window by selecting Debug Windows Immediate. In the Immediate window, type the following statement:

?lblResult.Text

After typing the preceding statement, press Enter. The Immediate window displays "55." The Result "55" gives an indication that the result is a string and not a number. This is enough to identify that the problem was due to the datatype. The numbers entered in the two text boxes were set in the Text property of the text boxes. In the DoArithmetic procedure, when you added the two numbers by accessing the Text property of the text boxes, the "+" operator worked as the concatenation operator to concatenate two strings rather than adding two numbers. Therefore, the values entered in the text boxes must be converted to a numeric datatype before adding them.

After you've found the actual error, you can stop debugging and correct the code. To stop the debugging process, select Debug Stop Debugging.

Next, remove the breakpoint (Press F9 at the line at which the breakpoint was set). Modify the line in the DoArithmetic procedure to read:

lblResult = Cint(txtNum1.Text) + Cint(txtNum2.Text)

After you fix the code and run the application, you'll notice that now the page gives the correct output.

Attaching a Debugger

In addition to attaching a debugger to an application when you start it, you can attach a debugger while an application is already running. To do so, complete the following steps:

1.Open the application in Visual Studio .NET.

2.Select Debug Processes to open the Processes dialog box.

3.Ensure that the "Show system processes" option is selected.

4.In the Available Processes pane, all the processes are listed. Scroll

through the list to select aspnet_wp.exe.

5.Click Attach to open the Attach To Process dialog box. From the available choices, select Common Language Runtime and Script.

6.Click OK and then click Close.

After you've attached the debugger to your running application, you can debug the application to trace the source of error.

Note You can attach a debugger to a running Web page only if it is running in Internet Explorer. If you are viewing the page within the IDE, you will not be able to attach a debugger with your page.

The ASP.NET Trace functionality

In ASP.NET, the trace feature ensures that the programmers are able to log their applications by providing the means to monitor and examine program performance either during development or after deployment. ASP.NET allows tracing at two levels:

§Page-level tracing

§Application-level tracing

Trace capability of ASP.NET is declared in the TraceContext class. To enable the Trace Page, the Trace directive must be set to True. The Trace property is exposed as a

public property within ASP.NET pages. The Trace property refers to the TraceContext of the ASP.NET page.

The TraceContext class is a noninheritable public class of the .NET Framework that is used for capturing the execution details of a Web request and presenting the data on the page. For developers to include messages for specific Trace categories, this class can be a good utility. You need to include the System.Web namespace in your Web project to be able to use this class.

The class has certain properties and methods that provide the functionality for enabling the debugging of the ASP.NET pages.

Table 7-2 and Table 7-3 list the properties and methods exposed by the TraceContext class.

Table 7-2: Properties of the TraceContext class

Property

IsEnable

Description

Indicates whether tracing is enabled for the current Web request. Allows browsers to determine the state of tracing for the current Web request for the page or the application. You can use this property to check whether or not the page or application should include the tracing information before writing anything to the trace log. You can set this property for the page by including a trace="tr ue" attribute in the @ Page directive as the first element on

Table 7-2: Properties of the TraceContext class

Property

TraceMode

Description

the page. To set this property for the entire application, use the application's Web.config file.

Indicates the sequence in which the trace messages should be displayed to the requesting browser. The sequence of the trace messages can be sorted alphabeticall y or in the order in which they were processed by using user-defined categories.

Note

When the IsEnable property is set to True for the entire

 

application, it is mandatory to exclusively set the property to False

 

for any page that needs to be restricted from displaying the tracing

 

information.

Table 7-3: Public instance methods of the TraceContext class

Method

Equals

Description

Used to check whether or not the instance of an object equals the current object.

GetHashCode

 

Used for

 

 

 

 

hashing

 

 

algorithms

 

 

and data

Table 7-3: Public instance methods of the TraceContext class

Method

ToString

GetType

Description

structure, such as a hash table.

Used to return a string that represents the current object.

Used to return the type of the object passed.

Warn

 

Used to

 

 

 

 

write the

 

 

trace

 

 

information

 

 

along with

 

 

the optional

 

 

exception

 

 

data in the

 

 

Trace log.

 

 

The

 

 

warnings

 

 

that are

 

 

written into

 

 

the Trace

 

 

log appear

 

 

as red text.

 

 

 

Write

 

Used to

 

 

 

 

write to the

 

 

Trace log.

After discussing the TraceContext class properties and methods, let us now understand the two levels of tracing.

Page-level tracing

ASP.NET makes it easy to debug and test applications by providing a trace capability. After the trace capability is enabled, ASP.NET provides the following functionalities automatically:

§Creates and appends a table called the table of performance data to the end of the ASP.NET page.

§Allows a developer to add custom diagnostic messages in the code wherever required.

Basically, the following are the two ways to generate trace statements in a page:

§Use the code written within a file.

§Use an HTML editor.

While generating the trace statements, you can include custom trace messages to the Trace log. Then, with the help of an HTML editor, you can present those messages and other trace information in a better manner.

You'll now write an ASP.NET page that generates the trace statements. Both Visual Studio .NET and Notepad can be used for writing the code. In this case, Notepad is used to create the ASPX file. The steps involved in writing the code for the page are described as follows:

1.Open Notepad and type the following code:

2.<%@ Page Language="VB" Trace="False"%>

3.<html>

4.<head>

5.<title> Trace Demo </title>

6.</head>

7.

8.<Script runat="server">

9.Public Function Addition(FNum As Integer, SNum As Integer) As Integer

10.Trace.Write("Inside Addition() FNum: ", FNum.ToString())

11.Trace.Warn("Inside Addition() SNum: ", SNum.ToString())

12.return FNum + SNum

13.End Function

14.</Script>

15.

16.<body>

17.Calling the Addition Function: 10 + 5 = <%=Addition(10,5)%>

18.</body>

</html>

19.Save the file as an ASPX file in a Web directory on the Web server. In this case, the file is named TraceStat.aspx.

20.Execute the TraceStat.aspx file. Figure 7-2 shows the output as shown in the browser when the ASP.NET page (TraceStat.aspx) is executed.

Figure 7-2: An example of the Trace.Write() method

In this code, the Trace.Write statements generate the trace statements. The Addition function takes two integer values and returns an integer value as the sum of the two numbers taken as parameters. In the Calling statement, the Addition function is called by using the <% and the %> delimiters used for specifying the ASP code.

Using the same code that generated the trace statement, you'll now look at the steps involved in presenting the statements generated in the ASP.NET page itself. The steps involved are described as follows:

1. Open the file TraceStat.aspx in Notepad and add the following directive as the first element in the file:

<%@ Page Trace="true" %>

2.Save the file in the same location with the same name.

3.Reexecute the TraceStat.aspx file. Figure 7-3 shows the output as

displayed in the browser when the ASP.NET page (TraceStat.aspx) is executed.

Figure 7-3: The output with Tracing enabled

In Figure 7-3, the trace information has been appended at the end of the ASP.NET. Looking at the output, the trace statements are as follows:

§Inside Addition() Fnum:

§Inside Addition() Snum:

@Page directives are special instructions that ASP.NET uses when Note processing a request for an ASP.NET resource. @Page directives can

be used to override or apply configuration settings for an ASP.NET page. A directive must be the first element on a page.

Application-level tracing

Application-level Tracing is enabled by using the Web.config file. This file is also used to enable the ASP.NET framework to gather the HTTP request information for the entire application.

Unlike page-level Trace statements, application-level Tracing does not present the Trace information in a browser unless specified, but the information can be displayed in a Webbased Trace viewer application. The Trace viewer displays trace information for a sequence of requests to the application, thus making it mandatory to store the matrix for each request in memory until tracing is enabled. This can be done by including a TraceContext class that participates in the HTTP execution of each request for the application.

By opening the root Web.config file and looking at the tracing section, the following code can be seen:

<configuration>

<system.web>

<trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" />

</system.web>

</configuration>

The Trace element has four attributes. These attributes are described in Table 7-4.

Table 7-4: Attributes of the Trace element

Attribute

enabled

Description

Indicates whether or not the applicationlevel Tracing is enabled. This attribute can take one of the two values, True or False. By default, the value is set to False.

requestLimit

 

Takes an

 

 

 

 

integer

 

 

value that

 

 

specifies the

 

 

total number

 

 

of trace

 

 

requests to

 

 

keep

 

 

cached in

 

 

memory on

 

 

a per-

 

 

application

 

 

basis. By

 

 

default, the

 

 

value is set

 

 

to 10.

 

 

 

pageOutput

 

Indicates

 

 

 

 

whether or

 

 

not the

 

 

Trace

 

 

information

 

 

would be

 

 

presented

 

 

on the

 

 

ASP.NET

 

 

page. This

 

 

attribute can

 

 

take one of

 

 

the two

 

 

values, True

 

 

or False. By

 

 

default the

 

 

value is set

 

 

to False.

 

 

 

traceMode

 

Indicates

 

 

Table 7-4: Attributes of the Trace element

 

Attribute

 

 

Description

 

 

 

 

 

 

 

 

 

 

 

the mode in

 

 

 

 

 

which the

 

 

 

 

 

Trace

 

 

 

 

 

information

 

 

 

 

 

is

 

 

 

 

 

presented.

 

 

 

 

 

The

 

 

 

 

 

information

 

 

 

 

 

can be

 

 

 

 

 

sorted by

 

 

 

 

 

time or

 

 

 

 

 

category.

 

 

 

 

 

 

Note

Sorting by category is used to differentiate between the settings

 

 

 

made by the system and the Trace.Write() settings enabled by

 

the developer. On the other hand, sorting by time sorts the information by the amount of time spent in the call.

You'll use the same sample code as used for the page-level Tracing to implement the application-level Tracing. However, you need to remove the @ Page directive to implement the application-level Tracing. Then, modify the Web.config settings as follows:

<configuration>

<system.web>

<trace

enabled="true"

requestlimitrequestLimit="10"

pageoutputpageOutput="false"

tracemodetraceMode="SortByTime"

/>

</system.web>

</configuration>

Figures 7-4 and 7-5 show the output when the pageOutput attribute in the Web.config file is set to False and when the attribute is set to True, respectively. Do remember to remove all tracing directives from the @ Page directives that you may have declared in the individual ASPX pages. Controlling trace behavior of an ASP.NET Web site becomes easier using the Web.config file, because it is the only file that is used to enable or disable the tracing ability of the Web site. For large Web sites, it is recommended that trace mode be controlled using the Web.config file rather than from the individual pages.

Соседние файлы в папке c#