- •Using Your Sybex Electronic Book
- •Acknowledgments
- •Contents at a Glance
- •Introduction
- •Who Should Read This Book?
- •How About the Advanced Topics?
- •The Structure of the Book
- •How to Reach the Author
- •The Integrated Development Environment
- •The Start Page
- •Project Types
- •Your First VB Application
- •Making the Application More Robust
- •Making the Application More User-Friendly
- •The IDE Components
- •The IDE Menu
- •The Toolbox Window
- •The Solution Explorer
- •The Properties Window
- •The Output Window
- •The Command Window
- •The Task List Window
- •Environment Options
- •A Few Common Properties
- •A Few Common Events
- •A Few Common Methods
- •Building a Console Application
- •Summary
- •Building a Loan Calculator
- •How the Loan Application Works
- •Designing the User Interface
- •Programming the Loan Application
- •Validating the Data
- •Building a Math Calculator
- •Designing the User Interface
- •Programming the MathCalculator App
- •Adding More Features
- •Exception Handling
- •Taking the LoanCalculator to the Web
- •Working with Multiple Forms
- •Working with Multiple Projects
- •Executable Files
- •Distributing an Application
- •VB.NET at Work: Creating a Windows Installer
- •Finishing the Windows Installer
- •Running the Windows Installer
- •Verifying the Installation
- •Summary
- •Variables
- •Declaring Variables
- •Types of Variables
- •Converting Variable Types
- •User-Defined Data Types
- •Examining Variable Types
- •Why Declare Variables?
- •A Variable’s Scope
- •The Lifetime of a Variable
- •Constants
- •Arrays
- •Declaring Arrays
- •Initializing Arrays
- •Array Limits
- •Multidimensional Arrays
- •Dynamic Arrays
- •Arrays of Arrays
- •Variables as Objects
- •So, What’s an Object?
- •Formatting Numbers
- •Formatting Dates
- •Flow-Control Statements
- •Test Structures
- •Loop Structures
- •Nested Control Structures
- •The Exit Statement
- •Summary
- •Modular Coding
- •Subroutines
- •Functions
- •Arguments
- •Argument-Passing Mechanisms
- •Event-Handler Arguments
- •Passing an Unknown Number of Arguments
- •Named Arguments
- •More Types of Function Return Values
- •Overloading Functions
- •Summary
- •The Appearance of Forms
- •Properties of the Form Control
- •Placing Controls on Forms
- •Setting the TabOrder
- •VB.NET at Work: The Contacts Project
- •Anchoring and Docking
- •Loading and Showing Forms
- •The Startup Form
- •Controlling One Form from within Another
- •Forms vs. Dialog Boxes
- •VB.NET at Work: The MultipleForms Project
- •Designing Menus
- •The Menu Editor
- •Manipulating Menus at Runtime
- •Building Dynamic Forms at Runtime
- •The Form.Controls Collection
- •VB.NET at Work: The DynamicForm Project
- •Creating Event Handlers at Runtime
- •Summary
- •The TextBox Control
- •Basic Properties
- •Text-Manipulation Properties
- •Text-Selection Properties
- •Text-Selection Methods
- •Undoing Edits
- •VB.NET at Work: The TextPad Project
- •Capturing Keystrokes
- •The ListBox, CheckedListBox, and ComboBox Controls
- •Basic Properties
- •The Items Collection
- •VB.NET at Work: The ListDemo Project
- •Searching
- •The ComboBox Control
- •The ScrollBar and TrackBar Controls
- •The ScrollBar Control
- •The TrackBar Control
- •Summary
- •The Common Dialog Controls
- •Using the Common Dialog Controls
- •The Color Dialog Box
- •The Font Dialog Box
- •The Open and Save As Dialog Boxes
- •The Print Dialog Box
- •The RichTextBox Control
- •The RTF Language
- •Methods
- •Advanced Editing Features
- •Cutting and Pasting
- •Searching in a RichTextBox Control
- •Formatting URLs
- •VB.NET at Work: The RTFPad Project
- •Summary
- •What Is a Class?
- •Building the Minimal Class
- •Adding Code to the Minimal Class
- •Property Procedures
- •Customizing Default Members
- •Custom Enumerations
- •Using the SimpleClass in Other Projects
- •Firing Events
- •Shared Properties
- •Parsing a Filename String
- •Reusing the StringTools Class
- •Encapsulation and Abstraction
- •Inheritance
- •Inheriting Existing Classes
- •Polymorphism
- •The Shape Class
- •Object Constructors and Destructors
- •Instance and Shared Methods
- •Who Can Inherit What?
- •Parent Class Keywords
- •Derived Class Keyword
- •Parent Class Member Keywords
- •Derived Class Member Keyword
- •MyBase and MyClass
- •Summary
- •On Designing Windows Controls
- •Enhancing Existing Controls
- •Building the FocusedTextBox Control
- •Building Compound Controls
- •VB.NET at Work: The ColorEdit Control
- •VB.NET at Work: The Label3D Control
- •Raising Events
- •Using the Custom Control in Other Projects
- •VB.NET at Work: The Alarm Control
- •Designing Irregularly Shaped Controls
- •Designing Owner-Drawn Menus
- •Designing Owner-Drawn ListBox Controls
- •Using ActiveX Controls
- •Summary
- •Programming Word
- •Objects That Represent Text
- •The Documents Collection and the Document Object
- •Spell-Checking Documents
- •Programming Excel
- •The Worksheets Collection and the Worksheet Object
- •The Range Object
- •Using Excel as a Math Parser
- •Programming Outlook
- •Retrieving Information
- •Recursive Scanning of the Contacts Folder
- •Summary
- •Advanced Array Topics
- •Sorting Arrays
- •Searching Arrays
- •Other Array Operations
- •Array Limitations
- •The ArrayList Collection
- •Creating an ArrayList
- •Adding and Removing Items
- •The HashTable Collection
- •VB.NET at Work: The WordFrequencies Project
- •The SortedList Class
- •The IEnumerator and IComparer Interfaces
- •Enumerating Collections
- •Custom Sorting
- •Custom Sorting of a SortedList
- •The Serialization Class
- •Serializing Individual Objects
- •Serializing a Collection
- •Deserializing Objects
- •Summary
- •Handling Strings and Characters
- •The Char Class
- •The String Class
- •The StringBuilder Class
- •VB.NET at Work: The StringReversal Project
- •VB.NET at Work: The CountWords Project
- •Handling Dates
- •The DateTime Class
- •The TimeSpan Class
- •VB.NET at Work: Timing Operations
- •Summary
- •Accessing Folders and Files
- •The Directory Class
- •The File Class
- •The DirectoryInfo Class
- •The FileInfo Class
- •The Path Class
- •VB.NET at Work: The CustomExplorer Project
- •Accessing Files
- •The FileStream Object
- •The StreamWriter Object
- •The StreamReader Object
- •Sending Data to a File
- •The BinaryWriter Object
- •The BinaryReader Object
- •VB.NET at Work: The RecordSave Project
- •The FileSystemWatcher Component
- •Properties
- •Events
- •VB.NET at Work: The FileSystemWatcher Project
- •Summary
- •Displaying Images
- •The Image Object
- •Exchanging Images through the Clipboard
- •Drawing with GDI+
- •The Basic Drawing Objects
- •Drawing Shapes
- •Drawing Methods
- •Gradients
- •Coordinate Transformations
- •Specifying Transformations
- •VB.NET at Work: Plotting Functions
- •Bitmaps
- •Specifying Colors
- •Defining Colors
- •Processing Bitmaps
- •Summary
- •The Printing Objects
- •PrintDocument
- •PrintDialog
- •PageSetupDialog
- •PrintPreviewDialog
- •PrintPreviewControl
- •Printer and Page Properties
- •Page Geometry
- •Printing Examples
- •Printing Tabular Data
- •Printing Plain Text
- •Printing Bitmaps
- •Using the PrintPreviewControl
- •Summary
- •Examining the Advanced Controls
- •How Tree Structures Work
- •The ImageList Control
- •The TreeView Control
- •Adding New Items at Design Time
- •Adding New Items at Runtime
- •Assigning Images to Nodes
- •Scanning the TreeView Control
- •The ListView Control
- •The Columns Collection
- •The ListItem Object
- •The Items Collection
- •The SubItems Collection
- •Summary
- •Types of Errors
- •Design-Time Errors
- •Runtime Errors
- •Logic Errors
- •Exceptions and Structured Exception Handling
- •Studying an Exception
- •Getting a Handle on this Exception
- •Finally (!)
- •Customizing Exception Handling
- •Throwing Your Own Exceptions
- •Debugging
- •Breakpoints
- •Stepping Through
- •The Local and Watch Windows
- •Summary
- •Basic Concepts
- •Recursion in Real Life
- •A Simple Example
- •Recursion by Mistake
- •Scanning Folders Recursively
- •Describing a Recursive Procedure
- •Translating the Description to Code
- •The Stack Mechanism
- •Stack Defined
- •Recursive Programming and the Stack
- •Passing Arguments through the Stack
- •Special Issues in Recursive Programming
- •Knowing When to Use Recursive Programming
- •Summary
- •MDI Applications: The Basics
- •Building an MDI Application
- •Built-In Capabilities of MDI Applications
- •Accessing Child Forms
- •Ending an MDI Application
- •A Scrollable PictureBox
- •Summary
- •What Is a Database?
- •Relational Databases
- •Exploring the Northwind Database
- •Exploring the Pubs Database
- •Understanding Relations
- •The Server Explorer
- •Working with Tables
- •Relationships, Indices, and Constraints
- •Structured Query Language
- •Executing SQL Statements
- •Selection Queries
- •Calculated Fields
- •SQL Joins
- •Action Queries
- •The Query Builder
- •The Query Builder Interface
- •SQL at Work: Calculating Sums
- •SQL at Work: Counting Rows
- •Limiting the Selection
- •Parameterized Queries
- •Calculated Columns
- •Specifying Left, Right, and Inner Joins
- •Stored Procedures
- •Summary
- •How About XML?
- •Creating a DataSet
- •The DataGrid Control
- •Data Binding
- •VB.NET at Work: The ViewEditCustomers Project
- •Binding Complex Controls
- •Programming the DataAdapter Object
- •The Command Objects
- •The Command and DataReader Objects
- •VB.NET at Work: The DataReader Project
- •VB.NET at Work: The StoredProcedure Project
- •Summary
- •The Structure of a DataSet
- •Navigating the Tables of a DataSet
- •Updating DataSets
- •The DataForm Wizard
- •Handling Identity Fields
- •Transactions
- •Performing Update Operations
- •Updating Tables Manually
- •Building and Using Custom DataSets
- •Summary
- •An HTML Primer
- •HTML Code Elements
- •Server-Client Interaction
- •The Structure of HTML Documents
- •URLs and Hyperlinks
- •The Basic HTML Tags
- •Inserting Graphics
- •Tables
- •Forms and Controls
- •Processing Requests on the Server
- •Building a Web Application
- •Interacting with a Web Application
- •Maintaining State
- •The Web Controls
- •The ASP.NET Objects
- •The Page Object
- •The Response Object
- •The Request Object
- •The Server Object
- •Using Cookies
- •Handling Multiple Forms in Web Applications
- •Summary
- •The Data-Bound Web Controls
- •Simple Data Binding
- •Binding to DataSets
- •Is It a Grid, or a Table?
- •Getting Orders on the Web
- •The Forms of the ProductSearch Application
- •Paging Large DataSets
- •Customizing the Appearance of the DataGrid Control
- •Programming the Select Button
- •Summary
- •How to Serve the Web
- •Building a Web Service
- •Consuming the Web Service
- •Maintaining State in Web Services
- •A Data-Driven Web Service
- •Consuming the Products Web Service in VB
- •Summary
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 |