DekGenius.com
[ Team LiB ] Previous Section Next Section

17.4 Methods Reference

AddCacheItemDependencies

Response.AddCacheItemDependencies(ByVal cacheKeys As ArrayList)

Adds a list of cache keys contained in an ArrayList to the list of cache item keys upon which the output cache of the current response depends. If one of the cache items identified by the keys is modified, the output cache of the current response will be invalidated and a fresh response will be generated.

Parameter

cacheKeys

An ArrayList containing one or more cache item key names.

Example

The example shows how you can use the AddCacheItemDependencies method to set a number of cache keys as dependencies for the output cache of the current response. If any of the cache items represented by these keys is modified, the output cache is invalidated and the page is refreshed by using Response.Redirect.

<%@ Page Language="vb" %>
<%@ OutputCache Duration="300" VaryByParam="None" %>
<html>
   <head>
      <title>Adding cache dependencies in ASP.NET</title>
      <script runat="server">
         Sub Page_Load( )
            Dim myArrayList As New ArrayList
            myArrayList.Add("Key1")
            myArrayList.Add("Key2")
            Response.AddCacheItemDependencies(myArrayList)
            Message.Text = DateTime.Now.ToString( )
         End Sub
         Sub Button1_Click(sender As Object, e As EventArgs)
            Cache("Key1") = "foo" & DateTime.Now.ToString( )
            Response.Redirect("AddCacheItemDependencies.aspx")
         End Sub
         Sub Button2_Click(sender As Object, e As EventArgs)
            Cache("Key2") = "bar" & DateTime.Now.ToString( )
            Response.Redirect("AddCacheItemDependencies.aspx")
         End Sub
      </script>
   </head>
<body>
   <form runat="server">
      <asp:label id="Message" runat="server"/>
      <asp:button id="Button1" text="Change Key 1" 
         onClick="Button1_Click" runat="server"/>
      <asp:button id="Button2" text="Change Key 2" 
         onClick="Button2_Click" runat="server"/>
   </form>
</body>
</html>

Notes

The AddCacheItemDependencies method is useful when you want to output cache a page, but the page depends on the value of several items stored in the ASP.NET cache. Rather than caching the page with a very short duration to avoid stale data, you can use AddCacheItemDependencies to automatically invalidate the output cache when the dependencies change.

AddCacheItemDependency

Response.AddCacheItemDependency(ByVal cacheKey As String)

Adds a cache item key to the list of cache keys upon which the output cache of the current response depends. If the cache item identified by the key is modified, the output cache of the current response will be invalidated and a fresh response will be generated.

Parameter

cacheKey

A String containing the cache item key to add.

Example

The example shows how you can use the AddCacheItemDependency method to set a cache key as a dependency for the output cache of the current response. If the cache item represented by this key is modified, the output cache is invalidated and the page is refreshed by using Response.Redirect.

<%@ Page Language="vb" %>
<%@ OutputCache Duration="300" VaryByParam="None" %>
<html>
   <head>
      <title>Adding a cache dependency in ASP.NET</title>
      <script runat="server">
         Sub Page_Load( )
            Response.AddCacheItemDependency("Key1")
            Message.Text = DateTime.Now.ToString( )
         End Sub
         Sub Button1_Click(sender As Object, e As EventArgs)
            Cache("Key1") = "foo" & DateTime.Now.ToString( )
            Response.Redirect("AddCacheItemDependency.aspx")
         End Sub
      </script>
   </head>
<body>
   <form runat="server">
      <asp:label id="Message" runat="server"/>
      <asp:button id="Button1" text="Change Key 1" onClick="Button1_ Click"          runat="server"/>
   </form>
</body>
</html>

Notes

The AddCacheItemDependency method provides the same functionality as the AddCacheItemDependencies method, but for a single cache item rather than multiple items.

AddFileDependencies

Response.AddFileDependencies(ByVal filenames As ArrayList)

Adds a list of files contained in an ArrayList to the list of files upon which the output cache of the current request depends. If any of these files is modified, the output cache is invalidated.

Parameter

filenames

An ArrayList containing one or more path/filenames.

Example

The example shows how you can use the AddFileDependencies method to set a number of files as dependencies for the output cache of the current response. If any of these files is modified, the output cache is invalidated.

<%@ Page Language="vb" %>
<%@ OutputCache Duration="300" VaryByParam="None" %>
<html>
   <head>
      <title>Adding file dependencies in ASP.NET</title>
      <script runat="server">
         Sub Page_Load( )
            Dim myArrayList As New ArrayList
            myArrayList.Add(Server.MapPath("dep.txt"))
            myArrayList.Add(Server.MapPath("dep1.txt"))
            Response.AddFileDependencies(myArrayList)
            Message.Text = DateTime.Now.ToString( )
         End Sub
      </script>
   </head>
<body>
   <asp:label id="Message" runat="server"/>
</body>
</html>

Notes

The AddFileDependencies method is useful when you want to output cache a page, but the page depends on the value of several files on the web server (which can be accessed by a file path from the web server). Rather than caching the page with a very short duration to avoid stale data, you can use AddFileDependencies to automatically invalidate the output cache when the dependencies change.

AddFileDependency

Response.AddFileDependency(ByVal filename As String)

Adds a file to the list of files upon which the output cache of the current request depends. If the named by the filename argument is modified, the output cache is invalidated.

Parameter

filename

A String containing the path and filename to add.

Example

The example below shows how you can use the AddFileDependency method to set a file as a dependency for the output cache of the current response. If the file is modified, the output cache is invalidated.

<%@ Page Language="vb" %>
<%@ OutputCache Duration="300" VaryByParam="None" %>
<html>
   <head>
      <title>Adding a file dependency in ASP.NET</title>
      <script runat="server">
         Sub Page_Load( )
            Response.AddFileDependency(Server.MapPath("dep.txt"))
            Message.Text = DateTime.Now.ToString( )
         End Sub
      </script>
   </head>
<body>
   <asp:label id="Message" runat="server"/>
</body>
</html>

The dep.txt file named in the code above should reside in the same directory as the page. The contents of the page can be whatever you choose. If the file content is changed, the cache will be invalidated.

Notes

The AddFileDependency method provides the same functionality as the AddFileDependencies method, but for a single file rather than multiple files.

AddHeader

Response.AddHeader(ByVal name As String, ByVal value As String)

Adds an HTTP header with the specified name and value to the output stream.

Parameters

name

A String argument containing the name for the header.

value

A String argument containing the value for the header.

Notes

The AddHeader property provides for backward compatibility with classic ASP. This property has been deprecated in favor of the new AppendHeader method.

AppendHeader

Response.AppendHeader(ByVal name As String, _
  ByVal value As String)

Adds an HTTP header with the specified name and value to the output stream. This method can be used to add custom HTTP headers or to modify the value of standard HTTP headers.

Parameters

name

A String argument containing the name for the header.

value

A String argument containing the value for the header.

Example

The example sets the HTTP Content-Type header to "text/xml" and then displays the new value by setting the Text property of the Message Label control to the value of the ContentType property. This causes the page output to be treated as XML.

Sub Page_Load( )
   Response.AppendHeader("Content-Type", "text/xml")
   Message.Text = Response.ContentType
End Sub

Notes

When using this method with HTTP headers related to caching policy, if more restrictive settings are applied through the use of the ASP.NET cache APIs, the more restrictive settings will take priority over the settings applied using AppendHeader.

AppendToLog

Response.AppendToLog(ByVal param As String)

Appends the text specified by the param argument to the IIS log file for the current IIS application.

Parameter

param

A String argument containing the text to be appended to the IIS log.

Example

The following example writes a message to the IIS log for the application the page is a part of, and then writes a message to the ASP.NET Message label control indicating that the message was written:

Sub Page_Load( )
   Response.AppendToLog("Hello from Page_Load!")
   Message.Text = "Message written to IIS Log!"
End Sub

The IIS log entry generated by the example above looks similar to the following:

2001-10-14 00:13:14 127.0.0.1 - 127.0.0.1 80 GET 
/ASPdotNET_iaN/Chapter_17/AppendToLog.aspx 
Hello+from+Page_Load! 200 BrowserString

Notes

Unlike the AppendToLog method in classic ASP, which had a limit of 80 characters per call, you can write as much text as you wish to the log by using AppendToLog in ASP.NET. The IIS Log files are located by default in %windir%\System32\LogFiles\W3SVCx\exdate.log, where %windir% is the name of the Windows directory, x is the number of the Web site for the log (this is the IIS Metabase name for the desired application), and date is the creation date of the log file.

ApplyAppPathModifier

String = Response.ApplyAppPathModifier(ByVal virtualPath _
                    As String)

Given a virtual path to a resource, returns a string containing a new virtual path containing the SessionID. This new virtual path can be used to create absolute URLs for use in applications that use cookieless Sessions.

Parameters

String

A String argument that will receive the modified virtual path.

virtualPath

A String argument containing the virtual path to be modified.

Example

The following example retrieves a virtual path including the SessionID and displays the path by using the Text property of the Message label control:

Sub Page_Load( )
   Dim NewPath As String
   NewPath = Response.ApplyAppPathModifier(Request.Path)
   Message.Text = "Modified virtual path = " & NewPath
End Sub

The web.config file to set the Session state handler to use cookieless Sessions is shown below:

<configuration>
   <system.web>
      <sessionState mode="InProc" cookieless="true"/>
   </system.web>
</configuration>

Notes

This method is very useful when making use of the cookieless Session state functionality introduced by ASP.NET. If the cookieless attribute of the sessionState config section in web.config is not set to True, this method will simply return the virtual path passed in without modification.

BinaryWrite

Response.BinaryWrite(ByVal buffer( ) As Byte)

Allows writing of binary content to the output stream. No modification of the output is performed before sending the binary content to the client.

Parameter

buffer( )

A Byte array containing the binary data to be written to the output stream.

Example

Here is an example of BinaryWrite:

Sub Page_Load( )
   Dim ImageStream As New FileStream(MapPath("aspnetian.jpg"), _
      FileMode.Open, FileAccess.Read)
   Dim ImageBytes(ImageStream.Length) As Byte
   ImageStream.Read(ImageBytes, 0, ImageStream.Length)
   ImageStream.Close( )
   Response.ContentType = "image/bmp"
   Response.BinaryWrite(ImageBytes)
   Response.End( )
End Sub

Notes

This method is especially useful for writing binary content retrieved from a database to the browser. When writing image or other nontext data to the browser, you should set the Response.ContentType property to the appropriate MIME type for the image type being sent (such as "image/jpg").

Clear

Response.Clear( )

Clears the content of the current output stream.

Parameters

None

Notes

The Clear method clears all currently buffered output, but does not clear the HTTP response headers. If buffering of output is disabled by setting the BufferOutput property to False, this method will not have any effect, since it only clears buffered content. This behavior is different from classic ASP, in which calling Clear when buffering is disabled results in an error.

ClearContent

Response.ClearContent( )

Clears the content of the current output stream.

Parameters

None

Example

The example writes a text message using Response.Write and then clears the buffered output by calling Response.Clear. If buffering is on, the text message will never be sent to the browser.

Sub Page_Load( )
   Response.Write("This content will not be seen.")
   Response.Clear( )
   Message.Text = _
      "Content written with <i>Response.Write</i> was cleared."
End Sub

Notes

The ClearContent method clears all currently buffered output, but does not clear the HTTP response headers. HTTP headers can be cleared by calling the ClearHeaders method. If buffering of output has been disabled by setting the BufferOutput property to False, the ClearContent method will not have any effect, since it only clears buffered content.

ClearHeaders

Response.ClearHeaders( )

Clears the HTTP headers from the current output stream.

Parameters

None

Example

The example sets the HTTP Content-Type header to "text/xml", clears the HTTP headers by calling the ClearHeaders method, and then writes the value of the Response.ContentType property to the Text property of the Message ASP.NET Label control. The displayed Content-Type is the default of "text/html".

Sub Page_Load( )
   Response.AppendHeader("Content-Type", "text/xml")
   Response.ClearHeaders( )
   Message.Text = Response.ContentType
End Sub

Notes

The ClearHeaders method clears only the HTTP response headers, not the buffered content.

Close

Response.Close( )

Closes the network socket for the current response.

Parameters

None

Example

See the example for the SuppressContent property.

Notes

The Close method can be used to immediately close the network socket for the current response. This closure will typically result in a browser error (such as "Cannot find server") being displayed to the client.

End

Response.End( )

Stops processing the current request and sends all buffered content to the client immediately.

Parameters

None

Example

The example below writes the text "Hello, World!" to the browser, calls Response.End, and then attempts to set the Text property of the Message ASP.NET Label control to "Hello, World!" However, that code will not be executed, as the End method immediately halts execution of page processing.

Sub Page_Load( )
   Response.Write("Hello, World!")
   Response.End( )
   Message.Text = "Hello, World!"
End Sub

In fact, the code above will result in only the "Hello, World!" text being output to the browser, as even the rendering of the static HTML and controls in the page will not occur.

Notes

When the End method is called, in addition to sending buffered output to the client and terminating processing, the Application_EndRequest event is fired.

Flush

Response.Flush( )

Immediately sends all buffered output to the client.

Parameters

None

Example

See the example for the BufferOutput property. If you comment out the lines that set BufferOutput to False and then uncomment the line that calls Response.Flush, you will see that the Flush method allows you to explicitly send buffered content to the browser.

Notes

Since buffering is on by default in ASP.NET, the Flush method becomes especially useful. Rather than turning off buffering, which results in any content sent from a Response.Write call being sent immediately to the browser, you can use Response.Flush to send content in discrete chunks or to ensure that an entire operation completes before sending the currently buffered content.

You can also combine calls to Response.Flush with calls to Response.Clear to allow you to perform preverification on content before it is sent to the browser. If a given set of calculations or output encounters an error, you can call Response.Clear to clear the problematic output and then replace it with an error message or with other replacement content. If there are no problems with the output, you can call Response.Flush to send the buffered output to the browser and then continue processing.

Pics

Response.Pics(ByVal value As String)

Adds a PICS-Label header to the output stream for the current response. The Platform for Internet Content Selection (PICS) is used to rate Internet content based on violence, sexual content, language, and nudity.

Parameter

value

A String argument containing the text for the PICS-Label header.

Example

The following example sets a PICS header that specifies RSAC as the rating organization, sets the rating effective period from 8/1/2001 to 2/28/2002, and sets the ratings as follows:

  • Violence - 1

  • Sexual content - 2

  • Adult Language - 3

  • Nudity - 4

Sub Page_Load( )
   Dim PICSLabel As String
   PICSLabel &= "(PICS-1.1 <http://www.rsac.org/ratingsv01.html> "
   PICSLabel &= "labels on " & Chr(34)
   PICSLabel &= "2001.08.01T06:00-0000" & Chr(34)
   PICSLabel &= " until " & Chr(34)
   PICSLabel &= "2002.02.28T23:59-0000" & Chr(34)
   PICSLabel &= " ratings (V 1 S 2 L 3 N 4))"
   Response.PICS(PICSLabel)
   Message.Text = PICSLabel
End Sub

Notes

The PICS-Label header is used for rating the content of a site. Users can configure their browsers to disallow viewing of sites that send PICS-Label headers, and whose ratings state that the site contains a higher level of content in one of the rated categories than the browser is configured to allow. Additional information on the PICS standard for content ratings is available at the World Wide Web Consortium web site at http://www.w3c.org.

Redirect

Response.Redirect(ByVal url As String)
Response.Redirect(ByVal url As String, _)
  ByVal endResponse As Boolean)

Redirects the currently executing page to another page specified by the URL argument, optionally terminating the processing of the current page.

Parameters

url

A String argument containing the URL for the page to redirect to.

endResponse

A Boolean argument indicating whether to terminate processing of the current page. If the argument is omitted, the method call causes processing of the current page to be discontinued.

Example

The example redirects the current request to BufferOutput.aspx and directs ASP.NET to discontinue processing of the current page:

Sub Page_Load( )
   Response.Redirect("BufferOutput.aspx", True)
End Sub

Notes

Unless additional processing needs to be done in the page from which you call Response.Redirect, you should always pass True as the second argument to Response.Redirect to prevent server resources from being wasted by continuing to process the current page. This feature is new for ASP.NET. When calling Response.Redirect with only the url argument, processing of the current page is discontinued automatically.

Note that when redirecting to a page such as BufferOutput.aspx in which buffering is turned off, or to a page that calls Response.Flush, the redirect will not complete until the target page has completed processing. This means that all content on the target page will be seen at once, rather than as it is rendered or flushed from the buffer.

Write

Response.Write(ByVal ch As Char)
Response.Write(ByVal obj As Object)
Response.Write(ByVal s As String)
Response.Write(ByVal buffer( ) As Char, ByVal index As Integer, _
 ByVal count As Integer)

Allows writing of arbitrary content to the output stream. Content may be character data, an Object (using the object's ToString( ) method), or String data.

Parameters

ch

A Char argument containing a character to write to the output stream.

obj

An Object argument containing an object whose string representation will be written to the output stream.

s

A String argument containing text to write to the output stream.

buffer( )

A Char array argument containing the characters to write to the output stream.

index

An Integer argument containing the starting point in the Char array from which to being writing.

count

An Integer argument containing the number of characters to write.

Example

The example creates an array of Chars, sets the values of the Chars, and then loops through the array and displays its contents by calling Response.Write:

Sub Page_Load( )
   Dim MyChars(2) As Char
   Dim MyChar As Char
   MyChars(0) = CChar("A")
   MyChars(1) = CChar("B")
   MyChars(2) = CChar("C")
   For Each MyChar in MyChars
      Response.Write(MyChar)
   Next
End Sub

Notes

As shown above, the Write method in ASP.NET gains a number of new overloaded implementations. The above code could also be written by using another overloaded implementation that accepts an array of Chars, a starting index, and the count of Chars to write, as follows:

Response.Write(MyChars, 0, 3)

The implementation of the Write method that takes an Object as an argument takes advantage of the built-in ToString method of the object class to display the string representation of the object. ToString is inherited by every .NET class and, by default, returns the namespace and class name of the object's class. Classes that wish to send other information about themselves can override the inherited implementation of ToString to send this information.

WriteFile

Response.WriteFile(ByVal fileName As String)
Response.WriteFile(ByVal fileName As String, _
 ByVal includeHeaders As Boolean)
Response.WriteFile(ByVal fileHandle As IntPtr, _
 ByVal offset As Long, ByVal size As Long)
Response.WriteFile(ByVal fileName As String, _
 ByVal offset As Long, ByVal size As Long)

Writes a file specified in one of the overloaded arguments to the output stream.

Parameters

fileName

A string argument containing the path and filename of the file whose content should be written to the output stream.

includeHeaders

A Boolean argument indicating whether the contents of the file should be written to a memory block.

fileHandle

An argument of type IntPtr containing a handle to a file. You can get the handle by creating a new FileStream object from the file and then querying the FileStream's Handle property.

offset

An argument of type Long containing the byte position in the file from which writing should start.

size

An argument of type Long containing the number of bytes that should be written to the output stream.

Example

The example writes the contents of the file dep.txt to the output stream of the current response:

Sub Page_Load( )
   Response.WriteFile("dep.txt")
End Sub

Notes

The WriteFile method can be used in a variety of ways to output text content directly from a file. Attempts to write other content types (such as image data) will fail.

    [ Team LiB ] Previous Section Next Section