Structure of Sailors.mdb

Introduction and Objective

Sailors. mdb supports a hypothetical web site for competitive sailors. The web site includes pages to notify sailors of upcoming regattas, changes in rules, reports on past regattas, and personalized pages based on each sailor's interests. Additional features allow the posting and statistical analysis of regatta results and the ranking of sailors.

Vocabulary and Business Rules

Sailors, in this database are people who race sailboats. These people have the normal personal information such as names and nationalities, as well as an assigned professional class, which reflects their commitment and accomplishment in the sport of yachting. The most skilled sailors, those of Olympic caliber, are rated Professional Class 1 while those who compete at an amateur level are class 3.

Boats are owned by Sailors. A boat has a name and an identifying sail number. Every boat is of a boat class.

A Boat Class is a group of boats of the same shape, sail area and hull size, thus ensuring an even competition among the sailors. Sailors generally race in one class only and thus are not interested in information for boats of other classes.

Sailors race under the aegis of yacht clubs, the organizations which typically sponsor regattas. Yacht clubs have an identifying flag called a club burgee, may have a web site, and each year a yacht club has a meeting at which time information for the season is disseminated. Larger boats are limited to sailing from clubs with a crane to hoist the boat from its trailer to the water.

Competitions generally consist of a series of races (typically 3 to 10), which together constitute a regatta. Based on the results of regattas, sailors are ranked each month from first (most skilled) to 20th (least skilled). Appendix A

Where to Download

This database, in Access format, is available from the Wrox site. The procedures to create the queries for Microsoft SQL Server are also available from the same site in the file Sailors. . The end of this appendix lists the information to create the structure of the database by hand.

Structure and Relationships of Tables

The Sailors database contains five tables. There are no relationships permanently created, they are created in queries as needed.

People Table Sailors are listed in the People table; each person is a record. The People table can be related to the Clubs table and to the boats table, since each sailor is a member of a club and most sailors own boats. In addition, the People table can be related to the Rank table. As in all tables of this database there is an ID field with a data type of autonumber. To keep the database small for the download, there are only twenty sailors.

Boats Within the Boat table each record is a boat. The boats can be related to the People table by the PeopleiD as well as the Boat Class table.

BoatCiass This table has only a few records, each representing a class of boats. It can only be directly related to the Boats table. Since all the boats of a given class have the same length, weight and sail area, this information is kept only in the Boat Class table. In our simple example there are just three classes.

Rank Each record in the Rank table represents one sailor in one month of one year. Fields hold the sailor's ID as well as the rank number. This database covers the four months from December 1999 to March 2000.

Clubs Each yacht club holds a record in this table. In addition to contact information, this table holds data for the URL of the club's home page. An image of the club burgee (flag) is held in two places, a file on the server and in a BLOB field in this table. Overview of Queries One group of queries, those beginning with qAll, merely list the records of the table. An exception is the qAllRankings query, which joins the People, Clubs and Rank tables to create a useful recordset for reporting the standings.

A second group of queries begins with qparm. These are for demonstrating the use of passing parameters through the ADO command object. This group includes the qparminsert queries, which are called to append records to tables. 742 Structure of Sailors.mdb

Structure of Tables

Table Field Name Field Type Field Size Notes

Boat Class ClassiD AutoNumber 4 Attributes: Fixed Size, Auto- Number (Long) Increment

ClassName Text 50 ClassLength Number (Long) 4 ClassWeight Number (Long) 4 ClassEntered Date/Time 8 Format: Long Date

Boats BoatsiD AutoNumber 4 attributes: Fixed Size Number (Long) Auto-Increment

BoatName Text 50 Boatel ass Text 50 BoatLaunched Date/Time 8 BoatCertified Yes/No 1 BoatNote Memo Boat Photo OLE Object BoatValue Currency 8 Decimal Places: Auto Format: $#,##0.00;($#,##0. 00)

743 Appendix A

Table Field Name Field Type Field Size Notes

Clubs ClubiD AutoN umber 4 Attributes: Fixed Size Number (Long) Auto-Increment ClubCode Text so ClubName Text so ClubAnnualMeeting Date/Time 8 ClubDues Currency 8 Decimal Places: Auto Format: $#,##0.00;($#,##0. 00) ClubWWWSite Hyperlink

ClubBurgeeFile Text 50 ClubBurgee OLE Object ClubHasCranes Yes/No 1 ClubMembership Number (Long) 4 ClubNote Memo

People PeopleiD AutoN umber 4 Number (Long)

PeopleNameLast Text 50

PeopleNameFirst Text 50 PeopleDOB Date/Time 8 Format: Short Date PeopleProfessionalClass Number (Long) 4

PeopleClubCode Text 50 PeopleReferee Yes/No 1 PeopleState Text so PeopleView Text 50

744 Structure of Sailors.mdb

Table Field Name Field Type Field Size Notes

Rank ID AutoN umber 4 Attributes: Fixed Size Number (Long) Auto-Increment

SailoriD Number (Long) 4 Year Number (Long) 4 Month Number (Long) 4 Rank Number (Long) 4

Structure of Queries

Query Name Query Details qAllBoatClasses SELECT BoatClass.ClassName FROM BoatClass ORDER BY BoatClass.ClassName; qAllBoatNames SELECT Boats.BoatName FROM Boats; qAllBoats SELECT Boats.BoatClass, Boats.BoatName FROM Boats ORDER BY Boats.BoatClass, Boats.BoatName; qAllClubs SELECT Clubs.ClubName, Clubs.ClubCode FROM Clubs ORDER BY Clubs.ClubName; qAllRankings SELECT People.PeopleiD, People.PeopleNameLast, People.PeopleNameFirst, Clubs.ClubName, Rank.Year, Rank.Month, Rank. Rank FROM (Rank INNER JOIN People ON Rank.SailoriD = People.PeopleiD) INNER JOIN Clubs ON People.PeopleClubCode = Clubs.ClubCode ORDER BY Clubs.ClubName, Rank.Year, Rank.Month, Rank.Rank;

745 Appendix A

Query Name Query Details

qDemoQueryGrid SELECT People.PeopleNameLast, People.PeopleNameFirst, People.PeopleProfessionalClass

FROM People WHERE (((People.PeopleProfessionalClass)=2)) ORDER BY People.PeopleNameLast;

qparmBoats PARAMETERS Class Text; SELECT Boats.BoatsiD, Boats.BoatName FROM Boats WHERE (((Boats. BoatClass )=[Class]));

qparminsertBoat PARAMETERS Name Text, Class Text, Launched DateTime, Certified Bit, Notes LongText, [Value] Currency; INSERT INTO Boats ( BoatName, BoatClass, BoatLaunched, BoatCertified, BoatNote, BoatValue) SELECT [Name] AS Exprl, [Class] AS Expr2, [Launched] AS Expr3, [Certified] AS Expr4, [Notes] AS ExprS, [Value] AS Expr6; qparminsertBoatClass INSERT INTO BoatClass ( ClassName, ClassBoatLength, ClassBoatWeight, ClassSailAreaMainJib, ClassSailAreaSpinnaker, ClassAuthority ) SELECT [Name] AS Exprl, [Length] AS Expr2, [Weight] AS Expr3, [MainJib] AS Expr4, [Spinnaker] AS ExprS, [Authority] AS Expr6; qparminsertPerson PARAMETERS FirstName Text, LastName Text, DOB DateTime, ProfessionalClass Long, ClubCode Text, Referee Bit, State Text; INSERT INTO People ( PeopleNameFirst, PeopleNameLast, PeopleDOB, PeopleProfessionalClass, PeopleClubCode, PeopleReferee, PeopleState ) SELECT [FirstName] AS Exprl, [LastName] AS Expr2, [DOB] AS Expr3, [ProfessionalClass] AS Expr4, [ClubCode] AS ExprS, [Referee] AS Expr6, [State] AS Expr7; qParmSailorRanking PARAMETERS ClubCode Text, Ranking Long; SELECT People.PeopleiD, People.PeopleNameLast, People.PeopleNameFirst, People.PeopleProfessionalClass, People.PeopleClubCode, Rank.Year, Rank.Month, Rank.Rank FROM People INNER JOIN Rank ON People.PeopleiD = Rank.SailoriD WHERE (((People.PeopleClubCode)=[ClubCode]) AND ((Rank.Rank)<=[Ranking]))

ORDER BY Rank.Year, Rank.Month, Rank.Rank;

746 Structure of Sailors.mdb

Query Name Query Details qparmVerifyLogin PARAMETERS FirstName Text, LastName Text, ClubCode Text; SELECT People.PeopleNameFirst, People.PeopleNameLast, People.PeopleClubCode FROM People WHERE (((People.PeopleNameFirst)=[FirstName]) AND ((People.PeopleNameLast)=[LastName]) AND ((People.PeopleClubCode)=[ClubCode])); qranktest SELECT Rank.Rank, Rank. Year, Rank.Month, Rank.SailoriD FROM Rank ORDER BY Rank.Rank, Rank. Year, Rank.Month, Rank.SailoriD DESC; qTestWherein SELECT People.PeopleNameLast, People.PeopleNameFirst, People.PeopleClubCode FROM People WHERE (((People.PeopleClubCode) In ('scow','dsyc')));

747

- Structure of Clothier.mdb

Introduction and Objective

The Clothier database supports an Internet site to manage new items in the inventory of a clothing wholesaler. As the wholesaler contracts to buy clothing from manufacturers, the buyers post the items on the web site so they can be ordered by individual stores.

Vocabulary and Business Rules

An item refers to a given model (design) of clothing. An item is not one piece of clothing, but rather one offering by the wholesaler such as the "Mountain Walker" hiking trousers. Every item belongs to a department, such as Women's Sportswear or Men's Formalwear. In addition, each item has a type such as trousers, shirts, or hats.

Items have a release date and since the wholesaler wants to show clothes as early as possible, they are frequently posted to the site prior to release. A quantity per box helps the sales staff since orders are made in full-box quantities. To make this database simpler we use only one price, the wholesaler's buying price.

This business buys from three vendors. Each vendor has a name and a vendor code.

Where to Download

This database is available from the Wrox site. We make it available in Access97 format, which can also be read by Access 2000. The end of this Appendix also lists the information to create the structure of the database by hand. Appendix B

Structure of Tables and Queries

Items Table Each clothing item (design) gets its own record. However, for this site there is no need to differentiate among the sizes and colors. Fields for ordering are included, such as the price and quantity packed per box so the buyer can estimate delivery costs. A numeric code field identifies the vendor and can be used for joins to the vendoriD field of the vendors table.

Note the clarification in the name of the price field. Many of my students start with fields named price, but most items have at least two prices (buy and sell) and can have many more (discount price, manufacturer's suggested retail price, etc). I suggest that a field named Price is always followed by one or more adjectives describing which price.

Vendors Table This wholesaler buys from several vendors, each of which has its own record in this table. The VendoriD field can be joined to the ItemVendor field of the Items table.

In this simple database there are no stored queries.

Table Data

If you are unable to download the tables (like when I lectured in Ulaan Batar in '94, although my friends in Mongolia now communicate by Email without problem), you can create the structure by hand from the data below.

Table Field Name Field Type Field Size Notes

Items ItemiD Number (Long) 4 Attributes: Fixed Size, Auto- Increment ItemName Text 50

ItemDepartment Text 50

ItemType Text 50

ItemPriceBuy Currency 8 Decimal Places: Auto Default Value: 0 Format: $#,##0.00;($#,##0.00)

750 Structure of Clothier.mdb

Table Field Name Field Type Field Size Notes Items ItemVendor Number (Integer) 2

ItemQtyPerBox Number (Long) 4

ItemDateRelease Date/Time 8

Vendors VendoriD Number (Long) 4 Attributes: Fixed Size, Auto- Increment VendorName Text 50

VendorCode Text 50

751

Profile.mdb Database Schema

The following tables describe the profile. mdb database.

Tables profile

Field Name Data Length Indexed Req. OLen. Description Type fname Text 30 No Yes Yes First Name mname Text 30 No No Yes Middle Name lname Text 30 No No Yes Last Name handle Text 75 No No Yes Nickname usehandle Yes/No No No Use Handle instead of Name in profile phone Text 20 No No Yes Phone Number email Text 100 Yes No Yes Email Address (dup) password Text 20 Yes No Yes Password to (dup) edit profile address Text 100 No No Yes Address

city Text 50 Yes No Yes City (dup) state Text 30 Yes No Yes State (dup) Appendix C

Field Name Data Length Indexed Req. OLen. Description Type

zip Text 20 Yes No Yes Zip Code (dup) country Text 20 Yes No Yes Country (dup) image Text 50 No No Yes Image file name template Integer No No Template Number to use in profile fontstyle Text 75 No No No Font Style for Headings in page fontsize Integer No No Font Size for Headings in page fontcolor Integer No No Font Color for Headings in page bgimage Text 50 No No Yes Background Image for page bgcolor Integer No No Background Color for page linkcolor Integer No No Hyperlink Color for page vlinkcolor Integer No No Visited Hyperlink Color for page alinkcolor Integer No No Active Hyperlink Color for page tblbgimage Text 50 No No Yes Background Image for tables in page tblbgcolor Integer No No Background Color for tables in page

754 Profile.mdb Database Schema

Field Name Data Length Indexed Req. OLen. Description Type textcolor Integer No No Font color for text in page tblborder Integer No No Table Border width for tables in page website Text 100 No No Yes Web Site Address newsletter Yes/No No No Does User want to receive Newsletter? job Text 255 No No Yes Job Description in profile hobbies Memo No No Yes Hobbies in profile

bio Memo No No Yes Biography in profile other Memo No No Yes Additional Comments in profile

BLOBs

Field Name Data Length Indexed Req. OLen. Description Type

fname Text Yes Yes First Name email Text 100 No No Yes Email Address from profile picture OLEObj. No No BLOB picture sound OLEObj. No No BLOB sound (.wav file)

755 Appendix C

Stored Queries

deletetest DELETE * FROM profile WHERE email LIKE 'takempis~hatever.net'; lnserttest INSERT INTO profile ( fname, mname, lname, handle, usehandle, phone, email, password, address, city, state, zip, country, website, newsletter, job, hobbies, bio, other, [image), template, fontstyle, fontsize, fontcolor, bgimage, bgcolor, linkcolor, vlinkcolor, alinkcolor, tblbgimage, tblbgcolor, textcolor, tblborder ) VALUES('Kevin', •c•, 'Spencer•, 'Kevin', FALSE, 'lll-222-3333', •takempisoaol.com', 'hello', 'address', •city', •state', 'lllll', 'USA', 'http://www.takempis.com1 , TRUE, 'Internet Database Programming•, 'programming', 'I was born. I lived. I will die', 'whatever', •none•, l, 'Arial', 2, 29, •rosesbg. jpg', 30, 29, 30, 28, •rosesbg.jpg', 18, 30, 0) paramse/ecttest SELECT profi e . * FROM profile WHERE email LIKE mystr; selecttest SELECT profile.* FROM profile; updatetest UPDATE prof le SET email : 'takempis~hatever.net• WHERE email a •takempisoaol.com';

756 Profile.mdb Database Schema

757

I

Creating a Sailors Database in SQL Server

This section covers the required steps to create the Sailors database in SQL Server and assumes you already have the Access Sailors database on your machine. You will need administrator rights to the SQL Server database that you use, and it is recommended that you have SQL Server installed on your workstation. These procedures have been tested with SQL Server 6.5 and SQL Server 7.0.

We will be exporting the tables and table data from the Access Sailors database to the SQL Server Sailors database. This is by far the easiest method to duplicate the Access database into SQL Server.

Creating the Sailors Database

Start SQL Server Enterprise Manager and expand the databases folder. Right click on Databases and choose New Database from the popup menu. Enter the name of Sailors for the database name and select an initial database size of 5 MB, which is more than enough for this database. Take the default for all other options and click on the Create Now button (or OK button if using version 7).

The database has now been created and we need to set up a DSN next.

Creating the Data Source Name

Chapter 2 stepped you through creating a DSN in detail, so we'll just cover the highlights here with no illustrations. Select the System DSN tab in the ODBC Data Source Administrator dialog and click on the Add button.

In the next dialog, choose Microsoft SOL Server and click the Finish button. Give the DSN a name of SOLSailor and select the server where the version of SQL Server that you are using is installed.

On the next dialog select the option With SOL Server authentication using a logon ID and password entered by the user. Enter the logon ID and password of the account you are using to access the Sailors database on your SQL Server. Click Next to continue. Appendix D

Once you receive the next dialog you may need to change the default database to Sailors, if the logon ID you are using has access to more than one database. Accept all other defaults on this dialog and click the Next button. Accept all defaults on the next dialog and click the Finish button.

The next dialog gives you the option of testing the DSN to ensure you are able to connect successfully. It is always recommended that you test the DSN. Once you have tested the DSN click OK to close the dialog and the new DSN will be set up.

Exporting the Tables

Open the Access Sailors database and click on the Tables tab. Perform the following steps for each table listed. Select a table and right click on it, and choose Save As/Export from the popup menu Gust Export for Access 2000). Click OK on the Save As dialog.

Save As ·- 6 EJ

• 'To an flcternal File or Datab~

W1thn the C,Lrrent Database as

760 Creating a Sailors Database in SQL Server

In the Save Table dialog choose ODBC Databases () in the Save As Type combo box.

Suve Tuhle 'llouiCiuss ' In . · fii:J

File uame: lBoatclass.mclb

save as type :

the 5eU4J J:rogram, cliCk Add~emove, n the Office 97 VaUPack.

Once you click on ODBC Databases (), the Export dialog will appear. Click on OK here without changing the table name.

Exporl iJEJ

Export Boatclass to; OK

cancel n ooe.c Database

761 Appendix D

The Select Data Source dialog will appear and you need to click on the Machine Data Source tab and select the SQLSailor DSN as shown below.

Select DetB Source iJEJ

File Date. Source Me.chme Date. Source j

User System System System Text Files User Visue.J FoxPro De.te.be.se User Visue.J FoxPro Te.bles User Xtreme sample date. System

~ew ..

A Machine Date. Source 1s speCific to this me.chme. e.nd cannot be she.red "User" date. sources e.re specific to e. user on this machine "System" date. sources ce.n be used by all users on th1s machine. or by e. system-wide seMce.

OK Ce.ncel Help

Once you click OK on the previous dialog you will be prompted with the SOL Server Login dialog asking for the password for the user id that was specified in the DSN, as shown here.

De.te. Source: SQLSe.ilor

fi Use Trusted Connection Cancel

.Login 10 !sa Jjelp

£as sword Qptions »

Once you have specified the correct password, click on OK. The table will be created in SQL Server, and the data that exists in the table in Access will be loaded into the new table in SQL Server.

Repeat this process for all tables in the Access Sailors database. Note that it is not possible to do all tables at once, without writing complex code. This code would need to extract the database schema, work out how to use this schema to build tables, and extract data, all within the code.

762 Creating a Sailors Database in SQL Server

763

Active Server Pages Object Model

This appendix offers a handy reference to the Active Server Pages object model, and in each case provides the properties, methods and events for the object, along with their collections.

The Request Object

Together, the Request object and the Response object form the 'conversational mechanism' of ASP. The Request object is responsible for controlling how the user sends information to the server. Using the Request object, the server can obtain information about what the user wants- either explicitly (e.g. through programmed ASP code) or implicitly (e.g. through the ffiTP headers).

Collections Description ClientCertificate Client certificate values sent from the browser. Read Only Cookies Values of cookies sent from the browser. Read Only Form Values of form elements sent from the browser. Read Only QueryString Values of variables in the ffiTP query string. Read Only ServerVariables Values of the ffiTP and environment variables. Read Only

Property Description TotalBytes Specifies the number of bytes the client is sending in the body of the request. Read Only

Method Description BinaryRead Used to retrieve data sent to the server as part of the POST request Appendix E

The Response Object The Response object is responsible for sending the server's output to the client. In this sense, the Response object is the counterpart to the Request object: the Request object gathers information from both the client and the server, and the Response object sends, or resends, the information to the client by writing to the HTTP data stream.

Collection Description Cookies Values of all the cookies to send to the browser.

Properties Description Buffer Determines whether the page is to be buffered until complete CacheControl Determines whether proxy servers are allowed to cache the output generated by ASP Char set Appends the name of the character set to the content-type header Content Type HTTP content type (e.g. "Text/HTML") for the response Expires Number of minutes between caching and expiry, for a page cached on the browser ExpiresAbsolute Explicit date and/or time of expiry for a page cached on a browser IsClientConnected Indicates whether the client has disconnected from the server PICS Adds the value of a PICS label to the pies-label field of the response header Status Value of the HTTP status line returned by the server

Methods Description AddHeader Adds or changes a value in the HTML header AppendToLog Adds text to the web server log entry for this request BinaryWri te Sends text to the browser without character-set conversion Clear Erases any buffered HTML output End Stops processing the page and returns the current result Flush Sends buffered output immediately Redirect Instructs the browser to connect to a different URL Write Writes variable values, strings etc. to the current page as a string

766 Active Server Pages Object Model

The Response interface elements can be divided into groups, like this:

Response Items Description Write, BinaryWrite Inserts information into a page Cookies Sends cookies to the browser Redirect Redirects the browser Buffer, Flush, Clear, End Buffers the page as it is created Expires,ExpiresAbsolute,ContentType, Sets the properties of a page AddHeader,Status,CacheContol,PICS,Charset IsClientConnected Checks the client connection

The Application Object

Each application is represented by an instance of the Application object. This object stores variables and objects for application-scope usage. It also holds information about any currently-active sessions.

Collections Description

Contents Contains all of the items added to the application through script commands StaticObjects Contains all of the objects added to the application with the tag

Methods Description

Lock Prevents other clients from modifying application properties Unlock Allows other clients to modify application properties

Events Description

OnStart Occurs when a page in the application is first referenced On End Occurs when the application ends, i.e. when the web server is stopped

767 Appendix E

The Session Object The Session object is used to keep track of an individual browser as it navigates through the web site.

Collections Description Contents Contains all of the items added to the session through script commands StaticObjects Contains all of the objects added to the session with the tag

Method Description

Abandon Destroys a Session object and releases its resources

Properties Description CodePage Sets the codepage that will be used for symbol mapping LCID Sets the locale identifier SessioniD Returns the session identification for this user Timeout Sets the timeout period for the session state for this application, in minutes

Events Description OnStart Occurs when the server creates a new session OnEnd Occurs when a session is abandoned or times out

The Server Object

The main use of the Server object is to create components.

Property Description Script Timeout Length of time a script can run before an error occurs

Methods Description CreateObject Creates an instance of an object or server component HTMLEncode Applies HTML encoding to the specified string MapPath Converts a virtual path into a physical path URLEncode Applies URL encoding including escape chars to a string

768 Active Server Pages Object Model

The ObjectContext Object When we use MTS (Microsoft Transaction Server) to manage a transaction, we have the functionality within our script to commit (or to abort) the transaction. This functionality is provided by the Obj ectContext object.

Methods Description Set Complete Declares that the script knows no reason for the transaction not to complete. If all participating components call Set Complete, then the transaction will complete. SetComplete overrides any previom SetAbort method that has been called in the script SetAbort Aborts a transaction initiated by an ASP

Events Description OnTransactionCommit Occurs after a transacted script's transaction commits

OnTransactionAbort Occurs if the transaction is aborted

769

Microsoft ActiveX Data Objects 2.0 Library Reference

In this section we will find the objects, methods, and properties necessary for ADO transactions using VB. This should aid the programmer when connections are to be made to a database from within a web application.

All properties are read/write unless otherwise stated.

Objects

Name Description

Command A Command object is a definition of a specific command that you intend to execute against a data source.

Connection A Connection object represents an open connection to a data store. Error An Error object contains the details about data access errors pertaining to a single operation involving the provider.

Errors The Errors collection contains all of the Error objects created in response to a single failure involving the provider. Appendix F

Name Description Field A Field object represents a column of data within a common data type. Fields A Fields collection contains all of the Field objects of a Recordset object. Parameter A Parameter object represents a parameter or argument associated with a Command object based on a parameterized query or stored procedure. Parameters A Parameters collection contains all the Parameter objects of a Command object. Properties A Properties collection contains all the Property objects for a specific instance of an object. Property A Property object represents a dynamic characteristic of an ADO object that is defined by the provider. Recordset A Recordset object represents the entire set of records from a base table or the results of an executed command. At any time, the Recordset object only refers to a single record within the set as the current record.

Command Object

Methods

Name Returns Description Cancel Cancels execution of a pending Execute or Open call. CreateParameter Parameter Creates a new Parameter object. Execute Recordset Executes the query, SQL statement, or stored procedure specified in the CornrnandText property.

Properties

Name Returns Description ActiveConnection Variant Indicates to which Connection object the command currently belongs. CommandText String Contains the text of a command to be issued against a data provider.

772 Microsoft ActiveX Data Objects 2.0 Library Reference

Name Returns Description CommandTimeout Long Indicates how long to wait, in seconds, while executing a command before terminating the command and generating an error. Default is 30.

CommandType CommandTypeEnum Indicates the type of Command object.

Name String Indicates the name of the Command object.

Parameters Parameters Contains all of the Parameter objects for a Command object. Prepared Boolean Indicates whether or not to save a compiled version of a command before execution.

Properties Properties Contains all of the Property objects for a Command object.

State Long Describes whether the Command object is open o closed. Read only.

Connection Object

Methods

Name Returns Description BeginTrans Integer Begins a new transaction. Cancel Cancels the execution of a pending, asynchronous Execute or Open operation. Close Closes an open connection and any dependant objects. CommitTrans Saves any changes and ends the current transaction. Execute Recordset Executes the query, SQL statement, stored procedure, o provider specific text. Open Opens a connection to a data source, so that commands can be executed against it. OpenSchema Recordset Obtains database schema information from the provider. RollbackTrans Cancels any changes made during the current transaction and ends the transaction.

773 Appendix F

Properties

Name Returns Description Attributes Long Indicates one or more characteristics of a Connection object. Default is 0. CommandTimeout Long Indicates how long, in seconds, to wait while executing a command before terminating the command and generating an error. The default is 30. ConnectionString String Contains the information used to establish a connection to a data source. ConnectionTimeout Long Indicates how long, in seconds, to wait while establishing a connection before terminating the attempt and generating an error. Default is 15. Cursor Location CursorLocationEnum Sets or returns the location of the cursor engine. DefaultDatabase String Indicates the default database for a Connection object. Errors Errors Contains all of the Error objects created in response to a single failure involving the provider. IsolationLevel IsolationLevelEnum Indicates the level of transaction isolation for a Connection object. Write only.

Mode ConnectModeEnum Indicates the available permissions for modifyin~ data in a Connection. Properties Properties Contains all of the Property objects for a Connection object. Provider String Indicates the name of the provider for a Connection object. State Long Describes whether the Connection object is open or closed. Read only. Version String Indicates the ADO version number. Read only.

774 Microsoft ActiveX Data Objects 2.0 Library Reference

Events

Name Description BeginTransComplete Fired after a BeginTrans operation finishes executing. CommitTransComplete Fired after a Commit Trans operation finishes executing. ConnectComplete Fired after a connection starts. Disconnect Fired after a connection ends. ExecuteComplete Fired after a command has finished executing. Info Message Fired whenever a ConnectionEvent operation completes successfully and additional information is returned by the provider. RollbackTransComplete Fired after a RollbackTrans operation finished executing. Will Connect Fired before a connection starts. WillExecute Fired before a pending command executes on the connection.

Error Object

Properties

Name Returns Description Description String A description string associated with the error. Read only. HelpContext Integer Indicates the ContextiD in the help file for the associated error. Read only. Help File String Indicates the name of the help file. Read only. NativeError Long Indicates the provider-specific error code for the associated error. Read only. Number Long Indicates the number that uniquely identifies an Error object. Read only. Source String Indicates the name of the object or application that originally generated the error. Read only.

SQLState String Indicates the SQL state for a given Error object. It is a five• character string that follows the ANSI SQL standard. Read only.

775 Appendix F

Errors Collection

Methods

Name Returns Description

Clear Removes all of the Error objects from the Errors collection.

Refresh Updates the Error objects with information from the provider.

Properties

Name Returns Description

Count Long Indicates the number of Error objects in the Errors collection. Read only.

Item Error Allows indexing into the Errors collection to reference a specific Error object. Read only.

Field Object

Methods

Name Returns Description

AppendChunk Appends data to a large or binary Field object.

GetChunk Variant Returns all or a portion of the contents of a large or binary Field object.

Properties

Name Returns Description ActualSize Long Indicates the actual length of a field's value. Read only.

Attributes Long Indicates one or more characteristics of a Field object.

776 Microsoft ActiveX Data Objects 2.0 Library Reference

Name Returns Description DataFormat Variant Write only. DefinedSize Long Indicates the defined size of the Field object. Write only.

Name String Indicates the name of the Field object. NumericScale Byte Indicates the scale of numeric values for the Field object. Write only.

OriginalValue Variant Indicates the value of a Field object that existed in the record before any changes were made. Read only. Precision Byte Indicates the degree of precision for numeric values in the Field object. Read only. Properties Properties Contains all of the Property objects for a Field object.

Type DataTypeEnum Indicates the data type of the Field object. UnderlyingValue Variant Indicates a Field object's current value in the database. Read only.

Value Variant Indicates the value assigned to the Field object.

Fields Collection

Methods

Name Returns Description

Append Appends a Field object to the Fields collection.

Delete Deletes a Field object from the Fields collection.

Refresh Updates the Field objects in the Fields collection.

777 Appendix F

Properties

Name Returns Description

Count Long Indicates the number of Field objects in the Fields collection. Read only.

Item Field Allows indexing into the Fields collection to reference a specific Field object. Read only.

Parameter Object

Methods

Name Returns Description AppendChunk Appends data to a large or binary Parameter object.

Properties

Name Returns Description Attributes Long Indicates one or more characteristics of a Parameter object. Direction ParameterDirectionEnum Indicates whether the Parameter object represents an input parameter, an output parameter, or both, or if the parameter is a returr value from a stored procedure. Name String Indicates the name of the Parameter object. NumericScale Byte Indicates the scale of numeric values for the Parameter object. Precision Byte Indicates the degree of precision for numeric values in the Parameter object. Properties Properties Contains all of the Property objects for a Parameter object. Size Long Indicates the maximum size, in bytes or characters, of a Parameter object.

778 Microsoft ActiveX Data Objects 2.0 Library Reference

Name Returns Description

Type DataTypeEnum Indicates the data type of the Parameter object. Value Variant Indicates the value assigned to the Parameter object.

Parameters Collection

Methods

Name Returns Description

Append Appends a Parameter object to the Parameters collection.

Delete Deletes a Parameter object from the Parameters collection.

Refresh Updates the Parameter objects in the Parameters collection.

Properties

Name Returns Description

Count Long Indicates the number of Parameter objects in the Parameters collection. Read only.

Item Parameter Allows indexing into the Parameters collection to reference a specific Parameter object. Read only.

Properties

Methods

Name Returns Description

Refresh Updates the Property objects in the Properties collection with the details from the provider.

779 Appendix F

Properties

Name Returns Description

Count Long Indicates the number of Property objects in the Properties collection. Read only. Item Property Allows indexing into the Properties collection to reference a specific Property object. Read only.

Property Object

Properties

Name Returns Description Attributes Long Indicates one or more characteristics of a Property object. Name String Indicates the name of the Property object. Read only. Type DataTypeEnum Indicates the data type of the Property object. Value Variant Indicates the value assigned to the Property object.

Recordset Object

Methods

Name Returns Description AddNew Creates a new record for an updateable Recordset object. Cancel Cancels execution of a pending asynchronous Open operation. Cancel Batch Cancels a pending batch update.

780 Microsoft ActiveX Data Objects 2.0 Library Reference

Name Returns Description CancelUpdate Cancels any changes made to the current record, or to a new record prior to calling the Update method.

Clone Recordset Creates a duplicate Recordset object from an existing Recordset object.

Close Closes the Recordset object and any dependent objects. CompareBookmarks CompareEnum Compares two bookmarks and returns an indication of the relative values. Delete Deletes the current record or group of records. Find Searches the Recordset for a record that matches the specified criteria.

GetRows Variant Retrieves multiple records of a Recordset object into an array.

GetString String Returns a Recordset as a string. Move Moves the position of the current record in a Recordset. MoveFirst Moves the position of the current record to the first record in the Recordset. Move Last Moves the position of the current record to the last record in the Recordset. MoveNext Moves the position of the current record to the next record in the Recordset. MovePrevious Moves the position of the current record to the previous record in the Recordset.

NextRecordset Recordset Clears the current Recordset object and returns the next Recordset by advancing through a series of commands.

Open Opens a Recordset.

Requery Updates the data in a Recordset object by re• executing the query on which the object is based. Resync Refreshes the data in the current Recordset object from the underlying database.

Save Saves the Recordset to a file.

781 Appendix F

Name Returns Description

Supports Boolean Determines whether a specified Recordset object supports particular functionality. Update Saves any changes made to the current Recordset object. UpdateBatch Writes all pending batch updates to disk.

Properties

Name Returns Description AbsolutePage PositionEnum Specifies in which page the current record resides. AbsolutePosition PositionEnum Specifies the ordinal position of a Recordset object's current record. ActiveCommand Object Indicates the Command object that created the associated Recordset object. Read only. ActiveConnection Variant Indicates to which Connection object the specified Recordset object currently belongs. BOF Boolean Indicates whether the current record is before the first record in a Recordset object. Read only. Bookmark Variant Returns a bookmark that uniquely identifies the current record in a Recordset object, or sets the current record to the record identified by a valid bookmark.

CacheSize Long Indicates the number of records from a Recordset object that are cached locally in memory. CursorLocation CursorLocationEnum Sets or returns the location of the cursor engine CursorType CursorTypeEnum Indicates the type of cursor used in a Recordset object.

782 Microsoft ActiveX Data Objects 2.0 Library Reference

Name Returns Description DataMember String Specifies the name of the data member to retrieve from the object referenced by the DataSource property. Write only. DataSource Object Specifies an object containing data to be represented as a Recordset object. Write only EditMode EditModeEnum Indicates the editing status of the current record. Read only. EOF Boolean Indicates whether the current record is after thE last record in a Recordset object. Read only. Fields Fields Contains all of the Field objects for the current Recordset object. Filter Variant Indicates a filter for data in the Recordset. Lock Type LockTypeEnum Indicates the type of locks placed on records during editing. MarshalOptions MarshalOptionsEnum Indicates which records are to be marshaled back to the server. MaxRecords Long Indicates the maximum number of records to return to a Recordset object from a query. Default is zero (no limit). PageCount Long Indicates how many pages of data the Recordset object contains. Read only. PageSize Long Indicates how many records constitute one page in the Recordset. Properties Properties Contains all of the Property objects for the current Recordset object. Record Count Long Indicates the current number of records in the Recordset object. Read only. Sort String Specifies one or more field names the Recordset is sorted on, and the direction of the sort. Source String Indicates the source for the data in a Recordset object.

783 Appendix F

Name Returns Description State Long Indicates whether the recordset is open, closed, or whether it is executing an asynchronous operation. Read only. Status Integer Indicates the status of the current record with respect to match updates or other bulk operations. Read only. StaylnSync Boolean Indicates, in a hierarchical Recordset object, whether the parent row should change when the set of underlying child records changes. Read only.

Events

Name Description EndOfRecordset Fired when there is an attempt to move to a row past the end o the Recordset. FetchComplete Fired after all the records in an asynchronous operation have been retrieved into the Recordset. FetchProgress Fired periodically during a length asynchronous operation, to report how many rows have currently been retrieved. FieldChangeComplete Fired after the value of one or more Field object has been changed. MoveComplete Fired after the current position in the Recordset changes. RecordChangeComplete Fired after one or more records change. RecordsetChangeComplete Fired after the Recordset has changed. WillChangeField Fired before a pending operation changes the value of one or more Field objects.

WillChangeRecord Fired before one or more rows in the Recordset change. WillChangeRecordset Fired before a pending operation changes the Recordset. WillMove Fired before a pending operation changes the current position in the Recordset.

784 Microsoft ActiveX Data Objects 2.0 Library Reference

Method Calls Quick Reference

Command

Command. Cancel Parameter = Command.CreateParameter(Name As String, Type As DataTypeEnum, Direction As ParameterDirectionEnum, Size As Integer, [Value As Variant]) Recordset = Command.Execute(RecordsAffected As Variant, Parameters As Variant, Options As Integer)

Connection Integer = Connection.BeginTrans Connection.Cancel Connection.Close Connection.CommitTrans Recordset = Connection.Execute(CommandText As String, RecordsA!fected As Variant, Options As Integer) Connection.Open(ConnectionString As String, UseriD As String, Password As String, Options As Integer) Recordset = Connection.OpenSchema(Scherna As SchemaEnum, [Restrictions As Variant], [SchernaiD As Variant]) Connection.RollbackTrans

Errors Errors.Clear Errors.Refresh

Field Field.AppendChunk(Data As Variant) Variant= Field.GetChunk(Length As Integer)

Fields Fields.Append(Name As String, Type As DataTypeEnum, DefinedSize As Integer, Attrib As FieldAttributeEnum) Fields.Delete(Index As Variant) fields.Refresh

Parameter Parameter.AppendChunk(Val As Variant)

785 Appendix F

Parameters Parameters.Append(Object As Object) Parameters.Delete(Index As Variant) Parameters.Refresh

Properties

Properties .Refresh

Recordset Recordset.AddNew([FieldList As Variant], [Values As Variant]) Recordset. Cancel Recordset.CancelBatch(AffectRecords As AffectEnum) Recordset.Cance1Vpdate Recordset = Recordset.Clone(LockType As LockTypeEnum) Recordset.Close CompareEnum = Recordset.CompareBookmarks(Bookmarkl As Variant, Bookmark2 As Variant) Recordset.Delete(AffectRecords As AffectEnum) Recordset.Find(Criteria As String, SkipRecords As Integer, SearchDirection As SearchDirectionEnum, [Start As Variant]) Variant= Recordset.GetRows(Rows As Integer, [Start As Variant], [Fields As Variant]) String= Recordset.GetString(StringFormat As StringFormatEnum, NumRows As Integer, ColumnDelimeter As String, RowDelimeter As String, NullExpr As String) Recordset.Move(NumRecords As Integer, [Start As Variant]) Recordset .MoveFirst Recordset.MoveLast Recordset.MoveNext Recordset .MovePrevious Recordset = Recordset.NextRecordset([RecordsAffected As Variant]) Recordset.Open(Source As Variant, ActiveConnection As Variant, CursorType As CursorTypeEnum, LockType As LockTypeEnum, Options As Integer) Recordset.Requery(Options As Integer) Recordset.Resync(AffectRecords As AffectEnum, ResyncValues As ResyncEnum) Recordset.Save(FileName As String, PersistFormat As PersistFormatEnum) Boolean= Recordset.Supports(CursorOptions As CursorOptionEnum) Recordset.Vpdate([Fields As Variant], [Values As Variant]) Recordset.VpdateBatch(AffectRecords As AffectEnum)

786 Microsoft ActiveX Data Objects 2.0 Library Reference

787

VBScript Reference

Array Handling

Dim- declares a variable. An array variable can be static, with a defined number of elements, or dynamic, and can have up to 60 dimensions. ReDim- used to change the size of an array variable which has been declared as dynamic. Preserve- keyword used to preserve the contents of an array being resized (otherwise data is lost when ReDim is used). If you need to use this then you can only re-dimension the rightmost index of the array. Erase - reinitializes the elements of a fixed-size array or empties the contents of a dynamic array:

DJ.m arEmp oyees ReDim arEmployees (9,1) arEmployees (9,1) = "Phil" ReDim arEmployees (9,2) 'loses the contents of element (9,1) arEmployees (9,2) = "Paul" ReDim Preserve arEmployees (9,3) 'preserves the contents of (9,2) arEmployees (9,3) = "Smith" Erase arEmployees •now we are back to where we started - empty array

LBound- returns the smallest subscript for the dimension of an array. Note that arrays always start from the subscript zero so this function will always return the value zero. UBound- used to determine the size of an array:

Dim strCUstomers (10, S) ~ntSizeFirst • UBound (strCustomers, 1) 'returns SizeFirst = 10 intSizeSecond = UBound strCustomeXJL,_.,2._._ ___' returns SizeSecond.l_....f":...._;;S,______

The actual number of elements is always one greater than the value returned by UBound because the array starts from zero. Appendix G Assignments

Let- used to assign values to variables (optional). Set -used to assign an object reference to a variable.

Let intNumberOfDays = 365

Set txtMyTextBox = txtcontrol txtMyTextBox.Value = "Hello World"

Constants

Empty- an empty variable is one that has been created, but has not yet been assigned a value. Nothing- used to remove an object reference: Set txtMyTextBox = txtATextBox 'assigns object reference Set txtMyTextBox = Nothing 'removes object reference

Null- indicates that a variable is not valid. Note that this isn't the same as Empty. True- indicates that an expression is true. Has numerical value -1. False- indicates that an expression is false. Has numerical value 0.

Error constant

Constant Value vbObjectError &h80040000

System Color constants

Constant Value Description vbBlack &hOOOOOO Black vbRed &hFFOOOO Red vbGreen &hOOFFOO Green vbYellow &hFFFFOO Yellow vbBlue &hOOOOFF Blue vbMagenta &hFFOOFF Magenta vbCyan &hOOFFFF Cyan vbWhite &hFFFFFF White

790 VBScript Reference

Comparison constants

Constant Value Description vbBinaryCompare 0 Perform a binary comparison. vbTextCompare 1 Perform a textual comparison.

Date and Time constants

Constant Value Description vbSunday 1 Sunday vbMonday 2 Monday vbTuesday 3 Tuesday vbWednesday 4 Wednesday vbThursday 5 Thursday vbFriday 6 Friday vbSaturday 7 Saturday vbFirstJan1 1 Use the week in which January 1 occurs (default). vbFirstFourDays 2 Use the first week that has at least four days in the new year. vbFirstFullWeek 3 Use the first full week of the year. vbUseSystem 0 Use the format in the regional settings for the computer. vbUseSystemDayOfWeek 0 Use the day in the system settings for the first weekday.

Date Format constants

Constant Value Description

vbGeneralDate 0 Display a date and/ or time in the format set in the system settings. For real numbers display a date and time. For integer numbers display only a date. For numbers less than 1, display time only. vbLongDate 1 Display a date using the long date format specified in the computer's regional settings. Table Continued on Following Page

791 Appendix G

Constant Value Description vbShortDate 2 Display a date using the short date format specified in the computer's regional settings. vbLongTime 3 Display a time using the long time format specified in the computer's regional settings. vbShortTime 4 Display a time using the short time format specified in the computer's regional settings.

Message Box Constants

Constant Value Description vbOKOnly 0 Display OK button only. vbOKCancel 1 Display OK and Cancel buttons. vbAbortRetryignore 2 Display Abort, Retry, and Ignore buttons. vbYesNoCancel 3 Display Yes, No, and Cancel buttons. vbYesNo 4 Display Yes and No buttons. vbRetryCancel 5 Display Retry and Cancel buttons. vbCritical 16 Display Critical Message icon. vbQuestion 32 Display Warning Query icon. vbExclamation 48 Display Warning Message icon. vbinformation 64 Display Information Message icon. vbDefaultButtonl 0 First button is the default. vbDefaultButton2 256 Second button is the default. vbDefaultButton3 512 Third button is the default. vbDefaultButton4 768 Fourth button is the default. vbApplicationModal 0 Application modal. vbSystemModal 4096 System modal.

String constants

Constant Value Description vbCr Chr (13) Carriage return only

vbCrLf Chr (13) & Carriage return and linefeed (Newline) Chr (10)

792 VBScript Reference

Constant Value Description vbFormFeed Chr (12) Form feed only vbLf Chr (10) Line feed only vbNewLine Newline character as appropriate to a specific platform vbNullChar Chr(O) Character having the value 0 vbNullString String having the value zero (not just an empty string) vbTab Chr(9} Horizontal tab vbVerticalTab Chr(ll) Vertical tab

Tristate constants

Constant Value Description TristateUseDefault -2 Use default setting TristateTrue -1 True TristateFalse 0 False

VarType constants

Constant Value Description vbEmpty 0 Uninitialized (default) vbNull 1 Contains no valid data vbinteger 2 Integer subtype vbLong 3 Long subtype vbSingle 4 Single subtype vbDouble 5 Double subtype vbCurrency 6 Currency subtype vbDate 7 Date subtype vbString 8 String subtype vbObject 9 Object vbError 10 Error subtype vbBoolean 11 Boolean subtype Table Continued on Following Page

793 Appendix G

Constant Value Description

vbVariant 12 Variant (used only for arrays of variants) vbDataObject 13 Data access object vbDecimal 14 Decimal subtype vbByte 17 Byte subtype vbArray 8192 Array

Control Flow For ... Next -executes a block of code a specified number of times: Dim intSalary (10) For intCounter = 0 to 10 intSalary (intCounter) 20000 Next

For Each . . . Next -repeats a block of code for each element in an array or collection: For Each Item In Request.QueryString("MyControl") Response.Write Item & "
" Next Do ... Loop- executes a block of code while a condition is true or until a condition becomes true. Note that the condition can be checked either at the beginning or the end of the loop: the difference is that the code will be executed at least once if the condition is checked at the end.

Do While strDayOfWeek <> "Saturday" And strDayOfWeek <> •sunday" MsgBox ("Get Up! Time for work") Loop Do MsgBox ("Get Up! Time for work")

Loop Until strDayOfWeek = "Saturday" Or strDayOfWeek "Sunday" We can also exit from a Do . . . Loop using Exit Do:

Do MsgBox ("Get Up! Time for work") If strDayOfWeek " "Sunday" Then Exit Do End If Loop Until strDayOfWeek = "Saturday"

If ... Then . .. Else- used to run various blocks of code depending on conditions: If intAge < 20 Then MsgBox ("You're just a slip of a thing!") Elseif intAge < 40 Then MsgBox ( "You' re in your prime ! ") Else MsgBox ( "You' re older and wiser") End If

794 VBScript Reference

Select Case-used to replace If ... Then ... Else statements where there are many conditions: Select Case intAge case 21,22,23,24,25,26 MsgBox ("You're in your prime") Case 40 MsgBox ("You're fulfilling your dreams") Case Else MsgBox ("Time for a new challenge") End Select

While . . . Wend- executes a block of code while a condition is true:

While strDayOfWeek <> "Saturday" AND strDayOfWeek <> "Sunday" MsgBox ("Get Up! Time for work") Wend

With- executes a series of statements for a single object:

With myDiv.style .posLeft = 200 .posTop "' 300 .color = Red End With

Functions VBScript contains several inbuilt functions that can be used to manipulate and examine variables. These have been subdivided into these general categories: 0 Conversion functions 0 Date/time functions 0 Math functions 0 Object management functions Q Script engine identification functions 0 String functions 0 Variable testing functions

For a full description of each function and the parameters it requires, see the Microsoft web site at http://msdn.microsoft.com/scripting/.

Conversion Functions

These functions are used to convert values in variables between different types:

Function Description

Abs Returns the absolute value of a number.

Asc Returns the numeric ANSI (or ASCII) code number of the first character in a string. Table Continued on Following Page

795 Appendix G

Function Description AscB As above, but provided for use with byte data contained in a string. Returns result from the first byte only. AscW As above, but provided for Unicode characters. Returns the Wide character code, avoiding the conversion from Unicode to ANSI. Chr Returns a string made up of the ANSI character matching the number supplied. ChrB As above, but provided for use with byte data contained in a string. Always returns a single byte. ChrW As above, but provided for Unicode characters. Its argument is a Wide character code, thereby avoiding the conversion from ANSI to Unicode. CBool Returns the argument value converted to a Variant of subtype Boolean. CByte Returns the argument value converted to a Variant of subtype Byte. CCur Returns the argument value converted to a Variant of subtype Currency COate Returns the argument value converted to a Variant of subtype Date. CDbl Returns the argument value converted to a Variant of subtype Double. Cint Returns the argument value converted to a Variant of subtype Integer. CLng Returns the argument value converted to a Variant of subtype Long CSng Returns the argument value converted to a Variant of subtype Single CStr Returns the argument value converted to a Variant of subtype String. Fix Returns the integer (whole) part of a number. If the number is negative, Fix returns the first negative integer greater than or equal to the number Hex Returns a string representing the hexadecimal value of a number. Int Returns the integer (whole) portion of a number. If the number is negative, Int returns the first negative integer less than or equal to the number. Oct Returns a string representing the octal value of a number. Round Returns a number rounded to a specified number of decimal places. Sgn Returns an integer indicating the sign of a number.

Date/Time Functions

These functions return date or time values from the computer's system clock, or manipulate existing values:

Function Description Date Returns the current system date. DateAdd Returns a date to which a specified time interval has been added.

796 VBScript Reference

Function Description DateDiff Returns the number of days, weeks, or years between two dates. DatePart Returns just the day, month or year of a given date. DateSerial Returns a Variant of subtype Date for a specified year, month and day. DateValue Returns a Variant of subtype Date. Day Returns a number between 1 and 31 representing the day of the month.

Hour Returns a number between o and 2 3 representing the hour of the day.

Minute Returns a number between 0 and 59 representing the minute of the hour.

Month Returns a number between 1 and 12 representing the month of the year. MonthName Returns the name of the specified month as a string. Now Returns the current date and time.

Second Returns a number between o and 59 representing the second of the minute. Time Returns a Variant of subtype Date indicating the current system time. TimeSerial Returns a Variant of subtype Date for a specific hour, minute, and second. Time Value Returns a Variant of subtype Date containing the time. Weekday Returns a number representing the day of the week. WeekdayName Returns the name of the specified day of the week as a string. Year Returns a number representing the year.

Math Functions These functions perform mathematical operations on variables containing numerical values:

Function Description Atn Returns the arctangent of a number. Cos Returns the cosine of an angle. Exp Returns e (the base of natural logarithms) raised to a power. Table Continued on Following Page

797 Appendix G

Function Description Log Returns the natural logarithm of a number. Randomize Initializes the random-number generator. Rnd Returns a random number. Sin Returns the sine of an angle. Sqr Returns the square root of a number. Tan Returns the tangent of an angle.

Miscellaneous Functions

Function Description Eval Evaluates an expression and returns a boolean result (e.g. treats x=y as an expression which is either true or false). Execute Executes one or more statements (e.g. treats x=y as a statement which assigns the value of y to x). RGB Returns a number representing an RGB color value

Object Management Functions These functions are used to manipulate objects, where applicable:

Function Description CreateObject Creates and returns a reference to an ActiveX or OLE Automation object. GetObject Returns a reference to an ActiveX or OLE Automation object. LoadPicture Returns a picture object.

Script Engine Identification These functions return the version of the scripting engine:

Function Description ScriptEngine A string containing the major, minor, and build version numbers of the scripting engine. ScriptEngineMajorVersion The major version of the scripting engine, as a number. ScriptEngineMinorVersion The minor version of the scripting engine, as a number. ScriptEngineBuildVersion The build version of the scripting engine, as a number.

798 VBScript Reference

String Functions

These functions are used to manipulate string values in variables:

Function Description Filter Returns an array from a string array, based on specified filter criteria. Format Currency Returns a string formatted as currency value. FormatDateTime Returns a string formatted as a date or time. FormatNumber Returns a string formatted as a number. Format Percent Returns a string formatted as a percentage. InStr Returns the position of the first occurrence of one string within another. InStrB As above, but provided for use with byte data contained in a string. Returns the byte position instead of the character position. InstrRev As InStr, but starts from the end of the string. Join Returns a string created by joining the strings contained in an array. LCase Returns a string that has been converted to lowercase. Left Returns a specified number of characters from the left end of a string. LeftB As above, but provided for use with byte data contained in a string. Uses that number of bytes instead of that number of characters. Len Returns the length of a string or the number of bytes needed for a variable. LenB As above, but is provided for use with byte data contained in a string. Returns the number of bytes in the string instead of characters. LTrim Returns a copy of a string without leading spaces. Mid Returns a specified number of characters from a string. MidB As above, but provided for use with byte data contained in a string. Uses that numbers of bytes instead of that number of characters. Replace Returns a string in which a specified substring has been replaced with another substring a specified number of times. Right Returns a specified number of characters from the right end of a string. RightB As above, but provided for use with byte data contained in a string. Uses that number of bytes instead of that number of characters. RTrim Returns a copy of a string without trailing spaces. Space Returns a string consisting of the specified number of spaces. Table Continued on Following Page

799 Appendix G

Function Description Split Returns a one-dimensional array of a specified number of substrings. StrComp Returns a value indicating the result of a string comparison. String Returns a string of the length specified made up of a repeating character. StrReverse Returns a string in which the character order of a string is reversed. Trim Returns a copy of a string without leading or trailing spaces. UCase Returns a string that has been converted to uppercase.

Variable Testing Functions These functions are used to determine the type of information stored in a variable:

Function Description IsArray Returns a Boolean value indicating whether a variable is an array. IsDate Returns a Boolean value indicating whether an expression can be converted to a date. Is Empty Returns a Boolean value indicating whether a variable has been initialized. IsNull Returns a Boolean value indicating whether an expression contains no valid data IsNumeric Returns a Boolean value indicating whether an expression can be evaluated as a number. IsObject Returns a Boolean value indicating whether an expression references a valid ActiveX or OLE Automation object. TypeName Returns a string that provides Variant subtype information about a variable. VarType Returns a number indicating the subtype of a variable.

Variable Declarations Class- Declares the name of a class, as well as the variables, properties, and methods that comprise the class. Const- Declares a constant to be used in place of literal values. Dim- declares a variable.

Error Handling On Error Resume Next- indicates that if an error occurs, control should continue at the next statement. Err- this is the error object that provides information about run-time errors.

Error handling is very limited in VBScript and the Err object must be tested explicitly to determine if an error has occurred.

800 VBScript Reference

Input/Output

This consists of Msgbox for output and Input Box for input:

MsgBox

This displays a message, and can return a value indicating which button was clicked.

MsgBox "Hello There",20,"Hello Message","c:\windcws\M Help.hlp",123

H e llo M essHg e 1!2 1

t!elp ]

The parameters are: "Hello There"- this contains the text of the message (the only obligatory parameter). 2 0 - this determines which icon and buttons appear on the message box. "Hello Message"- this contains the text that will appear as the title of the message box. "c: \windows \MyHelp. hlp" -this adds a Help button to the message box and determines the help file that is opened if the button is clicked. 123- this is a reference to the particular help topic that will be displayed if the Help button is clicked.

The value of the icon and buttons parameter is determined using the following tables:

Constant Value Buttons vbOKOnly 0

vbOKCancel 1 Cancel

vbAbortRetryingnore 2 Be try Ignore

vbYesNoCancel 3 No Cancel

vbYesNo 4 _t:4o

vbRetryCancel 5 Cancel

801 Appendix G

Constant Value Buttons vbDefaultButton1 0 The first button from the left is the default. vbDefaultButton2 256 The second button from the left is the default. vbDefaultButton3 512 The third button from the left is the default. vbDefaul tBut ton4 768 The fourth button from the left is the default.

Constant Value Description Icon vbCritical 16 Critical Message

vbQuestion 32 Questioning Message

vbExclamation 48 Warning Message !

vbinformation 64 lnforma tional Message

Constant Value Description vbApplicationModal 0 Just the application stops until user clicks a button. vbSystemModal 4096 On Win16 systems the whole system stops until user clicks a button. On Win32 systems the message box remains on top of any other programs.

To specify which buttons and icon are displayed you simply add the relevant values. So, in our example we add together 4 + 0+ 16 to display the Yes and No buttons, with Yes as the default, and the Critical icon. If we used 4 + 2 56 + 16 we could display the same buttons and icon, but have No as the default. You can determine which button the user clicked by assigning the return code of the MsgBox function to a variable: intButtonClicked; MagBox ("Hello There",35,"Hello Message")

Notice that brackets enclose the MsgBox parameters when used in this format. The following table determines the value assigned to the variable intButtonClicked:

Constant Value Button Clicked Constant Value Button Clicked vbOK 1 OK vbignore 5 Ignore vbCancel 2 Cancel vbYes 6 Yes vbAbort 3 Abort vbNo 7 No vbRetry 4 Retry

802 VBScri pt Reference lnputBox This accepts text entry from the user and returns it as a string.

strName = InputBox ("Please enter your name","Login","John Smith",500,500)

. VBScr~pt Lo '" EJ P1e.,se enter vour ""me

The parameters are: "Please enter your name"- this is the prompt displayed in the input box. 11 Login 11 -this is the text displayed as the title of the input box.

11 John Smith 11 - this is the default value displayed in the input box. 50 0 - specifies the x position of the input box in relation to the screen. 50 o - specifies the y position of the input box in relation to the screen.

As with the MsgBox function, you can also specify a help file and topic to add a Help button to the input box.

Procedures

Call -optional method of calling a subroutine. Function- used to declare a function. Sub -used to declare a subroutine.

Other Keywords

Rem- old style method of adding comments to code (it's now more usual to use an apostrophe (' ).) Opt ion Explicit - forces you to declare a variable before it can be used (if used, it must appear before any other statements in a script).

Visual Basic Run-time Error Codes

The following error codes also apply to VBA code and many will not be appropriate to an application built completely around VBScript. However, if you have built your own components then these error codes may well be brought up when such components are used.

803 Appendix G

Code Description Code Description 3 Return without GoSub 502 Object not safe for scripting 5 Invalid procedure call 503 Object not safe for initializing 6 Overflow 504 Object not safe for creating 7 Out of memory 505 Invalid or unqualified reference 9 Subscript out of range 506 Class not defined 10 This array is fixed or 1001 Out of memory temporarily locked

11 Division by zero 1002 Syntax error 13 Type mismatch 1003 Expected ':' 14 Out of string space 1004 Expected ';' 16 Expression too complex 1005 Expected '(' 17 Can't perform requested 1006 Expected')' operation 18 User interrupt occurred 1007 Expected ']' 20 Resume without error 1008 Expected '{' 28 Out of stack space 1009 Expected ')' 35 Sub or Function not 1010 Expected identifier defined 47 ToomanyDLL 1011 Expected'=' application clients

48 Error in loading DLL 1012 Expected 'If' 49 Bad DLL calling 1013 Expected 'To' convention

51 Internal error 1014 Expected 'End' 52 Bad ffie name or number 1015 Expected 'Function' 53 File not found 1016 Expected 'Sub' 54 Bad file mode 1017 Expected 'Then' 55 File already open 1018 Expected 'Wend' 57 Device 1/0 error 1019 Expected 'Loop' 58 File already exists 1020 Expected 'Next' Table Continued on Following Page

804 VBScript Reference

Code Description Code Description 59 Bad record length 1021 Expected 'Case' 61 Disk full 1022 Expected 'Select' 62 Input past end of file 1023 Expected expression 63 Bad record number 1024 Expected statement 67 Too many files 1025 Expected end of statement 68 Device unavailable 1026 Expected integer constant 70 Permission denied 1027 Expected 'While' or 'Until'

71 Disk not ready 1028 Expected 'While', 'Until' or end of statement 74 Can't rename with 1029 Too many locals or arguments different drive 75 Path/File access error 1030 Identifier too long 76 Path not found 1031 Invalid number 91 Object variable not set 1032 Invalid character

92 For loop not initialized 1033 Un-terminated string constant 93 Invalid pattern string 1034 Un-terminated comment 94 Invalid use of Null 1035 Nested comment 322 Can't create necessary 1036 'Me' cannot be used outside of a temporary file procedure 325 Invalid format in resource 1037 Invalid use of 'Me' keyword file 380 Invalid property value 1038 'loop' without 'do' 423 Property or method not 1039 Invalid 'exit' statement found 424 Object required 1040 Invalid 'for' loop control variable 429 OLE Automation server 1041 Variable redefinition can't create object 430 Class doesn't support OLE 1042 Must be first statement on the line Automation

432 File name or class name 1043 Cannot assign to non-ByVal not found during OLE argument Automation operation

805 Appendix G

Code Description Code Description 438 Object doesn't support this 1044 Cannot use parentheses when property or method calling a Sub 440 OLE Automation error 1045 Expected literal constant 442 Connection to type library 1046 Expected 'In' or object library for remote process has been lost. Press OK for dialog to remove reference 443 OLE Automation object 1047 Expected 'Class' does not have a default value 445 Object doesn't support this 1048 Must be defined inside a Class action 446 Object doesn't support 1049 Expected Let or Set or Get in named arguments property declaration 447 Object doesn't support 1050 Expected 'Property' current locale setting 448 Named argument not 1051 Number of arguments must be found consistent across properties specification 449 Argument not optional 1052 Cannot have multiple default property I method in a Class 450 Wrong number of 1053 Class initialize or terminate do not arguments or invalid have arguments property assignment 451 Object not a collection 1054 Property set or let must have at least one argument 452 Invalid ordinal 1055 Unexpected 'Next' 453 Specified DLL function 1056 'Default' can be specified only on not found 'Property' or 'Function' or 'Sub' 454 Code resource not found 1057 'Default' specification must also specify 'Public' 455 Code resource lock error 1058 'Default' specification can only be on Property Get Table Continued on Following Page

806 VBScript Reference

Code Description Code Description 457 This key is already 5016 Regular Expression object expected associated with an element of this collection 458 Variable uses an OLE 5017 Syntax error in regular expression Automation type not supported in Visual Basic

462 The remote server 5018 Unexpected quantifier machine does not exist or is unavailable 481 Invalid picture 5019 Expected ']' in regular expression 500 Variable is undefined 5020 Expected ')' in regular expression 501 Cannot assign to variable 5021 Invalid range in character set 32811 Element not found

For more information about VBScript, visit Microsoft's VBScript site, at http://msdn.microsoft.com/scripting.

807

Index

vs. SQL Server, 655 Symbols AccessBLOB COM object, 608, 609 &, 99,113 Action fields  , 99 deletes, processing , 379 columns, blank spaces, 699 updates, processing, 370 HTML Tables, empty cells, 635 requestforms,352 *, SELECT statement, 111 action stored procedures, 562

operating systems, 36 single field and datum, 305 overview, 12 syntax, 304 PHP, compared, 30 adFldLong parameter Attributes property, restrictions, 29 519, 523 server requirements, 37 adLockBatchOptimistic lock, 280 server-side solutions, 26 adLockOptimistic lock, 279, 313, 317, 327 benefits, 26 adLockPessimistic lock, 276 ServerVariables function, 342 adLockReadOnly lock, 275, 327 source code, protection, 27 ADO, 11, 18, 225, 230 specialised software, integration, 27 ADO verbs, 687 stored procedures, 543 ADO verbs, defining, 493 troubleshooting, 231 Command object, 227 common errors, 232 refreshing, 643 debugging, 236 common errors, 470 error page, 231, 237 DSN, 471 test-runs, 249 number, 470 viewing variable values, 247 Connection object, 187, 227 universal readability, 27 creating instance, 229 web servers, 36 DSN connection, establishing, 230 ActiveConnection parameter, 270 error handling, 441 ActiveConnection property, 487, 551 recordsets, returning, 230 connection string I object, 489 connection pooling, 205 ActiveX COM objects, 225 cookies, 414 Access header DSN determining end of, 608 setting up, 64 stripping, 604 DSN-less connections, 195 AccessBLOB COM object, 608, 609 common errors, 197 BLOB data, retrieving from Access error object database, 606 error syntax, 452 building, 604 properties, 440 InStr () function, 608 error trapping, 266, 443 registering on web server, 606 Errors collection, 20, 267, 440 logging ActiveX Data Objects ADO errors, 458 Fields collection, 20, 164 See ADO HTML Tables, empty cells, 635 adAffectAll implicit connections, 188 Update method, recordsets, 318 installing, 63 adAffectCurrent Memo fields bug, 618 Delete method, recordsets, 320 move commands, 329 Update method, recordsets, 318 MSDN Library adClipString Platform SDK, 473 GetString method, 171 music store example, 24 adCmdText object model, 18 in-line SQL statements, 505 Command object, 19, 486 AddNew method Connection object, 19 arrays, 306 recordset object, 19 cDate function, 305 OLE-DB, interaction, 225 common errors, 306 providers, 226 IsDate function, 305 Parameters collection, 20 recordsets, 304 performance testing, 662 displaying results, 670 PerfTest page, 672

810 Index

Properties collection, 20 ASPUpLoad record sets uploading BLOB data, 611, 615 methods, 293 asterisk (*), SELECT statement, 111 multiple, 637 Attributes property, 488 record count, 633 Avg() function, 344 Recordset object, 227 RDS, 228 restrictions, 29 B server requirements, 37 server-side solutions, 26 BatchOptimistic, lock type, 319 benefits, 26 beta testing, 237 SQL data, 625 BETWEEN... AND keywords, WHERE clause, date validation, 632 121 filtering invalid characters, 628 BGCOLOR property, 514 Null values, 626 binary data troubleshooting, 231 storage, 598 Connection string, 235 Bit fields, 660 cursor types, 233 debugging, 236 BLOB fields (Binary Large OBject), 597, 660 permissions, 235 Access header, 598 test-runs, 249 BLOB data, retrieving, 606 update batch, 318 stripping header, 604 version history, 61 MIME types, 602 ADO Errors collection, 492, 550 storage in Access, 598 adOpenDynamic cursor, 273 stored file names (the Easy Way), 599 inaccurate record count, 633 stored in database (the Hard Way), 601 adOpenForwardOnly cursor, 270, 662 advantage over Easy Way, 617 saving blob to recordset, 617 inaccurate record count, 633 uploading, 611 adOpenKeySet cursor, 272 ASPUpLoad, 611, 615 record count, 633 FILE form field, 612 adOpenStatic cursor, 274 FileUp object, 615 record count, 633 multipart/form-data, 611 aggregate functions, 344 SAFileUp, 615 Alert function, 348, 701 SAFileUP, 611 ampersand, 99, 113 stored file names (the Easy Way), 613 stored in database (the Hard Way), 615 Append method, 488 browsers appending parameters, 501 cookie storage, 404 AppendChunk method, 488 business rules adFldLong parameter Attributes property, stored procedures, 544 519, 523 Mid function, 524 stuffing data, 519, 525 c variant variables, appending, 519 Application object, ASP, 13 Cancel method, 487 Application_OnStart procedure cascade delete referential integrity, 130 Global.asa, 688 cascade update referential integrity, 130 arguments, 111 CCur function from recordsets, 86 data to currency conversions, 353, 371 ASP cDate function see Active Server Pages AddNew method, 305

811 Index

CGI properties, 487 see Common Gateway Interface ActiveConnection, 487 checkboxes, 347, 354, 365, 704 CommandText, 487 Chilli Soft CommandTimeout, 487 CommandType, 487 Chilli!ASP, 29 Name, 487 clauses, 111 Prepared, 487 Clear method State, 487 clearing pre-existing errors, 437 refreshing, 643 client-side solutions SQL server, receiving return values, 497 benefits and drawbacks, 28 stored procedures, 658 CLng function structure, 486 long data type, converting to, 354 when necessary, 489 ColdFusion, 30 when useful, 502 colspan property, TD tag, 514 CommandText property, 487, 496 ColumnDelimiter, 171, 174 altering database structure, 493 COM objects passing parameters to stored procedures, Access header, determining end of, 608 551 AccessBLOB COM object, 608, 609 CommandTimeout property, 487, 494 BLOB data, retrieving from Access CommandType property, 487, 496 database, 606 in-line SQL statements, 505 building, 604 options, 493 called by ASP, 225 stored procedures handles, 225 executing, 513 instances, 225 specifying, 500 InStr () function, 608 text string commands, 523 registering on web server, 606 Common Gateway Interface, 15 combo box CGI scripts, 16 loading disadvantages, 16 Sailors web site, 699, 700 processor time, 652 OPTION elements, adding, 362 compilation errors, 451 Command object, 19, 547, 562 Component Object Model as Source parameter, 264 see COM objects enumeration values, 268 concatenation, 113 error handling, 267 Connection object, 19, 187, 487, 569 CreateParameter () function, 659 Access, passing value to action stored creating, 355, 493, 551 procedure, 570 Data Definition Language, 486 ADO errors collection, 441 database, modifying, 490 connections, making, 189 defined, 227 common errors, 190 executing, 355, 501 syntax, 189 methods, 487 creating, 492 Cancel, 487 creating instance, 229 CreateParameter, 487 defined, 227 Execute, 487 DSN connection, establishing, 230 OLE-DB, 228 Execute method, 569 overview, 486 parameters, passing, 572 parameters collection, 659 implicit/ explicit connections, 188 passing values multiple recordsets, 192 to Access select stored procedure, 547 oConn.Open parameter to SQL Server select stored procedure, 553 punctuation, 196

812 Index

recordsets, returning, 230 CreateParameter method, 487 schemas,207,208 CreateParameter object common mistakes, 213 appending parameters to Parameters SQL server, passing values to action stored collection, 507 procedure, 573 arguments, 501 connection pooling, 205, 652 CStr function connection properties, 206 converting to strings, 371 connection strings Null values, 627 connection objects, compared, 259, 489 cursor types, 662 connections dynamic, 273, 326 closing and re-opening, 668 Forward Only, 270, 662 consumers common errors, 233 defined, 226 Find method errors, 303 ContentType property, Response object keyset driven, 272 MIME types, 603 static, 274 cookies, 403 cursors, as synonym of recordsets, 111 as instruments of evil, 407 see also recordsets ASP page, 404 CursorType parameter, 270 cookie checks, 421 adOpenDynamic cursor, 273 Cookie Munger, 407 adOpenForwardOnly cursor, 270 cookie-denial, 406 adOpenKeySet cursor, 272 cookie-less visitors, 420 adOpenStatic cursor, 274 data held, 406 database look-up, 415 syntax, 415 D deleting, 420 data, 342 expiration date, 404, 413, 418 Data Definition Language, 486 getting, 414 Data Shape, 201 in simple ASP reading, 408 Data Source Name writing, 411 see DSN keys,409 Data Source object multiple, 409 defined, 228 purpose, 403 data stores, 17 resetting, 419, 424 data validation errors, 450 response buffer, 426 databases Sailors web site, 689, 692, 705 Access vs. SQL Server, 655 deleting, 710 ADO errors, 82 setting, 408, 415 indexes, 657 size limits, 405 look-up using cookies, 415 storage location, 404 schemas, 207 tampered cookies, 405 arguments, 210 user preferences, setting, 409 common mistakes, 213 using, 407 technique, 208 ways in which lost or ruined, 405 security, 82 with ADO and database, 414, 419 structure, modifying, 489 with simple ASP column, adding, 490 column, dropping, 495 writing, 408 date values, 353 Count property, 488 DCOM (Distributed COM), 228

813 Index

Delete error handling recordsets, 320 ADO error handling, 266, 443 Delete method, 488 ADO Errors collection, 440 DELETE statement, 372 logging ADO errors, 458 criteria parameter, 373 ASP I ADO common errors, 232 delete confirmation, 376 clearing pre-existing errors, 437 delete, processing, 377 common ADO errors, 470 hidden fields, 375 DSN, 471 tablename parameter, 373 number, 470 security, 471 development errors, 441 common scripting errors, 467 error page, 453 script timeout, 470 Direction property, 488 compilation errors, 451 Directory Services, 201 continuing execution, 466 DSN custom errors, 437 ADO connection, establishing, 189, 230 data validation errors, 450 common errors, 232 debugging, 236 creating, 81 development errors, 441, 453 for Access database, 65 displaying errors, 457 for SQL database, 67 DSN-less connections, 195 error messages, 465 common errors, 197 production errors, 462 ODBC drivers, accessing, 227 Recordset object, 256 practical tip, 73 run-time errors, 451 setting up, 64 select statement errors, 449 types, 65 stored procedures, 545 dynamic image tags test-runs, 249 from stored file name, 600 trapping, 437 Dynamic Link Libraries (DLLs), 225 true errors, 446 dynamic web pages Event Viewer, 654 business impact, 12 Execute method, 487 Connection object, 569 parameters, passing, 572 E explicit connections, 188 making, 189 End method common errors, 190 errors, 492 syntax, 189 entity names,  , 99 multiple recordsets, 192 EOF property reading records, 95 common errors, 95 F Error object, 492 fields, 13 ADO tables, building, 169 error syntax, 452 properties, 440 fields collection, 164 creating, 443 File DSN, 65 SQL Server, 579 FILE form field VB Script uploading BLOB files, 612 error syntax, 452 FileSystemObject object, 457 properties and methods, 436 FileUp object run-time errors, 451 BLOB data, uploading, 615 Form collection, accessing values from form

814 Index

fields, 615 SQL statements, incorporating data into, 132 SaveAsBlob method, 617 hard coding, 133 UserFileName property, 614 user-entered dates, 138 filter property user-entered numbers, 133, 137 user-entered text, 137 recordsets, 304 styles, 410 Find method, 299, 326 HTTP,228 syntax, 299 HTTPS, 228 traps, 303 For ... Next loops tables, 92 common mistakes, 93 foreign key fields, 130 liS form fields see Internet Information Server (IIS) FILE form field, 612 image source tag, 599 Form collection, FileUpObject, 615 implicit connections, 188 POST method IN keyword, WHERE clause, 122 uploading, 611 include files, 683, 725 FROM statement, 512 ADO error handling, 457 FrontPage ADO verbs, 687 Personal Web Server (PWS), 48 Sailors database, 712, 718 authentication checks, 684 common functions, 685 G database, connecting to GetString method, recordsets, 171 Sailors database, 699, 729 databases, connecting to, 685 common errors, 172 parameters databases, disconnecting from, 685 ColumnDelimiter, 171, 174 error handling, 683 records, number of, 171 menu options, 686 RowDelimiter, 171 Index Server, 201 StringFormat code, 171 indexes, 657 Global.asa, 688 INNER JOIN statement, 130 Sailors web site, 735 inner joins, 130, 512 H input boxes handles Sailors web site, 698 COM objects, 225 input placeholders, 505 hard coding, 133 INSERT statement hidden fields, 361, 726 adding, 341 DELETE statement, 375 custom functions, combined with, 632 INSERT statement, 346 INSERT INTO, 353 UPDATE statement, 361 processing data, 349 HTML pages records, inserting into tables, 343 commentstag,259 unspecified columns, 343 data from recordsets, 84 instances HTML Tables, empty cells, 635 COM objects, 225  , 635 instantiation, 83 list boxes, filling from database, 160 InStr function common errors, 164 BLOB fields, use in, 608 finding characters in strings, 365 single and double quote searches, 629

815 Index

Internet Explorer LockType parameter, 275 PWS installations, problems, 56, 58, 59 adLockBatchOptimistic lock, 280 Internet Information Server (liS) adLockOptimistic lock, 279 ADO, installing, 61 adLockPessimistic lock, 276 ASP, 36 adLockReadOnly lock, 275 installing record count, 633 on NT Server, 37 login process, 689, 714 on Windows 2000, 43 cookies, 689, 692 Internet Publishing login form, 693 native OLEDB provider, 201 login verification, 710 Internet Server Application Program registration, new users, 695 Interfaces (ISAPI) processor time, 652 irregular data, 597 M BLOB data, 598 Max() function, 344 uploading, 612 IS API MDAC see Internet Server Application Program see Microsoft Data Access Components Interfaces (ISAPI) (MD A C) IsDate function Memo fields, 519, 617, 660 AddNew method, 305, 312 Microsoft Data Access Components date validation, 632 (MDAC), 229 IsNull function, 626 ADO, installing, 62 fields, checking for null values, 450 Mid function, appending chunks, 524 Item method, 488 MIME (Multipurpose Internet Mail Extensions) types, 602 headers, 602 J Response object, 602 Min() function, 344 Java Server Pages, 30 Move command, 329 Jet 4.0, 201 Move methods JOINs, 130 common errors, 233 INNER JOIN, 130 MoveFirst method, 89, 100, 329 Sailors web site, 735 when to use, 88 MoveLast method, 329 K MoveNext method, 89, 100, 233, 328 recordsets, advancing, 514 keys, 13 MovePrevious method, 329 keywords, 111 MS Access Upsizing tools, 656 MS query grid see query grid L MSDN Library ASP errors, 473 Len function Platform SDK, ADO errors, 473 field validation, 348 multipart/form-data list boxes, 426 uploading BLOB data, 611

816 Index

N Open Database Connectivity (ODBC), 15, 230 Name property, 487, 488 drivers, 15, 227 Network Monitor, 655 DSN, 227 NextRecordset routine, 641 history, 226 NotePad native OLEDB providers, switching to, 202 PWS installations, problems, 57 OLE-DB, 17, 227 NT Server schema, 210 ADO, installing, 61 Open method ASP, 36 parameters, 255 installing, 38 OpenTextFile method Internet Information Server {liS}, installing, parameters, 457 37 option buttons (radio buttons) NT Workstation Sailors web site, 699 ASP, 36 OPTION elements NULL data combo boxes, 362 errors, 235, 626 Option Explicit, 83 table warping, 99 Options parameter, 283 NumericScale property, 488 Oracle native OLEDB provider, 201 ORDER BY clause, 117, 512 0 ASC/DESC keywords, 117 ObjectContext object, ASP, 13 common errors, 118 oConn.Open parameter orphaned records, 130 punctuation, 196 owner prefixes, 575 ODBC stored procedures, 555 see Open Database Connectivity (ODBC) OLAP p see Online Analytical Processing (OLAP) OLE (Object Linking and Embedding) Package object Objects, 597 Access, storing different file types, 598 OLE-DB, 17, 230 Parameter objects Command object, 228 appending to Parameters collection, 501, 506 Data Source object, 228 methods native providers, 200 AppendChunk, 488 when to use, 202 properties providers, 17,226 Attributes, 488 schema, 210 Direction, 488 relational databases, 227 Name, 488 Rowset object, 228 NumericSca/e, 488 Precision, 488 Session object, 228 setting, 513 On Error Resume Next, 436 Size, 488 one-to-many relationships, 130 Type, 488 Online Analytical Processing (OLAP), 201 Value, 488 ONMOUSEOUT variables, declaring, 522 Sailors login form, building, 694 parameters ONMOUSEOVER ActiveConnection parameter, 270 Sailors login form, building, 694 adFldLong parameter Attributes property, 519

817 Index

appending to Parameters collection, 507 ASP, 36 avoiding creation of parameter object, 508 benefits, 47 Connection object, passing parameters installing using, 572 from NT option pack, download, 51 CursorType parameter, 270 on Windows 98, Win98CD, 48 adOpenDynamic cursor, 273 sources, 47 adOpenForwardOnly cursor, 270 typical problems, Win9x, 55 adOpenKeySet cursor, 272 ASP page, opens in wrong application, 55 adOpenStatic cursor, 27 4 ASP roadmap, 61 date, 518 default page, 59 LockType parameter, 275 FTP message, loss of, 57 adLockBatchOptimistic lock, 280 IE 4.01, cannot see, 59 adLockOptimistic lock, 279 IE changes URL, 58 adLockPessimistic lock, 276 IE connects to internet, 56 adLockReadOnly lock, 275 MTS not installed, 60 numeric, 518 NotePad adds .txt, 57 TCP/IP, 58 object, 255 of Recordset PHP, 30 Options parameter, 283 placeholders, 500 passing in SQL statement, 502 input, 505 Source parameters, 256, 257, 559 POST method Command object, 264 SQL statements, 260 uploading, 611 stored procedure, 261 Precision property, 488 table names, 257 Prepared property, 487, 494 specifying, for stored procedures, 568 processor bottlenecks, 652 stored procedures, passing to, 509, 518, 546, processor throttling, 652 658 providers, 17 string, 518 defined, 226 stuffing, 519 native OLEDB providers, 200 from recordsets, 85 Data Shape, 201 variant variables, appending, 519 Directory Services, 201 Parameters collection Index Server, 201 methods Internet Publishing, 201 Jet 4.0, 201 Append, 488 ODBC Drivers, 201 Delete, 488 OLAP, 201 Item, 488 Oracle, 201 Refresh, 488, 644 Persisted Recordset, 201 properties Remote Provider, 201 Count, 488 Site Server Search, 201 parent/child relationships, 130 SQL Server, 201 passwords, 82 when to use, 202 Performance Monitor, 654 PWS performance testing, 662 see Personal Web Server (PWS) analyzing results, 671 displaying results, 670 PerfTest page Q testing, 672 performance queries 201 Persisted Recordset, see stored procedures Web Server (PWS), 46 Personal Query Analyser, 661 61 ADO, installing, Index Analysis, 662

818 Index query grid, 125 connections, 188 arguments, 125 explicit, 192 sorting, 127 multiple recordsets, 192 SQL statements, making, 125 data as argument in function, 86 tables, adding, 125 common mistakes, 86 testing, 128 data in expressions, 85 common mistakes, 86 quotes data in tables, 91, 167, 171 converting single quote marks, 234, 686, 730 data, editing, 328 errors, 234, 628 defined, 111 single I double, when to use, 137 delete, 320, 325 delete confirm, 324 syntax, 320 R filter property, 304 radio buttons, 413 Find method, 299 Raise method syntax, 299 custom errors, 437 traps, 303 RDS GetString method, 171 common errors, 172 see Remote Data Services HTML page, writing data to, 84 records, 13, 89 instantiation, 83 counters, 98 common mistakes, 84 INSERT statement, 343 list boxes, filling, 161 MoveFirst method, 89, 100 common errors, 164 MoveNext method, 89, 100 locking, 327, 559 moving through records, 89, 100 methods, 91, 293 reading with EOF, 95 supported methods, 294 common errors, 95 MoveFirst method, 88, 100 updating, 356 MoveNext method, 100 recordset object, 19, 556, 558 multiple, 637 defined, 227 NextRecordset routine, 641 errors, 256 Open method, 83, 559 Open method opening, 559 parameters, 255 with SQL statements, 111 passing values to Access select stored preparation, 81 procedure, 556 common errors, 82 passing values to SQL Server select stored database structure, 82 procedure, 560 DSN, 81 recordsets user ID and password, 82 AddNew method, 304 record count, 633 alternative syntax, 305 records, navigation, 328 arrays, 306 returning, 230 common errors, 306 SampleMultiRecordset stored procedure, Optimistic Lock type, 308 638 single field and datum, 305 schema, 208 syntax, 304 State property values, 638 adLockOptimistic lock, 313, 317 Supports method, 296 advancing, 514 syntax, 82 closing, 230 Update method, 304, 309, 313 common mistakes, 233 alternative syntax, 314 common scripting errors, 469 syntax, 313 UpdateBatch, 318 variables, stuffing data, 85

819 Index referential integrity, 130 Rs.Open cascade delete, 130 commenting out when troubleshooting, 143 cascade update, 130 run-time errors, 451 orphaned records, 130 Refresh Parameters collection method, 644 s Refresh method, 488 SAFileUP relational databases, 13, 130 uploading BLOB data, 611, 615 fields, 13 Sailors database, 21 keys, 13 ASP and ADO, improvements, 22 OLE-DB, 227 columns, queries, 14 adding, 490 records, 13 dropping, 495 SQL, 14 include files tables, 13 to connect to database, 685 Remote Data Services (RDS), 228 to disconnect from database, 685 Remote Provider return value from SQL server, 497 native OLEDB provider, 201 Sailors web site, 682 request forms, 352 add new club form, 344 Action fields, 352 processing Add, 349 data to currency conversions, 353 ADO query error, 441 long data type, 354 boat registration page, 720 Request object, ASP, 13 converting single quote marks, 730 hidden fields, 726 ServerVariables function, 342 include files, connecting to database, 729 reserved words, 236 validations, 728 response buffer Cookie Setter, 411 cookies, 426 cookies, 409 Response object, 13 resetting, 420 ContentType property, MIME type header, cookies using ASP-ADO, 415 602 Default.asp page End method, 492, 550 cookies, 692 Response.BinaryWrite delete club form, 373 binary data to browser, 603 processing delete, 377 Response. End display boats page, 716 in troubleshooting SQL statements, 144 recordset fields, inserting, 719 Response.Write, 84 display ranking page, 732 INNER JOIN, 735 common mistakes, 85 fields, 165 error messages, Sailors web site, 692 GetString method, 174 in troubleshooting SQL statements, 142 Home Page Using preference, 412 return code, 576 include files, 683 from SQL Server, 576 ADO verbs, 687 stored procedures, 576 authentication checks, 684 RETURN statement, 582 common functions, 685 return values, 499, 576 error handling, 683 Access, limitations of, 586 menu options, 686 retrieving, 580, 583 login process, 689 RowDelimiter, 171 Alert function, 701 Rowset object Default.asp page, 690 error messages, 692 closing, 230 defined, 228

820 Index

login form, building, 693 Task manager, 654 ONMOUSEOUT, 694 Wcat, 655 ONMOUSEOVER, 694 server-side solutions LoginVerification.asp page, 710 benefits, 26 Register.asp page, 695 debugging, easier, 27 combo box, building, 699 source code, protection, 2 7 input boxes, 698 specialised software, integration, 27 option buttons (radio buttons), 699 universal readability, 27 RegistrationConfirmation.asp page, 702 drawbacks, 27 checkboxes, 704 increased server load, 28 705 cookies, multiple trips, 28 SQL strings, executing, 705 ServerVariables function WelcomeBack.asp page, 707 Session variable, 708 Request object, ASP, 342 options page, 714 Session object record sets ASP, 13 AddNew method, 306, 309 avoiding storing ADO objects, 660 Is Date function, 312 OLE-DB session object Find method, 300 defined, 228 Update method, 314 sessions session timeouts, 738 session timeouts, 738 Set Preference form, 410 Session variable, 708 Source parameter, 258 Session_OnStart procedure, 688 table procedures, 167 SET keyword updating forms, 357 UPDATE statement, 356 processing update, 366 Site Server Search, 201 SampleMultiRecordset stored procedure Size property, 488 multiple recordsets, 640 Source parameters, 256, 257, 559 schemas, 207 Command object, 264 arguments, 210 enumeration values, 268 common mistakes, 213 error handling, 267 defined,207 Options parameter, 283 parameters, 207 SQL statements, 260 technique, 208 stored procedures, 261 SELECT statement, 114, 512 table names, 257 asterisk (*), 111 Split function common errors, 115 information, extracting from strings, 460 errors, 449 SQL, 14 WHERE clause, 362 asterisk(*), 111 select stored procedures, 547 common scripting errors, 468 simple, 542 concatenation, 113 Server object, 13 common errors, 114 CreateObject method, 83 data, truncation error, 235 servers date validation, 632 connection pooling, 652 DELETE statement, 372 processor bottlenecks, 652 filtering invalid characters, 628 processor throttling, 652 flavors, 110 tools HTML forms, data from, 132 Event Viewer, 654 hard coding, 133 Network Monitor, 655 user-entered dates, 138 Performance Monitor, 654 user-entered numbers, 133, 137 System Monitor (Windows 9x), 653 user-entered text, 137

821 Index

INSERT statement, 341, 343 parameters, 568 introduction, 109 Query Analyser, 661 JOINs, 130 query grid long statements, 113 sorting, 127 Null values, 625 testing, 128 ORDER BY clause, 117 recordset object, passing values using, 560 ASC/DESC keywords, 117 remote administration, 655 common errors, 118 return code, 576 query grid, 125 return values to Command object, 497 arguments, 125 schema queries, listing, 211 tables, adding, 125 stored procedures, 657 recordsets, opening, 111 table structure, 617 reserved words, 236 Text fields, 617 SELECT statements, 114 bug, 618 common errors, 115 true errors, 446 single quotes, errors, 234 values, retrieving, 580, 583 single/ double quotes, when to use, 137 RETURN statement, 582 SQL statements as Source parameters, 260 vs. Access, 655 syntax, 110 SQL statements arguments, 111 stored procedures, compared, 541 clauses, 111 State property, 487 keywords, 111 State property values troubleshooting, 142, 242 commenting out lines, 143, 242, 244 recordsets, 638 hard coding variables, 146 stored procedures, 657 nonexistent data, 147 Access, limitations of, 586 Response.End, 144 action stored procedures, 562 Response. Write statement, 142 Command object, passing values to Access, 563 retyping/rebuilding SQL statement, 145 Command object, passing values to SQL Server, saving original, 145 566 simplifying statement and adding clauses, 145 Connection object, passing values to Access, 570 UPDATE statement, 341, 356,369 Connection object, passing values to SQL Server, WHERE clause, 119 573 IS NOT operator, 121 return values, retrieving, 580, 583 LIKE/NOT LIKE comparison operators, 121 applications, 543 numeric comparison operators, 120 Active Server Pages, 543 simple, 120 business rules, 544 to find specific record, 121 as Source parameter, 261 values, types, 120 benefits, 541 SQL queries flexibility, 543 optimizing, 661 maintainability, 542 SQL Server performance, 542 Command object reusability, 542 passing values to action stored procedure, 566 Command object, 547 passing values using, 553 creating, 499, 548, 553 Connection object, passing values to action defined, 541 stored procedure, 573 efficiency, 671 data storage, 599 execute permission, granting, 553 DSN, creating, 67 executing, 500, 513 error object, 579 multiple recordsets, 638 MIME types, 602 owner prefixes, 555, 575 native OLEDB provider, 201 owners, specifying, 569

822 Index

parameterized, 542 text string commands, 523 parameterized Access stored queries, 669 textarea fields, 348 parameters, specifying in SQL Server, 568 TH tag, 514 passing parameters, 509 Transact-SQL, 668 passing values, 546, 725 traps record sets stored procedures, 545 building, 734 TristateFalse, 457 returning, 712 TristateMixed, 457 select stored procedures, 547 TristateTrue, 457 simple select stored procedures, 542 TristateUseDefault, 457 traps, 545 troubleshooting SQL, 142 values, retrieving, 575, 580, 583 hard coding variables, 146 return code, 576 commenting out lines, 143 RETURN statement, 582 string date types, 353 nonexistent data, 147 string parameters, 518 Response.End, 144 stuffing parameters, 519, 525 Response. Write statement, 142 adFldLong parameter Attributes property, retyping/rebuilding SQL statement, 145 519 saving original, 145 from recordsets, 85 simplifying statement and adding clauses, variants, 519 145 Sum() function, 344 Type property, 488 Supports method, 296 large text parameters, 523 recordsets, 294 System DSN, 65 u System Monitor (Windows 9x), 653 update batch, 318 BatchOptimistic, lock type, 319 T syntax, 318 table procedures, 167 Update method loops, 170 recordsets, 309, 313 tables, 13, 347 UPDATE statement forms, 361 data from recordsets, 91, 167 GetString method, 171, 173 SET keyword, 356 INSERT statement, 343 update processing, 369 For ... Next loops, 92 update/insert, distinction between, 341 common mistakes, 93 updating changed fields only, 370 HTML Tables, empty cells, 635 WHERE clause, 356 table names as Source parameters, 257 updating, 356 tags, 91 User DSNs, 65 warping by NULLS, 99 user ID, 82  , 99 Task manager, 654 TCP/IP v PWS installations, problems, 58 Value property, 488 TD tag, 514 variables text boxes declaring, 551 building, 364 dimensioning, 83 Text fields, 519, 617, 660 Option Explicit, 83

823 Index

stuffing data from recordsets, 85 displaying text only, 365 viewing values, 247 WHERE clause, 119, 512 variants, 559 BETWEEN ... AND keywords, 121 stuffing fields, 519 common mistakes, 234 VB script cookies, 415, 419 Alert function, 348 Delete method, recordsets, 320 Len function, 348 DELETE statement, 373, 380 Response. Write IN keyword, 122 common mistakes, 85 IS NOT operator, 121 VB Script LIKE/NOT LIKE comparison operators, 121 common errors, 467 logical operators, 124 error object login verification, 712 error syntax, 452 numeric comparison operators, 120 properties and methods, 436 simple, 120 run-time errors, 451 to find specific record, 121 InStr function, 628 UPDATE statement, 356 IsNull function, 626 values, types, 120 Timer () function, 662 Windows 2000 Visual lnterdev ADO, installing, 61 (PWS), 47 Personal Web Server ASP, 36 installing, 43 Internet Information Server (liS), installing, w 43 WAM Personal Web Server (PWS), 48 see Web Application Manager (WAM) Windows 98 Wcat Personal Web Server (PWS), 47 see Web capacity analysis tool (Wcat) installation, 48 Web Application Manager (WAM) Windows 9x processor time, 652 ADO, installing, 61 Web capacity analysis tool (Wcat), 655 Windows NT web site URLs see NT

824 Index

825