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

140

Saturday Afternoon

Fragment Caching

Fragment caching is an approach that caches a portion of a page in memory rather than the entire page as is done when using page output caching. Suppose you have a heavily accessed evaluation or survey form, whose content is static for each user, but whose answers you would like to track based upon a unique userid or value stored or passed in the URL. Using page output caching is not going to provide you much benefit, because it depends upon a unique URL string for caching the output. In our scenario, every request for the page content will generate a unique URL.

Please refer to the FragmentOutputExample.aspx page in the Session 14 folder on the accompanying CD. This example illustrates storing the static survey form in a file called SurveyForm.htm. The first time the page is loaded, SurveyForm.htm is opened and its text is inserted into a cache variable sMyForm. An absolute expiration of 10 seconds is applied to the cached variable, so that all requests occurring 10 seconds after the initial request will load this fragment of the page from cache, rather than loading it from disk.

When you look at the content of the SurveyForm.htm page, you can see that it is a simple survey form that does not change from user to user. Instead, its results need to be uniquely stored based upon the userid information passed in the URL. You can handle this scenario nicely in ASP.NET by caching the fragment of static information in a data cache and retrieving the static data during the generation of the dynamic page (see Listing 14-2).

Listing 14-2 Using fragment caching

<%@ Import Namespace=”System.IO.StringWriter”%> <%@ Import Namespace=”System.IO.File”%>

<%@ Import Namespace=”System.IO”%> <%@ Import Namespace=”System”%> <%@ Page Language=”vb” %>

<HTML>

<HEAD>

<META HTTP-EQUIV=”Content-Type” CONTENT=”text/html; charset=windows-1252”> <SCRIPT LANGUAGE=”VB” RUNAT=”server”>

Sub Page_Load(ByVal Sender As System.Object, ByVal e As System.EventArgs) ‘ Checks to see if the Form is in Memory

Dim bCheckCache as Boolean bCheckCache =CheckCache(“sMyForm”) Select Case bCheckCache

Case True ‘ Set the lblCached to True lblCached.Text = “True”

Case False ‘Set the lblCached to False lblCached.Text =”False”

End Select End Sub

Function CheckCache(sItem as String)

‘Checks for the existince of a Cached Item Dim bCached as Boolean

If Cache.Get(sItem) = Nothing Then bCached = False

Else

bCached = True

Session 14—ASP.NET Caching

141

End If

Return bCached End Function

Function GetCachedForm(sFileName as String, sCacheItem as String) ‘Dim String for Cached HTML Form

Dim sMyForm as String

‘Dim StreamReader to Read HTML From File Dim sr As StreamReader

‘See if Cache Exists

If CheckCache(sCacheItem) Then sMyForm = Cache.Get(sCacheItem)

‘Otherwise if it doesn’t read in survey to cache Else

sr = File.OpenText(server.MapPath(sFileName)) ‘Open File While sr.peek <> -1 ‘Loop Through File

sMyForm = sMyForm & sr.ReadLine() ‘Load Line of Text from File End While

sr.close() ‘ Close FileStream

sr = Nothing ‘Optional Destroy Object Cache.Insert(sCacheItem,sMyForm,Nothing, datetime.Now.AddSeconds(10),

timespan.zero) ‘Insert the HTML Form End If

Return sMyForm End Function

Sub btnSubmit_Click(sender As Object , e As System.Web.UI.WebControls.CommandEventArgs)

‘Insert Code to Write Survey Information to Log File or Database End Sub

</SCRIPT>

</HEAD>

<BODY>

<FORM ID=”FragmentOutputExample” METHOD=”get” ACTION=”FragmentOutputExample.aspx”>

<H2>

Example of Fragment Caching a Form </H2>

<BR>

<%Response.write(GetCachedForm(“SurveyForm.htm”, “sMyForm”))%>

<ASP:BUTTON ID=”btnSubmit” RUNAT=”SERVER” TEXT=”Button” ONCOMMAND=”btnSubmit_Click”></ASP:BUTTON>

<BR>

<P>

</P>

<HR SIZE=”1”> <P>

Was the above form in Cache?  

<ASP:LABEL ID=”lblCached” RUNAT=”SERVER”></ASP:LABEL> </P>

<P>

Page Compiled at:<%=datetime.now.tolongtimestring()%> </P>

</FORM>

</BODY>

</HTML>