DekGenius.com
[ Team LiB ] Previous Section Next Section

18.3 Methods Reference

ClearError

Server.ClearError( )

Clears the last exception thrown.

Parameters

None

Notes

The ClearError method is new to ASP.NET. You can use this method at the beginning of page processing to clear the last exception so that the information provided by the GetLastError method is specific to an exception occurring on the current page.

CreateObject

objvar = Server.CreateObject(ProgID)
objvar = Server.CreateObject(Type)

Returns a reference to a COM object created based on the supplied ProgID.

Parameters

objvar

A variable of type Object to receive the reference to the newly created object.

ProgID

A String variable or literal containing the COM programmatic ID of the desired object.

Type

The type name of a runtime callable wrapper (RCW) class that the tlbimp.exe utility generated to expose a COM object to managed code.

Example

The code example declares an object variable, uses Server.CreateObject to assign a reference to a newly created ADO Recordset object to the variable, and then opens the recordset and returns the RecordCount property to the browser by using the Message label control:

Sub Page_Load( )
   Dim rs1
   Dim ConnString As String
   ConnString = "driver={SQL Server};server=(local)\NetSDK;"
   ConnString =  ConnString & "database=Pubs;Trusted_Connection=yes"
   rs1 = Server.CreateObject("ADODB.Recordset")
   ' 1 and 3 are the values for adOpenKeyset and adLockOptimistic
   rs1.Open("SELECT * FROM Authors", ConnString, 1, 3)
   Message.Text = "There are " & rs1.RecordCount & _
      " records in the Authors table.<br/>"
End Sub

Figure 18-1 shows the output of a page that combines the example for the CreateObject method with the example for the CreateObjectFromClsid method.

Figure 18-1. Output of CreateObject and CreateObjectFromClsid examples
figs/anet2_1801.gif

Notes

This method enables backward compatibility with classic ASP applications and allows the late-bound use of COM components in ASP.NET applications. For new development, it is preferable to use other means to achieve the results that this method was used for in classic ASP. These means include:

  • Using the TlbImp.exe utility to create a RCW for the component, which enables early binding and optimizes the performance of calls between managed and unmanaged code. If you add a reference to a COM component in the Visual Studio .NET IDE, the RCW is created for you automatically.

  • Rewriting custom COM components to run in the managed environment. This method is preferable, as it entirely eliminates the marshalling cost of switching between managed and unmanaged code.

It is important for you to consider the second alternative for COM components that are called frequently and perform a little work each time they're called (as opposed to components that are called once and perform larger amounts of work per call). The distinction between these models is often referred to as "chatty" versus "chunky" communications. The cost of chatty components in marshalling between managed and unmanaged code tends to be significantly higher compared to the amount of work being done in each call. When upgrading COM components to run in the managed environment, you should convert chatty components first and then look at chunky components.

If you want ASP.NET to fire the OnStartPage and OnEndPage events used in some COM components to access the ASP intrinsics, you must add the ASPCompat attribute to the page's @ Page directive:

<%@ Page ASPCompat="true" %>

When ASPCompat is set to True, ASP.NET creates unmanaged intrinsic objects to pass to the component's OnStartPage method. ASP.NET also switches from executing in multithreaded apartment (MTA) to single-threaded apartment (STA) mode to ensure compatibility with COM components created in Visual Basic 5 or 6. This can have a significant negative impact on performance, so be sure to test your application carefully to determine whether the performance will be acceptable when using this attribute.

In ASP.NET, unlike in ASP, it isn't necessary to use the Set keyword with CreateObject, as shown in the previous example. It also isn't necessary to use Set objName = Nothing to release the reference to the object, since the managed reference is eventually garbage collected, at which point the COM object is dereferenced and destroyed.

CreateObjectFromClsid

objvar = Server.CreateObjectFromClsid(Clsid)

Returns a reference to a COM object created based on the supplied COM CLSID.

Parameters

objvar

A variable of type Object to receive the reference to the newly created object.

Clsid

A String variable or literal containing the COM CLSID (a type of globally unique identifier (GUID) for the component that is found in the Registry) of the desired object.

Example

The code example declares an object variable, uses Server.CreateObjectFromClsid to assign a reference to a newly created ADO Recordset object to the variable, and then opens the recordset and returns the RecordCount property to the browser using the Message label control.

Sub Page_Load( )
   Dim rs1
   Dim ConnString As String
   ConnString = "driver={SQL Server};server=(local)\NetSDK;"
   ConnString =  ConnString & "database=Pubs;Trusted_Connection=yes"
   rs1 = Server.CreateObjectFromClsid( _
      "00000535-0000-0010-8000-00AA006D2EA4")
   ' 1 and 3 are the values for adOpenKeyset and adLockOptimistic
   rs1.Open("SELECT * FROM Titles", ConnString, 1, 3)
   Message.Text &= "There are " & rs1.RecordCount & _
      " records in the Titles table.<br/>"
End Sub

Notes

This method is new to ASP.NET and, like the CreateObject method, it allows the late-bound use of COM components in ASP.NET applications.

The other notes relating to the CreateObject method also apply equally to the CreateObjectFromClsid method.

Execute

Server.Execute(Path)
Server.Execute(Path, Writer)

Executes a request on the URL passed by the Path argument and optionally captures the output of the requested page by using an instance of the TextWriter class supplied by the Writer argument.

Parameters

Path

A String variable or literal specifying the URL to execute. The URL passed to the Execute method may be absolute (containing all the information needed to locate the resource, including the protocol type and server name) or relative (containing only the relative path of the resource).

Writer

An instance of any class derived from the TextWriter class (found in the System.IO namespace); used to capture the output of the execution of the requested URL.

Example

The code example declares a string variable, creates a new TextWriter, and then calls Server.Execute to execute a page based on the CreateObject example code and capture its results. Figure 18-2 shows the output of the example.

Figure 18-2. Output of CreateObject and CreateObjectFromClsid examples
figs/anet2_1802.gif
Sub Page_Load( )
   Dim Url As String = "CreateObject.aspx"
   Dim sw As New System.IO.StringWriter( )
   Server.Execute(Url, sw)
   Message.Text = "Request output:<br/><br/>" & sw.ToString( )
End Sub

Notes

The Execute method is a useful feature that first appeared in the IIS 5.0 version of Active Server Pages. ASP.NET includes an overloaded version of the method, adding the Writer argument for capturing, manipulating, and/or saving the output of the request being executed.

When called passing only the URL, the Execute method automatically inserts the output of the request into the HTML output stream of the calling page.

When called passing both the URL and an object reference derived from the TextWriter class (such as StringWriter, StreamWriter, or HtmlTextWriter), the output is not automatically added to the HTML output stream, but may be obtained, as in the previous example, by calling the ToString method of the writer class.

GetLastError

LastException = Server.GetLastError( )

Returns the last exception thrown.

Parameter

LastException

An object of type Exception to receive the application's last exception.

Example

The code in GetLastError.aspx displays a button that, when clicked, calls a server-side event handler that declares three Integers and purposely divides by zero (a no-no) to cause an exception. The code in the Page_Error event handler declares an Exception object and a String, gets the Exception using GetLastError, tests whether the object reference is valid and assigns the Message property of the exception to the string variable, and then writes the value to the browser using the Response.Write method. You can also call the GetLastError method from the Application_Error event handler, which you can place in the global.asax file to catch errors that have not been handled at the page level.

<%@ Page Language="VB" %>
<html>
<head>
   <title>Examining the Last Error</title>
   <script runat="server">
      Sub CauseError(sender As Object, e As EventArgs)
         Dim x, y, z As Integer
         
         y = 1
         z = 0
         x = y / z
      End Sub
      Sub Page_Error(Source As Object, E As EventArgs)
         Dim LastError As Exception
         Dim ErrMessage As String
         LastError = Server.GetLastError( )
         If Not LastError Is Nothing Then
            ErrMessage = LastError.Message
         Else
            ErrMessage = "No Errors"
         End If
         Response.Write("Last Error = " & ErrMessage & "<br/><br/>")
         Server.ClearError( )
      End Sub
   </script>
</head>
<body>
   <form runat="server">
      <h4><font face="verdana">Cause an Error to Occur...</font></h4>
      <asp:button text="CauseError" OnClick="CauseError" runat="server"/>
   </form>
</body>
</html>

Notes

You'll find this method useful for getting information about an error from a custom error-handling page. GetLastError returns information only when called in the Page_Error or Application_Error event handlers because once these events have been fired, the exception is cleared automatically.

HtmlDecode

returnstring = Server.HtmlDecode(s)
Server.HtmlDecode(s,output)

Returns a string in which any HTML information encoded by the HtmlEncode method (described later in this chapter) is decoded back into its standard HTML format.

Parameters

returnstring

A String variable to receive the decoded string from the method.

s

A string variable containing the encoded HTML that the method will decode.

output

An instance of any class derived from the TextWriter class (found in the System.IO namespace) used to capture the decoded string.

Example

The code example declares two string variables, sets the value of StrToDecode to the encoded equivalent of <p>Hello, World!</p>, assigns the return value of the Server.HtmlDecode call to StrToReturn, and then writes the value to the browser using the Message label control:

Sub Page_Load( )
   Dim StrToDecode As String
   Dim StrToReturn As String
   StrToDecode = "&lt;p&gt;Hello, World!&lt;/p&gt;"
   StrToReturn = Server.HtmlDecode(StrToDecode)
   Message.Text = StrToReturn
End Sub

Notes

This method provides a simple way to undo the effects of calling HtmlEncode on a given string. You can also use it as an educational tool to demonstrate the relationship between various characters used in HTML and ASP (such as the greater-than (>) and less-than (<) symbols) and their encoded equivalents.

When called with only the s argument, this method returns a string. When called with both an s argument and an output argument (such as a StringWriter or HtmlTextWriter class instance), the method does not return a value; instead, you can obtain the decoded string by calling the ToString method of the writer object.

While this method is useful, you probably won't use it as frequently as its cousin, UrlDecode, which is described later in this chapter.

HtmlEncode

returnstring = Server.HtmlEncode(s)
Server.HtmlEncode(s, output)

Returns a string in which any HTML tags found are encoded by using the HTML literal equivalents of symbols such as > (&gt;), < (&lt;), and even quotes (&quot;). This allows developers to display HTML and ASP source code on the page, rather than treating it as rendered output or code to execute.

Parameters

returnstring

A String variable to receive the encoded string from the method.

s

A string variable containing the HTML that the method will encode.

output

An instance of any class derived from the TextWriter class, such as a StringWriter class instance (found in the System.IO namespace), used to capture the encoded string.

Example

The code example declares two string variables, sets the value of StrToEncode, assigns the return value of the Server.HtmlEncode call to StrToReturn, and then writes the value to the browser using the Message label control. Note that you have to view the HTML source to see the actual string returned by the method call.

Sub Page_Load( )
   Dim StrToEncode As String
   Dim StrToReturn As String
   StrToEncode = "<%@ Page Language=""VB"" %>"
   StrToReturn = Server.HtmlEncode(StrToEncode)
   Message.Text = StrToReturn
End Sub

Notes

This method is great for displaying the source of a page for educational purposes. It is also particularly useful for encoding text entered by users that may or may not be displayed or written to the browser. Without this encoding (or some form of filtering or validation of the input), it might be possible for the user to enter script or other code that the browser or server could execute. This possibility could pose a very large security risk.

Whether with HtmlEncode or with some form of filtering or validation, you should always ensure that text entered by your users that will be used or displayed by your application does not contain unexpected characters or content.

Like the HtmlDecode method, HtmlEncode is overloaded. It returns a string when called with the s argument alone, and it does not return a value when called with both an s and an output argument. Instead, it sends the encoded HTML to the output class instance.

MapPath

PhysicalPath = Server.MapPath(Path)

Returns a string containing the physical path in the server's filesystem that corresponds to the virtual or relative path specified by the Path argument.

Parameters

PhysicalPath

A String variable to receive the physical path from the method.

Path

A String variable containing the virtual or relative path to be mapped.

Example

The code example declares two string variables, sets the value of RelativePath, assigns the return value of the Server.MapPath call to PhysicalPath, and then writes the value to the browser by using the Message label control:

Sub Page_Load( )
   Dim RelativePath As String
   Dim PhysicalPath As String
   RelativePath = "HtmlEncode.aspx"
   PhysicalPath = Server.MapPath(RelativePath)
   Message.Text = PhysicalPath
End Sub

Notes

You can use this method to determine the physical location for creating a new file in response to a user action or code event.

In classic ASP, attempting to use this method with the MS-DOS (.) and (..) relative directory syntax would result in an error. In ASP.NET, no error occurs. In the previous example, using "../HtmlEncode.aspx" for the Path returns a physical path mapping the file HtmlEncode.aspx to the parent folder of its physical location. Using "./HtmlEncode.aspx" for the Path returns the same physical path mapping as in the original example.

The MapPath method dynamically determines whether the provided path is a relative or virtual path based on whether the leading character is a slash (/) or backslash (\). If the leading character is either one, the path is assumed to be a complete virtual path. If not, the path is assumed to be relative to the physical path of the currently executing page.

If the last component in Path is a filename, the MapPath method does not verify its existence. In other words, the code example returns the same absolute path whether or not HtmlEncode.aspx exists.

A more flexible version of the MapPath method has been added to the Request object that enables you to specify a base directory for resolving mappings and lets you allow mapping of paths across different applications. You can read more about the Request.MapPath method in Chapter 16.

Transfer

Server.Transfer(Path)
Server.Transfer(Path, preserveForm)

Discontinues execution of the current page and transfers execution to the page specified by the Path argument. This allows control of an application to be redirected to the page specified by the Path argument without any response being sent to the client.

In contrast to the Execute method, which returns control to the page in which it is called once the page specified in the Execute method finishes processing, the Transfer method does not return control to the calling page.

Parameters

Path

A String variable containing the path to the page to which execution will be transferred.

preserveForm

A Boolean variable that indicates whether the Form and QueryString collections should be cleared before transferring control to the page that the Path argument specifies.

Example

The code example declares a string variable containing the name of the page to transfer control to, and then calls Server.Transfer. Note that the call that sets the Message.Text property will never be executed.

Sub Page_Load( )
   Dim Url As String = "CreateObject.aspx"
   Server.Transfer(Url)
   Message.Text = "This code will never be executed!"
End Sub

Notes

The ability to clear the Form and QueryString collections prior to passing control to the page that the Path argument specifies is new in ASP.NET. This is convenient for passing control to pages that you did not create and that might break if they encounter unexpected values, or if you want to keep the Form or QueryString contents private. If you do not pass a preserveForm argument, the default behavior is for the Form and QueryString collections to be preserved.

Make sure that no code in your page must execute after a Server.Transfer. If you have such code, you may want to consider using Server.Execute instead.

UrlDecode

returnstring = Server.UrlDecode(s)
Server.UrlDecode(s,output)

Returns a string in which any special character sequences resulting from encoding by the UrlEncode method (described later in this chapter) are decoded back into the original format. For example, a URL with a query string such as:

http://localhost/ASPdotNET_iaN/Chapter_18/UrlDecode. aspx?strtodecode=This%20is%20a%20good%20string.

would return the following string from the UrlDecode method:

This is a good string.

Parameters

returnstring

A string variable to receive the decoded string from the method.

s

A string variable containing the encoded URL to be decoded by the method.

output

An instance of any class derived from the TextWriter class (found in the System.IO namespace) used to capture the decoded string. Examples are the StringWriter and HtmlTextWriter classes.

Example

The code example declares two string variables, sets the value of StrToDecode to the encoded equivalent of the QueryString's StrToDecode value, assigns the return value of the Server.UrlDecode call to StrToReturn, and then writes the value to the browser using the Message label control:

Sub Page_Load( )
   Dim StrToDecode As String
   Dim StrToReturn As String
   StrToDecode = Request.QueryString("StrToDecode")
   StrToReturn = Server.UrlDecode(StrToDecode)
   Message.Text = StrToReturn
End Sub

Notes

New in ASP.NET, this method provides a simple way to undo the effects of calling UrlEncode on a given string. It is especially useful for retrieving values passed in the query string, since these values commonly contain characters, such as spaces and commas, that are not allowed in URLs.

When called with only the s argument, this method returns a string. When called with both the s argument and output argument, the method does not return a value; instead, the decoded string is sent to the output writer.

UrlEncode

returnstring = Server.UrlEncode(s)
Server.UrlEncode(s, output)

Returns a string in which any characters not allowed in URLs are encoded by using the URL literal equivalents, such as %2c for comma and + for space. This makes it very simple to pass any string as a query string value and, thanks to the new UrlDecode method, just as simple to retrieve the unencoded value.

Parameters

returnstring

A String variable to receive the encoded string from the method.

s

A String variable containing the value to be encoded by the method.

output

An instance of any class derived from the TextWriter class (found in the System.IO namespace); used to capture the encoded string. Classes derived from TextWriter include StringWriter and HtmlTextWriter.

Example

The code example declares two string variables, sets the value of StrToEncode, assigns the return value of the Server.UrlEncode call to StrToReturn, and then writes the HTML anchor tag containing a query string with the encoded value to the browser using the Message label control:

Sub Page_Load( )
   Dim StrToEncode As String
   Dim StrToReturn As String
   StrToEncode = "Hello, World!"
   StrToReturn = Server.UrlEncode(StrToEncode)
   Message.Text = "<a href=""UrlDecode.aspx?StrToDecode=" & StrToReturn
   Message.Text &= """>" & StrToReturn & " - Click to Decode!</a>"
End Sub

Notes

This method replaces non-URL-allowable characters in strings that need to be passed as part of a URL. For example, one of the most difficult things to pass as part of a URL is another URL. The UrlEncode method replaces all slash (/), dot (.), and colon (:) characters for you. Figure 18-3 shows the output of the previous example.

Figure 18-3. Output of server UrlEncode
figs/anet2_1803.gif

Like the UrlDecode method, UrlEncode is overloaded. It returns a string when called with the s argument alone and does not return a value when called with both the s and output arguments. Instead, the encoded URL is sent to the writer object.

UrlPathEncode

returnstring = Server.UrlPathEncode(s)

Returns a string containing a URL whose path portion is encoded using the URL literal equivalents of symbols such as slash (/), colon (:), and dot (.). The method also encodes any spaces in the remaining portion of the URL, since spaces in the query string may be unexpectedly truncated by some browsers.

Parameters

returnstring

A String variable to receive the encoded string from the method.

s

A String variable containing the URL to be encoded by the method.

Example

The code example declares two string variables, sets the value of StrToEncode, assigns the return value of the Server.UrlPathEncode call to StrToReturn, and then writes the value to the browser as part of a hyperlink:

Sub Page_Load( )
   Dim StrToEncode As String
   Dim StrToReturn As String
   StrToEncode = "http://www.aspnetian.com/Chapter18/UrlPathEncode.aspx"
   StrToReturn = Server.UrlPathEncode(StrToEncode)
   Message.Text = "<a href=""UrlPathEncode.aspx?target=" & _
      StrToReturn & """>" & StrToReturn & "</a><br/>"
   Message.Text &= "Target = " & Request("Target")
End Sub

Notes

This method existed in classic ASP, but was undocumented.

    [ Team LiB ] Previous Section Next Section