CHAPTER 8

Publishing Information and Applications

Preparing Information for Publishing
Publishing Dynamic Applications
Publishing Information and Using a Database

Internet Information Server can publish both information and applications. This means that your Web site can contain anything from static pages of information to interactive applications. You can also find and extract information from, and insert information into, databases.

This chapter explains how to:

- Prepare your computer and your information for publishing.

- Install and use interactive applications on your computer.

- Publish by using an Open Database Connectivity (ODBC)–compliant data source.

# Preparing Information for Publishing

Most Web pages are formatted in Hypertext Markup Language (HTML). HTML files are simple ASCII text files with codes embedded to indicate formatting and hypertext links. HTML specifications are changing constantly. You should probably review the HTML specifications (available on the Internet) to fully plan your HTML pages.

## Authoring HTML Files

You can use any text editor, such as Notepad or Write, to create and edit your HTML files; but you will probably find an HTML editor, such as Microsoft® FrontPage™ or Internet Assistant for Microsoft® Word, easier to use.

You use the HTML editor or other system to create HTML files, which can include hyperlinks to other files on your system. If you want to include images or sounds, you will also need appropriate software to create and edit those files.

## Publishing HTML and Other File Formats

Your files can include images and sound. You can even create links to Microsoft® Office files or to almost any other file format. Remote users must have the correct viewing application to view non-HTML files. For example, if you know that all remote users will have Microsoft Word, you can include links to Microsoft Word .doc files. The user can click the link and the document will appear in Word on the user’s computer.

Once you have created your information in HTML or other formats, you can either copy the information to the default directory InetPub\Wwwroot, or you can change the default home directory to the directory containing your information.

## MIME Type Configuration

If your Web site includes files that are in multiple formats, your computer must have a Multipurpose Internet Mail Extension (MIME) mapping for each file type. If MIME mapping on the server is not set up for a specific file type, browsers may not be able to retrieve the file. See the Windows NT registry for the default MIME mappings.

To configure additional MIME mappings, start the Registry Editor (Regedt32.exe) and open

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Services\InetInfo\Parameters\MimeMap

Add a REG_SZ value for the MIME mapping required for your computer with the following syntax:

`<mime type>,<filename extension>,<unused parameter>,<gopher type>`

For example:

`text/html,htm,/unused,1
image/jpeg,jpeg,/unused,5`

The string associated with the value (that is, the value content) should be blank. The default entry with the file-name extension specified as an asterisk (*) is the default MIME type used when a MIME mapping does not exist. For example, to handle a request for the file Current.vgr when the the file-name extension .vgr is not mapped to a MIME type, your computer will use the MIME type specified for the asterisk extension, which is the type used for binary data.Usually, this will cause browsers to save the file to disk.

## Including Other Files with the Include Statement

You can add common information into HTML files just before sending the files to users. This feature is handy for including the same text on each HTML page, such as copyright information or a link to the home page.

The format of the include statement is:

`<!--#include file="value"-->`

The value can contain a relative path or the full path, from the home directory of your WWW service.

For example, to include a link to your home page in each HTML document:

1. Create the file Linkhome.htm, which contains the HTML codes you want to repeat; for example, a button to your home page. The file would contain HTML code that looks similar to this:

``

<A HREF="/homepage.htm"><IMG SRC="/images/button_h.gif"></A>

2. Use the file-name extension .stm when you create your Web pages (rather than .htm or .html).

Notes The .stm extension tells Internet Information Server that there is an include statement in the file. If you name the file with an .htm or .html extension, the include statement will be ignored.

Using .stm files may affect performance. Therefore, use this extension only when necessary.

However, in the Windows NT registry, you can change the default .stm extension to any extension you want, except for .htm or .html. For details, see the ServerSideIncludesExtension registry key in Chapter 10, “Configuring Registry Entries.”

3. In each .stm file, use an include file statement where you want the repeated information to appear. For example:

``

You can return to: <!--#include file="/linkhome.htm"--> at any time

Note that all paths are relative to the WWW home directory and can include virtual directories.

# Publishing Dynamic Applications

One of the most exciting features you get when you use Microsoft Internet Information Server is the ability to develop applications or scripts that remote users start by clicking HTML links or by filling in and sending an HTML form. Using programming languages such as C or Perl, you can create applications or scripts that communicate with the user in dynamic HTML pages.

## Creating the Applications or Scripts

Interactive applications or scripts can be written in almost any 32-bit programming language, such as C or Perl, or as Windows NT batch files (which have the .bat or .cmd file-name extension). When you write your applications or script you can use one of two supported interfaces, Microsoft Internet Server Application Programming Interface (ISAPI) or Common Gateway Interface (CGI). Documentation for ISAPI is available from Microsoft by subscription to the Microsoft Developer Network (MSDN). You can find an introduction to CGI later in this chapter; CGI information readily accessible by way of the Internet. Batch files can issue any command valid at the command prompt.

Applications that use ISAPI are compiled as dynamic-link libraries (DLLs) that are loaded by the WWW service at startup. Because the programs are resident in memory, ISAPI programs are significantly faster than applications written to the CGI specification.

### ISAPI Perl Available for Download

Hip, Inc., the independent software vendor that develops Perl for Win32 platforms, has developed a version of Perl that runs as an ISAPI application. This means that Perl server scripts can run much faster than before by taking advantage of the in-process model of ISAPI. An unsupported release of ISAPI Perl is now available for download at http://www.perl.hip.com/. More information is available on that WWW site. Please use the perlis@mail.hip.com e-mail alias to ask questions or send feedback, especially if you have existing Perl scripts.

### Internet Server API

ISAPI for Windows NT can be used to write applications that Web users can activate by filling out an HTML form or clicking a link in an HTML page on your Web site. The remote application can then take the user-supplied information and do almost anything with it that can be programmed, and then return the results in an HTML page or post the information in a database.

ISAPI can be used to create applications that run as DLLs on your Web server. If you have used Common Gateway Interface (CGI) scripts before, you will find that the ISAPI applications have much better performance because your applications are loaded into memory at server run-time. They require less overhead because each request does not start a separate process.

Another feature of ISAPI allows pre-processing of requests and post-processing of responses, permitting site-specific handling of Hypertext Transfer Protocol (HTTP) requests and responses. ISAPI filters can be used for applications such as customized authentication, access, or logging.

You can create very complex sites by using both ISAPI filters and applications. ISAPI extensions can also be combined with the Internet Database Connector to create highly interactive sites.

For complete information about programming with ISAPI, see the Microsoft Win32 BackOffice Software Development Kit (SDK), available from MSDN. See the introductory chapter of this guide, “Before You Begin,” for further information about obtaining the ISAPI SDK.

### Common Gateway Interface

Common Gateway Interface (CGI) is a set of specifications for passing information between a client Web browser, a Web server, and a CGI application. A client Web browser can start a CGI application by filling out an HTML form or clicking a link in an HTML page on your Web server. As with ISAPI, the CGI application can take the information the client Web browser supplies and do almost anything that can be programmed, then return the results of the application in an HTML page, or post the information to a database. Because simple CGI applications are often written using scripting languages such as Perl, CGI applications are sometimes referred to as “scripts.”

Microsoft Internet Information Server can use most 32-bit applications that run on Windows NT and conform to the CGI specifications.

The following figure illustrates how a browser, a server, and a CGI application exchange information by using CGI. The rest of this section discusses this five-part process.

#### Client Sends Request

A client browser can make a CGI request to a server by either of two methods:

GET

The client appends data to the URL it passes to the server.

POST

The client sends data to the server by way of the HTTP message data field, thereby overcoming size limitations inherent to the GET method.

The client initiates a CGI process by clicking any of the following on an HTML page:

- A hypertext link that runs the script directly.

- The “Submit” button in an HTML form.

- An inline object retrieved with the GET method.

- A search object (that is, one that uses the HTML tag ISINDEX).

#### Server Receives Request

The URL that the client browser sends to the server contains the name of the CGI script or application to be run. The server compares the file name’s extension to the server's Script Mapping registry key to determine which executable to launch. The server has Script Map entries for .cmd and .bat files, which launch Cmd.exe; and for .idc files, which launch the Internet Database Connector. To enable the server to launch a type of CGI application without an extension mapping, add an entry for that application type to the registry key. For example, to enable Perl scripts to run, add an entry like the following:

`.pl: REG_SZ: C:\RESKIT\PERL\BIN\PERL.EXE %s %s`

Where

- \Reskit\Perl\Bin\ is the directory containing the executable.

- Perl.exe is the command executed.

- the first %s is the translated path of the PERL script (the URL translated to a local path).

- The second %s is the query string (information in the URL) and is passed as a command line parameter only if the query string does not contain an equals (=) sign.

#### Server Passes Request to Application

The server passes information to the CGI application by means of environment variables, then launches the application. Some of these variables are server-related; the majority come from the client browser and relate either to the client browser or to the request it is sending. See the table of variables at the end of this chapter for a partial list of environment variables.

#### CGI Application Returns Data to Server

The application performs its processing. If it is appropriate, the application then writes data in a format the client can receive to the standard output stream (STDOUT). The application must follow a specific format in returning data:

1. The first line or lines contain server directives, and must contain the MIME content-type. Other server directives are Location (which redirects the client to, or returns, another document) and Status.

2. A blank line must follow server directives.

3. The data the application returns to the client follows the blank line.

#### Server Returns Data to Client

The server takes the data it receives from STDOUT and adds standard HTTP headers. It then passes the HTTP message back to the client.

For more information about CGI, refer to the CGI specifications at http://hoohoo.ncsa.uiuc.edu/cgi/.

### CGI and Internet Information Server

The WWW service supports the standard Common Gateway Interface (CGI) specification. However, you should be aware of the following, unique to the implementation of CGI on Internet Information Server:

- For this release, only 32-bit CGI applications work with the WWW service.

- The REMOTE_USER environment variable is not present when the user is logged in as the anonymous user (that is, when the Web server is accessed anonymously).

- All of the variables defined for ISAPI applications are passed to the CGI application as environment variables.

Note that CGI applications are typically stand-alone executables. This is in contrast to ISAPI applications, which are typically loaded as DLLs and are therefore server extensions. Thus, ISAPI applications offer enhanced performance when compared to CGI applications and scripts.

### Security Considerations for Executables

Common Gateway Interface (CGI) executables must be used with extreme caution to prevent potential security risk to the server. As a rule, give only Execute permission to virtual directories that contain CGI or Internet Server API (ISAPI) applications.

It is highly recommended that you configure script mapping. Script mapping ensures that the correct interpreter (Cmd.exe, for example) starts when a client requests an executable file.

World Wide Web content directories should be assigned Read permission only. Any executable files intended for downloading from Windows NT File System (NTFS) drives should have only Read access enabled.

You can run batch files as CGI executable files, but you must do so with extreme caution to prevent potential security risk to the server.

Note CGI executable files can also have the file-name extension .exe or .cgi.

### Execute Permission for ISAPI Applications

Internet Information Server opens ISAPI applications in the security context of the calling user. An access check is performed against that calling user. To restrict execution to selected users, NTFS permissions can be used with ISAPI applications such as the Internet Database Connector (IDC).

For example, to secure the IDC without putting permissions on the .idc file, you can grant NTFS Execute permission for Inetsrv\Httpodbc.dll to the appropriate users. Httpodbc.dll is the name of the ISAPI application DLL that implements the IDC. Then, whenever a user tries to execute the IDC, the server will check the permissions. Access will be allowed only if Execute permission has been granted for that user.

Note Once an ISAPI application has been loaded, it remains loaded until the WWW service is stopped. Internet Information Server does not track security descriptor changes after the ISAPI application has been loaded. If you change permissions for an ISAPI application after it has been loaded, you must stop and restart the WWW service before the change will take effect.

Take care in setting Access Control Lists (ACLs) on the Winnt directory and its subdirectories. Some ISAPI applications and databases require access to files and DLLs in these directories.

Note ISAPI application DLLs can have the file-name extension .dll or .isa.

## Installing Your Application on Internet Information Server

Once you have written your application or script, place it in the Scripts directory, a virtual directory for applications. This virtual directory has Execute access.

You must also ensure that every process started by your application is running by using an account with adequate permissions. If your application interacts with other files, the account you assign to your program must have the appropriate permissions to use those files. By default, applications run using the IUSR_computername account, which must have adminstrator and execute permissions for these application files.

## Running Your Application

If your application does not require data from the user, you will typically create a link to your application in a simple HTML file. If your application does require data from the user, you will probably use an HTML form. In other instances you can just send a Uniform Resource Locator (URL), usually containing data parameters, to invoke a program.

An HTML link to an application that does not require input from the user might look like the following example:

`http://www.company.com/scripts/catalog.exe`

where Scripts is the virtual directory for interactive applications.

If you are creating an application that requires input from the user, you will need to understand both HTML forms and how to use the forms with ISAPI or CGI. This information is widely available on the Internet or from other sources.

### Associating Interpreters with Applications

Because you have the flexibility to create applications in almost any programming language, Internet Information Server uses the file-name extension to determine which interpreter to invoke for each application. The default interpreter associations are listed below. You can use the Registry Editor to create additional associations.

Extension | Default Interpreter
.bat, .cmd | Cmd.exe
.idc | Httpodbc.dll
.exe, .com | System

### Security Implications

When you allow remote users to run applications on your computer, you run the risk of hackers attempting to break into your system. Microsoft Internet Information Server is configured by default to reduce the risk of malicious intrusion by applications in two important ways.

First, the virtual directory Scripts contains your applications. Only an administrator can add programs to a directory marked as an execute-only directory. Thus, unauthorized users cannot copy a malicious application and then run it on your computer without first gaining administrator access.

It is recommended that you grant read and execute permission for the IUSR_computername account on the directory associated with the virtual folder, and full control only to the administrator. Perl scripts (.pl file-name extension) and IDC files (.idc and .htx file-name extensions) need both read and execute permission. However, to prevent someone from installing an unsafe file on your server, do not grant write permission.

Second, if you have configured the WWW service to allow only anonymous logons, all requests from remote users will use the IUSR_computername account. By default, the IUSR_computername account is unable to delete or change files by using the Windows NT File System (NTFS) unless specifically granted access by an administrator. Thus, even if a malicious program were copied to your computer, it would be unable to cause much damage to your content because it will only have IUSR_computername access to your computer and files.

# Publishing Information and Using a Database

With the WWW service and the Open Database Connectivity (ODBC) drivers provided with Internet Information Server, you can:

- Create Web pages with information contained in a database.

- Insert, update, and delete information in the database based on user input from a Web page.

- Perform other Structured Query Language (SQL) commands.

## How the Internet Database Connector Works

Conceptually, database access is performed by Internet Information Server as shown in the following diagram.

Web browsers (such as Internet Explorer, or browsers from other companies such as Netscape) submit requests to the Internet server by using HTTP. The Internet server responds with a document formatted in HTML. Access to databases is accomplished through a component of Internet Information Server called the Internet Database Connector (IDC). The Internet Database Connector, Httpodbc.dll, is an ISAPI DLL that uses ODBC to gain access to databases.

The following illustration shows the components for connecting to databases from Internet Information Server.

The IDC uses two types of files to control how the database is accessed and how the output Web page is constructed. These files are Internet Database Connector (.idc) files and HTML extension (.htx) files.

The Internet Database Connector files contain the necessary information to connect to the appropriate ODBC data source and execute the SQL statement. An Internet Database Connector file also contains the name and location of the HTML extension file.

The HTML extension file is the template for the actual HTML document that will be returned to the Web browser after the database information has been merged into it by the IDC.

## Installing ODBC and Creating System Data Sources

When the ODBC option is selected during setup, ODBC version 2.5 components are installed. This version of ODBC supports System DSNs (Data Source Names) and is required for using ODBC with Microsoft Internet Information Server.

System DSNs were introduced in ODBC version 2.5 to allow Windows NT services to use ODBC.

#### To install the ODBC drivers

1. If you did not install the ODBC Drivers and Administration option, run Setup again by clicking the Internet Information Server Setup icon in the Microsoft Internet Server program group. You will need the Windows NT Server compact disc, or a network installation directory containing the complete contents of the compact disc.

2. Click the OK button.

3. Click the Add/Remove button.

4. Click the OK button.

5. Select the ODBC Drivers and Administration option.

6. Click the OK button.

7. The Install Drivers dialog box appears.

8. To install the SQL Server driver, select the SQL Server driver from the Available ODBC Drivers list box, and click the OK button.

Setup completes copying files.

#### To create the system data sources

1. Double-click the Control Panel icon in the Main program group of Program Manager.

2. Double-click the ODBC icon.

The ODBC Data Sources dialog box appears.

You may see other data sources in the list if you previously installed other ODBC drivers.

3. Click the System DSN button.

Important Be sure to click the System DSN button. The Internet Database Connector will work only with System DSNs.

The System Data Sources dialog box appears.

4. Click the Add button.

The Add Data Source dialog box appears.

5. Select an ODBC driver in the list box and click OK. A dialog box specific to your driver will appear.

6. Enter the name of the data source.

The data source name is a logical name used by ODBC to refer to the driver and any other information required to access the data, such as the actual server name or location of the database. The data source name is used in Internet Database Connector files to tell Internet Information Server where to access the data.

For Microsoft SQL Server, the server name, network address, and network library displayed in the Setup dialog box are specific to your installation. If you do not know what to enter in these controls, accept the defaults. To find out the details, click the Help button and find the section that describes your network.

7. Click the OK button.

The System Data Sources dialog box will be displayed again, but now will have the name of the data source displayed.

8. Click the Close button to close the System Data Sources dialog box.

9. Click the Close button to close the Data Sources dialog box.

10. Click the OK button to complete the ODBC and DSN setup.

### 32-Bit ODBC Drivers

The Internet Database Connector requires 32-bit ODBC drivers. Refer to the Internet Information Server Help files or the Windows NT ODBC Help file for information about the ODBC option.

### Microsoft Access ODBC Drivers

The Internet Database Connector requires the 32-bit ODBC drivers shipped with Microsoft® Office 95 and Microsoft® Access 95. The ODBC driver for Microsoft Access 2.0 will not work with Internet Information Server.

## Authoring Web Pages with Database Access

In order to provide access to a SQL database from your Web page, you will need to create an Internet Database Connector file (.idc file-name extension) and an HTML extension file (.htx file-name extension).

## Walking through a Sample Database Query

This example starts with a simple Web page called Sample.htm. The sample Web page will contain one hyperlink that will result in a query being executed using the ODBC driver for Microsoft SQL Server, with the results returned as another Web page.

The following graphic shows Dbsamp1.htm as it is displayed by Microsoft Internet Explorer (assuming that Internet Information Server has been installed on a computer called “webserver”).

When the hyperlink “Click here to run query” is clicked, another Uniform Resource Locator (URL) is sent to the server. The URL precedes the hyperlink text (it is formatted as hidden text):

`<A HREF="http://webserver/samples/dbsamp/dbsamp1.idc">Click here to run query</A>`

The Internet Database Connector file for the IDC to use (Dbsamp1.idc) is referenced in the URL. Extension file mapping precludes the need to reference Httpodbc.dll in the URL.

On Internet Information Server, the entire process of using the Internet Database Connector for this example is performed in six steps, as shown in the following diagram.

1. The URL is received by Internet Information Server.

The URL is sent by the Web browser.

2. Internet Information Server loads Httpodbc.dll and provides it with the remaining information in the URL.

.Idc files are mapped to Httpodbc.dll. Httpodbc.dll loads and obtains the name of the Internet Database Connector file (and other items) from the URL passed to Internet Information Server.

3. Httpodbc.dll reads the Internet Database Connector file.

The Internet Database Connector file contains several entries in the format

``

field: value

In the Sample.idc file, the ODBC data source is specified by:

``

Datasource: Web SQL

And the HTML extension file is specified by:

``

Template: sample.htx

Here are the entire contents of the file Sample.idc referenced in the preceding URL:

``

Datasource: Web SQL
Username: sa
Template: sample.htx
SQLStatement:
+SELECT au_lname, ytd_sales
+ from pubs.dbo.titleview
+ where ytd_sales>5000

In the sample .idc file the data source name is “Web SQL” The ODBC installation notes tell how to create a data source called Web SQL.

The other items contained in the sample .idc file include:

- User name, which must be a valid logon to the ODBC datasource; in this example, the logon is to the “sa” account on a Microsoft SQL Server.

- Template, which specifies the file to use to merge the results.

- SQL Statement, which contains the SQL statement to execute.

See “Learning the Features of the Internet Database Connector,” later in this chapter, for definitions for all the fields that can be specified in Internet Database Connector files.

The SQLStatement in Sample.idc returns all the author last names and year-to-date sales in units from the “pubs” sample database in SQL Server for authors whose books have year-to-date sales of more than 5000 dollars.

4. The IDC connects to the ODBC data source, and executes the SQL statement contained within the Internet Database Connector file.

The connection is made to the ODBC data source by the IDC, which in this example loads the ODBC driver for SQL Server and connects to the server specified in the definition of the data source. Once the connection is made, the SQLStatement in the Internet Database Connector file is sent to the SQL Server ODBC driver, which in turn sends it to SQL Server.

5. The IDC fetches the data from the database, and merges it into the HTML extension file.

After the SQL statement has been executed, IDC reads the HTML extension file specified in Sample.idc (Sample.htx). HTML extension (.htx) files contains special HTML tags which IDC uses to control where and how the data returned from the SQL statement is merged.

6. The IDC sends the merged document back to Internet Information Server, which returns it to the client.

After all the data has been merged into Sample.htx, the complete HTML document is sent back to the client.

The resulting Web page is displayed in the Microsoft Internet Explorer as shown following.

## Understanding the Sample.htx File

To return data to the WWW client, the .idc file merges the HTML extension .htx file and the ODBC data. This combined data is attached to standard HTTP headers (200 OK status, Content-Type, and so on) and passed to the WWW service and returned to the client.

The .htx file is an HTML document with some additional tags enclosed by <%%> or <!--%%-->, which the .idc file uses to add dynamic data to the document. The HTML formatting in the .htx file typically formats the data being returned. There are six keywords (begindetail, enddetail, if, else, endif, and “%z”) that control how the data from the database is merged with the HTML format in the .htx file. Database column names specify what data is returned in the HTML document. For example, the following line in an .htx file merges data from the Emailname column for every record processed:

`<%begindetail%><%Emailname%><%enddetail%>`

The Sample.htx file is an HTML document that contains Internet Database Connector tags for data returned from the database (the tags are shown in bold for clarity). Some HTML formatting has been removed to highlight the IDC tags.

Most of the HTML formatting has been removed for clarity.

<HTML>
<BODY>
<HEAD><TITLE>Authors and YTD Sales</TITLE></HEAD>
<%if idc.sales eq ""%>

<H2>Authors with sales greater than <I>5000</I></H2>
<%else%>

<H2>Authors with sales greater than <I><%idc.sales%></I></H2>
<%endif%>

<P>
<%begindetail%>
<%if CurrentRecord EQ 0 %>

Query results:
<B>Author YTD Sales<BR></B>
<%endif%>
<%au_lname%><%ytd_sales%>
<%enddetail%>
<P>
<%if CurrentRecord EQ 0 %>
<I><B>Sorry, no authors had YTD sales greater than </I><%idc.sales%>.</B>

<P>
<%else%>

<HR>
<I>
The Web page you see here was created by merging the results of the SQL query with the template file Sample.htx.
<P>
The merge was done by the Microsoft Internet Database Connector and the results were returned to this Web browser by the Microsoft Internet Information Server.
</I>
<%endif%>

</BODY>
</HTML>

The <%begindetail%> and <%enddetail%> sections delimit where rows returned from the database will appear in the document. Columns returned from the query are surrounded by <%%>, such as <%au_lname%> and <%ytd_sales%> in this example.

## Learning the Features of the Internet Database Connector

The Internet Database Connector has several features that help create Web pages containing data from a database.

### Internet Database Connector Files

Internet Database Connector files contain the information used to access the database. The following section describes the features of Internet Database Connector files.

#### Parameters

The example in the preceding section shows only the simplest kind of query, a query that was defined completely in the Internet Database Connector file. Although this type of query is useful, even more powerful Web pages can be constructed through the use of parameters. Parameters are the names and values of HTML-form controls, such as “<INPUT…>”, and names specified directly in URLs. These names and values are sent by Web browsers and can be used in SQL statements on the server.

For example, in the last section the query in Sample.idc returned only the authors whose year-to-date sales exceeded 5000. By using a parameter, you could build a Web page that asks the user to decide what number to use instead of 5000.

The Web page must prompt the user for the year-to-date sales figure and then name the associated variable to “sales.” Dbsamp2.htm shows a form with an input field used to obtain the number:

The HTML syntax for the input field and button in Sample2.htm is:

`<FORM METHOD="POST" ACTION="/scripts/samples/sample2.idc">
<P>
Enter YTD sales amount: <INPUT NAME="sales" VALUE="5000" >
<P>
<INPUT TYPE="SUBMIT" VALUE="Run Query">
</FORM>`

``

In the Internet Database Connector file Sample2.idc, you use the parameter shown in bold in place of the number 5000:

`SQLStatement:
+SELECT au_lname, ytd_sales
+ from pubs.dbo.titleview
+ where ytd_sales > %sales%`

``

Here the parameter name must be “sales” so that it corresponds to the <INPUT NAME= “sales” …> on the Web page. Parameters must be enclosed with percent characters (%) to distinguish them from a normal identifier in SQL. When the Internet Database Connector encounters the parameter in the .idc file, the Internet Database Connector substitutes the value sent by the Web browser and then sends the SQL statement to the ODBC driver.

The percent character (%) is also a wildcard character in SQL. You can use wildcards in an SQL query to search for an element in a table that contains certain characters. To insert a single “%” for a SQL wildcard, use “%%.” This prevents the IDC from trying to use the % as a parameter marker. For example:

`SQLStatement:
+SELECT au_lname, ytd_sales, title
+ from pubs.dbo.titleview
+ where title like '%%%title%%%'`

For a percent sign to be recognized as an SQL wildcard you must double it and then add the percent characters around the parameter to distinguish the string as a parameter. In the example, the query searches for all entries in the title column with the word title in them. This query returns the following:

`title
title and deed
main title page
author and title`

To return all entries with the word title as the first five letters, you would format the query as follows:

`SQLStatement:
+SELECT au_lname, ytd_sales, title
+ from pubs.dbo.titleview
+ where title like '%title%%%'`

In this example, the following results are returned:

`title
title and deed`

To return all entries with the word title as the last five letters, you format the query as follows:

`SQLStatement:
+SELECT au_lname, ytd_sales, title
+ from pubs.dbo.titleview
+ where title like '%%%title%'`

In this example, the following results are returned:

`title
author and title`

You can build powerful collections of Web pages by using the output of one query to provide links to other queries. For example, to show the titles for an individual author, instead of returning the author name as plain text, you can format it as a link and then use the link to do another query.

Another example included Internet Information Server shows how to do this type of linkage. Dbsamp3.htm is used to run the query in Sample3.idc, which uses Sample3.htx for the output template. Sample3.htx will return author last names as links, which, when clicked, will display the titles for each author by using Sample3a.idc and Sample3a.htx.

#### Fields in Internet Database Connector (.idc) Files

The following tables list the fields that can be specified in an Internet Database Connector file. Note that parameters or server variables may appear anywhere in an .idc file.

Required Fields in an Internet Database Connector (.idc) File

Field | Description
Datasource | The name that corresponds to the ODBC system Data Source Name (DSN) you created earlier by using the ODBC Administrator or the tool provided with the samples.
Template | The name of the HTML extension file that formats the data returned from this query. By convention these files use the file-name extension .htx.
SQLStatement | The SQL statement to execute. The SQL statement can contain parameter values, which must be enclosed with percent characters (%) from the client. The SQLStatement can occupy multiple lines in the Internet Database Connector file. Following the SQLStatement field, each subsequent line beginning with a plus sign (+) is considered part of the SQLStatement field. Multiple SQLStatements can appear in the same file.

Optional Fields in an Internet Database Connector (.idc) File

Field | Description
DefaultParameters = param=value [, param=value] […] | The parameter values, if any, that will be used in the Internet Database Connector file if a parameter is not specified by the client.
Expires | The number of seconds to wait before refreshing a cached output page. If a subsequent request is identical, the cached page will be returned without ever accessing the database. The Expires field is useful when you want to force a requery of the database after a certain period of time. The IDC does not cache output pages by default. It caches them only when the Expires field is used.
MaxFieldSize | The maximum buffer space allocated by the IDC per field. Any characters beyond this will be truncated. The parameter applies only to fields returned from the database that exceed 8192 bytes. The default value is 8192 bytes.
MaxRecords | The maximum number of records that the IDC will return from any one query. The MaxRecords value is not set by default, meaning that a query can return up to 4 billion records. Set this value to limit the records returned.
ODBCConnection | Insert this field with the value of pool to add the connection to the connection pool, which keeps the connection to the database open for future requests. The IDC then sends data through a pooled connection for subsequent execution of an .idc file that contains the same values for Datasource, Username, and Password. Set this option to improve performance using the Internet Database Connector. Also, there is a nonpool option, which specifies that the connection for the .idc file in which this option is set should not be taken from the connection pool. Set the value of this field to nopool to manage the cache of connections more precisely. Also, if there is a limit on the number of current connections, you do not want the connection pool to monopolize all the connections; otherwise, no one else could connect to the SQL Server. Note To set the default to connection pooling, you must set the PoolIDCConnections registry entry to 1. For details, see Chapter 10, “Configuring Registry Entries.”
Password | The password that corresponds to the user name. If the password is null, this field can be left out.
RequiredParameters | The parameter names, if any, that Httpodbc.dll will ensure are passed from the client; otherwise, it will return an error. Parameter names are separated with a comma.
Translationfile | The path to the file that maps non-English characters (such as à, ô, or é) so that browsers can display them properly in HTML format. If the translation file is not in the same directory as the .idc file, you must type the full path to the translation file. Syntax: Translationfile: C:\directoryname\filename. Use the Translationfile field if you are publishing a database in a language other than English. A translation file is a text file with each special character mapped in the following format: value=string<CR> where value is an international character and string is the HTML translation code.
Username | A valid user name for the data source name supplied in the Datasource field. Note If you use Microsoft SQL Server with the integrated security option, the username and password fields in the .idc file are ignored. The logon to SQL Server is performed using the credentials of the Web user. If the request is made as the anonymous user, the username and password are determined by the settings for the anonymous user (IUSR_computername by default) in the Internet Service Manager. If the client request contained logon credentials, the username and password supplied by the end user are used to log on to SQL Server.
Content-Type | Any valid MIME type describing what will be returned to the client. Almost always this will be “text/html” if the .htx file contains HTML.

### ODBC Advanced Optional Fields

ODBC advanced options allow debugging and fine-tuning of the ODBC driver used by the Internet Database Connector. For more details about these options, consult your ODBC driver documentation or the ODBC Software Development Kit (SDK). The format in the IDC file is:

`ODBCOptions: Option Name=Value[,Option Name=Value…]`

For example, to stop the SQL statement from running for more than 10 seconds and enabling tracing of ODBC function calls, in the IDC file you would specify:

`ODBCOptions: SQL_QUERY_TIMEOUT=10, SQL_OPT_TRACE=1, SQL_OPT_TRACEFILE=C:\Sql.log`

All options are described in the following table:

Option Name | Value | Purpose
SQL_ACCESS_MODE | 0 = Read/Write 1 = Read Only. | An indicator for the ODBC driver or data source that the connection is not required to support SQL statements that cause updates to occur. This mode can be used to optimize locking strategies, transaction management, or other areas as appropriate to the driver or data source. The driver is not required to prevent such statements from being submitted to the data source. The behavior of the driver and data source when asked to process SQL statements that are not read-only during a read-only connection is implementation-defined. SQL_ACCESS_MODE set to 0 is the default, which allows reading and writing.
SQL_LOGIN_TIMEOUT | Integer | The number of seconds to wait for a logon request to complete before disconnecting. The default is driver-dependent and must be nonzero. If the value is 0, the timeout is disabled and a connection attempt will wait indefinitely. If the specified timeout exceeds the maximum log on timeout in the data source, the driver substitutes that value.
SQL_OPT_TRACE | 0 = Trace off 1 = Trace on | When tracing is on, each ODBC function call made by Httpodbc.dll is written to the trace file. You can specify a trace file with the SQL_OPT_TRACEFILE option. If the file already exists, the ODBC appends to the file. Otherwise, it creates the file. If tracing is on and no trace file has been specified, ODBC writes to the file Sql.log.
SQL_OPT_TRACEFILE | File name | The name of the trace file to use when SQL_OPT_TRACE=1. The default is SQL.LOG
SQL_PACKET_SIZE | Integer | The network packet size, in bytes, to be used to exchange information between the database management system (DBMS) and the Web Server. Note Many data sources either do not support this option or can return only the network packet size. If the specified size exceeds the maximum packet size or is smaller than the minimum packet size, the driver substitutes that value.
SQL_TRANSLATE_DLL | File name | The name of a DLL containing the functions SQLDriverToDataSource and SQLDataSourceToDriver that the driver loads and uses to perform tasks such as character-set translation.
SQL_TRANSLATE_OPTION | Integer | Value controlling translation functionality, which is specific to the translation DLL being used. Consult the documentation for the driver and translation DLL for details.
SQL_TXN_ISOLATION | Integer 1=Read Uncommited 2=Read Committed 4=Repeatable Read 8=Serializable 16=Versioning | Sets the transaction isolation level. The Internet Database Connector does not support transactions than span more than the request in the .idc file. However, for some DBMSs, setting the SQL_TXN_ISOLATION option to 1 (Read Uncommited) will result in higher concurrency and therefore better performance. However, with this setting, data that has not been committed to the database by other transactions may be retrieved .
SQL_MAX_LENGTH | Integer | The maximum amount of data that the driver returns from a character or binary column. This option is intended to reduce network traffic and should only be used when the data source (as opposed to the driver) in a multiple-tier driver can implement it.
SQL_MAX_ROWS | Integer | The maximum number of rows to return for a SELECT statement. If the value equals 0 (the default), then the driver returns all rows. This option is intended to reduce network traffic when the data source itself can limit the return rows, as opposed to the MaxRecords built-in variable in the Internet Database Connector, which limits the rows fetched.
SQL_NOSCAN | 0=Scan for and convert escape clauses 1=Do not scan for and convert escape clauses | Specifies whether the driver does not scan SQL strings for escape clauses. If set to 0 (the default), the driver scans SQL strings for escape clauses. If set to 1, the driver does not scan SQL strings for escape clauses; instead, the driver sends the statement directly to the data source. If your SQL statement does not contain any ODBC escape clauses, a special syntax enclosed by curly braces ( { } ), then setting this option to 1 will provide a small performance gain by directing the driver to not scan the SQL string.
SQL_QUERY_TIMEOUT | Integer 0=No timeout | The number of seconds to wait for a SQL statement to execute before canceling the query. When set to 0 (the default) there is no timeout. If the specified timeout exceeds the maximum timeout in the data source, or is smaller than the minimum timeout, the driver substitutes that value.
Integer | Driver Specific | Driver-specific option values can be specified in the form number=value. For example,
    4322=1, 234=String

### Using Select Multiple List Boxes in HTML Forms

When an HTML form containing a <SELECT MULTIPLE…> tag is used, the Internet Database Connector converts the items selected into a comma-separated list; the list can be used in the .idc file just like other parameters. However, because the parameter is actually a list, it will typically only be used for SQLSelect statements with an IN clause, as in the following examples.

If the parameter name in the .idc file is enclosed in single quotation marks, each element of the list will be enclosed in single quotation marks also. You should enclose the parameter name in single quotation marks whenever the column in the IN clause is a character column or other type in which literals are quoted (dates and times, for example). If there are no single quotation marks around the parameter name, no quotation marks will be placed around each element of the list. You should not enclose the parameter name in single quotation marks when the column in the IN clause is a numeric type or any other type in which literals are not enclosed in single quotation marks.

For example, if an HTML form contained the multiple-choice list box shown below:

`<SELECT MULTIPLE NAME="region">
<OPTION VALUE="Western">
<OPTION VALUE="Eastern">
<OPTION VALUE="Northern">
<OPTION VALUE="Southern">
</SELECT>`

You can construct an .idc file with an SQL statement:

`SQLStatement: SELECT name, region FROM customer WHERE region IN ('%region%')`

If the user selected “Northern,” “Western,” and “Eastern” from the HTML form, the SQL statement would be converted to:

`SELECT name, region FROM customer WHERE region IN ('Northern', 'Western', 'Eastern')`

Another example of an HTML form is shown below, but this time uses numeric data, and therefore no quotation marks enclose the parameter in the .idc file.

`<SELECT MULTIPLE NAME="year">
<OPTION VALUE="1994">
<OPTION VALUE="1995">
<OPTION VALUE="1996">
</SELECT>`

You can construct an .idc file with an SQLStatement:

`SQLStatement: SELECT product, sales_year FROM sales WHERE sales_year IN (%year%)`

If the user selected “1994” and “1995” from the HTML form, the SQL statement would be converted to:

`SELECT product, sales_year FROM sales WHERE sales_year IN (1994, 1995)`

### Using Batch Queries and Multiple Queries

In an .idc file, you can group SQL queries in two ways, as batch queries or as multiple queries.

#### Batch Queries

If you are querying databases that can simultaneously process several queries in a SQL statement (such as SQL Server database), you should format your statements in batch query syntax to optimize performance. For example:

`SQLSTatement:
+insert into perf(testtime, tag) values (getdate(), '%tag%')
+SELECT au_lname, ytd_sales from pubs.dbo.titleview where ytd_sales>5000
+SELECT count(*) as nrecs from pubs.dbo.titleview where ytd_sales>5000`

#### Multiple Queries

If you are querying databases that cannot process a series of SQL queries simultaneously, then formulate your queries as multiple queries. For example:

`SQLStatement:
+insert into perf(testtime, tag) values (getdate(), '%tag%')
SQLStatement:
+SELECT au_lname, ytd_sales from pubs.dbo.titleview where ytd_sales>5000
SQLStatement:
+SELECT count(*) as nrecs from pubs.dbo.titleview where ytd_sales>5000`

Batch queries are processed together at once, whereas multiple queries are processed one at a time. Therefore, you will get better performance by formatting your queries as a batch if your database can handle batch queries.

### HTML Extension (.htx) Files

HTML extension files contain a number of keywords that control how the output HTML document is constructed. These keywords are explained in the following sections.

#### <%begindetail%>, <%enddetail%>

The <%begindetail%>, <%enddetail%> keywords surround a section of the HTML extension file in which the data output from the database will be merged. Within the section, the column names delimited with <% and %> or <!--%%-->are used to mark the position of the returned data from the query. For example:

`<%begindetail%>
<%au_lname%>: <%ytd_sales%>
<%enddetail%>`

will list the columns au_lname and ytd_sales. Any column can be referred to in this way. Column names can also be referred to elsewhere in the HTML extension file.

Note If there are no records returned from the query, the <%begindetail%> section will be skipped. For each SQL statement that generates a result set (for example, SELECT), there should be a corresponding <%begindetail%> <%enddetail%> section in the .htx file.

#### <%if%>, <%else%>, <%endif%>

HTML extension files can contain conditional logic with an if-then-else statement to control how the Web page is constructed. For example, one common usage is to insert a condition to display the results from the query on the first row within a <%begindetail%> section; but if there are no records returned by the query, to display the text “Sorry, no authors had YTD sales greater than” %idc.sales%. By using the <%if%> statement and a built-in variable called “CurrentRecord” you can tailor the output so that the error message is printed when no records are returned. Here is an example showing the use of the <%if%> statement.

`<%begindetail%><%if CurrentRecord EQ 0 %>`

Query results:

`<B>Author YTD Sales<BR></B>
<%endif%>
<%au_lname%><%ytd_sales%>
<%enddetail%>
<P>
<%if CurrentRecord EQ 0 %>
<I><B>Sorry, no authors had YTD sales greater than </I><%idc.sales%>.</B>
<P>
<%else%>
<HR>
<I>
The Web page you see here was created by merging the results of the SQL query with the template file Sample.htx.
<P>
The merge was done by the Microsoft Internet Database Connector and the results were returned to this Web browser by the Microsoft Internet Information Server.
</I>
<%endif%>`

</BODY>
</HTML>

The general syntax is:

`<%if condition %>
HTML text
[<%else%>
HTML text]
<%endif%>`

Where condition is of the form:

value1 operator value2

and operator can be one of the following:

EQ | if value1 equals value2
LT | if value1 is less than value2
GT | if value1 is greater than value2
CONTAINS | if any part of value1 contains the string value2

The operands value1 and value2 can be column names, one of the built-in variables (CurrentRecord or MaxRecords, see below), an HTTP variable name (see following), or a constant. When used in an <%if%> statement, values are not delimited with <% and %>. For example, to do special processing on author name “Green,” use the condition:

`<%begindetail%>
<%if au_lname EQ "Green"%>
this guy is green!
<%endif%>
<%enddetail%>`

The <%if%> statement can also be used to do special processing based on information from HTTP variables. For example, to format a page differently based on the type of client Web browser you could include the following in the HTML extension file.

`<%if HTTP_USER_AGENT contains "Mozilla"%>
client supports advanced HTML features
<%else%>
client is <%HTTP_USER_AGENT%>
<%endif%>`

#### CurrentRecord, MaxRecords

The CurrentRecord built-in variable contains the number of times the <%begindetail%> section has been processed. The first time through the <%begindetail%> section, the value is zero. Subsequently, the value of CurrentRecord changes every time another record is fetched from the database.

The MaxRecords built-in variable contains the value of the MaxRecords field in the Internet Database Connector file. MaxRecords and CurrentRecord can only be used in <%if%> statements.

#### Parameters from Internet Database Connector files

Parameters from Internet Database Connector files can be accessed in the HTML extension file by prefixing the name of the parameter with “idc” and a period. In Sample3.htx shown earlier, you could show the value of the parameter %sales% by including the line:

`The value of the sales parameter is: <%idc.sales%>`

#### HTTP variables

Several variables in HTML extension files can give a lot of information about the environment and Web client connected to the server. In addition all headers sent by the client are available. To access them by using the Internet Database Connector you must convert them:

1. Add HTTP_ to the beginning.

2. Convert all dashes to underscores.

3. Convert all letters to uppercase.

The following table gives a listing of default variables. These are environment variables for CGI applications and HTTP variables for IDC applications.

Internet Information Server Variables

Variable | Meaning
ALL_HTTP | All HTTP headers that were not already parsed into one of the listed variables. These variables are of the form HTTP_<header field name>, for example:

    HTTP_ACCEPT: */*, q=0.300, audio/x-aiff, audio/basic, image/jpeg, image/gif, text/plain, text/html
    HTTP_USER_AGENT: Microsoft Internet Explorer/0.1 (Win32)
    HTTP_REFERER: http://webserver/samples/dbsamp/dbsamp3.htm
    HTTP_CONTENT_TYPE: application/x-www-form-urlencoded
    HTTP_CONTENT_LENGTH: 10
AUTH_TYPE | The type of authorization in use. If the user name has been authenticated by the server, this will contain Basic. Otherwise, it will not be present.
CONTENT_LENGTH | The number of bytes that the script can expect to receive from the client.
CONTENT_TYPE | The content type of the information supplied in the body of a POST request.
GATEWAY_INTERFACE | The revision of the CGI (Common Gateway Interface) specification with which this server complies.
HTTP_ACCEPT | Special-case HTTP header. Values of the Accept: fields are concatenated, separated by a comma (,); for example, if the following lines are part of the HTTP header:

    accept: */*; q=0.1

    accept: text/html

    accept: image/jpeg
then the HTTP_ACCEPT variable will have a value of:
    */*; q=0.1, text/html, image/jpeg
LOGON_USER | The user’s Windows NT account.
PATH_INFO | Additional path information, as given by the client. This comprises the trailing part of the URL after the script name but before the query string (if any).
PATH_TRANSLATED | The value of PATH_INFO, but with any virtual path name expanded into a directory specification.
QUERY_STRING | The information that follows the question mark (?) in the URL that referenced this script.
REMOTE_ADDR | The IP address of the client.
REMOTE_HOST | The hostname of the client.
REMOTE_USER | The user name supplied by the client and authenticated by the server.
REQUEST_METHOD | The HTTP request method.
SCRIPT_NAME | The name of the script program being executed.
SERVER_NAME | The server’s hostname (or IP address) as it should appear in self-referencing URLs.
SERVER_PORT | The TCP/IP port on which the request was received.
SERVER_PORT_SECURE | The value of 0 or 1. The value 1 indicates the request is on the encrypted port.
SERVER_PROTOCOL | The name and version of the information-retrieval protocol relating to this request, usually HTTP/1.0.
SERVER_SOFTWARE | The name and version of the Web server under which the Internet Server Extension is running.
URL | The URL of the request.

© 1996 by Microsoft Corporation. All rights reserved.