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

Beginning ASP.NET 2.0 With CSharp (2006) [eng]

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

Chapter 15

How It Works

The working of this is simple: by enabling the trace element in Web.config, you are instructing ASP.NET to keep track of the trace information, but not to show it in the page. When you navigate to Trace.axd, ASP.NET recognizes this special URL, and instead of returning the standard 404 error page (or a custom page if you have one configured), it returns a list of pages that have been accessed in the application. Clicking the View Details link displays the trace information for that page.

The <trace> element has several attributes in Web.config, as described in the following table.

Attribute

Description

 

 

enabled

Indicates whether or not application tracing is enabled. The default value

 

is False.

localOnly

When set to True, this ensures that Trace.axd is only accessible from the

 

local machine. True is the default value, and stops remote users of the

 

site from accessing the trace information.

mostRecent

Indicates whether or not the most recent trace requests are kept. The

 

default is False, which keeps the first n items, where n is determined by

 

the requestLimit attribute. If this is True, then the most recent n items

 

are kept.

pageOutput

When this is set to True, the trace output is shown in the actual page, as

 

well as being stored for show by Trace.axd. The default is False,

 

although this doesn’t affect pages that have tracing enabled on them

 

directly.

requestLimit

The number of trace requests to store.

traceMode

Indicates the order in which the trace requests are shown. The default is

 

SortByTime, where the order is time-based, but this can also be SortBy

 

Category, where the requests are shown alphabetically.

 

 

The greatest thing about application tracing is that it can be invaluable in finding bugs in a running system. You can edit pages to add Trace.Write and turn on application tracing — the trace information will be stored, but the users won’t see any of it. You can then examine the trace details to help diagnose any problems.

Using the Debugger

The tracing features of ASP.NET 2.0 provide a great way to trace the flow of the application, but probably the most important weapon in your coding arsenal is the debugger. This allows you to halt the application while it is running, examine variables, and step through the code line by line. The debugger is built into Visual Web Developer and Visual Studio 2005, so you don’t have to run a separate application — you simply run the application from the development tool. The best way to learn debugging is to actually use it, as you do in the following Try It Out.

588

Dealing with Errors

Try It Out

Debugging

1.In the Wrox United application for the chapter, open Checkout.aspx.cs.

2.In the Page_Load event, place the cursor on the line that checks to see if the cart has a value:

if (Profile.Cart == null)

3.Set a breakpoint on this line. You can do this in one of three ways. The first is by selecting the Toggle Breakpoint option from the Debug menu. The next is by pressing F9, and the last is by clicking the gray border at the left of the line of code:

4.Whichever method you use, this is a toggle, so performing the same action again removes the breakpoint. When a breakpoint is set, the gray border will show a red circle and the line will be highlighted, as shown in Figure 15-8.

Figure 15-8

5.Scroll down to the Wizard1_FinishButtonClick event, and place a breakpoint on the following line:

foreach (CartItem item in Profile.Cart.Items)

6.Run the application from VWD or VS and navigate to the Checkout page. The page will not display — you’ll see that you are stopped in the debugger (see Figure 15-9).

7.Press F5, or select Continue from the Debug menu. The page now appears.

8.Add some items to the shopping cart and then navigate to the end of the Checkout page again. When the breakpoint is reached, press F5, and you’ll see the error message shown in Figure 15-10.

You’ve hit an exception so the debugger halts. This is because of a change to the checkout code you did earlier, where you had an incorrect SQL statement so that you could force an exception.

589

Chapter 15

Figure 15-9

Figure 15-10

9.Click the View Detail link to show the details of the exception. Click the plus sign (+) to expand the details (see Figure 15-11), and you’ll see that the exception shows your custom text and that there is an InnerException.

10.Click this open to show the original exception, in that there isn’t a table called no_Orders. This isn’t something that can be corrected while running the application, so you need to stop debugging.

11.From the Debug menu, select Stop Debugging, or press Shift+F5.

590

Dealing with Errors

Figure 15-11

12.Edit the code to correct the error, changing no_Orders back to Orders:

cmd.CommandText = “INSERT INTO ORDERS(MemberName ...”;

13.Run the application again, and navigate to the Checkout page again, making sure you have logged in and there are at least three items in your shopping cart.

14.When the breakpoint is reached in Page_Load, press F5 to continue.

15.Continue through the checkout process, noticing that the breakpoint doesn’t get hit when you click the Next button. The breakpoint in Page_Load will only be reached the first time the page is loaded because the code block in which the breakpoint is set is only when IsPostBack is false.

16.When you get to the end of the checkout process, click Finish, and another breakpoint will be reached, as shown in Figure 15-12.

17.From the Debug menu, select Step Over, or press F10. Notice that execution moves to the next line.

18.Keep pressing F10 until you get to the line that sets the @Quantity parameter. Notice how execution moves to the next line each time you step.

19.Hover the cursor over the item of item.Quantity, and you’ll see the tooltip showing the value of the variable.

20.Without moving the currently active line, hover the cursor over the item of the foreach line. You’ll see another tooltip, but this time there isn’t a value. That’s because this is a complex type, a CartItem, but notice that there is a little plus sign on the left.

591

Chapter 15

Figure 15-12

21.Hover over or click the +, and the properties (both public and private) are shown for the item (see Figure 15-13).

Figure 15-13

22.From the Debug menu, select Step Into, or press F11. This will step into the line of code, opening up the code for the shopping cart, in the property get, as depicted in Figure 15-14.

Figure 15-14

23.Keep pressing F11 until you are back into the checkout code.

24.Right-click the trans.Commit() line, and select the Run To Cursor option. Notice how all intermediate code is run, but that the next line is the trans.Commit() line.

592

Dealing with Errors

25.From the Debug menu, select Delete All Breakpoints, or select Control+Shift+F9.

26.Press F5 to continue the code, and you’ll be back in the browser.

How It Works

Debugging works because VWD controls the interaction of code. Normally the code runs without interruption, but a breakpoint tells VWD to suspend code at the appropriate line. And because VWD is in control, its debugging capabilities enable you to view variables, step through code line by line, and so on. Stepping through code is further enhanced by the fact that you can step into code called from the current routine. In this example, you stepped from the code in Checkout.aspx.cs into Shopping.cs, enabling you to follow the program flow line by line.

Debugging is extremely useful for not only tracking down problems in code, but also for understanding the flow of code. You can use it to understand which methods are called, the order in which they are called, and what code does in those methods. It’s a practical skill that will make you a good programmer, so it’s worthwhile spending time getting used to the debugger.

It’s worth pointing out the difference between the various actions of the debug toolbar. These are summarized in the following table. An empty entry for the shortcut key means that there is no default key for that action.

 

Toolbar Icon

Shortcut Key

Description

 

 

 

 

 

 

 

 

F5

Run the application if it currently isn’t running, or con-

 

 

 

 

 

 

 

tinue running the application if it is currently paused at a

 

 

 

 

breakpoint.

 

 

 

 

Pause the running of the application.

 

 

 

 

 

 

 

Shift+F5

Stop debugging the application.

 

 

 

 

 

 

 

 

 

Ctrl+Shift+F5

Restart the application.

 

 

 

 

 

 

 

 

 

 

Show the next statement, which highlights the next state-

 

 

 

 

 

 

 

 

 

 

 

 

ment to be executed.

 

 

 

F11

Step into a method. If the current line contains a method

 

 

 

 

 

 

 

or property from another class, then stepping into that

 

 

 

 

method will load the code file for the class and allow

 

 

 

 

stepping through the code for the method or property.

 

 

 

F10

Step over a method. If the current line contains a method

 

 

 

 

or property from another class, then stepping over will

 

 

 

 

execute the line without allowing stepping through the

 

 

 

 

code for the method or property.

 

 

 

 

Table continued on following page

593

Chapter 15

 

Toolbar Icon

Shortcut Key

Description

 

 

 

 

 

 

 

 

Shift+F11

Step out, which steps out of the current method or prop-

 

 

 

 

 

 

 

erty. This is useful if you have stepped into a method but

 

 

 

 

don’t want to continue stepping though the lines. Step-

 

 

 

 

ping out will take you back to the calling routine.

 

 

 

 

Hex display, which displays the output in hexadecimal.

 

 

 

 

Show the output window, which shows the actions VWD

 

 

 

 

 

 

 

 

or VS take during debugging.

 

 

 

 

 

It’s worth getting used to using both the buttons and the shortcut keys because it makes debugging quicker.

During the debugging exercise, you saw how you could hover the cursor over a variable to see the contents of that variable. But the viewing of variables is not just restricted to hovering the cursor over them, because there are special debugging windows that help with this. One of these is the Locals window (see Figure 15-15), which shows the local variables for the current procedure.

Figure 15-15

Here you have all of the local variables, and those that are complex types can be expanded to show the properties.

The Watch window allows you to watch variables. When in Debug mode, you can highlight a variable, right-click it and select Add Watch from the menu. The use of the Watch window is the same as the Locals window, the only difference being that the Watch window only shows variables that you choose.

The Call Stack shows the current stack trace, which is the hierarchy of methods — which methods have been called from other methods. You can see the Call Stack at the bottom right of the screen when you are debugging. For example, in the shopping cart code, the stack trace displayed in Figure 15-16 might be shown.

Here the highlighted line is the current line of code, and you can see that it is the Quantity property of the CartItem (get_Quantity is shown because this is actually how the underlying code works; showing it is the Get part of the property). The second line shows the method that called this Quantity property, and this is Wizard1_FinishButtonClick.

594

Dealing with Errors

Figure 15-16

There are other windows, but Locals, Watch, and Call Stack aree the most common, and to get the best from the debugger you really have to practice. It’s worth experimenting just to get a feel for how the debugger works, and the sort of things that are possible.

Summar y

It may seem odd that we’ve had a whole chapter on the negative aspects of building web sites, but ultimately this will make you a better developer. After all, possessing knowledge is all well and good, but knowing how to cope with problems that arise is just as important. So this chapter looked at defensive coding, where you must take a pessimistic attitude. This takes the view that your code should be as robust as possible, not making assumptions about anything, such as parameters passed into methods. This is especially true when you’re dealing with SQL statements that take data from the user, so you looked at how to replace the building of a SQL statement using concatenation with SqlParameter objects to prevent hacking attacks.

Another part of defensive coding is the use of validation controls, which provide a simple way to ensure that data entered by users is correct. Because these controls give both clientand server-side validation, users get a great experience because the validation notifies them of problems before posting back to the server.

Additionally, this chapter discussed the following topics:

Exceptions, where you learned how to cope with the unexpected (cue the inquisition leaping in from off frame — ”Nobody expects the exception” — apologies to the Monty Python team) Dealing with exceptions is a tricky business, and should be limited to those situations where you can gracefully recover from the problem. One of the key tenets is that you should always leave the application in a stable state when recovering from exceptions.

Handling exceptions globally or at least how to manage their details globally, with the global.asax file. You saw that for both trapped and untrapped exceptions, the details can be centrally logged, ensuring that you always know of errors wherever they happen with the application.

595

Chapter 15

Tracing and debugging, and how you can track down problems within code. Tracing gives the capability to write the status of the running code, with the capability to switch the trace output on and off without affecting the trace statements themselves. Debugging delves into the code in more detail, enabling you to step through the code as it runs. These are the key techniques of learning how to find errors.

You’re very nearly at the end of the book, and a lot of material has been covered. The final chapter looks at topics that will lead you from the book content to further learning and at topics of how to move forward with the knowledge you have. It also covers how to deploy your application so that it can be hosted by an ISP, allowing your great code to be seen by the whole world.

Exercises

1.Add defensive coding to the GenerateThumbnail method of the ImageHandling class stored in the App_Code directory.

2.Add validation controls to the Checkout page, the part that accepts the delivery address. There is a check box to copy the address from the membership details of the user, but there is nothing to ensure that all of the fields are filled in.

3.Use the debugger.

596

16

Deployment, Builds,

and Finishing Up

It’s been a long journey since you started this book by building a quick example web site, and then starting to build your full-fledged Wrox United application. You now have a web site that uses e-commerce to take customer details and credit card numbers, displays up-to-the-minute content, allows users to view (and listen to) multimedia, and references a multitude of data sources, all within the course of 15 chapters. This is the kind of thing that could have taken six months in the past and a whole team of developers. However, it doesn’t end here. I’m often tempted at the end of a project to put my feet up and say, well I’ve done all the hard work, it’s all smooth sailing now. However, I have been painfully disabused of this notion on more than one occasion. Even if you’re confident of the extremely unlikely scenario of your application having no bugs and being simple to maintain, and your client never having any further questions to ask or features to add, you still have to deploy your site. Visual Web Developer has a feature that allows you to copy your web site from a local folder to a remote location, and you’ll make use of that in this chapter.

After you’ve deployed your site, what next? If you succeed in becoming a professional developer, you will undoubtedly talk to plenty of companies who will set the final deadline as the day you deliver the working code to them. If you pencil in another project the day after this deadline, you might end up getting into trouble when you find yourself required back on site at your old project because something breaks down or doesn’t work in the way it was intended. Testing is often completely overlooked by both companies and developers. Chapters 14 and 15 talked about various ways for testing your code as you create it, but testing your code after you’ve deployed the site should also feature in your timeline. If possible, you should also test it alongside your proposed user base. Even if everything goes fine, you should be prepared to maintain this site, make adjustments, and make sure that the site owners can run it in your absence.

And lastly, what should you do next after reading this book? Do you run out and apply for a set of developer jobs? Or do you have to go out and buy another book? You’ll get a thorough grounding in what you should be looking to do next.