Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
(ebook) Visual Studio .NET Mastering Visual Basic.pdf
Скачиваний:
120
Добавлен:
17.08.2013
Размер:
15.38 Mб
Скачать

THE ASP.NET OBJECTS 1037

and you can’t access them directly. You must call the PostedFile object’s Save method to save the file to a disk file, and this must take place from within your Web application. After saving the uploaded files to the server file system, you can open and process them just like any other file.

By now, you have a good idea of how Web applications work. The user interface of a Web application is an HTML file that can be rendered on the browser. Since browsers haven’t changed drastically in the last couple of years, nothing really exceptional takes place at the client. All the work is done on the server, by the code you place behind the controls of the application. The form you send to the client consists of HTML and Web controls. Web controls are just an illusion: they look like Windows controls, and you can program their events (which aren’t many anyway), but the client sees HTML controls (and in some cases a few scripts).

To program a control, usually a button, enter the appropriate code in its Click event handler. You can access the various controls on the form as if you were programming a VB application. Is that all there is to Web applications? Hardly. This is what the IDE can hide from you, but there’s a lot that can’t be hidden. In the following section, I will go quickly through the basic ASP.NET objects and list their basic properties and methods. These are the objects ASP developers have had to work with, and ASP.NET is no exception.

The ASP.NET Objects

The following objects represent the basic entities of an ASP application. To make the most of ASP.NET, you must learn when and how to use these objects.

The Page Object

The Page object represents the page requested by the client. The requested page is an ASPX file, but the Page object is totally independent from this file. Unlike the other ASP.NET objects, the Page object exposes two events, the Load and Unload events, which are fired when the page is loaded and unloaded respectively. The most important method of the Page event is the IsPostBack property, which is True if the page is posted back. This property is False the first time the page is loaded and True when the Submit button on the page is clicked. Nearly every ASP.NET application uses the Load event and the IsPostBack property to determine whether it should initialize the page. If the page is posted back, we don’t want to initialize its controls again. The following event handler is included in most ASPX pages:

Private Sub Page_Load(ByVal sender As System.Object, _

ByVal e As System.EventArgs) Handles MyBase.Load If Not Page.IsPostBack Then

{ put user code to initialize the page here } End If

End Sub

The Page object exposes another very interesting method, the DataBind method, which causes all the data-bound controls on the page to be bound to their corresponding fields. You’ll find more about binding Web controls to fields in the following chapter.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

1038 Chapter 23 INTRODUCTION TO WEB PROGRAMMING

The Response Object

The Response object is derived from the HttpResponse object, which exposes the properties and methods you need to manipulate the output sent to the client computer from within your Web application’s code. The properties and methods used commonly in ASP.NET programming are the following:

Properties

Buffer When the Buffer property is True, the server buffers its output and sends it to the client after it has finished processing the request. When False, the output is sent to the client in pieces, as it becomes available.

ContentType This property sets (or gets) the HTTP MIME type of the output. Its value for an HTML page is text/html.

Cookies This property is a collection that contains the cookies placed on the client computer by the Web application. The Cookies collection is discussed in more detail later in this chapter.

Expires This property gets or sets a period (in minutes) during which the current page in the client’s cache will expire. Cached pages are not fetched from the server—they appear instantly because they’ve been cached to the client.

ExpiresAbsolute This property is similar to the Expires property, but it specifies the absolute date and time at which the page will expire.

IsClientConnected This is a read-only property that determines whether the client is still connected to the server. Use this property in a program that takes long to execute to find out whether the user has disconnected and, if so, interrupt the execution of the program, because the user will never see the results.

Methods

ClearContent Clears all content output from the buffer stream.

ClearHeaders Clears all headers from the buffer stream.

Close Closes the connection to a client.

End Terminates the execution of the current request and sends all currently buffered output to the client.

Flush Sends all currently buffered output to the client. If your application takes a long time to execute, call this method from time to time so that the user knows that the application is still running on the server.

Redirect The Redirect method accepts a URL as argument and redirects the client to the specified URL. If the Web application consists of more than a single page (which is usually the case), use the Redirect method to invoke another page. For more information on using the Redirect method, see the section “Handling Multiple Forms in Web Applications,” later in this chapter.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

THE ASP.NET OBJECTS 1039

Write Call this method to add information to the output stream. The simplest form of the Write method accepts a string as argument, but you can also send characters or even an object to the client.

WriteFile This method sends the contents of a file on the server’s file system directly to the client.

The Request Object

The Request object is derived from the HttpRequest object, which exposes the properties and methods you need to manipulate the requests made by the client computer from within your Web application’s code. The properties of the Request object used commonly in ASP.NET programming are the following. The methods are fairly advanced and not as common in ASP.NET programming, so I’ve omitted them.

Properties

ApplicationPath Returns the application’s virtual root path on the server.

Browser An object that returns information about the capabilities of the browser running on the client. Some of the properties exposed by the Browser object are the following:

Property of the Browser Object

Description

AOL

True if the client is an America Online (AOL) browser

BackgroundSounds

True if the browser supports background sounds

Beta

True if this is a beta release of the browser

Browser

The string (if any) transmitted in the User-Agent header

CDF

True if client supports Channel Definition Format

 

(CDF) for webcasting

Cookies

True if client supports cookies. If the user has turned off

 

the cookies, this property will still return True.

Crawler

True if the browser is a Web crawler search engine

Frames

True if client supports HTML frames

JavaApplets

True if browser supports Java applets

JavaScript

True if browser supports JavaScript

MajorVersion, MinorVersion

The major and minor version numbers of the browser

Platform

The name of the platform used by the client

Tables

True if browser supports HTML tables

VBScript

True if browser supports VBScript

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

1040 Chapter 23 INTRODUCTION TO WEB PROGRAMMING

ContentLength The length (in bytes) of the content sent by the client. As you will see shortly, it is possible for a client to upload files to the server.

ContentType Returns the MIME content type of the incoming request. The ContentType property of an HTML page is text/html.

Cookies Returns a collection with the cookies sent by the client.

FilePath Returns the virtual path of the current request.

IsSecureConnection True if the connection uses secure sockets (that is, HTTPS).

PhysicalPath Gets the physical file system path corresponding to the requested URL.

QueryString Gets the collection of HTTP query string variables.

RawUrl Gets the raw URL of the current request.

RequestType Gets or sets the HTTP data transfer method (GET or POST) used by the client.

ServerVariables Gets a collection of Web server variables.

TotalBytes Gets the number of bytes in the current input stream.

Url Gets information about the URL of the current request.

UrlReferrer Gets information about the URL of the client’s previous request that linked to the current URL.

UserHostAddress Gets the IP host address of the remote client.

UserHostName Gets the DNS name of the remote client.

UserLanguages Gets a sorted string array of client language preferences.

The Server Object

This object exposes mostly methods, which are used as helper functions in processing Web requests.

Properties

MachineName The server machine name.

ScriptTimeout The request’s time-out in seconds.

Methods

Execute Requests another page, whose URL is passed to the Execute method as argument. Optionally, you can retrieve the output generated by the second page and include it in the current page. See the section “Handling Multiple Forms in Web Applications” later in this chapter for more information on using this method.

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com

THE ASP.NET OBJECTS 1041

GetLastError Returns the last exception.

HtmlDecode Accepts as argument a string that has been encoded to eliminate illegal HTML characters and decodes it. If you pass the following string to the HtmlDecode method,

HTML tags are delimited by the < and > symbols

it will return the string

HTML tags are delimited by the < and > symbols

HtmlEncode Encodes a string so that it can be displayed on the browser. If you pass the following string to the HtmlEncode method,

HTML tags are delimited by the < and > symbols

it will return the string

HTML tags are delimited by the < and > symbols

You can then pass this string to the HtmlDecode method to reconstruct the original string.

MapPath Returns the physical file path of a virtual path passed as argument. Notice that the virtual path need not exist. The MapPath method will prefix it with the path of the virtual folder in which the application resides. If you pass to the MapPath method the name of a folder, the method will assume that it’s relative to the application’s path.

Transfer Aborts execution of the current page and transfers control to a new page. The new page is executed as if it were called directly by the client application. This method differs from the Execute method in that the control is not returned to the original page.

The Transfer method accepts a second optional argument, which is a True/False value that indicates whether the parameters passed to the original page (either through the QueryString or through the Form property) will be passed to the second page. The default value is False (the parameters are not passed to the second page).

UrlDecode Decodes an HTTP-encoded string (such as the URL submitted to the server by the client).

UrlEncode Encodes a string for HTTP transmission. The expression

Server.UrlEncode(“who am I?”)

will return the following string:

who+am+I%3f

UrlPathEncode Encodes the path portion of a URL in a format suitable for transmission to the client. The statement

Response.Write(Server.UrlPathEncode(“http://www.server.com/myfile.htm”))

will print this string on the page:

http%3a%2f%2fwww.server.com%2fmyfile.htm

Copyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com