1. Trang chủ
  2. » Công Nghệ Thông Tin

Microsoft ASP Net 3.5 Step By Step (phần 14) pdf

30 275 0

Đ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

Thông tin cơ bản

Định dạng
Số trang 30
Dung lượng 1,23 MB

Nội dung

Chapter 16 Caching Output 361 { Thread.Sleep(0); Response.Write("This page was generated and cached at: " + DateTime.Now.ToString()); Response.Cache.SetNoServerCaching(); Response.Cache.SetLastModified(DateTime.Now); } } Caching Locations In addition to varying the number of cached versions of a page, you may tell ASP.NET where to cache the content. This is controlled through either the Location attribute in the OutputCache directive or by using the HttpCachePolicy class’s SetCacheability method. ASP.NET supports several output caching locations for which you can specify using the OutputCache directive:  Any Page can be cached by the browser, a downstream server, or on the server  Client Page should be cached on the client browser only  Downstream Page should be cached on a downstream server and the client  Server Page will be cached on the server only  None Disable caching The HttpCachePolicy also allows you to determine the location of the cached content pro- grammatically. This is done through the HttpCachePolicy.SetCacheability method (or the HttpResponse.CacheControl property), which takes a parameter of the HttpCacheability enu- meration. The enumeration is a bit easier to read than the attributes used in the OutputCache directive. They include:  NoCache Disable caching  Private Only cache on the client  Public Cache on the client and the shared proxy  Server Cache on the server  ServerAndNoCache Specify that the content is cached at the server but all others are explicitly denied the ability to cache the response  ServerAndPrivate Specify that the response is cached at the server and at the client but nowhere else; proxy servers are not allowed to cache the response 362 Part III Caching and State Management Output Cache Dependencies We saw how ASP.NET supports data caching in Chapter 15. The contents of the application data cache in ASP.NET may be fl ushed due to various dependencies. The same is true of ASP. NET output caching. The response object has a number of methods for setting up depen- dencies based on cached content. For example, you may want to set up a page that renders data from a text fi le. You can set up a CacheDependency on that text fi le so that when the text fi le is changed, the cached output is invalidated and reloaded. Caching Profi les One of the problems associated with using the OutputCache directive directly is that the val- ues become hard-coded. Changing the caching behavior means going in and changing the source code of the page. A feature added to ASP.NET 2.0 and later versions is the ability to add caching profi les. That way, setting the caching behavior variables is offl oaded to the con- fi guration fi le, and output caching becomes an administration issue and not a programming issue (as it should be). The web.confi g fi le may include an outputCacheSettings section that may contain a list of outputCacheProfi les. The outputCacheProfi les are simply key-value pairs whose keys are the output caching variables (such as Duration). When you mention the profi le name in the OutputCache directive, ASP.NET will simply read the values out of the confi guration fi le and apply them to the OutputCache directive. The following exercise illustrates setting up a cache profi le instead of hard-coding the values into the page. Set up a cache profi le 1. Add a cache profi le to the site’s web.confi g fi le. If web.confi g isn’t already there, go ahead and add one to the project. Then add a cache profi le to web.confi g nested be- tween the system.web opening and closing tags. Name the cache profi le profi le. <configuration> <system.web> <caching> <outputCacheSettings> <outputCacheProfiles> <add name="profile" duration="60" varyByParam="TextBoxName" /> </outputCacheProfiles> </outputCacheSettings> </caching> </system.web> </configuration> Chapter 16 Caching Output 363 2. Change the OutputCache directive in the Default.aspx page to use the new profi le: <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" trace="false"%> <%@ OutputCache CacheProfile="profile" %> 3. Surf to the page. It should work exactly as it did before when the caching values were hard-coded. That is, run the page, type a name, and note the date and time stamp. Type a new name and note the date and time stamp. Type the original name, submit it, and you should see the original cached page appear (as long as you complete the post within the specifi ed time window). Caching User Controls Just as whole pages may be cached, ASP.NET supports caching User controls as well. Imagine your job is to create a sizable Web site that allows users to navigate through information via various navigation controls (menus, hyperlinks, and so forth). For example, imagine a part of your page shows links or other navigation controls that lead users to the most recent news, summary information, and other places. The actual content may change, but the links prob- ably don’t. If the links don’t change very often and the cost of generating that section of the page is expensive, it makes sense to move the functionality into a User control and apply the OutputCache directive to the User control. Doing so will cause ASP.NET to cache the portion of the page represented by the control. The OutputDirective may be applied to the ASCX fi le that comprises a User control. The OutputDirective for a User control may also use the Shared property to tell ASP.NET to cache one version of the control for all pages that use it, resulting in potentially even higher perfor- mance over the span of many hits (the default is false). The following exercise illustrates caching the output of a User control. User controls and output caching 1. Create a simple User control for the OutputCaching project. Navigation controls are perfect for caching, so create a control that has a menu. Name the control SiteMenu.ascx. Drag a Menu control onto the User control, as shown here: 364 Part III Caching and State Management Add some menu items, as shown in this graphic: 2. Add the OutputCache directive with the following parameters in the control source, like so: <%@ Control Language="C#" AutoEventWireup="true" CodeFile="SiteMenu.ascx.cs" Inherits="SiteMenu" %> <%@ OutputCache Duration="60" VaryByParam="none" %> 3. Create a new page in the project. Name it UseSiteMenuControl.aspx. Chapter 16 Caching Output 365 4. Drag the SiteMenu User control onto the UseSiteMenuControl page. When ASP.NET loads and runs your Web page, ASP.NET will cache the User control because the User control mentions the OutputDirective. 5. Make sure tracing is turned on in the UseSiteMenuControl.aspx fi le. (That is, set the Trace=”true” attribute in the Page directive.) Surf to the page. The fi rst time you surf to the page, you’ll see the following information in the control tree section of the Trace output: Notice the entire control tree was rendered. Push the refresh key (F5 in Internet Explorer) while looking at UseSiteMenuControl.aspx. Examine the control tree portion of the Trace output again. Notice that ASP.NET uses the cached control instead of re- rendering the entire SiteMenu control. 366 Part III Caching and State Management When Output Caching Makes Sense As with other caching techniques, one of the most effective strategies is to turn on output caching for those pages that are accessed frequently but yet are expensive to generate. Also, be sure to cache only those pages that don’t change frequently (otherwise, you may be bet- ter off simply not using output caching). For example, pages full of controls that render a great deal of HTML are probably expensive. Imagine a page including a DataGrid displaying an employee directory. This is a perfect can- didate for caching for several reasons. First, a database access (or even an in-memory cache hit) is required. Second, a DataGrid is pretty expensive to render—especially if it needs to fi gure out the schema of the employee directory table on the fl y. Finally, an employee direc- tory probably doesn’t change very often. By caching it once, you can avoid spending a great deal of unnecessary cycles. A related issue here is to be careful when typing asterisks into the output caching parameters such as VaryByParam. Using VaryByParam=* tells ASP.NET to generate a new page for every single request in which any query string parameter has changed. That’s almost the same as Chapter 16 Caching Output 367 not caching altogether—with the added cost of the memory consumed by the output cache. However, this may make sense for Web sites with limited audiences where the parameter variance between requests remains limited. In addition, be wary of how caching might affect the appearance of your page on differ- ent browsers. Much of the time, content will appear the same regardless of the browser. However, if you cache some content that depends on a specifi c browser feature (such as Dynamic HTML), clients whose browsers don’t understand the feature may see some very weird behavior in the browser. Tuning the behavior of the output cache is also important. Effective caching is always a mat- ter of balance. Although you can potentially speed up your site by employing output cach- ing, the cost is memory consumption. Using instrumentation tools can help you balance performance against cost. Finally, User controls often represent a prime output caching opportunity—especially if they don’t change frequently. Wrapping the portion of a page that doesn’t change in an output- cached User control will usually enhance the perceived performance of your application at a minimal cost because only the User control content is cached. Summary Caching is a tried and true way to improve the performance of almost any system. By making frequently used content available quickly through the output cache, you can often speed up the perceived performance of your application by a wide margin. Turning on output caching in ASP.NET is a matter of including the correct directive at the top of your page. Naive use of the cache involves simply placing it on the page code and setting the Duration to some number and the VaryByParam attribute to none. However, you may also control various behaviors of the output cache by setting variables within the OutputCache directive. You may also control output caching behaviors through the HttpCachePolicy class, available through the Cache property of the Response object. Later versions of ASP.NET support cache profi les so you don’t have to hard-code the caching pa- rameters into the OutputDirective. User controls often represent a prime output caching opportunity—especially if they’re navigation controls or some other control that doesn’t change very often. By applying the OutputCache directive to the User control, ASP.NET caches that part of the page on which it was placed. 368 Part III Caching and State Management Chapter 16 Quick Reference To Do This Cache a page’s output Add the OutputCache directive to the page. Store multiple versions of a page based on varying query string parameters Use the VaryByParam attribute of the OutputCache directive. Store multiple versions of a page based on varying headers Use the VaryByHeader attribute of the OutputCache directive. Store multiple versions of a page based on varying browsers Use the VaryByCustom attribute of the OutputCache directive, selecting browser as the value. Specify the location of the cached content Specify the Location attribute in the OutputCache directive. Access caching attributes programmatically Use the Cache property of the Response object, which is an instance of the HttpCachePolicy class. Offl oad output caching confi guration to the web.confi g fi le Add outputCacheProfi le elements to your web.confi g fi le. Use them as necessary. Cache a User control Apply the OutputCache directive to the control’s ASCX fi le. To D o Th is 369 Part IV Diagnostics and Plumbing [...]... seen throughout the tour of ASP. NET, one of the main goals has always been to incorporate as much of the management of Web development as possible into ASP. NET At this point, Internet Information Services (IIS) is really only a middle manager in the scheme of things Many facilities previously handled exclusively by IIS are now handled by ASP. NET (although IIS brings many ASP. NET features under its auspices... exceptions within ASP. NET Page Tracing The first place to start with debugging is to examine ASP. NET page tracing The Page class has a property named Trace When Trace is turned on, it tells the ASP. NET runtime to insert a rendering of the entire context of the request and response at the end of the HTML sent to the client We’ve already seen page tracing to some extent When we looked at the ASP. NET serverside... as ASP. NET and Windows Forms go a long way toward making development more standardized and predictable (good things in software practice) However, there are still almost inevitable times when you need to figure out what’s wrong with an application that decides to behave differently than you expected it to This chapter covers the support provided by ASP. NET for figuring out what’s wrong with your ASP. NET. .. This tells ASP. NET to show the 404Error.htm page when a file isn’t found ASP. NET will show SomethingBadHappened.htm for any other error 7 Now add handlers to generate the errors Handle the 404 error button by directing the client to a nonexistent page (in this example, there is no page named NonExistent aspx, so redirecting to it will cause a 404 error) Handle the second error generator by throwing... take a look at trapping exceptions in a more graceful way Unhandled Exceptions In the last example page that threw an exception, ASP. NET responded by redirecting to the default error page ASP. NET also lets you trap exceptions by setting up a handler for Error events fired by HttpApplication so that you may handle them more appropriately The easiest way to accomplish this is to define a handler in your... logged manually to the debug console by setting up the TraceFinished event handler in the Trace context System.Diagnostics.Debug is a standard NET type that’s helpful for managing tracing and debugging information Since version 2.0, ASP. NET has had the ability to plug in the WebPageTraceListener type so that calls to System.Diagnostics.Trace are also inserted into the ASP. NET trace Setting it up is simply... ASP. NET features under its auspices with version 7.0 running in Integrated mode) One of those facilities is managing custom error pages In ASP. NET, you may introduce custom error pages (instead of the client being bombarded with ASP. NET error messages) To tell ASP. NET to display a particular page on encountering errors anywhere within your application, just tweak the web.config file Table 17-2 shows the... set the Trace property of the page to true You may turn on tracing either by modifying the ASPX code directly or by setting the Trace property using the designer Here’s the Trace property being turned on directly within the ASPX code as part of the page directive As soon as you turn tracing on... pages off = display ASP. NET error pages remoteOnly Display custom errors to client, display ASP. NET errors locally The following example illustrates how to work with custom error pages Work with error pages In this example, you’ll add some error pages to your application and see what conditions cause them to appear 1 Open the DebugORama project 2 Add a new Web Form named ThrowErrors.aspx to the DebugORama... Diagnostics and Debugging 385 4 In this example, Page_Load is the first breakpoint Visual Studio encounters At this point, you may start stepping through the code F10 steps over methods, whereas F11 steps into methods Alternatively, you may use Debug, Step Over and Debug, Step Into from the main menu 5 Hover your mouse cursor over any variables you see Notice how Visual Studio displays the value of the . response 36 2 Part III Caching and State Management Output Cache Dependencies We saw how ASP. NET supports data caching in Chapter 15. The contents of the application data cache in ASP. NET may. within ASP. NET. Page Tracing The fi rst place to start with debugging is to examine ASP. NET page tracing. The Page class has a property named Trace. When Trace is turned on, it tells the ASP. NET. UseSiteMenuControl page. When ASP. NET loads and runs your Web page, ASP. NET will cache the User control because the User control mentions the OutputDirective. 5. Make sure tracing is turned

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