Beginning asp net 2.0 with c phần 9 pptx

77 306 0
Beginning asp net 2.0 with c phần 9 pptx

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

Using ASP.NET Tracing You first looked at tracing in Chapter 14. It is the technique of adding code to your pages, for a few rea- sons: for debugging purposes, to output values of variables, or simply to find out where in your code certain things happen. The great thing about ASP.NET tracing is that not only is it extremely simple to do, but it’s also easily configurable and doesn’t require tracing code to be removed if you don’t want the trace information shown. What’s also great is that you get a wealth of additional information about the page, which can be useful for both debugging purposes and for learning about ASP.NET. Tracing Individual Pages Tracing can be turned on for individual pages by adding the Trace attribute to the Page directive: <%@ Page Trace=”true” %> On its own, this outputs a great deal of information about the page, but you can also add your own out- put using the Trace class, which has methods to write output to the trace log: Trace.Write(“my information”) The following Try It Out shows tracing in action. Try It Out Page-Level Tracing 1. In the Wrox United application for the chapter, open Checkout.aspx in Source View. 2. Add the Trace attribute to the Page directive: <%@ Page Trace=”True” %> 3. Save the file and run the application. 4. Add some items from the shop to your shopping cart and navigate to the Checkout page, where you’ll see that the bottom of the page has lots of information added. You might have to scroll down the page to see all of the information. 5. Switch back to VWD and open the code file for the Checkout page. 6. At the top of the Page_Load event, add the following line of code: Trace.Write(“In Page_Load”); 7. Before the check to see if the user is authenticated, add the following: Trace.Write(“In page_Load”, User.Identity.IsAuthenticated.ToString()); if (User.Identity.IsAuthenticated) 8. Save the page and run the application, again navigating to the Checkout page. 9. Scroll the page down so you can see the Trace Information section, as shown in Figure 15-6. 10. Here you can see that the output from the Trace.Write statements is mixed with the output that ASP.NET puts into the trace. Take a look at how this works and what information the trace output produces. 584 Chapter 15 18_042583 ch15.qxd 4/4/06 2:52 PM Page 584 Figure 15-6 11. Edit Checkout.aspx again and set the Trace attribute to False: <%@ Page Trace=”False” %> 12. Save the page and run the application, again navigating to the Checkout page. Notice that the trace information is gone from the page, even though the Trace.Write statements are still in the code. How It Works The first thing to look at is what all of this trace information is, and what it is useful for. There are many sections, as detailed in the following table. Section Contains Request Details Details of the request, such as the status code. Trace Information The flow of page events, showing the category, message, and time from the first to last byte of information sent to the browser. Control Tree The hierarchy of controls in the page. Session State Any session variables in use. Application State Any application variables in use. Request Cookies Collection The cookies stored for the current site. Response Cookies Collection Any cookies set during the page processing. Headers Collection The HTTP headers. Response Headers Collection Any headers set during the page processing. Form Collection Contents of the form. QueryString Collection Any querystring parameters for the request. Server Variables The HTTP server variables. 585 Dealing with Errors 18_042583 ch15.qxd 4/4/06 2:52 PM Page 585 All of this information is useful, although some sections are more useful than others. The Control Tree, for example, clearly shows the hierarchy of controls. You saw this in Chapter 14 when you looked at per- formance, but it’s also useful for understanding how the page is made up from the hierarchy of controls. At the top is the Page object, beneath that the Master page, and then controls within the Master page. This continues with all of the page objects, and shows the unique name of the control as well as its type. The Trace Information section shows the events in the order in which they are raised, so it is great for seeing exactly when things happen. Without any trace information of your own, the standard page events are shown, and anything you write is slotted into its correct space. So take a look what you actually did: protected void Page_Load(object sender, System.EventArgs e) { Trace.Write(“In Page_Load”); if (!Page.IsPostBack) { if (Profile.Cart == null) { NoCartlabel.Visible = true; Wizard1.Visible = false; } Trace.Write(“In Page_Load”, User.Identity.IsAuthenticated.ToString()); if (User.Identity.IsAuthenticated) Wizard1.ActiveStepIndex = 1; else Wizard1.ActiveStepIndex = 0; } In the first statement, you used Trace.Write to output a single string, which is displayed in the Message column. With the second Trace.Write, you passed in two parameters, and in this case, the first becomes the Category and the second becomes the Message. You can put trace statements anywhere within your code, and the output will be displayed in the Trace Information section, so it’s a great way to simply see what’s happening in your code. There is a also a Warn method of the Trace class, which outputs in the same way as Write, but the content is in red. This is useful for picking out statements within the trace output. The other thing you may have noticed is that by changing the value of the Trace attribute at the top of page to False, no trace output is displayed. You didn’t have to remove the Trace.Write statements from the code, because these are simply ignored if tracing isn’t enabled. This is great during develop- ment, because you can liberally sprinkle Trace.Write statements throughout your code to give you a good understanding of the program flow, and you can turn on or off the tracing without having to remove or comment out these statements. Tracing All Pages Although tracing in individual pages is useful, what’s great is being able to control tracing for the entire application. This is done with a configuration setting in Web.config, within the <system.web> section: <trace enabled=”True” /> 586 Chapter 15 18_042583 ch15.qxd 4/4/06 2:52 PM Page 586 When the enabled attribute is set to True, tracing is enabled for the application, but the output isn’t shown in the pages. Instead, it is stored for viewing by way of a special URL— Trace.axd — which doesn’t point to a physical file, but is instead interpreted by ASP.NET. You give application tracing a go in the next Try It Out. Try It Out Application-Level Tracing 1. In Source View in Checkout.aspx, remove the Trace attribute from the Page directive at the top of the page. 2. Open Web.config and add the following within the <system.web> section: <trace enabled=”True” /> 3. Save the file and run the application, navigating to the Checkout page. 4. Within Internet Explorer, select File➪New➪Window (or press Control+N) to launch a new win- dow from the same site. 5. In the address bar, change Checkout.aspx to Trace.axd and press Enter. You should see some- thing like Figure 15-7. Figure 15-7 6. Click the View Details link on the Checkout.aspx line, and you will see the trace page you’ve already seen. Notice that it contains the two pieces of data that were added to Checkout.aspx in the Page_Load event. 587 Dealing with Errors 18_042583 ch15.qxd 4/4/06 2:52 PM Page 587 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 sys- tem. 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 sim- ply 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 Chapter 15 18_042583 ch15.qxd 4/4/06 2:52 PM Page 588 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 follow- ing 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 Dealing with Errors 18_042583 ch15.qxd 4/4/06 2:52 PM Page 589 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 Chapter 15 18_042583 ch15.qxd 4/4/06 2:52 PM Page 590 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 exe- cution 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 Dealing with Errors 18_042583 ch15.qxd 4/4/06 2:52 PM Page 591 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 inter- mediate code is run, but that the next line is the trans.Commit() line. 592 Chapter 15 18_042583 ch15.qxd 4/4/06 2:52 PM Page 592 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 inter- ruption, 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 program- mer, 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 sum- marized 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 Dealing with Errors 18_042583 ch15.qxd 4/4/06 2:52 PM Page 593 [...]... the NETWORK SERVICE for the App_Data folder The reason you have to do this is ASP. NET 2.0 runs under this particular service, and so if ASP. NET 2.0 wants to access the database, a request to access it will come from this particular service In ASP. NET 1.1, you would add permissions for the ASPNET account to do this In ASP. NET 2.0, the NETWORK SERVICE account does the same However, there have been occasions... community for ASP. NET ❑ www .asp. net: The official Microsoft ASP. NET web site ❑ http://msdn.microsoft.com /asp. net/ : The MSDN reference for all things ASP. NET- related, and an essential reference for any developer ❑ www.15seconds.com: A great magazine-like site with loads of free articles on ASP. NET 2.0 ❑ http://beta .asp. net: Microsoft’s coverage of the latest version of ASP. NET ❑ www.dotnet247.com: A compendium,... connections, you can end up with a Connection Pooling error Unlike classic ASP where it was common practice to set the connection to Nothing, all that’s needed is to close any open connections once you’ve finished them The number of open connections that can be maintained is finite and connections are reused from a pool If you have only one unclosed connection on a small site, you might never notice... to change, right-click that folder, select Properties, and change the permissions Click the Add button to bring up the Select Users or Groups dialog box (see Figure 16-10) Type Network Service and click Check Names (If you don’t type in the correct case, it will capitalize the name for you.) Figure 16-10 Click OK In the Properties dialog box (refer to Figure 16 -9) , make sure the Write check box is checked... A compendium, online cross-reference of all the Usenet newsgroups, including all of the ASP. NET 2.0 groups ❑ http://msdn.microsoft.com/coding4fun/default.aspx: MSDN’s site on fun coding topics ❑ www.codeproject.com: A good resource for free source code and tutorials Summar y This hasn’t really been a chapter about a particular subject, but rather an extended wrapping up and welcome to the real world... application is configured as a virtual directory (this process is described in Appendix B) Occasionally IIS doesn’t work in the way it should, and often non-specific errors can be fixed if you run the aspnet_regiis executable with the –i switch To do this, go to the command prompt and go to the C: \Windows\Microsoft .Net\ Framework\v2.0 50727 folder From this folder, type the following and press Enter: aspnet_regiis... type CMD to bring up the command prompt 2 Type the following command and press Enter: XCOPY C: \BegASPNET2\Begin\Chapter16\WroxUnited C: \BegASPNET2\Begin\Chapter16\WroxUnited3 /E 3 You are presented with the screen shown in Figure 16-7, and asked whether the target is a file name or directory Press d because it is a directory XCOPY will now copy all the files over Figure 16-7 4 5 6 604 Close the command... 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... your code 599 Chapter 16 This doesn’t just stop with remote file locations, but also with connection strings If you are using a local database to test your code, you will have to change the connection settings as well Your local database might use SQL Express, but your main server might be SQL Server 2005 — once again, no extra code is needed, it can just be worked by commenting the line out: ... references are changed so that file references are specific to the new machine and that the requisite components are installed This is the most likely reason for your code failing on your host’s machine The best way to do this is to place any machine-specific information within the Web.config file and then reference it from inside the appSettings, as discussed in Chapter 2 Then you can change any information . trans.Commit() line. 5 92 Chapter 15 18 _0 425 83 ch15.qxd 4/4 /06 2: 52 PM Page 5 92 25. From the Debug menu, select Delete All Breakpoints, or select Control+Shift+F9. 26 . Press F5 to continue the code,. chapter copy of WroxUnited (C: BegASPNET2BeginChapter16WroxUnited) and select the Web Site➪Copy Web Site option (see Figure 16-1). Figure 16-1 600 Chapter 16 19 _0 425 83 ch16.qxd 4/4 /06 2: 52. mentioned within your code. 599 Deployment, Builds, and Finishing Up 19 _0 425 83 ch16.qxd 4/4 /06 2: 52 PM Page 599 This doesn’t just stop with remote file locations, but also with connection strings.

Ngày đăng: 09/08/2014, 18:22

Tài liệu cùng người dùng

  • Đang cập nhật ...

Tài liệu liên quan