Professional ASP.NET 3.5 in C# and Visual Basic Part 115 ppsx

10 224 0
Professional ASP.NET 3.5 in C# and Visual Basic Part 115 ppsx

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

Thông tin tài liệu

Evjen c23.tex V2 - 01/28/2008 3:38pm Page 1099 Chapter 23: Caching SqlConnection( ConfigurationManager.ConnectionStrings["AppConnectionString1"].ConnectionString); SqlDataAdapter da = new SqlDataAdapter("Select * from Customers", conn); myCustomers = new DataSet(); da.Fill(myCustomers); SqlCacheDependency myDependency = new SqlCacheDependency("Northwind", "Customers"); Cache.Insert("firmCustomers", myCustomers, myDependency); Label1.Text = "Produced from database."; } else { Label1.Text = "Produced from Cache object."; } GridView1.DataSource = myCustomers; GridView1.DataBind(); } < /script > In this example, the SqlCacheDependency class associated itself to the Customers table in the Northwind database as before. This time, however, you use the Cache object to insert the retrieved dataset along with a reference to the SqlCacheDependency object. The Insert method of the Cache class is constructed as follows: Cache.Insert(key As String, value As Object, dependencies As System.Web.Caching.CacheDependency) You can also insert more information about the dependency using the following construct: Cache.Insert(key As String, value As Object, dependencies As System.Web.Caching.CacheDependency absoluteExpiration As Date, slidingExpiration As System.TimeSpan) And finally: Cache.Insert(key As String, value As Object, dependencies As System.Web.Caching.CacheDependency absoluteExpiration As Date, slidingExpiration As System.TimeSpan) priority As System.Web.Caching.CacheItemPriority, onRemoveCallback As System.Web.Caching.CacheItemRemovedCallback) The SQL Server cache dependency created comes into action and does the same polling as it would have done otherwise. If any of the data in the Customers table has changed, the SqlCacheDependency class invalidates what is stored in the cache. When the next request is made, the Cache("firmCustomers") is found to be empty and a new request is made to SQL Server. The Cache object again repopulates the cache with the new results generated. When the ASP.NET page from Listing 23-8 is called for the first time, the results generated are shown in Figure 23-8. 1099 Evjen c23.tex V2 - 01/28/2008 3:38pm Page 1100 Chapter 23: Caching Figure 23-8 Figure 23-9 1100 Evjen c23.tex V2 - 01/28/2008 3:38pm Page 1101 Chapter 23: Caching Because this is the first time that the page is generated, nothing is in the cache. The Cache object is, there- fore, placed in the result set along with the association to the SQL Server cache dependency. Figure 23-9 shows the result for the second request. Notice that the HTML table is identical because it was generated from the identical DataSet , but the first line of the page has changed to indicate that this output was produced from cache. On the second request, the dataset is already contained within the cache; therefore, it is retrievable. You aren’t required to hit SQL Server to get the full results again. If any of the information has changed within SQL Server itself, however, the Cache object returns nothing; a new result set is retrieved. Summary SQL Server cache invalidation is an outstanding feature of ASP.NET that enables you to invalidate items stored in the cache when underlying changes occur to the data in the tables being monitored. Post-Cache Substitution fills in an important gap in ASP.NET’s technology, enabling you to have both the best highly dynamic content and a high-performance Web site with caching. When you are monitoring changes to the database, you can configure these procedures easily in the web.config file, or you can work programmatically with cache invalidation directly in your code. These changes are possible because the CacheDependency object has been unsealed. You can now inherit from this object and create your own cache dependencies. The SQL Server cache invalidation process is the first example of this capability. 1101 Evjen c24.tex V2 - 01/28/2008 3:40pm Page 1103 Debugging and Error Handling Your code always runs exactly as you wrote it, and you will never getitrightthefirsttime.So, expect to spend about 30 percent of your time debugging and, to be a successful debugger, learn to use the available tools effectively. Visual Studio has upped the ante, giving you a host of new features that greatly improve your debugging experience. So many of these new features, howeve r, can be overwhelming at first. This chapter breaks down all the techniques available to you, one at a time, while presenting a holistic view of Visual Studio, the Common Language Runtime (CLR), and the Base Class Library (BCL). Everyone knows that debugging is twice as hard as writing a program in the first place. So if you’re as clever as you can be when you write it, how will you ever debug it? — Brian Kernighan Additionally, because debugging is more than stepping through code, this chapter discusses e ffi- cient error and exception handling, tracing and logging, and cross-language (C#, Visual Basic, client-side JavaScript, XSLT, and SQL Stored Procedure) debugging. Design-Time Support Visual Studio has always done a good job of warning you of potential errors at design time. Syntax notifications or squiggles underline code that won’t compile or that might cause an error before you have compiled the project. A new error notification pops up when an exception occurs during a debugging session and recommends a course of action that prevents the exception. At every step, Visual Studio tries to be smarter, anticipating your needs and catching common mistakes. Rico Mariani, the Chief Architect of Visual Studio, has used the term ‘‘The Pit of Success’’ to describe the experience Microsoft wants you to have with Visual Studio. When Microsoft designed these new features, they wanted the customer to simply fall into winning practices. The company Evjen c24.tex V2 - 01/28/2008 3:40pm Page 1104 Chapter 24: Debugging and Error Handling tried to achieve this by making it more difficult for you to write buggy code or make common mistakes. Microsoft’s developers put a great deal of thought into building APIs that point you in the right direction. Syntax Notifications Both the Visual Basic and C# editors show squiggles and tooltips for many syntax errors well before compilation, as illustrated in Figure 24-1. Figure 24-1 Syntax notifications aren’t just for CLR programming languages; Visual Studio has also greatly improved the XML Editor since its original release with enhancements like the following: ❑ Full XML 1.0 syntax checking ❑ Support for XSD and DTD validation and IntelliSense ❑ Support for XSLT 1.0 syntax checking Figure 24-2 shows a detailed tooltip indicating that the element < junk > doesn’t have any business being in the web.config file. The editor knows this because of a combination of the XSD validation support in the XML Editor and the addition of schemas for configuration files such as web.config .Thisisawelcome change for anyone who, when manually editing a web.config file,haswonderedifheguessedtheright elements. See the Chapter 10 for more details on these XML-related features. Figure 24-2 The ASPX/HTML Editor benefits from these improvements as well; for example, Figure 24-3 shows a warning that the < hanselman/ > element is not available in the active schema. Code that appears in < script runat="Server"/ > blocks in ASP.NET p ages is also parsed and marked with squiggles. This makes including code in your pages considerably easier. Notice also that the ASP.NET page in Figure 24-3 has an XHTML DOCTYPE declaration on the first line, and the HTML element has a default XHTML namespace. This HTML page is treated as XML because XHTML has been targeted. 1104 Evjen c24.tex V2 - 01/28/2008 3:40pm Page 1105 Chapter 24: Debugging and Error Handling XHTML is the HTML vocabulary of markup expressed with all the syntax rules of XML. For example, in HTML you could create a < br > tag and never close it. In XHTML you use the closing tag < br / >. XHTML documents look exactly like HTML documents because they are, in fact, expressing the same semantics. Because XHTML documents are XML, they require a namespace on their root element and should have a DOCTYPE as well. Figure 24-3 To add a hanselman element, you must put it in its own namespace and add a namespace declaration in the root HTML element. The Visual Basic Editor takes assistance to the next level with a smart tag like the pulldown/button that appears when you hover your mouse over a squiggle. A very nicely rendered modeless window appears with your code in a box along with some suggested changes to make your code compile. Figure 24-4 shows a recommendation to insert a missing End If ; making the correction is simple — just click Insert the missing ’End If’ . Figure 24-4 1105 Evjen c24.tex V2 - 01/28/2008 3:40pm Page 1106 Chapter 24: Debugging and Error Handling All these design-time features exist to help you ensure better code while it’s being written, before it’s been compiled and run. Two related features help you run arbitrary code within the development environment as well as organize the tasks still to be performed. Immediate and Command Window The Immediate Window lets you run arbitrary bits of code in Design mode without compiling your application. You can e valuate code at design time or while you’re debugging. It can be a great way to test a line of code or a static method quickly. The Immediate mode of this window is used primarily for debugging. Access the Immediate Window from Debug ➪ Windows ➪ Immediate. To evaluate a variable or run a method, simply click in the Immediate Window and type a question mark (?) followed by the expression, variable, or method you want to evaluate. The immediate window can also be switched into t he Command Window by prefacing commands with a greater-than sign (>). When you enter a greater-than sign in the Immediate/Command Win- dow, an IntelliSense drop-down appears exposing the complete Visual Studio object model as well as any macros that you may have recorded. Command mode of this window is used for executing Visual Studio Commands without using the menus. You can also execute commands that may not have a menu item. If you type > alias into the Command window, you receive a complete list of all current aliases a nd their definitions. Some useful command aliases include the following: ❑ > Log filename /overwrite /on|off :The Log command starts logging all output from the com- mand window to a file. If no filename is included for logging, go to cmdline.log .Thisisoneof the more useful and least-used features of the debugger, and reason enough to learn a few things about the immediate/Command Window. ❑ > Shell args /command /output /dir:folder :The Shell command allows you to launch exe- cutable programs from within the Visual Studio Command window such as utilities, command shells, batch files, and so on. Task List The Task list in Visual Studio is more useful than you might think. People who haven’t given it much attention are missing out on a great feature. The Task list supports two views: User Tasks and Comments. User Tasks view enables you to add and modify tasks, which can include anything from ‘‘Remember to Test’’ to ‘‘Buy Milk.’’ These tasks are stored in the .suo (solution user options) that is a parallel partner to the .sln files. The Comments view shows text from the comments in your code where those lines are prefixed with a specific token. Visual Studio comes configured to look for the TODO: token, but you can add your own in Tools ➪ Options ➪ Environment ➪ Task List. In Figure 24-5, the comment token HACK has been added in the Options dialog box. A comment appears in the source with HACK: preceding it, so that comment line automatically appears in the Task List in the docked window at the bottom of Visual Studio. The three circles in Figure 24-5 illustrate the connection 1106 Evjen c24.tex V2 - 01/28/2008 3:40pm Page 1107 Chapter 24: Debugging and Error Handling between the word HACK added to the Options dialog box and its subsequent appearance in the source code and Task List. You and your team can add as many of these tokens as you’d like. Figure 24-5 Tracing Tracing is a way to monitor the execution of your ASP.NET application. You can record exception details and program flow in a way that doesn’t affect the program’s output. In classic ASP, tracing and debug- ging facilities were nearly nonexistent, forcing developers to use ‘‘got here’’ debugging in the form of many Response.Write statements that litter the resulting HTML with informal trace statements announc- ing to the programmer that the program ‘‘got here’’ and ‘‘got there’’ with each new line executed. This kind of intrusive tracing was very inconvenient to clean up and many programmers ended up creating their own informal trace libraries to get a round these classic ASP limitations. In ASP.NET, there is rich support for tracing. The destination for trace output can be configured with TraceListeners like the EventLogTraceListener . Configuration of TraceListeners is covered later in this 1107 Evjen c24.tex V2 - 01/28/2008 3:40pm Page 1108 Chapter 24: Debugging and Error Handling section. ASP.NET also includes a number of small improvements to tracing over ASP.NET 1.x, including trace forwarding b etween the ASP.NET page-specific Trace class and standard Base Class Library’s (BCL) System.Diagnostics.Trace used by non–Web developers. Additionally, the resolution of the timing output by ASP.NET tracing has increased precision — from 6 digits to 18 digits for highly accurate profiling between ASP.NET 1.1 and ASP.NET 2.0/3.5. System.Diagnostics.Trace and ASP.NET’s Page.Trace There are multiple things named Trace in the whole of the .NET Framework, so it may appear that trac- ing isn’t unified between Web and non-Web applications. Don’t be confused because there is a class called System.Diagnostics.Trace and there is also a public property on System.Web.UI.Page called Trace .The Trace property on the Page class gives you access to the System.Web.TraceContext and the ASP.NET-specific tracing mechanism. The TraceContext class collects all the details and timing of a Web request. It contains a number of methods, but the one you’ll use the most is Write . It also includes Warn , which simply calls Write() , and also ensures that the output generated by Warn is colored red. If you’re writing an ASP.NET application that has no supporting components or other assemblies that may be used in a non-Web context, you can usually get a great deal of utility using only the ASP.NET TraceContext . However, ASP.NET support tracing is different from the rest of the base class library’s tracing. You’ll explore ASP.NET’s tracing facilities first, and then learn how to bridge the gap and see some new features that make debugging even easier. Page-Level Tracing ASP.NET tracing can be enabled on a page-by-page basis by adding Trace="true" to the Page directive in any ASP.NET page: <%@ Page Language="C#" Inherits="System.Web.UI.Page" Trace="true" %> Additionally, you can add the TraceMode attribute that sets SortByCategory or the default, SortByTime . You might include a number of categories, one per subsystem, and use SortByCategory to group them, or you might use SortByTime to see the methods t hat take up the most CPU t ime for your application. You can enable tracing programmatically as well, using the Trace.IsEnabled property. The capability to enable tracing programmatically means you can enable tracing via a querystring, cookie, or IP address; it’s up to you. Application Tracing Alternatively, you can enable tracing for the entire application by adding tracing settings in web.config . In the following example, pageOutput="false" and requestLimit="20" are used, so trace information is stored for 20 requests, but not displayed on the page: <configuration> <system.web> <trace enabled="true" pageOutput="false" requestLimit="20" traceMode="SortByTime" localOnly="true" /> </system.web> </configuration> The page-level settings take precedence over settings in web.config ,soif enabled="false" is set in web.config but trace="true" is set on the page, tracing occurs. 1108 Evjen c24.tex V2 - 01/28/2008 3:40pm Page 1109 Chapter 24: Debugging and Error Handling Viewing Trace Data Tracing can be viewed for multiple page requests at the application level b y requesting a special page (of sorts) called trace.axd .Notethat trace.axd doesn’t actually exist; it is actually provided by System.Web.Handlers.TraceHandler ,aspecial IHttpHandler to which trace.axd is bound. When ASP.NET detects an HTTP Request for trace.axd , that request is handled by the TraceHandler rather than by a page. Create a Web site and a page, and in the Page_Load event, call Trace.Write() . Enable tracing in the web.config as shown in Listing 24-1. Listing 24-1: Tracing using Page.Trace Web.config <configuration> <system.web> <trace enabled="true" pageOutput="true" /> </system.web> </configuration> VB Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load ’All on one line! Trace.Write("This message is from the START OF the Page_Load method!") End Sub C# protected void Page_Load(object sender, EventArgs e) { Trace.Write("This message is from the START of the Page_Load method!"); } Hit the page in the browser a few times and notice that, although this page doesn’t create any HTML to speak of, a great deal of trace information is presented in the browser, as shown in Figure 24-6, because the setting is pageOutput="true" . The message from Trace.Write appears after Begin Load and before End Load — it’s right in the middle of the Page_Load method where you put it. The page was automatically JIT-compiled as you ran it, and that initial performance hit is o ver. Now that it’s been compiled into native code, a subsequent run of this same page, performed by clicking Refresh in the browser, took only 0.000167 seconds on my laptop because the page had already compiled. It’s very easy and very useful to collect this kind of very valuable performance timing data between Trace statements. Incidentally, this simple page is more than 100 times faster than when the first edition of this book was written in 2004. Both computers and the JITter continue to improve! Eleven different sections of tracing information provide a great deal of detail and specific insight into the ASP.NET page-rendering process, as described in the following table. 1109 . the timing output by ASP. NET tracing has increased precision — from 6 digits to 18 digits for highly accurate profiling between ASP. NET 1.1 and ASP. NET 2.0 /3. 5. System.Diagnostics.Trace and ASP. NET s. shown in Figure 23- 8. 1099 Evjen c 23. tex V2 - 01/28/2008 3: 38pm Page 1100 Chapter 23: Caching Figure 23- 8 Figure 23- 9 1100 Evjen c 23. tex V2 - 01/28/2008 3: 38pm Page 1101 Chapter 23: Caching Because. later in this 1107 Evjen c24.tex V2 - 01/28/2008 3: 40pm Page 1108 Chapter 24: Debugging and Error Handling section. ASP. NET also includes a number of small improvements to tracing over ASP. NET

Ngày đăng: 05/07/2014, 19:20

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

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

Tài liệu liên quan