Save Your Cache


Save Your Cache!

At some point during your ASP.NET research and training missions, you will want to understand the concerns of working with the stateless HTTP protocol. The good news is that ASP.NET is very flexible and offers several choices. The bad news is that there are enough options available to encourage confusion. Eventually you will come across the two topics of cache management and state management, and then the confusion will begin.

On the surface, ASP.NET cache management appears to be similar to ASP.NET state management. That is, both cache and state are related to the preservation of "data" between HTTP requests . However, as you'll learn, there's a huge difference between cache management and state management. Adding to the confusion, ASP.NET has introduced a new feature referred to as application cache, which is really a state management feature.

start sidebar
Holding My Breath, Waiting for Microsoft to Call Me

For some reason, Microsoft named the new application-level state management feature application cache . Even worse , they decided to store the feature in a .NET Framework class called System.Web.Caching.Cache . As you can guess, you access this class from the Cache property of both the HttpContext object and the Page object. Do you see a pattern here?

Microsoft is convinced that this new class, this new feature, is related to the cache management topic. If Microsoft had consulted me before they went and named this new .NET Framework class, I would have suggested that they name it ApplicationStateOnSteroids. [2] For some reason, the Microsoft marketing department has not called me. Do you think they may have lost my number?

end sidebar
 

In an effort to clear things up, I discuss output cache in the following section, which focuses on cache management. I discuss the topic of application cache (unofficially known as ApplicationStateOnSteroids) in the later section "Application-Level State," which focuses on state management. By the time you work through the information in this chapter, you will have a firm understanding of both cache management and state management.

Introducing Output Cache

In the earlier section "Preparation for Cache and State," I included two figures to resurface the sequence of events that occur each time an HTTP request is received by IIS and ASP.NET. You were reminded how the Application_Start and BeginRequest events began the sequenced event series. The page-level events (Page Init, Page Load, and so forth) were shown to occur a bit later. The end of the sequenced series included more application/session-level events (e.g., the EndRequest event).

As you'll see, there's an intimate connection between output cache management and the sequence of events that occurs when an HTTP request is received. Let's drill down further.

Generally speaking (in this context), the HTTP request is asking for a specific Web page. Once the request is received, the application-level events are raised, the page-level events are raised, a few more application-level events are raised, and then the intrinsic Response object is delivered to the client's browser. The Response object contains the HTML that is rendered on the client's browser.

Tip  

It is never too early to think about using cache. If possible, your initial application design should include plans to take advantage of cache opportunities. A potentially huge performance gain can be realized.

When you start thinking about using the caching features of ASP.NET, you are really thinking about altering the sequence in which the application/page-level events are raised. In other words, you can cause the application-level events PreRequestHandlerExecute and PostRequestHandlerExecute, and more important, the group of page-level events, to not execute. Therefore, you could possibly avoid unneeded server-side processing.

For example, the application-level BeginRequest event is always raised. Additionally, the application-level EndRequest event is always raised. This is true regardless of your use of output cache management. On the other hand, a decision to " turn on" caching for a given page (or user control) will result in other events not being raised at all (that is, in between the raised BeginRequest and EndRequest events).

Cross-Reference  

I discuss the technique of enabling output cache for a page or a user control later in the section "Using Output Cache."

Generally speaking, if a page is not cached, the page-level events are raised in order to update the Response object with new HTML to satisfy the HTTP request. Otherwise, if a page is cached, there is no need to process the page-level events. The existing page (the Response object with previously rendered HTML) is retrieved from the output cache and delivered to the client that is sending the HTTP request.

start sidebar
Handlers, Modules, and Application-Level Events

You may have noticed (via the Global.asax file) that a pair of application-level events are associated with the "handler" execution: PreRequestHandlerExecute and PostRequestHandlerExecute. When I saw these events for the first time, I could not help but ask, "What is a handler ?"

I discovered that an HTTP handler is a component that implements the IHttpHandler interface. The System.Web.HttpApplication and System.Web.UI.Page classes both implement the IHttpHandler interface and are therefore HTTP handlers. Handlers serve as "targets" for an HTTP request (much like an Internet server API or ISAPI extension).

As it turns out, a special component referred to as an IHttpModule works closely with the IHttpHandler . As you may have guessed, a component needs to implement the IHttpModule interface to become an HTTP module (much like an Internet server API or ISAPI filter). An example of this is an HTTP module referred to as the OutputCache module ( System.Web.Caching.OutputCacheModule ).

This becomes relevant when you observe that there are a pair of application-level events/ methods that are obviously tied to cache: ResolveRequestCache and UpdateRequestCache . The OutputCache module is registered to handle these two events when (and if) they are raised.

Together, the ResolveRequestCache and UpdateRequestCache events/methods are responsible for seeing that all HTTP requests are served from the output cache when appropriate. These two events/methods are also responsible for seeing to it that the handler execution (which includes the group of page-level events/methods) is bypassed when appropriate and for checking that the output cache is updated (when appropriate) after the handler completes execution.

If you are curious , you can easily discover what the other HTTP modules are running behind the scenes ("filtering" each HTTP request before and after the handler is executed). You need only view the Modules property of the HttpApplication object. There you will find an HttpModuleCollection class hosting the OutputCache HTTP module , the Session HTTP module ( System.Web.SessionState.SessionStateModule ), and other HTTP modules.

end sidebar
 

In designing your ASP.NET application, you will want to be on the lookout for opportunities to use output cache (e.g., a page that infrequently changes). You will want to identify those cases where the HTML delivered by one Response object can satisfy the needs of multiple/subsequent HTTP requests. Under these scenarios, there is no need to execute the page-level events (and related application-level events/methods) to generate a new page. To satisfy subsequent HTTP requests, the "existing" page can be retrieved from cache.

In the following section, you will take a look at exactly how you would "turn on" output cache in your ASP.NET application. Additionally, you will examine a few of the configuration techniques used for output cache (e.g., setting cache expiration time, caching multiple versions of pages, and so forth).

Using Output Cache

You now have a basic, under-the-hood view of what output cache usage really does. With that foundational understanding, you can proceed to use output cache and still enjoy a sense of control over your ASP.NET application process, application-level events, and page-level events. The only thing that remains is a rather simple discussion of syntax and implementation.

Note  

Had I taken a more conventional approach to introducing output cache, I would have started at this point. Please keep that in mind as you seek out supplemental research material that covers the details of the ASP.NET output cache feature.

Once you identify the page (or user control) that you want to cache, you will need to do the following:

  • Choose your implementation approach. Will you use the HTML-based directive or the server-side code logic (or both)?

  • Determine if you want to cache multiple versions of the page (or user control).

  • Determine the length of time the page (or user control) should be cached.

If you take the HTML-based directive approach for your output cache implementation, you will need to edit the .aspx file (for page caching) or the .ascx file (for user control caching). The full syntax options of the @ OutputCache directive are as follows :

 <%@ OutputCache Duration="Desired#OfSeconds"  Location=  "Any  Client  Downstream  Server  None"  VaryByControl  ="YourControlname"  VaryByCustom  ="browser  customstring"      VaryByHeader="HTTPheaders" VaryByParam="YourParameterName" %> 

You have several choices when using the @ OutputCache directive inside your .aspx or .ascx file. For example, if you want to cache a page (or user control) for 10 seconds and you do not need to distinguish between multiple versions of the page (or user control), you use the following @ OutputCache directive statement at the top of your .aspx or .ascx file:

 <%@ OutputCache Duration="10" VaryByParam="None" %> 

The output cache feature is flexible enough to allow you to cache multiple versions of a page (or user control). In other words, as a page (or user control) can vary by input parameter, user session, and so on, you can cache each varying version. The easiest way to accomplish this is to use the appropriate parameter option available through the @ OutputCache directive. The following example shows the approach for caching multiple versions of a page (or user control) that might vary by an input parameter. The @ OutputCache directive would cause a separate version of the page (or user control) to be cached for 10 seconds per the unique values received in MyPassedParameter (i.e., via a query string or form post).

 <%@ OutputCache duration="10" varybyparam="MyPassedParameter" %> 

If you prefer, you can choose to control the page (or user control) output caching from inside your server-side code-behind file(s). To manipulate the cache policy for a page, you will need to use the SetExpires and SetCacheability methods of the Cache class (exposed by the Response object). When you work with a user control, the PartialCaching metadata attribute ( System.Web.UI.PartialCachingAttribute ) is available for programmatic implementation.

ASP.NET provides extensive cache management support (both for pages and user controls). Keep in mind that it is common to see a huge performance difference in your ASP.NET applications after you properly use cache management as a way to preserve data between HTTP requests. I will now switch gears to discuss the other type of data preservation practice: state management.

Tip  

Experiment with output cache. Feel free to enhance the sample applications (StateManagementVB and StateManagementCobol) created for this chapter. Consider adding cache management support by simply adding the @ OutputCache directive to the .aspx file as discussed in this section.

[2] OK, I'm attempting to make a good point in a semihumorous fashion. Considering the seriousness surrounding a .NET retraining effort, a little harmless fun here and there can't hurt.




COBOL and Visual Basic on .NET
COBOL and Visual Basic on .NET: A Guide for the Reformed Mainframe Programmer
ISBN: 1590590481
EAN: 2147483647
Year: 2003
Pages: 204

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net