Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
ASP .NET Database Programming Weekend Crash Course - J. Butler, T. Caudill.pdf
Скачиваний:
31
Добавлен:
24.05.2014
Размер:
3.32 Mб
Скачать

136

Saturday Afternoon

ASP.NET Updates to the ASP Response Model

In previous versions of ASP, the Response object used the Expires, ExpiresAbsolute, and CacheControl properties to support caching. While these methods and properties can still be used and implemented in the same way, you need to understand how to update the syntax of your ASP pages to reflect the new ASP.NET framework.

In ASP, using the Response.Expires property will insert an HTTP Header that tells the client browser to request another copy of the page only if it has been a specified number of minutes since the last request. So, by inserting the following code in your page:

<%Response.Expires = 10%>

You will ensure that after the first request, the browser will only request the page from the server if it hasn’t been requested in the last ten minutes. In ASP.NET this can be handled in the following manner:

<%Response.Cache.SetExpires(DateTime.Now.AddSeconds(600))%>

This method will set the cache to expire in 600 seconds or 10 minutes from the point that the first request for the page from any client was initiated. This method gives you very fine control over the expiration of the page as it takes full advantage of the new DateTime object, which provides a tremendous amount of flexibility in the calculation and formatting of date and time values.

Additionally you could set this same expiration rule using the OutPutCache page directive as follows:

<%@ OutputCache Duration=”600”%>

Caching with ASP.NET

ASP.NET supports three types of caching:

Page output caching, which involves storing the dynamic response generated by a request in memory.

Fragment caching, which involves storing a portion of a page in a non-user-specific key to improve access to this content as part of other dynamic or static pages.

Page data caching, which involves the storing of arbitrary objects across multiple requests.

Page Output Caching

Page output caching is typically utilized when you want to store the entire output of a dynamically created or static page in the cache of the server, the client, or a proxy server for rapid access across multiple requests. When the page is cached in the output cache, all subsequent requests for that page are served up from the output cache without activating the page that originally instantiated it.

Session 14—ASP.NET Caching

137

So, if you had a page default.aspx and had set the page to cache the response for a fixed period of 30 seconds from the last request, and you wanted that cached output to be stored on any cache-enabled device in the request stream such as the Web server or proxy-servers, you could set the OutputCache page directive as follows:

<%@ OutputCache Duration=”30” Location=”Any” VaryByParam=”None”>

Or I could use the following code that just replicates the above page directive,

<%

Response.Cache.SetExpires(DateTime.Now.AddSeconds(30))

Response.Cache.SetCacheability(HttpCacheability.Public)

%>

In the next section we will address two approaches for implementing the expiration/ validation policy: absolute cache expiration and sliding cache expiration.

Absolute cache expiration

When using the OutputCache page directive, you can specify that the content is expired a specified number of seconds after it was first requested. All further requests after the initial request will simply receive the content stored in the output cache; and the page will not be processed until the time frame specified has expired. Lets look at the following example contained on CD in the Session14 folder under the file named “AbsoluteCache.aspx.” In this example we illustrate a programmatic method for handling absolute cache expiration, rather than using the OutputCache page directive discussed earlier. By using this programmatic approach, we can establish a final date for a page to expire rather than simply a span of time from when it was first initiated. In this example we are expiring the page on a specific date of December 31, 2009.

Sliding cache expiration

The Cache object can utilize a Boolean property called SetSlidingExpiration. When this property is set to True, every time a new request is received for the page — for instance when a new user visits the page or when an existing page visitor selects the refresh button in his or her browser — then the page is initiated and the output cache expiration is reset based upon the code, as shown in Figure 14-1.

See the example SlidingCache.aspx on the CD in the Session 14 folder.

Cross-Ref

When the user selects the Click Here To Refresh hyperlink, the output page is retrieved from the output cache and redisplayed, thus no values on the page change. However, if the user selects the Refresh button from the toolbar, simulating a NEW request, then the page skips retrieving the page out of cache, and instead recompiles the page and resets the expiration on the output cache, even though the expiration time has not been reached! In other words, it slides the expiration.

138

Saturday Afternoon

Figure 14-1 An example of sliding expiration when a user requests a page from the output cache

The code in Listing 14-1 shows the source of the SlidingCache.aspx page shown in Figure 14-1.

Listing 14-1 Source of the SlidingCache.aspx file

<%@ Page Language=”VB” Debug=”False” Trace=”False” %> <HTML>

<HEAD>

<SCRIPT LANGUAGE=”VB” RUNAT=”server”>

Sub Page_Load(ByVal Sender As System.Object, ByVal e As System.EventArgs) SetOutPutCache()

End Sub

Sub SetOutPutCache

Dim dt As Date ‘ Creates a new DateTime Object

Dim bSlide as Boolean ‘ creates a Boolean Variable to Hold the Sliding Expiration State

Dim dSec as Double

dSec = 30 ‘Set the expiration delay in Seconds dt=datetime.now.addseconds(dSec) ‘ This calculates the time 20 seconds from

the time the Page is compiled

bSlide = True

Response.Cache.SetExpires(dt) ‘Sets the cache to expire in 20 seconds

Session 14—ASP.NET Caching

139

Response.Cache.SetCacheability(HTTPCacheability.Public) Response.Cache.SetSlidingExpiration(bSlide) ‘Sets the state of Sliding

Expiration

lblSlide.Text = bSlide lbldt.Text=datetime.Now.ToLongTimeString lblExpire.Text =dt.ToLongTimeString Select Case bSlide

Case True

dInfo.InnerHTML = “<p>Since you have the bSlide Value in your code set to True, everytime you refresh this page or another user refreshes the page, the expiration of the page is postponed by another “ & dSec & “ seconds.”

Case False

dInfo.InnerHTML = “<p>Since you have the bSlide Value in your code set to False, no matter how you refresh this page or how another user refreshes the page, the page will expire at “ & dt.ToLongTimeString & “.”

End Select End Sub

</SCRIPT>

</HEAD>

<BODY>

<H2>

Example of SetSlidingExpiration set to

<ASP:LABEL ID=”lblSlide” RUNAT=”SERVER”></ASP:LABEL> </H2>

<P>

This code was last executed at

<ASP:LABEL ID=”lbldt” RUNAT=”SERVER”></ASP:LABEL>

<P>

The output cache will expire on

<ASP:LABEL ID=”lblExpire” RUNAT=”SERVER”></ASP:LABEL>

<P>

<A HREF=”SlidingCache.aspx”>Click Here To Refresh </A> <DIV ID=”dInfo” RUNAT=”server”>

</DIV>

<P>

</P>

</BODY>

</HTML>

When Cache.SetSlidingExpiration is set to False, the page is always retrieved from the output cache for all existing users as well as for new requests.

To test this try changing

bslide=True

to

bslide=False

in Listing 14-1. This turns off the sliding expiration functionality. Therefore, all requests for the page, new or existing will be served from the output cache until you get past the expiration time of 30 seconds; the next request after this expiration time produces a reset of the expiration value. You can test this by looking at the code generation time stamp on the output page.