Active Server Pages Guide
Active Server Pages Guide
Welcome to the Active Server Pages Guide. This section provides detailed
information about creating ASP pages and developing Web applications. It
also describes the special event methods and interfaces available for
creating components for access by ASP or ISAPI extensions. In this section
you will find information on how to store your custom IIS configuration data
and how you can use built-in objects to manipulate that data. Finally, the
guide provides a library of script and program samples demonstrating a
variety of ways to interact with IIS.
The topics in this section introduce Active Server Pages, explain the basic
concepts of scripting with Active Server Pages, and discuss more complex
application issues such as how to maintain state.
Active Server Pages (ASP) makes it easy to generate dynamic content for
the Web and to build powerful Web applications. Whether you are a Web
designer or a Web developer, this introduction explains how ASP can help
you.
Pages
This is preliminary documentation for IIS 5.0 and is subject to change.
your Web server. Your Web server then calls ASP, which processes the
requested file from top to bottom, executes any script commands, and
sends a Web page to the browser.
Because your scripts run on the server rather than on the client, your Web
server does all the work involved in generating the HTML pages sent to
browsers. Server-side scripts cannot be readily copied because only the
result of the script is returned to the browser. Users cannot view the script
commands that created the page they are viewing.
Active Server Pages has been enhanced with features that make it easier to
use for scripters and Web application developers.
? New Flow Control Capabilities The ASP Server object now has two
new methods that you can use to control program flow:
Server.Transfer and Server.Execute. Rather than redirecting
requests, which requires an expensive round-trip to the client, you can
use these methods to transfer requests directly to an .asp file, without
leaving the server. For more information, see Sending Content to the
Browser.
? Error Handling ASP now has a new error-handling capability so that
you can trap errors in a custom error message .asp file. You can use
the new Server.GetLastError method to display useful information,
such as an error description or the line number where the error
occurred. For more information, see ASPError Object.
? Scriptless ASP Because static content is usually processed more
quickly than server-side content it was previously better to assign
an .asp file extension only to files that contained ASP functionality.
Whenever you needed to add ASP functionality to your static .html
files, you had to manually add .asp file extensions and correct related
hyperlinks. With this latest release of ASP, however, .asp files that do
not contain server-side functionality are now processed more quickly
than ever before. So, if you are creating an evolving Web application in
which files may eventually require ASP functionality, you can now
conveniently assign those files .asp file extensions, regardless of
whether they contain static or server-side content. For more
information, see Creating an ASP Page.
? Performance Enhanced Objects Active Server Pages now provides
performance enhanced versions of its popular installable components.
These objects will scale reliably in a wide range of Web publishing
environments. For more information, see Installable Components for
ASP.
? XML Integration Just as HTML enables you to describe the format of a
Web document, Extensible Markup Language (XML) enables you to
describe complex data structures. You will be able to share this
information across a variety of applications, clients, and servers. Using
Note To learn about new ASP features, see What's New in ASP.
? Transaction Flags IIS 4.0 used the required, requires new, and not
supported transaction flags to indicate that ASP was starting a new
transaction. In IIS 5.0, this behavior is unchanged. However, if an .asp
file executes a transacted .asp file using the new Server.Execute or
Server.Transfer methods, then the transaction flag state is
maintained for the second .asp file. If the second .asp file's
transaction flags indicate that transactions are supported or required,
then the existing transaction will be used and a new transaction will
not be started.
? ErrorsToNTLog
For IIS 5.0, all configurable parameters for ASP can be modified from
the metabase.
? Security for Local Server COM Objects IIS uses a new Windows COM
feature called cloaking to enable local server applications instantiated
from an .asp file to have the security context of the originating client.
In previous versions, the identity assigned to the local server COM
object depended on the identity of the user who created the object
instance.
? Objects Released Earlier In IIS 4.0, COM objects were only released
when ASP finished processing a page. In IIS 5.0, if a COM object does
not use the OnEndPage method and the reference count for the
object is zero, then the object is released prior to the completion of
processing.
? Creating an ASP Page: Describes an ASP file and explains how to add
script commands to a page.
? Working with Scripting Languages: Explains how to set the primary
language and how to use VBScript and JScript in server scripts.
? Using Variables and Constants: Provides an introduction to using
variables in ASP scripts and explains how to access constant
definitions.
? Interacting with Client-Side Scripts: Shows how to write server-side
scripts that create and interact with client-side scripts.
? Writing Procedures: Describes how to define procedures (functions
and subroutines) and call them from server-side scripts.
? Working with Collections: Describes how to access items in a built-in
object's collections, including access by iterating through a collection.
? Processing User Input: Explains how to collect and process
information gathered from an HTML form.
? Using Components and Objects: Explains how to create an instance
of an object provided by a COM component, how to use the ASP built-
in objects, and how to use the methods and properties of any object.
? Setting Object Scope: Demonstrates the scope, or extent, of an
object and describes how to create session and application scoped
objects.
? Sending Content to the Browser: Describes how to control the ways
in which pages are sent to a browser.
? Including Files: Explains how to use the #include statement to insert
the contents of a file into an .asp file.
? Managing Sessions: Describes how to preserve information about a
user.
? Accessing a Data Source: Explains how to use ASP and Microsoft
ActiveX Data Objects (ADO) to retrieve information from a database.
? Understanding Transactions: Demonstrates how to run a script under
a transaction context. Business and credit card applications often need
to the ability to run scripts and components within transactions.
? Debugging ASP Scripts: Describes how to use the Microsoft Script
Debugger to find and eliminate errors in your scripts.
? Built-in ASP Objects: Provides a quick overview of the ASP built-in
objects, and links to more detailed information.
? Active Server Pages Objects Quick Reference Card: Contains quick
reference information about ASP built-in objects.
An Active Server Pages (ASP) file is a text file with the extension .asp that
contains any combination of the following:
? Text
? HTML tags
? Server-side scripts
A quick way to create an .asp file is to rename your HTML files by replacing
the existing .htm or .html file name extension with an .asp extension. If
your file does not contain any ASP functionality, then the server dispenses
with the ASP script processing and efficiently sends the file to the client. As
a Web developer, this affords you tremendous flexibility because you can
assign your files .asp extensions, even if you do not plan on adding ASP
functionality until later.
To publish an .asp file on the Web, save the new file in a virtual directory
on your Web site (be sure that the directory has Script or Execute
permission enabled). Next, request the file with your browser by typing in
the file's URL. (Remember, ASP pages must be served, so you cannot
request an .asp file by typing in it's physical path.) After the file loads in
your browser, you will notice that the server has returned an HTML page.
This may seem strange at first, but remember that the server parses and
executes all ASP server-side scripts prior to sending the file. The user will
always receive standard HTML.
You can use any text editor to create .asp files. As you progress, you may
find it more productive to use an editor with enhanced support for ASP,
such as Microsoft® Visual InterDev™. (For more information, visit the
Microsoft Visual InterDev Web site at
http://msdn.microsoft.com/vinterdev/.)
ASP uses the delimiters <% and %> to enclose script commands. You can
include within the delimiters any command that is valid for the scripting
language you are using. The following example shows a simple HTML page
that contains a script command:
<HTML>
<BODY>
This page was last refreshed on <%= Now() %>.
</BODY>
</HTML>
The VBScript function Now() returns the current date and time. When the
Web server processes this page, it replaces <%= Now() %> with the current
date and time and returns the page to the browser:
If you are already familiar with client-side scripting, you are familiar with
the HTML <SCRIPT> tag used to enclose script commands and expressions.
You can also use the <SCRIPT> tag for server-side scripting whenever you
need to define procedures in multiple languages within an .asp file. For
more information, see Working with Scripting Languages.
<%
Dim dtmHour
dtmHour = Hour(Now())
Depending on the hour, this script assigns either the value "Good Morning!"
or the value "Hello!" to the string variable strGreeting. The <%= strGreeting %
> statement sends the current value of the variable to the browser.
Thus, a user viewing this script before 12:00 noon (in the Web server’s
time zone) would see this line of text:
Good Morning!
A user viewing the script at or after 12:00 noon would see this line of text:
Hello!
You can include HTML text between the sections of a statement. For
example, the following script, which mixes HTML within an If...Then...Else
statement, produces the same result as the script in the previous example:
<%
Dim dtmHour
dtmHour = Hour(Now())
If the condition is true—that is, if the time is before noon—then the Web
server sends the HTML that follows the condition (“Good Morning”) to the
browser; otherwise, it sends the HTML that follows Else (“Hello!”) to the
browser. This way of mixing HTML and script commands is convenient for
wrapping the If...Then...Else statement around several lines of HTML text.
The previous example is more useful if you want to display a greeting in
several places on your Web page. You can set the value of the variable
once and then display it repeatedly.
Rather than interspersing HTML text with script commands, you can return
HTML text to the browser from within a script command. To return text to
the browser, use the ASP built-in object Response. The following example
produces the same result as the previous scripts:
<%
Dim dtmHour
dtmHour = Hour(Now())
If you are working with JScript commands, you can insert the curly braces
that indicate a block of statements directly into your ASP commands even if
they are interspersed with HTML tags and text. For example:
<%
if (screenresolution == "low")
{
%>
This is the text version of a page.
<%
}
else
{
%>
This is the multimedia version of a page.
<%
}
%>
--Or--
<%
if (screenresolution == "low")
{
Response.Write("This is the text version of a page.")
}
else
{
Response.Write("This is the multimedia version of a page.")
}
%>
The ASP output directive <%= expression %> displays the value of an
expression. This output directive is equivalent to using Response.Write to
display information. For example, the output expression <%= city %> displays
the word Baltimore (the current value of the variable) on the browser.
The ASP processing directive <%@ keyword %> gives ASP information it needs
to process an .asp file. For example, the following directive sets VBScript
as the primary scripting language for the page:
The processing directive must appear on the first line of an .asp file. To
add more than one directive to a page, the directive must be within the
same delimiter. Do not put the processing directive in a file included with
the #include statement. (For more information, see Including Files.) You
must use a space between the at sign (@) and the keyword. The processing
? The LANGUAGE keyword sets the scripting language for the .asp file.
See Working with Scripting Languages.
? The ENABLESESSIONSTATE keyword specifies whether an .asp file uses
session state. See Managing Sessions.
? The CODEPAGE keyword sets the code page (the character encoding)
for the .asp file.
? The LCID keyword sets the locale identifier for the file.
? The TRANSACTION keyword specifies that the .asp file will run under a
transaction context. See Understanding Transactions.
Important You can include more than one keyword in a single directive.
Keyword/value pairs must be separated by a space. Do not put spaces
around the equal sign (=).
The following example sets both the scripting language and the code page:
For VBScript and JScript, you can use white space after the opening
delimiter and before the closing delimiter to make commands easier to
read. All of the following statements are all valid:
<%Color="Green"%>
<%
Color = "Green"
%>
ASP removes white space between the closing delimiter of a statement and
the opening delimiter of the following statement. However, it is good
practice to use spaces to improve readability. If you need to preserve the
white space between two statements, such as when you are displaying the
values of variables in a sentence, use an HTML nonbreaking space character
( ). For example:
<%
'Define two variables with string values.
strFirstName = "Jeff"
strLastName = "Smith"
%>
<P>This Web page is customized for "<%= strFirstName %> <%= strLastName %>." </P>
Programming languages such as Visual Basic, C++, and Java provide low-
level access to computer resources and are used to create complex, large-
scale programs. Scripting languages, however, are used to create programs
of limited capability, called scripts, that execute Web site functions on a
Web server or browser. Unlike more complex programming languages,
scripting languages are interpreted, instruction statements are sequentially
executed by an intermediate program called a command interpreter. While
interpretation reduces execution efficiency, scripting languages are easy to
learn and provide powerful functionality. Scripts can be embedded in HTML
pages to format content or used to implement COM components
encapsulating advanced business logic.
Active Server Pages makes it possible for Web developers to write scripts
that execute on the server in variety of scripting languages. In fact, several
scripting languages can be used within a single .asp file. In addition,
because scripts are read and processed on the server-side, the browser that
requests the .asp file does not need to support scripting.
You can use any scripting language for which the appropriate scripting
engine is installed on your Web server. A scripting engine is a program that
processes commands written in a particular language. Active Server Pages
comes with two scripting engines: Microsoft Visual Basic Scripting Edition
(VBScript) and Microsoft JScript. You can install and use engines for other
scripting languages, such as REXX, PERL, and Python.
If you are already a Visual Basic programmer, you can immediately begin
using VBScript, which is a subset of Visual Basic. If you are a Java, C, or
C++ programmer, you may find that JScript syntax is familiar to you, even
though JScript is not directly related to Java or C.
If you are familiar with another scripting language, such as REXX, Perl, or
Python you can obtain and install the appropriate scripting engine so that
you can use the language you already know. Active Server Pages is a COM
scripting host; to use a language you must install a scripting engine that
follows the COM Scripting standard and resides as a COM (Component
Object Model) object on the Web server.
To set the primary scripting language for all pages in an application, set
the Default ASP Language property on the App Options tab in the
Internet Information Services snap-in. .
To set the primary scripting language for a single page, add the <%@
LANGUAGE %> directive to the beginning of your .asp file. The syntax for this
directive is:
Follow the guidelines for using an ASP directive; for more information, see
Creating an ASP Page.
Note To use a language that does not support the Object.Method syntax
as the primary scripting language, you must first create the
LanguageEngines registry key.
For a list and description of all VBScript and JScript operators, functions,
statements, objects, properties, and methods, refer to the VBScript
Language Reference and JScript Language Reference. You can find this
reference at the Microsoft Windows Script Technologies Web site, located
at http://msdn.microsoft.com/scripting/.
Including Comments
Because the processing of all scripts in ASP is done on the server side,
there is no need to include HTML comment tags to hide the scripts from
browsers that do not support scripting, as is often done with client-side
scripts. All ASP commands are processed before content is sent to the
browser. You can use HTML comments to add remarks to an HTML page;
comments are returned to the browser and are visible if the user views the
source HTML.
VBScript Comments
<%
'This line and the following two are comments.
'The PrintTable function prints all
'the elements in an array.
PrintTable MyArray()
%>
<%= name 'This statement prints the variable name. (This script will fail.) %>
JScript Comments
<%
var x
x = new Date()
// This line sends the current date to the browser,
// translated to a string.
Response.Write(x.toString())
%>
Case Sensitivity
VBScript is not case sensitive. For example, you can use either Request or
request to refer to the ASP Request object. One consequence of case-
insensitivity is that you cannot distinguish variable names by case. For
example, you cannot create two separate variables named Color and color.
JScript is case sensitive. When you use JScript keywords in scripts, you
must type the keyword exactly as shown in the reference page for that
keyword. For example, using date instead of Date will cause an error. The
case shown in this documentation for the ASP built-in objects will work in
JScript commands.
VBScript
You can use the VBScript Option Explicit statement in an .asp file to
require variables to be explicitly declared with the Dim, Private, Public,
and ReDim statements. The Option Explicit statement must appear after
any ASP directives and before any HTML text or script commands. This
statement only affects ASP commands that are written in VBScript; it has
no effect on JScript commands.
JScript
Typically, you will only need to declare a variable in JScript when you need
to distinguish a variable inside a function from a global variable used
outside the function. In this case, if you do not distinguish between the
two variables, JScript will assume that that you referring exclusively to the
global variable. For more information on the var statement, see the JScript
Language Reference. You can find this reference at the Microsoft Windows
Script Technologies Web site, located at
http://msdn.microsoft.com/scripting/.
Variable Scope
The scope, or lifetime, of a variable determines which script commands can
access a variable. A variable declared inside a procedure has local scope;
the variable is created and destroyed every time the procedure is executed.
It cannot be accessed by anything outside the procedure. A variable
declared outside a procedure has global scope; its value is accessible and
modifiable by any script command on an ASP page.
If you declare variables, a local variable and a global variable can have the
same name. Modifying the value of one will not modify the value of the
other. If you do not declare variables, however, you might inadvertently
modify the value of a global variable. For example, the following script
commands return the value 1 even though there are two variables named
Y:
<%
Option Explicit
Dim Y
Y = 1
SetLocalVariable
Response.Write Y
Sub SetLocalVariable
Dim Y
Y = 2
End Sub
%>
The following script commands, on the other hand, return the value 2
because the variables are not explicitly declared. When the procedure call
sets Y to 2, the scripting engine assumes the procedure intended to modify
the global variable:
<%
Option Explicit
Dim Y = 1
SetLocalVariable
Response.Write Y
Sub SetLocalVariable
Y = 2
End Sub
%>
ASP provides two built-in objects into which you can store variables: the
Session object and the Application object.
You can also create object instances with session or application scope. For
more information, see Setting Object Scope.
Session Scope
<%
Session("FirstName") = "Jeff"
Session("LastName") = "Smith"
%>
To retrieve information from the Session object, access the named entry by
using the output directive (<%=) or Response.Write. The following example
uses the output directive to display the current value of Session
("FirstName"):
You can store user preferences in the Session object, and then access
<%
strScreenResolution = Session("ScreenResolution")
If strScreenResolution = "Low" Then
%>
This is the text version of the page.
<% Else %>
This is the multimedia version of the page.
<% End If %>
Application Scope
To retrieve information from the Application object, use the ASP output
directive (<%=) or Response.Write to access the named entry from any
subsequent page in the application. The following example uses the output
directive to display the value of Application("Greeting"):
Using Constants
A constant is a name that takes the place of a number or string. Some of
the base components provided with ASP, such as ActiveX Data Objects
(ADO), define constants that you can use in your scripts. A component can
declare constants in a component type library, a file that contains
information about objects and types supported by an COM component.
Once you have declared a type library in your .asp file you can use the
defined constants in any scripts in the same .asp file. Likewise, you can
declare a type library in your Global.asa file to use the defined constants in
any .asp file in an application.
To declare a type library, use the <METADATA> tag in your .asp file or
Global.asa file. For example, to declare the ADO type library, use the
following statements:
Or, rather than referring to the type library's universal unique indentifier
(UUID), you can also refer to the type library by file path:
You can then use ADO constants in the .asp file where you declared the
type library, or in an .asp file residing to an application containing a
Global.asa file with the ADO type library declaration. In the following
example, adOpenKeyset and adLockOptimistic are ADO constants:
<%
'Create and Open Recordset Object.
Set rstCustomerList = Server.CreateObject("ADODB.Recordset")
rstCustomerList.ActiveConnection = cnnPubs
rstCustomerList.CursorType = adOpenKeyset
rstCustomerList.LockType = adLockOptimistic
%>
The following table lists commonly used type libraries and UUIDs:
Note Using the <METADATA> tag rather than the #include directive may
improve the performance of your Web application.
You can define your own constants. In VBScript, use the Const statement.
In JScript, you can the var statement to assign a constant value to
variable. If you want to use your constants on more than one .asp file, put
the definitions in a separate file and include them in each .asp file that
uses the constants.
<SCRIPT LANGUAGE="VBScript">
<!--
client-side script
client-side script
.
.
.
-->
</SCRIPT>
<%
Dim dtmTime, strServerName, strServerSoftware, intGreeting
dtmTime = Time()
strServerName = Request.ServerVariables("SERVER_NAME")
strServerSoftware = Request.ServerVariables("SERVER_SOFTWARE")
<SCRIPT LANGUAGE="JScript">
<!--
function showIntroMsg()
{
switch(<%= intGreeting %>)
{
case 0:
msg = "This is the <%= strServerName%> Web server running <%= strServerSoftware %>.
break
case 1:
msg = "Welcome to the <%= strServerName%> Web server. The local time is <%= dtmTime
break
case 2:
msg = "This server is running <%= strServerSoftware %>."
break
}
document.write(msg)
-->
</SCRIPT>
Writing Procedures
This is preliminary documentation for IIS 5.0 and is subject to change.
You can place procedure definitions in the same .asp file that calls the
procedures, or you can put commonly used procedures in a shared .asp file
and use the #include directive to include it in other .asp files that call the
procedures. Alternatively, you could encapsulate the functionality in a COM
component.
Defining Procedures
Procedure definitions can appear within <SCRIPT> and </SCRIPT> tags and
must follow the rules for the declared scripting language. Use the
<SCRIPT> element for procedures in languages other than the primary
scripting language. However, use the scripting delimiters (<% and %>) for
procedures in the primary scripting language.
When you use the HTML <SCRIPT> tag, you must use two attributes to
ensure server-side processing of the script. The syntax for using the
<SCRIPT> tag is:
procedure definition
</SCRIPT>
The RUNAT=SERVER attribute tells the Web server to process the script on
the server. If you do not set this attribute, the script is processed by the
client browser. The LANGUAGE attribute determines the scripting language
used for this script block. You can specify any language for which you have
the scripting engine installed with the server. To specify VBScript, use the
value VBScript. To specify JScript, use the value JScript. If you do not set
the LANGUAGE attribute, the script block is interpreted in the primary
scripting language.
The commands in the script block must form one or more complete
procedures in the chosen scripting language. For example, the following
commands define the JScript procedure MyFunction.
<HTML>
<SCRIPT LANGUAGE=JScript RUNAT=SERVER >
function MyFunction()
{
Response.Write("You called MyFunction().")
}
</SCRIPT>
Calling Procedures
To call procedures, include the name of the procedure in a command. If you
are calling JScript procedures from VBScript, you must use parentheses
after the procedure name; if the procedure has no arguments, use empty
parentheses. If you are calling either VBScript or JScript procedures from
JScript, always use parentheses after the procedure name.
For VBScript, you can also use the Call keyword when calling a procedure.
However, if the procedure that you are calling requires arguments, the
argument list must be enclosed in parentheses. If you omit the Call
keyword, you also must omit the parentheses around the argument list. If
you use Call syntax to call any built-in or user-defined function, the
function’s return value is discarded.
<%
Sub Echo
Response.Write "</TABLE>"
End Sub
%>
function printDate()
{
var x
x = new Date()
Response.Write(x.toString())
}
</SCRIPT>
Most of the ASP built-in objects provide collections. Collections are data
structures similar to arrays that store strings, numbers, objects and other
values. Unlike arrays, collections expand and contract automatically as
items are retrieved or stored. The position of an item will also move as the
collection is modified. You can access an item in a collection by its unique
string key, by its index (position) in the collection, or by iterating through
all the items in the collection.
<%
Session.Contents("FirstName") = "Meng"
Session.Contents("LastName") = "Phua"
Session.Contents("Age") = 29
%>
You can access an item by using the string key you associated with the
item when you stored it in the collection. For example, the following
expression returns the string "Meng":
You could also access an item by using the index, or number, associated
with an item. For example, the following expression retrieves the
information stored in the second position of the Session object and returns
"Phua":
ASP collections are numbered starting with 1. The index associated with an
item might change as items are added to or removed from the collection.
You should not depend on an item’s index remaining the same. Indexed
access is generally used to iterate through a collection, as described in the
following topics, or to access an item in a read-only collection.
You can also use a shorthand notation to access items by name. ASP
searches the collections associated with an object in a particular order. If
an item with a particular name appears only once in an object's collections,
you can eliminate the collection name (although doing so may affect
performance):
Eliminating the collection name is generally safe when you are accessing
items stored in the Application or Session object. For the Request object,
however, it is safer to specify the collection name because the collections
could easily contain items with duplicate names.
<%
'Declare a counter variable.
Dim strItem
You can also iterate through a collection by using the VBScript For...Next
statement. For example, to list the three items stored in Session by the
previous example, use the following statements:
<%
'Declare a counter variable.
Dim intItem
Because you do not usually know how many items are stored in a
collection, ASP supports the Count property for a collection, which returns
the number of items in the collection. You use the Count property to
specify the end value of the counter.
<%
'Declare a counter variable.
Dim lngItem, lngCount
lngCount = Session.Contents.Count
'Repeat this loop until the counter equals the number of items
'in the collection.
For lngItem = 1 To lngCount
Response.Write Session.Contents(lngItem) & "<BR>"
Next
%>
In JScript, you use the for statement to loop through a collection. For
greater efficiency when using the Count property with a JScript for
statement, you should assign the value of Count to a local variable and
use that variable to set the end value of the counter. That way, the script
engine does not have to look up the value of Count each time through the
loop. The following example demonstrates this technique:
<%
var intItem, intNumItems;
intNumItems = Session.Contents.Count;
Microsoft JScript supports an Enumerator object that you can also use to
iterate through an ASP collection. The atEnd method indicates whether
there are any more items in the collection. The moveNext method moves
to the next item in the collection.
<%
Session.Contents("Name") = "Suki White"
Session.Contents("Department") = "Hardware"
.
.
.
//Create an Enumerator object.
var mycollection = new Enumerator(Session.Contents);
<%
'Send a cookie to the browser.
Response.Cookies("Fruit") = "Pineapple"
The cookie text in the HTTP response sent to the browser would appear as
the following:
You can also enumerate all the cookies in the Request.Cookies collection
and all the subkeys in a cookie. However, iterating through subkeys on a
cookie that does not have subkeys will not produce an item. You can avoid
this situation by first checking to see whether a cookie has subkeys by
using the HasKeys attribute of the Cookies collection. This technique is
demonstrated in the following example.
<%
'Declare counter variables.
Dim Cookie, Subkey
Mammals
->ELEPHANT = African
->DOLPHIN = Bottlenosed
Fruit = Pineapple
strUserID = Request.Cookies("User")
strUserName = Request.QueryString("User")
The case of the key name is set by the first collection to assign a value to
the key. Examine the following script:
<%
'Retrieve a value from QueryString collection using the UserID key.
strUser = Request.QueryString("UserID")
'Send a cookie to the browser, but reference the key, UserId, which has a different spel
Response.Cookies("UserId")= "1111-2222"
Response.Cookies("UserId").Expires="December 31, 2000"
%>
Although it may appear that key name UserId was assigned to the cookie,
in actuality, the key name UserID (which is capitalized differently) was
assigned to the cookie. The QueryString collection was first to define the
case of this key.
When you iterate through a collection that contains objects, you can either
access the object's Session or Application state information or access the
object's methods or properties. For example, suppose your application uses
several objects to create a user account, and each object has an
initialization method. You could iterate through the StaticObjects
collection to retrieve object properties:
<%
For Each Object in Session.StaticObjects
Response.Write Object & ": " & Session.StaticObjects(Object)
Next
%>
Using the ASP Request object you can create simple, yet powerful scripts
for collecting and processing data gathered with HTML forms. In this topic
you will not only learn how to create basic form processing scripts, but also
acquire useful techniques for validating form information, both on your Web
server and at the user's browser.
For example, the following HTML tags generate a form where a user can
enter their first name, last name, and age, and includes a button for
submitting information to a Web server. The form also contains an hidden
input tag (not displayed by the Web browser) that you can use to pass
additional information to a Web server.
Detailing the complete set of HTML form tags is outside the scope of this
topic, however, there are numerous sources of information that you can use
to learn about creating useful and engaging HTML forms. For example, use
your Web browser's source viewing feature to examine how HTML forms are
created on other Web sites. Also, visit Microsoft's MSDN Online Web site at
http://msdn.microsoft.com/ to learn innovative ways of using HTML forms
with other Internet technologies.
After creating an HTML form, you will need to process user input, which
means sending the information to an .asp file for parsing and manipulation.
Once again, examine the HTML code from the previous example. Notice that
the <FORM> tag's ACTION attribute refers to a file called Profile.asp. When
the user submits HTML information, the browser uses the POST method to
send to the information to an .asp file on the server, in this case
Profile.asp. The .asp file may contain scripts that process information and
interact with other scripts, COM components, or resources, such as a
database.
Using ASP, there are three basic ways to collect information from HTML
forms:
? A static .htm file can contain a form that posts its values to an .asp
file.
? An .asp file can create a form that posts information to another .asp
file.
? An .asp file can create a form that posts information to itself, that is,
to the .asp file that contains the form.
The first two methods operate in the same way as forms that interact with
other Web server programs, except that with ASP, the task of collecting and
processing form information is greatly simplified. The third method is a
particularly useful and will be demonstrated in the Validating Form Input
section.
For example, if the previous form example used the GET method
(METHOD="GET") and the user typed Clair, Hector, and 30, then the
following URL request would be sent to the server:
http://Workshop1/Painting/Profile.asp?FirstName=Clair&LastName=Hector&Age=30&UserStatus=Ne
<%
If Request.QueryString("UserStatus") = "New" Then
Response.Write "This is your first visit to this Web site!"
End if
%>
In this case, the Web server would return the following text to the user's
Web browser:
Hello Clair Hector. You are 30 years old! This is your first visit to this Web site!
The QueryString collection also has an optional parameter that you can
use to access one of multiple values that appear in the URL request (using
the GET method). You can also use the Count property to count the number
of times that a specific type of value appears.
For example, a form containing a list box with multiple items can generate
the following request:
http://OrganicFoods/list.asp?Food=Apples&Food=Olives&Food=Bread
Request.QueryString("Food").Count
To display the multiple values types, List.asp could contain the following
script:
<%
lngTotal = Request.QueryString("Food").Count
For i = 1 To lngTotal
Response.Write Request.QueryString("Food")(i) & "<BR>"
Next
%>
Apples
Olives
Bread
You can also display the entire list of values as a comma-delimited string
by using the following:
Form Collection
When you use the HTTP GET method to pass long and complex form values
to a Web server, you run the risk of losing information. Some Web servers
tend to restrict the size of the URL query string, so that lengthy form
values passed with the GET method might be truncated. If you need to
send a large amount of information from a form to a Web server, you
should use the HTTP POST method. The POST method, which sends form
data in the HTTP request body, can send a an almost unlimited number of
characters to a server. You can use the ASP Request object's Form
collection to retrieve the values sent with the POST method.
<%
lngTotal = Request.Form("Food").Count
For i = 1 To lngTotal
Response.Write Request.Form("Food")(i) & "<BR>"
Next
%>
The following client-side script validates user–input (in this case, the script
determines whether an account number entered by the user is actually a
number) prior to sending information to the server:
<SCRIPT LANGUAGE="JScript">
function CheckNumber()
{
if (isNumeric(document.UserForm.AcctNo.value))
return true
else
{
alert("Please enter a valid account number.")
return false
}
}
</FORM>
Using this method of processing and validating user input can greatly
enhance the usability and responsiveness of your Web based forms. For
example, by placing error information adjacent to the form field where
invalid information was entered, you make it easier for the user to discover
the source of the error. (Typically, Web-based forms forward requests to a
separate Web page containing error information. Users who do not
immediately understand this information may become frustrated.)
For example, the following script determines whether a user entered a valid
account number by posting information to itself (Verify.asp) and calling a
user defined function that queries a database:
<%
strAcct = Request.Form("Account")
If Not AccountValid(strAcct) Then
ErrMsg = "<FONT COLOR=Red>Sorry, you may have entered an invalid account number.</FONT
Else
Process the user input
.
.
.
Server.Transfer("Complete.asp")
End If
Function AccountValid(strAcct)
A database connectivity script or component method call goes here.
End Function
%>
In this example, the script is located in a file named Verify.asp, the same
file that contains the HTML form; it posts information to itself by specifying
Verify.asp in the ACTION attribute.
<%
var Name = Request.Form("Name")();
var Password = Request.Form("Password")();
About Components
A COM component is a reusable, programmatic building block that contains
code for performing a task or set of tasks. Components can be combined
with other components (even across networks) to create a Web application.
COM components execute common tasks so that you do not have to create
your own code to perform these tasks. For example, you can use a stock
ticker component to display the latest stock quotes on a Web page.
However, it would be difficult to create a script that provides the same
functionality. Also, the script would not be as reusable as a component.
If you are new to scripting, you can write scripts that use components
without knowing anything about how the component works. ASP comes with
base components that you can use immediately. For example, you can use
the ActiveX Data Objects (ADO) components to add database connectivity
to your Web pages. Additional components can also be obtained from third-
party developers.
If you are a Web application developer, components are the best way to
encapsulate your business logic into reusable, secure modules. For
example, you could use a component to verify credit card numbers by
calling the component from a script that processes sales orders. Because
the verification is isolated from the order process, you can update the
component when the credit card verification process changes, without
changing your order process. Also, since COM components are reusable, you
could reuse the component in other scripts and applications. Once you have
installed a component on your Web server, you can call it from a ASP
server-side script, an ISAPI extension, another component on the server, or
a program written in another COM-compatible language.
You can create components in any programming language that supports the
Component Object Model (COM), such as C, C++, Java, Visual Basic, or
numerous scripting languages. (If you are familiar with COM programming,
COM components are also known as Automation servers.) To run on the
Web server, your COM components cannot have any graphical user interface
elements, such as the Visual Basic MsgBox function; graphical interface
elements would only be viewable on the server, and not the browser.
VBScript:
JScript:
If you are already familiar with VBScript or JScript, note that you do not use
the scripting language’s function for creating a new object instance
(CreateObject in VBScript or New in JScript). You must use the ASP
Server.CreateObject method; otherwise, ASP cannot track your use of the
object in your scripts.
You can also use the HTML <OBJECT> tag to create an object instance.
You must supply the RUNAT attribute with a value of Server, and you must
provide the ID attribute set to the variable name you will use in your
scripts. You can identify the object by using either its registered name
(PROGID) or its registered number (CLSID).The following example uses the
registered name (PROGID) to create an instance of the Ad Rotator object:
<SCRIPTLET>
<Registration
Description="ConvertTemp"
ProgID="ConvertTemp.Scriptlet"
Version="1.00"
>
</Registration>
<SCRIPT LANGUAGE=VBScript>
Function Celsius(F)
Celsius = 5/9 * (F - 32)
End Function
Function Fahrenheit(C)
Fahrenheit = (9/5 * C) + 32
End Function
</SCRIPT>
</SCRIPTLET>
Before implementing this Windows Script Component you must save this
file with an .sct extension and then in Windows Explorer, right-click this file
and select Register. To use this Windows Script Component in a Web
page, you would use a server-side script such as the following:
<%
Option Explicit
Dim objConvert
Dim sngFvalue, sngCvalue
sngFvalue = 50
sngCvalue = 21
Object.Method parameters
For example, you can use the Write method of the Response built-in
object to send information to the browser as shown in the following
statement:
Object.Property
You can sometimes read and set the value of a property. In addition, for
some objects, you can also add new properties.
For some properties, you can display the current value by using the ASP
output directive. For example, the following statement returns TRUE if the
browser is still connected to the server:
<%
Dim dtmDate
Set dtmDate = GetObject("java:java.util.Date")
%>
The scope of an object determines which scripts can use that object. By
default, when you create an object instance, the object has page scope.
Any script command in the same ASP page can use a page-scope object;
the object is released when the .asp file completes processing the request.
The recommended scope for most objects is page scope. You can change
the scope of an object, however, to make it accessible from scripts on other
pages. This topic explains how to work with page scope objects and how to
change the scope of objects.
In general, you should avoid creating objects inside a loop. If you must
create objects in a loop, you should manually release the resources used by
an object:
<%
Dim objAd
For i = 0 To 1000
Set objAd = Server.CreateObject("MSWC.AdRotator")
.
.
.
objAd.GetAdvertisement
.
.
.
Set objAd = Nothing
Next
%>
To give an object session scope, store the object in the ASP Session built-
in object. You can use either the HTML <OBJECT> tag in a Global.asa file
or the Server.CreateObject method on an ASP page to create a session
scope object instance.
In the Global.asa file, you can use the <OBJECT> tag, extended with
RUNAT attribute (which must be set to SERVER) and the SCOPE attribute
(which must be set to Session). The following example creates a session-
scope instance of the Browser Type object of the Browser Capabilities
component:
Once you have stored the object in the Session object, you can access the
object from any page in the application. The following statement uses the
object instance created by the <OBJECT> tag in the previous example:
To display browser information in a different .asp file, you first retrieve the
instance of the BrowserType object stored in the Session object, and
then call the Browser method to display the name of the browser:
ASP does not instantiate an object that you declare with the <OBJECT> tag
until that object is referenced by a script command from an .asp file. The
Server.CreateObject method instantiates the object immediately. Thus,
the <OBJECT> tag offers better scalability than the Server.CreateObject
method for session-scope objects.
To give an object application scope, store the object in the ASP Application
built-in object. You can use either the <OBJECT> tag in a Global.asa file or
the Server.CreateObject method in an .asp file to create an application
scope object instance.
In the Global.asa file, you can use the <OBJECT> tag, extended with
RUNAT attribute (which must be set to Server) and the SCOPE attribute
(which must be set to Application). For example, the following is an
example of using the <OBJECT> tag to create an application-scope
instance of the Ad Rotator object:
After storing the Ad Rotator object in Application state, you can access
from any page in you application using a statement such as the following:
<%=MyAds.GetAdvertisement("CustomerAds.txt") %>
Because you may not always have control over the threading model of the
objects you use, the following guidelines will help you get the best
performance:
? Page scope objects Objects marked Both or Apartment will give you
the best performance.
? Application scope objects Objects marked Both, that also aggregate
the FreeThreadedMarshaler, will give you the best performance. You
can use either the <OBJECT> tag or the Server.CreateObject method
to store objects marked Both in the Application object. You must use
the HTML <OBJECT> tag with apartment-threaded objects.
? Session scope objects Objects marked Both will give you the best
performance. Using single-threaded or apartment-threaded objects will
cause the Web server to lock the session down to one thread. Free-
threaded objects do not lock down the session, but are slow. You can
use either the <OBJECT> tag or the Server.CreateObject method to
store objects in the Session object.
Sending Content
To send content to the browser from within ASP delimiters or from a
procedure, use the Write method of the Response object. For example,
the following statement sends a different greeting to the user depending
on whether the user has visited the page before:
<%
If blnFirstTime Then
Response.Write "<H3 ALIGN=CENTER>Welcome to the Overview Page.</H3>"
Else
Response.Write "<H3 ALIGN=CENTER>Welcome Back to the Overview Page.</H3>"
End If
%>
<H3 ALIGN=CENTER>
<% If blnFirstTime Then %>
Welcome to the Overview Page.
<% Else %>
Welcome Back to the Overview Page.
<% End If %>
</H3>
Intersperse script commands and HTML when you just need to return output
once or when it is more convenient to add statements to existing HTML
text. Use Response.Write when you do not want to break up a statement
with delimiters or when you want to build the string that is returned to the
browser. For example, you could construct a string of text that builds a
table row with values sent by an HTML form:
Request.Form returns the values sent from an HTML form (see Processing
User Input).
You can use the ContentType property of the Response object to set the
HTTP content type string for the content you send to a user. For example,
the following command sets the content type for channel definitions:
Other common content types are text/plain (for content returned as text
instead of interpreted HTML statements), image/gif (for GIF images),
image/jpeg (for JPEG images), video/quicktime (for movies in the Apple
QuickTime® format), and text/xml (for XML documents). In addition, a Web
server or Web browser may support custom MIME types. To see the content
types already defined by your Microsoft Web server, use the Internet
Information Services snap-in, to open the property sheets for your Web
site, click the HTTP Headers tab, and then click the File Types tab. These
file types may be used as a reference when you choose to manually set the
content type with ASP.
<%
If Session("CustomerID") = "" Then
Response.Redirect "Register.asp"
End If
%>
server-side scripts which are processed before any content is sent to the
user are said to be buffered. ASP enables you to turn buffering on or off,
and this configuration can greatly affect the behavior of the Redirect
method. Specifically, if you have buffering turned off, then you must
redirect the browser before your page's HTTP headers are returned to the
browser.
Place the Response.Redirect statement at the top of the page, before any
text or <HTML> tags, to ensure that nothing has been returned to the
browser. If you use Response.Redirect after content or headers have been
returned to the browser, you will see an error message. Also note that
Response.Redirect does not need to be followed by Response.End.
You can use the Server.Transfer method to transfer from one .asp file to
another file located on the same server instead of the Response.Redirect
method. With Server.Transfer you can directly transfer requests for .asp
files without ever leaving the server request queue, thus eliminating costly
round-trips.
For example, the following script demonstrates how you could use
Server.Transfer to jump between the pages of an application depending
on state information:
<%
If Session("blnSaleCompleted") Then
Server.Transfer("/Order/ThankYou.asp")
Else
Server.Transfer("/Order/MoreInfo.asp")
End if
%>
requested file.
You can also use Server.Transfer to transfer between .asp files located in
different applications. However, when you transfer to an .asp file located in
another application, the file will behave as if it was part of the application
that initiated the transfer (that is, the file has access only to variables
scoped for the initiating application, not for the application where the file
actually resides). For example, if you transfer from a file located in the
Sales Application to a file located in the Personnel Application, then the
Sales Application effectively borrows this file from the Personnel Application
and runs it as if it were part of the Sales Application.
ASP also provides the Server.Execute command that you can use to
transfer to a file, execute its content, and then return to the file that
initiated the transfer. If you are familiar with VBScript, it will help you to
think of Server.Execute as analogous to a procedure call, except that
instead of executing a procedure, you are executing an entire .asp file.
For example, the following script demonstrates how you could use
Server.Execute to do dynamic inclusion of .asp files:
<%
.
.
.
If blnUseDHTML Then
Server.Execute("DHTML.asp")
Else
Server.Execute("HTML.asp")
End If
.
.
.
%>
Buffering Content
By default, the Web server processes all script commands on a page before
any content is sent to the user. This process is known as buffering. You can
use the Buffer property of the Response object to disable buffering, so
that the Web server returns HTML and the results of scripts as it processes
a page.
The advantage of buffering your .asp files is that you can abort sending a
Web page if, for example, the script processing does not proceed correctly
or if a user does not have appropriate security credentials. Instead, you can
transfer the user to another page using Server.Transfer, or clear the
buffer (using the the Clear method of the Response object) to send
different content to the user. Depending on your application, you may want
to use the Clear method before transferring. The following example uses
both of these methods:
<HTML>
<BODY>
.
.
.
<%
If Request("CustomerStatus") = "" Then
Response.Clear
Server.Transfer("/CustomerInfo/Register.asp")
Else
Response.Write "Welcome back " & Request("FirstName") & "!"
.
.
.
End If
%>
</BODY>
</HTML>
You could also use Response.Buffer to prevent the Web server from
returning the HTTP header before a script can modify the header. Certain
properties and methods, such as Response.Expires and
Response.Redirect, modify the HTTP header.
If the Buffer property in a script is set to TRUE without also calling the
Flush method to immediately send buffered content to the browser, the
server will maintain Keep-Alive requests made by the client. The benefit of
writing scripts in this manner is that server performance is improved
because the server does not have to create a new connection for each
client request (assuming that the server, client, and any proxy servers all
support Keep-Alive requests). However, a potential drawback to this
approach is that buffering prevents the server's response from being sent
to the user until the server has finished processing the entire script. For
long or complicated scripts, users could experience long wait times before
seeing the page.
Buffering is turned on by default for ASP applications. You can use the
Internet Information Services snap-in, to turn off buffering for an entire ASP
application.
Although caching works well for many HTML pages, it often does not work
well for ASP pages that contain frequently updated information. For
example, pages that report stock market prices or display inventory for a
high-volume business must provide timely information. Information that is
even one hour old might not be accurate enough. If your application returns
personalized information, such as a custom home page, you want to ensure
that no user sees another user's personal information.
By default, ASP instructs proxy servers not to cache the ASP page itself
(although images, image maps, applets, and other items referenced from
the page are cached). You can allow caching for certain pages by using the
Response.CacheControl property to set the Cache-Control HTTP header
field. The default value of Response.CacheControl is the string "Private",
which prevents proxy servers from caching the page. To allow caching, set
the Cache-Control header field to Public:
Because HTTP headers must be sent to the browser or proxy before any
page content is sent, either put the Response.CacheControl property
before any HTML tags or, if you have disabled buffering, use
Response.Buffer to buffer the page.
The Cache-Control header field is part of the HTTP 1.1 specification. ASP
pages are not cached on proxy servers that support only HTTP 1.0 because
no Expires header field is sent.
http://www.microsoft.com/windows/ie/.
Using ASP, you can write scripts that dynamically create channels by
generating a channel definition file. An XML-based channel definition file
(.cdf) describes the organization and update schedule of a channel's
contents. Commands in the .cdf file use syntax similar to HTML tags, so
they are easy to learn and to generate from a script. When you write a
server-side script to create a channel definition file, give the file a .cdx
extension. When ASP reads a file with a .cdx extension, it automatically
sends the application/x-cdf content type, which tells the browser to
interpret the bytes as channel definitions. If you do not use the .cdx
extension, your script must manually set the content type to application/x-
cdf by using Response.ContentType.
Here is an example of how you might use channels. The following HTML
form asks the user to select channels. When submitted, the form calls a
script in a .cdx file to create the channel definitions.
The script in Chan.cdx builds the channel definitions based on the form
values submitted with the request.
Including Files
This is preliminary documentation for IIS 5.0 and is subject to change.
The virtual and file keywords indicate the type of path you are using to
include the file, and filename is the path and file name of the file you want
to include.
You can also use the file keyword with the syntax (..\) to include a file
from a parent, or higher-level, directory if the Enable Parent Paths option
is selected in the Internet Information Services snap-in.
ASP includes files before executing script commands. Therefore, you cannot
use a script command to build the name of an included file. For example,
the following script would not open the file Header1.inc because ASP
attempts to execute the #include directive before it assigns a file name to
the variable name.
<%
For i = 1 to n
statements in main file
%>
<!-- #include file="header1.inc" -->
<% Next %>
Note If the file that your ASP script includes contains a large number of
functions and variables that are unused by the including script, the extra
resources occupied by these unused structures can adversely affect
performance, and ultimately decrease the scalability of your Web
application. Therefore, it is generally advisable to break your include files
into multiple smaller files, and include only those files required by your
server-side script, rather than include one or two larger include files that
may contain superfluous information.
The following table shows the correct syntax for including files with the SRC
attribute by means of either virtual or relative paths:
Note You should not put any programmatic logic between the <SCRIPT>
tags when including by this method; use another set of <SCRIPT> tags to
add such logic.
Managing Sessions
This is preliminary documentation for IIS 5.0 and is subject to change.
If, for a specific session, you want to set a timeout interval that is shorter
than the default application timeout, you can also set the Timeout
property of the Session object. For example, the following script sets a
timeout interval of 5 minutes.
You can also set the timeout interval to be greater than the default value,
the value determined by the Session Timeout property.
Note A user's requests that are queued up for execution prior to initiating
Session.Abandon will execute within the context of the session being
abandoned. After Session.Abandon has completed execution, new
incoming requests will not be associated with the session.
The SessionID cookie is similar to a locker key in that, as the user interacts
with an application during a session, ASP can store information for the user
in a "locker" on the server. The user's SessionID cookie, transmitted in the
HTTP request header, enables access to this information in the way that a
locker key enables access to a locker's contents. Each time that ASP
receives a request for a page, it checks the HTTP request header for a
SessionID cookie.
After storing the SessionID cookie in the user's browser, ASP reuses the
same cookie to track the session, even if the user requests another .asp
file, or requests an .asp file running in other application. Likewise, if the
user deliberately abandons or lets the session timeout, and then proceeds
to request another .asp file, ASP begins a new session using the same
cookie. The only time a user receives a new SessionID cookie is when the
server administrator restarts the server, thus clearing the SessionID
settings stored in memory, or the user restarts the Web browser.
By reusing the SessionID cookie, ASP minimizes the number of cookies sent
to the browser. Additionally, if you determine that your ASP application
does not require session management, you can prevent ASP from tracking
session and sending SessionID cookies to users.
ASP will not send the session cookies under the following conditions:
You should also note that SessionID cookies are not intended to provide a
permanent means for tracking users across multiple visits to a Web site.
The SessionID information stored in the server computer's memory can be
easily lost. If you want track users who visit your Web application over a
longer periods, you must create a user identification by storing a special
<%
Session("FirstName") = "Jeff"
Session("LastName") = "Smith"
%>
To retrieve information from the Session object, access the named entry.
For example, to display the current value of Session("FirstName"):
You can store user preferences in the Session object, and then access that
preference to determine what page to return to the user. For example, you
can allow a user to specify a text-only version of your content in the first
page of the application and apply this choice on all subsequent pages that
the user visits in this application.
You can also store an object instance in the Session object, although doing
so can affect server performance. For more information, see Setting Object
Scope.
The Session object's Contents collection contains all of the variables that
have been stored (that is, those stored without using the HTML <OBJECT>
tag) for a session. By using the Contents collection's Remove method, you
can selectively remove a reference to a variable that was added for the
session state. The following script illustrates how to use the Remove
method to purge an item, in this case user discount information, from the
Session object:
<%
If Session.Contents("Purchamnt") <= 75 then
Session.Contents.Remove("Discount")
End If
%>
If desirable, you can also use the Contents collection's RemoveAll method
to completely remove all variables stored for the session:
Session.Content.RemoveAll()
Using the Remove method you can choose to delete items by name or by
index. The following script demonstrates how to cycle through values stored
in the Session object and conditionally remove values by index:
<%
For Each intQuote in Session.Contents
If Session.Contents(intQuote) < 200 Then
Session.Contents.Remove(intQuote)
End If
Next
%>
The browser will request the specified page, and all subsequent requests
will be routed to the same server as long as specific server names are not
referenced in the original URLs.
Using Cookies
A cookie is a token that the Web server embeds in a user's Web browser to
identify the user. The next time the same browser requests a page, it
sends the cookie it received from the Web server. Cookies allow a set of
information to be associated with a user. ASP scripts can both get and set
the values of cookies by using the Cookies collection of the Response and
Request objects.
Setting Cookies
If you want a cookie to be used only during the current user session, then
sending the cookie to the browser is all you need to do. However, if you
want to identify a user even after the user has stopped and restarted the
browser, you must force the browser to store the cookie in a file on the
client computer's hard disk. To save the cookie, use the Expires attribute
for Response.Cookies and set the date to some date in the future:
<%
Response.Cookies("VisitorID") = 49
Response.Cookies("VisitorID").Expires = "December 31, 2001"
%>
Getting Cookies
Similarly, to retrieve a key value from an indexed cookie, use the key name.
Cookie: VisitorID=49=Travel
Each cookie stored by ASP on the user's Web browser contains path
information. When the browser requests a file stored in the same location
as the path specified in the cookie, the browser automatically forwards the
cookie to the server. By default, cookie paths correspond to the name of
the application containing the .asp file that originally generated the cookie.
For example, if an .asp file, residing in an application called
UserApplication, generates a cookie, then each time a user's Web browser
retrieves any file residing in that application, the browser will forward the
cookie, in addition to any other cookies containing the
path /UserApplication.
To specify a path for a cookie other than the default application path, you
can use the ASP Response.Cookies collection's Path attribute. For
example, the following script assigns the path SalesApp/Customer/Profiles/
to a cookie called Purchases:
<%
Response.Cookies("Purchases") = "12"
Response.Cookies("Purchases").Expires = "January 1, 2001"
Response.Cookies("Purchases").Path = "/SalesApp/Customer/Profiles/"
%>
Whenever the Web browser containing the Purchases cookie requests a file
residing in the path /SalesApp/Customer/Profiles/ or in any of it
subdirectories, the browser forwards the cookie to the server.
You can use the following statement to set the cookie path so that the
user's Web browser will forward a cookie whenever the browser requests a
file from your server, regardless of application or path:
Response.Cookies("Purchases").Path = "/"
Not all browsers support cookies. Even with browsers that do support
cookies, some users prefer to turn off cookie support. If your application
needs to be responsive to browsers that don't support cookies, you cannot
use ASP session management.
In this case, you must write your own mechanism to pass information from
page to page in your application. There are two general ways to do this:
http://MyServer/MyApp/start.asp?name=Jeff
? Add hidden values to a form. For example, the following HTML form
contains a hidden control, which does not appear on the actual form
and remains invisible in the user's Web browser. The form passes a
user identification value, in addition to the information supplied by the
user, by using the HTTP POST method.
This method requires all link destinations that pass user information
to be coded as HTML forms.
If you are not using ASP session management, you should turn off session
support for your application. When sessions are enabled, ASP sends a
SessionID cookie to each browser that requests a page. To turn off session
support, clear the Enable Session State check box on the Application
Options property sheet in the Internet Information Services snap-in.
You should place this script as the first line in your .asp file, before any
other scripts. The default, when this tag is omitted, enables session
tracking.
Sessionless ASP pages can often improve the responsiveness of your server
by eliminating potentially time consuming session activity. For example,
consider the case of an ASP page containing two HTML frames: frames 1
and 2, both within one frameset. Frame 1 contains an .asp file that
executes a complex script, while frame 2 contains a simpler .asp file.
Because ASP executes session requests in sequential order, or serially, you
will not be able to see the contents of frame 2 until the script in frame 1
has executed. However, if you make the .asp file for frame 1 sessionless,
then ASP requests will no longer be serialized and the browser will render
the contents of frame 2 before the contents of frame 1 have finished
executing.
Unfortunately, the way in which multiple requests for different frames are
processed ultimately depends on the configuration of the user's Web
browser. Certain Web browsers may serialize requests despite the
sessionless configuration of your .asp files.
For more information about ADO, visit the Microsoft Universal Data Access
The following table lists OLE DB connection strings for several common
data sources:
Note Connection strings that use a UNC path to refer to a data source
located on a remote computer can pose a potential security issue. To
prevent unauthorized access of your data source, create a Windows account
for computers requiring access to the data and then apply appropriate NTFS
permissions to the data source.
issues:
For more information about these issues, visit the Microsoft Product
Support Services Web site at http://www.microsoft.com/support/.
<%
'Create a connection object.
Set cnn = Server.CreateObject("ADODB.Connection")
'Open a connection using the OLE DB connection string.
cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\MarketData\ProjectedSales.mdb
%>
Note The connection string does not contain spaces before or after the
equal sign (=).
The following script uses the Execute method to issue a query in the form
of a SQL INSERT command, which inserts data into a specific database
table. In this case, the script block inserts the name Jose Lugo into a
database table named Customers.
<%
'Define the OLE DB connection string.
strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Employees.md
Note that two parameters are specified in the statement used to execute
the query: adCmdText and adExecuteNoRecords. The optional
adCmdText parameter specifies the type of command, indicating that the
provider should evaluate the query statement (in this case, a SQL query) as
a textual definition of a command. The adExecuteNoRecords parameter
instructs ADO to not create a set of data records if there are no results
returned to the application. This parameter works only with command types
defined as a text definition, such as SQL queries, or stored database
procedures. Although the adCmdText and adExecuteNoRecords
parameters are optional, you should specify theses parameters when using
the Execute method to improve the performance of your data application.
For details about implementing component type libraries, see the Using
Constants section of the Using Variables and Constants topic.
In addition to the SQL INSERT command, you can use the SQL UPDATE
and DELETE commands to change and remove database information.
With the SQL UPDATE command you can change the values of items in a
database table. The following script uses the UPDATE command to change
the Customers table's FirstName fields to Jeff for every LastName field
containing the last name Smith.
<%
Set cnn = Server.CreateObject("ADODB.Connection")
cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Employees.mdb"
cnn.Execute "UPDATE Customers SET FirstName = 'Jeff' WHERE LastName = 'Smith' ",,adCmdTe
%>
To remove specific records from a database table, use the SQL DELETE
command. The following script removes all rows from the Customers table
where the last name is Smith:
<%
Set cnn = Server.CreateObject("ADODB.Connection")
cnn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Employees.mdb"
cnn.Execute "DELETE FROM Customers WHERE LastName = 'Smith'",,adCmdText + adExecuteNoRec
%>
Note You must be careful when using the SQL DELETE command. A
DELETE command without an accompanying WHERE clause will delete all
rows from a table. Be sure to include a SQL WHERE clause, which specifies
the exact rows to be deleted.
Recordset object has features that you can use, depending on your query
constraints, for retrieving and displaying a set of database rows, or records.
The Recordset object maintains the position of each record returned by a
query, thus enabling you to step through results one item at a time.
<%
'Establish a connection with data source.
strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Employees.m
Set cnn = Server.CreateObject("ADODB.Connection")
cnn.Open strConnectionString
%>
Note that in the previous example, the Connection object established the
database connection, and the Recordset object used the same connection
to retrieve results from the database. This method is advantageous when
you need to precisely configure the way in which the link with the database
is established. For example, if you needed to specify the time delay before
a connection attempt aborts, you would need to use the Connection object
to set this property. However, if you just wanted to establish a connection
using ADO's default connection properties, you could use Recordset
object's Open method to establish a link:
<%
strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Employees.m
strSQL = "SELECT FirstName, LastName FROM Customers WHERE LastName = 'Smith' "
Set rstCustomers = Server.CreateObject("ADODB.Recordset")
<%
Set rs = Server.CreateObject("ADODB.Recordset")
rs.Open "SELECT * FROM NewOrders", "Provider=Microsoft.Jet.OLEDB.3.51;Data Source=
Do Until rs.EOF
Response.Write rs("CustomerFirstName") & " " & rs("CustomerLastName") & "<
Response.Write rs("AccountNumber") & "<BR>"
Response.Write rs("Quantity") & "<BR>"
Response.Write rs("DeliveryDate") & "<BR><BR>"
rs.MoveNext
Loop
Else
Response.Write "There are less than " & rs.RecordCount & " new orders."
End If
rs.Close
%>
<%
'Open a connection using Connection object. Notice that the Command object
'does not have an Open method for establishing a connection.
strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Inventory.
Set cnn = Server.CreateObject("ADODB.Connection")
cnn.Open strConnectionString
need to define its value. Since ADO uses a large number of parameters, it
is easier to define parameters by means of a component type library, a file
containing definitions for every ADO parameter and constant. For details
about implementing ADO's type library, see the Using Constants section of
the Using Variables and Constants topic.
In the previous example, you will note that the script repeatedly constructs
and reissues a SQL query with different values, without having to redefine
and resend the query to the database source. Compiling your queries with
the Command object also offers you the advantage of avoiding problems
that can arise from concatenating strings and variables to form SQL
queries. In particular, by using the Command object's Parameter
collection, you can avoid problems related to defining certain types of
string, date, and time variables. For example, SQL query values containing
apostrophes (') can cause a query to fail:
Note that the last name O'Hara contains an apostrophe, which conflicts
with the apostrophes used to denote data in the SQL VALUES keyword. By
binding the query value as a Command object parameter, you avoid this
type of problem.
<%
'Open a connection using Connection object. The Command object
'does not have an Open method for establishing a connection.
strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\CompanyCatalog\S
Set cnn = Server.CreateObject("ADODB.Connection")
cnn.Open strConnectionString
cmn("type") = Request.Form("SeedType")
cmn.Execute ,,adCmdText + adExecuteNoRecords
%>
For more information about forms and using the ASP Request object, see
Processing User Input.
Pooling Connections
If you want your ODBC driver to participate in connection pooling you must
configure your specific database driver and then set the driver's CPTimeout
property in the Windows registry. The CPTimeout property determines the
length of time that a connection remains in the connection pool. If the
connection remains in the pool longer than the duration set by CPTimeout,
the connection is closed and removed from the pool. The default value for
CPTimeout is 60 seconds.
\HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBCINST.INI\driver-name\CPTimeout = timeout
(REG_SZ, units are in seconds)
For example, the following key sets the connection pool timeout to 180
seconds (3 minutes) for the SQL Server driver.
Note By default, your Web server activates connection pooling for SQL
Server by setting CPTimeout to 60 seconds.
Although you can reuse a connection across multiple pages by storing the
connection in ASP's Application object, doing so may unnecessarily keep
open a connection open, defeating the advantages of using connection
pooling. If you have many users that need to connect to the same ASP
database application, a better approach is to reuse a database connection
string across several Web pages by placing the string in ASP's Application
object. For example, you can specify a connection string in the Global.asa
file's Application_OnStart event procedure, as in the following script:
Then in each ASP file that accesses the database, you can write
to create an instance of the connection object for the page, and use the
script
cnn.Open Application("ConnectionString")
to open the connection. At the end of the page, you close the connection
with
cnn.Close
Closing Connections
<%
strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Data\Inventory.md
Set cnn = Server.CreateObject("ADODB.Connection")
cnn.Open strConnectionString
cnn.Close
%>
Understanding Transactions
This is preliminary documentation for IIS 5.0 and is subject to change.
About Transactions
A transaction is an operation that succeeds or fails as a whole. Transaction
processing is used to update databases reliably. When you are making
many related changes to a database or updating several databases at
once, you want to ensure that all of the changes are correctly executed. If
any of the changes fail, you want to restore the original state of the
database tables.
Without Component Services, you would have to write your scripts and
components to manually track the requested changes and restore data if
any changes failed. With Component Services, you simply declare your
scripts and components to require transactions and let Component Services
handle the transaction coordination. Transaction processing applies only to
database access; Component Services cannot roll back changes to the file
system or changes to other, nontransactional resources. The database your
application accesses must be supported by Component Services. Currently
Component Services supports SQL Server and any database that supports
the XA protocol from the X/Open consortium. Component Services will
continue to expand its support for other databases in the future.
<%
.
.
.
'End transaction.
Server.Transfer("/BookSales/EndTrans.asp")
%>
<%@ TRANSACTION=Required%>
<%
However, the interaction between the two scripts would constitute only a
single transaction. For more information about writing scripts with
Server.Transfer and Server.Execute, see Sending Content to the
Browser.
The @TRANSACTION directive must be the very first line on the page,
otherwise an error is generated. You must add the directive to each page
that should be run under a transaction. The current transaction ends when
the script finishes processing.
<%
'Buffer output so that different pages can be displayed.
Response.Buffer = True
%>
<HTML>
<BODY>
<H1>Welcome to the online banking service</H1>
<%
Set BankAction = Server.CreateObject("MyExample.BankComponent")
BankAction.Deposit(Request("AcctNum"))
%>
<%
'Display this page if the transaction succeeds.
Sub OnTransactionCommit()
%>
<HTML>
<BODY>
</BODY>
</HTML>
<%
Response.Flush()
End Sub
%>
<%
'Display this page if the transaction fails.
Sub OnTransactionAbort()
Response.Clear()
%>
<HTML>
<BODY>
</BODY>
</HTML>
<%
Response.Flush()
End Sub
%>
Object Scope
Generally, you should not store objects created from an COM component in
the ASP Application or Session objects. COM objects are deactivated when
the transaction is completed. Because the Session and Application objects
are intended for object instances that can be used across multiple ASP
pages, you should not use them to hold objects that will be released at the
end of a transaction.
Queuing Transactions
Updates to a database on a remote server could delay or abort the
completion of a transaction due to network delays or failures. Because all
portions of a transaction must be committed, your application might be
held up waiting for the commit or abort message from the remote server or
might abort a transaction because the database update could not be sent.
Note You can use the debugger to view scripts and locate bugs, but not
to directly edit your scripts. To fix bugs, you must edit your script with an
editing program, save your changes, and run the script again.
Enabling Debugging
Before you can begin debugging your server-side scripts, you must first
configure your Web server to support ASP debugging.
After enabling Web server debugging, you can use either of the following
methods to debug your scripts:
Scripting Errors
While debugging your server-side scripts you might encounter several types
of errors. Some of these errors can cause your scripts to execute incorrectly,
halt the execution of your program, or return incorrect results.
Syntax Errors
Run-Time Errors
Run-time errors occur after your script commences execution and result
from scripting instructions that attempt to perform impossible actions. For
example, the following script contains a function that divides a variable by
zero (an illegal mathematical operation) and generates a run-time error:
Function Findanswer(x)
'This statement generates a run-time error.
Findanswer = x/0
End Function
</SCRIPT>
Bugs that result in run-time errors must be corrected for your script to
execute without interruption.
Logical Errors
A logical error can be the most difficult bug to detect. With logical errors,
which are caused by typing mistakes or flaws in programmatic logic, your
script runs successfully, but yields incorrect results. For example, a server-
side script intended to sort a list of values may return an inaccurate
ordering if the script contains a > (greater than) sign for comparing values,
when it should have used a < (less than) sign.
Breakpoint Debugging
When an error occurs and you cannot easily locate the source of the error,
it is sometimes useful to preset a breakpoint. A breakpoint suspends
execution at a specific line in your script. You can set one or many different
breakpoints before a suspect line of script and then use the debugger to
inspect the values of variables or properties set in the script. After you
correct the error, you can clear your breakpoints so that your script can run
uninterrupted.
To set a breakpoint, open your script with Script Debugger, select a line of
script where you want to interrupt execution, and from the Debug menu
choose Toggle Breakpoint. Then use your Web browser to request the
script again. After executing the lines of script up to the breakpoint, your
computer starts the Script Debugger, which displays the script with a
statement pointer pointing to the line where you set the breakpoint.
In certain cases, you may want to enable the Script Debugger Break at
Next Statement if the next statement that runs is not in the .asp file that
you are working with. For example, if you set Break at Next Statement in
an .asp file residing in an application called Sales, the debugger will start
when you run a script in any file in the Sales application, or in any
application for which debugging has been enabled. For this reason, when
you set Break at Next Statement, you need to be aware that whatever
script statement runs next will start the debugger.
You can also add breakpoints to your server-side scripts written in VBScript
by inserting a Stop statement at a location before a questionable section
of server-side script. For example, the following server-side script contains
a Stop statement that suspends execution before the script calls a custom
function:
<%
intDay = Day(Now())
lngAccount = Request.Form("AccountNumber")
dtmExpires = Request.Form("ExpirationDate")
When you request this script, the debugger starts and automatically
displays the .asp file with the statement pointer indicating the location of
the Stop statement. At this point you could choose to inspect the values
assigned to variables before passing those variables to the component.
Note Do not confuse the debugger statement with the JScript break
statement. The break statement exits a currently running loop during
execution and does not activate the Microsoft Script Debugger, nor pause
execution.
For more information about Microsoft Script Debugger, see the Microsoft
Scripting Technologies site at http://msdn.microsoft.com/scripting/.
Active Server Pages provides built-in objects that make it easier for you to
gather information sent with a browser request, to respond to the browser,
and to store information about a particular user, such as user-selected
preferences. This topic briefly describes each object.
Application Object
You use the Application object to share information among all users of a
given application.
Request Object
You use the Request object to gain access to any information that is
passed with an HTTP request. This includes parameters passed from an
HTML form using either the POST method or the GET method, cookies, and
client certificates. The Request object also gives you access to binary data
sent to the server, such as file uploads.
Response Object
You use the Response object to control the information you send to a
user. This includes sending information directly to the browser, redirecting
the browser to another URL, or setting cookie values.
Server Object
The Server object provides access to methods and properties on the
server. The most frequently used method is the one that creates an
instance of an COM component (Server.CreateObject). Other methods
apply URL or HTML encoding to strings, map virtual paths to physical paths,
and set the timeout period for a script.
Session Object
You use the Session object to store information needed for a particular
user session. Variables stored in the Session object are not discarded when
the user jumps between pages in the application; instead, these variables
persist for the entire time the user is accessing pages in your application.
You can also use Session methods to explicitly end a session and set the
timeout period for an idle session.
ObjectContext Object
You use the ObjectContext object to either commit or abort a transaction
initiated by an ASP script.
ASPError Object
You can use the ASPError object to trap ASP error and return more
informative descriptions to users.
This guide provides an overview of Web application design and introduces the more advanced topics of
building components and ISAPI extensions, data access, Web-based transactions, and performance.
? Accessing Data with ASP: Introduces data access from a Web page with Microsoft ® ActiveX®
Data Objects (ADO).
? Processing Transactions: Outlines how IIS and Component Services, available with Windows
2000 or later, work together to provide Web-based transactions.
? Security Ramifications for IIS Applications: Introduces the issues Web developers face when
accessing and providing secure data.
? Development Technologies: Reviews some of the more recent Web technologies, such as XML
and Dynamic HTML.
? Developing Scalable Web Applications: Describes the impact that Web application design
decisions can have on server performance.
? Building Components for ASP: Reviews the development cycle for building components to be
used by ASP.
? Developing ISAPI Extensions and Filters: Describes the Internet Server API (ISAPI) within the
IIS architecture, and provides guidelines for developing ISAPI extensions and filters.
Open Internet standards have changed the architecture of distributed computing forever. The basic
language of the Web, HTML, has become a popular language for representing the elements of the user
interface. Cross-platform support for scripting languages and Java applets, as well as support for
embedded COM components, makes it possible to combine dynamic elements with static text for a
more interactive user experience. Web technologies aren't solely for use on the Internet, however. They
have been adapted for use by businesses to:
This section outlines general concepts that will assist you in building Web applications, such as the
following:
? Building on the Client/Server Architecture: Briefly outlines the history of the traditional client/server
design model.
? The New System Design: Introduces n-tier and distributed systems design, as an enhancement to
the client/server model.
? Microsoft Windows Distributed interNet Application Architecture: Outlines Microsoft Windows
DNA, the Microsoft architecture for building Web applications.
? Internet Information Services Architecture: Reviews the IIS components and programming model.
Before delving into the details of building a Web-based application, it might be helpful to review the
architectural model of the Web, and the roles of the browser and server in that model.
Typically, cooperating applications can be categorized as either a client or a server. The client application
requests services and data from the server, and the server application responds to client requests. Early
two-tier (client/server) applications were developed to access large databases, and incorporated the
rules used to manipulate the data with the user interface into the client application. The server's task was
simply to process as many requests for data storage and retrieval as possible.
Two-tier applications perform many of the functions of stand-alone systems: They present a user
interface, gather and process user input, perform the requested processing, and report the status of the
request. This sequence of commands can be repeated as many times as necessary. Because servers
provide only access to the data, the client uses its local resources to perform most of the processing. The
client application must contain information about where the data resides and how it is organized in the
database. Once the data has been retrieved, the client is responsible for formatting and displaying it to the
user.
One major advantage of the client/server model was that by allowing multiple users to simultaneously
access the same application data, updates from one computer were instantly made available to all
computers that had access to the server. However, as the number of clients increased, the server would
quickly become overwhelmed with client requests. Also, because much of the processing logic was tied
to a monolithic suite of applications, changes in business rules led to expensive and time-consuming
alterations to source code. Although the ease and flexibility of two-tier products continue to drive many
small-scale business applications, the need for faster data access and more rapid developmental timelines
has persuaded systems developers to seek out a new way of creating distributed applications.
Today's client/server applications resemble their ancestors so little that they have been given a new name,
the multi-tier application, also known as n-tier architecture. In this model, processing is distributed
between the client and the server, and business logic is captured in a middle tier. Most systems will
perform the following three main tasks, which correspond to three tiers, or layers, of the n-tier model:
Task Description
User interface and Labeled Tier 1 in the following graphic, this layer comprises the entire user
navigation experience. Not only does this layer provide a graphical interface so that users
can interact with the application, input data, and view the results of requests, it
also manages the manipulation and formatting of data once it arrives at the client.
In Web applications, the browser performs the tasks of this layer.
Business logic Tier 2, between the interface and data services layers, is the domain of the
distributed application developer. Business logic, which captures the rules that
govern application processing, connects the user at one end with the data at the
other. The functions that the rules govern closely mimic everyday business tasks,
and can be a single task, or a series of tasks.
Data services Shown as Tier 3 in the following graphic, data services are provided by a
structured (SQL, Oracle database) or unstructured store (Microsoft ®
Exchange, Microsoft® Message Queue Services), which manages and provides
access to the application data. A single application may enlist the services of one
or more data stores.
The three-tier architecture isolates each major piece of functionality. The presentation is independent of
the processing rules and business logic, which in turn is separate from the data. This model requires much
more analysis and design up front, but greatly reduces maintenance costs and increases functional
flexibility in the long run. The following diagram depicts the Microsoft technologies that service the
various tiers in the new system design.
Microsoft developed the Windows Distributed interNet Application Architecture (Windows DNA) as a
way to fully integrate the Web with the n-tier model of development. Windows DNA defines a
framework for delivering solutions that meet the demanding requirements of corporate computing, the
Internet, intranets, and global electronic commerce, while reducing overall development and deployment
costs.
Windows DNA architecture employs standard Windows-based services to address the requirements of
each tier in the multi-tiered solution: user interface and navigation, business logic, and data storage. The
various services are integrated through the Component Object Model (COM). The services used in
Windows DNA include:
Microsoft built Windows DNA using open protocols and public interfaces, making it easy for
organizations to integrate third-party products. In addition, by supporting industry-defined standards for
Internet computing, Windows DNA will make it easier for developers to respond to technology changes.
Some of the technologies recently added to the Windows DNA are outlined in the Development
Technologies section. The following diagram illustrates these technologies.
IIS is an integral part of the Windows DNA architecture. An important role of IIS is to link clients
accessing the system through the Hypertext Transfer Protocol (HTTP) to the other Windows DNA
services, such as DHTML, ASP, and so on. In addition, IIS includes a basic set of functionality that
systems developers can extend to define a customized application architecture.
? IIS Core Functionality: Describes the basic functionality that you can use to build Web
applications.
? IIS and Component Services: Outlines the functionality used to isolate, manage and coordinate
processing for transactional ASP applications.
? IIS Request Processing: Describes the evaluation procedure used to determine a request type.
The topics in this section describe this basic functionality, and define the relationship of IIS architecture to
the rest of the Windows DNA architecture. A general outline of how IIS processes HTTP requests is
also provided.
IIS defines a basic functionality that you can use to build Web applications. Active Server Pages (ASP)
and other Microsoft technologies have extended this basic functionality to create a rich environment for
application development. The basic server functionality is exposed through the Internet Server
Application Programmer Interface (ISAPI). ISAPI is described in detail in the Developing ISAPI
Extensions section.
ASP extends this functionality by providing a link to the COM architecture and thus the other participants
in Windows DNA. Similarly, you can extend the IIS architecture by defining a custom set of functions
using ISAPI. The relationship between the IIS core functionality, ASP, and extended architectures is
depicted in the following graphic:
IIS and Component Services work together to form a basic architecture for building Web applications.
IIS uses the functionality provided by Component Services to:
Note In IIS version 4.0, Microsoft Transaction Server (MTS) provided transaction support. In IIS 5.0,
and Windows 2000, Component Services provides all the transaction support of MTS, in addition to a
number of other component development and deployment features.
IIS defines Web applications as a collection of resource files that are grouped into a logical namespace.
By grouping resources into applications you gain the ability to share data throughout the namespace and
to run the application in an isolated process.
Internally, IIS coordinates isolated applications through an object known as the Web Application
Manager. This object includes a public interface (IWAMAdmin) that you can use to create programs
for administering Web applications. When you run a Web application in an isolated process, IIS uses
Component Services to coordinate concurrent access to resources and pass context information
between COM components.
IIS uses the Component Services ObjectContext object to give COM components that are called by
ASP access to the ASP built-in objects. For example, if you were building a COM component in Visual
Basic that needed to access a form submission from an HTML file, you could use the following code:
Component Services uses ObjectContext to maintain information about a particular instance of a COM
component. When IIS compiles the ASP script, it calls Component Services to create an
ObjectContext for tracking information about the ASP script. The ObjectContext includes an identity
property that uniquely identifies instance of the ASP script. For example, if your ASP script creates
instances of COM components that have been registered with Component Services, each of these
objects will be associated with the ASP script's ObjectContext. Similarly, when you create a
transactional ASP script with the @Transaction directive, Component Services is notified and a new
transaction is started. From that point onwards, Component Services will coordinate the updating of any
resources that are under its control. Component Services guarantees the transaction's integrity by
tracking any changes made to persisted resources.
Note In IIS version 4.0, transaction support was provided by Microsoft Transaction Server (MTS).
For IIS 5.0, and Windows 2000, Component Services provides all the transaction support of MTS, in
addition to a number of other features.
For further information on isolating and managing applications, see Defining Application Boundaries.
When IIS receives an HTTP request, it evaluates the URL to determine if the request is for static content
(HTML), or dynamic content (ASP or ISAPI).
Request Action
HTML Page IIS returns the page immediately in HTML format.
ISAPI extension IIS loads the ISAPI DLL (if it is not already running) and
the request is sent to the extension through the
Extension_Control_Block data structure.
File name extension mapped to a IIS loads the appropriate DLL file and presents the request
particular ISAPI extension through the Extension_Control_Block data structure.
The .asp extension, for example, is mapped to Asp.dll, so
that all requests for files with an .asp extension will be
directed to Asp.dll.
CGI application IIS creates a new process. IIS will then provide the query
string and other parameters that are included with the
request through the environment and standard input
(STDIN) handle for the process.
Design Decisions
This is preliminary documentation for IIS 5.0 and is subject to change.
Although there is a rich and continually expanding set of tools for Web application development, the
basic development cycle is similar to developing desktop applications in many respects. This section
focuses on design decisions that are unique to Web applications.
? Defining Application Boundaries: Describes the necessary steps needed to assemble you ASP
pages into a single Web application.
? Controlling Application Flow: Outlines the issues to keep in mind when designing how you will
control the flow of Web applications.
? Accommodating International Clients: Contains information relating to the localization of your Web
site into various languages.
An ASP-based application is a collection of ASP pages and COM components. When you define an
application, you use the Internet Information Services snap-in to designate the application's starting-point
directory in your Web site. Every file and folder under the starting-point directory in your Web site is
considered part of the application . Therefore, you can use the directory structure to form application
boundaries that define the scope of an application. You can have more than one application per Web
One of the most important tasks you face in developing your Web application is to determine how to
assemble your ASP pages into a single Web application. IIS uses the concept of a namespace to
identify applications. A namespace is a way of associating an area of memory with an easily recognized
name; it identifies a group of files as belonging together. IIS uses virtual directories to define namespaces
for applications. The following diagram illustrates this concept.
Scripts and ISAPI extension DLLs within an application boundary form a unit of isolation, which always
runs in a single server process. IIS administrators can either run applications in the same server process
as IIS, a pooled process (the default process), or they can isolate the application by running it in an
isolated process, which is particularly helpful during development and testing.
See Simplify Development With Process Isolation to learn more about isolating applications and
components.
In addition to running applications in a single process, you can also separate your components from .asp
files that call them, by running them in an isolated or pooled process. An isolated process would be a
good configuration for debugging your components. A pooled process provides superior protection for
the server without the overhead involved in maintaining a large number of isolated processes. To run your
components in their own process, you must create a new application and add your components to it with
the Component Services Manager.
1. Put all .asp files and components in the same process as IIS; this configuration provides the fastest
performance.
2. Put all .asp files and components in one process and IIS in an another process.
3. Put all .asp files and components in a pooled process, IIS in another process, and special
applications in an isolated process.
4. Put all .asp files and IIS in one process, and components in another process.
5. Put all .asp files in one process, components in another process, and IIS in a third process.
Because process boundaries represent different areas of memory, calling between them requires some
extra work by IIS. The mechanism for calling across process boundaries is known as marshaling.
Marshaled calls are slower than calls within a single process. Pooled and isolated applications, therefore,
do not perform as well as applications sharing the IIS process.
In earlier versions of IIS, all ISAPI applications (including ASP) shared the resources and memory of the
server process. Although this provided fast performance, unstable components could cause the server to
crash—not an acceptable behavior for a mission-critical application such as IIS. To make matters worse,
in-process components couldn't be unloaded unless the server was restarted—which meant that
modifying existing components would affect all sites that shared the same server, whether they were
directly affected by the upgrade or not.
Thanks to close integration with Component Services, applications in IIS version 4.0 and above can be
started in an isolated process. There are two reasons for doing this:
1. Component development; rather than taking down the entire server to update a single component,
you can stop and restart just a single application. In earlier versions of IIS, to add an updated
component to an application, or an entirely new application, you previously had to stop the Web
service, replace the old DLL with your new version in its shared location on the server, and restart
the Web service again. Now with an isolated process, you can update a production Web site
without shutting down all applications.
2. Process isolation, which limits the effects of a crash to the single application that caused it. In
addition to protecting your primary Web service from the crash, the application can be configured
to restart automatically as often as you like. In the case of an application fatal error, the
application's process is automatically terminated. Because the application is running in the
Component Services system process, all transactions in progress are aborted. The Windows
event log stores a record of the event, and Component Services restarts the application. The only
clients affected by the failure are those with outstanding requests to that specific application.
Process Isolation
If you decide to run your application as a separate process, or with other applications in a single pooled
process, you will need to select High (Isolated) or Medium (Pooled) from the Application
Protection drop-down list on the Home Directory or Virtual Directory property sheet. You should
first create an application for your application starting-point directory, if you haven't already done so.
Components that will run in the new process must be installed into the appropriate COM application.
For more information, see the Component Services documentation.
Out-of-Process Components
Note that out-of-process applications are different from out-of-process components, which are
executables that are run in a separate process. When Server.CreateObject is used to launch an
executable, the following error may occur:
This error is the result of a safety mechanism in ASP that prevents the unauthorized launching of
executables from within ASP. Not all executables are safe to use on the server, and may pose security
risks as well. Because in-process components are faster, more secure, and can be hosted by Component
If you want to enable the use of out-of-process components for testing and development purposes, you
must first set the AspAllowOutOfProcComponents metabase property to TRUE. This metabase
setting is accessible on both the IIsWebService and the IIsWebVirtualDir IIS Admin Objects.
? Take note that if you set the AspAllowOutOfProcComponents property to TRUE on the
IIsWebService object, all in-process applications will be able to launch executables from script.
An in-process application is a directory that has been marked as an application starting point, by
having the Low (IIS Process) or Medium (Pooled) option selected.
? If you set the AspAllowOutOfProcComponents property to TRUE on the IIsWebVirtualDir
object, and the application is marked to run in separate memory space (out of process), only the
affected application is allowed to launch executables from script. If the application is set to run in
process, the setting will have no effect.
The following ASP code demonstrates the steps required for setting the
AspAllowOutOfProcComponents parameter on the IIsWebService IIS Admin Object.
Note The user must have adequate permission to modify the metabase. If you attempt to modify the
metabase from an ASP script without sufficient privileges, you will encounter an error. In order to modify
the metabase from script, you must first log on as a user with administrative rights.
<%
' Get the IIsWebService Admin object.
Set objWebService = GetObject("IIS://LocalHost/w3svc")
Important You will need to restart the Web service after making this change.
For more information about setting metabase properties using the IIS Admin Objects, see Using IIS
Admin Objects.
By default, out-of-process applications and components, including ISAPI extensions, are not able to
access metabase properties. This restriction is primarily for security reasons, to prevent unauthorized
changes to the metabase. If you want to allow out-of-process applications to access the metabase, you
must do one of the following:
? Give the IWAM_machinename account access to the metabase (this is probably a bad idea,
from a system security standpoint).
? Change the identity of the out-of-process COM application from the interactive user
(IUSR_machinename, by default) to a specific user account, and give that account access to the
metabase (this is also somewhat risky, but the risk is limited to a single application).
For more information on changing application identity, see the Component Services documentation in the
Platform SDK.
One of the primary choices of any application design is the pattern of execution. In a well-designed
application, the logic of converting inputs to outputs by using modular processing units is obvious. The
COM architecture and Active Server Pages (ASP) address this need for modular design to control the
flow of execution in the Windows DNA architecture.
This section outlines some of the more important issues to keep in mind when designing how you will
control the flow of your Web application. The topics included are:
? Application Control Techniques: Describes the different ways to affect the general flow of
execution.
? Coordinating Client/Server Processing: Outlines the design goals when you distribute processing
between the client and server.
ASP provides six different ways to affect the general flow of execution. These six methods are depicted
in the following diagrams. The arrows in the diagrams represent the flow of execution.
Redirecting
Redirection is the process of diverting a request to another location. Redirecting requires a new request
to be sent to the server. However, in general, you should design your application to minimize the amount
of communication between the client and server. Many design problems that have been addressed by
redirecting in the past can now be accomplished by transferring, which does not initiate a new request.
See Coordinating Client/Server Processing for more information on this aspect of application design.
Transferring
The ability to transfer a request from one ASP page to another is introduced in IIS 5.0. Transferring is
similar to redirecting; however, it does not require that a new request be initiated. This is a much more
efficient way to control application flow. If you transfer the request to an ASP page outside of the
application boundary, the boundary will be temporarily extended to include the external ASP page. The
external ASP page will behave as if it were included within the application boundary of the calling ASP
page. Therefore, any objects or variables that have been given application scope will still be available in
the ASP page to which you have transferred. In addition to being faster than redirecting, transferring
preserves all of the ASP built-in objects from the original request, including form values from an HTTP
post.
Executing
The ability to execute a particular ASP script and return the result is introduced in IIS 5.0. Executing is
similar to a procedure call in most programming languages. This method of application flow control is
appropriate if you have developed an ASP application that accomplishes some function that you want to
incorporate, but have not built that function into a component.
Component Invocation
This is probably the most common way to control the flow of an application. The COM programming
model is integral to the Windows DNA, and should address the vast majority of design problems. Script
Components, a technology supported in IIS 5.0, make it easier to take existing scripts and convert them
to components.
You can accomplish component invocation by using the Server.CreateObject method. For more
information on script components, see Windows Script Components and Using Components and
Objects.
Exiting
Under normal circumstances you will want your ASP application to complete each line of script in the
page. There may be some circumstances, however, where you will need to simply end the response. For
example, if you have detected (by using the Response.IsClientConnected method) that the client is no
longer waiting for a response, you will want to terminate the ASP application.
You can accomplish exiting the ASP by using the Response.End method.
Procedural Processing
If you want to define subroutines or functions within your .asp file, you can do so by using the procedure
syntax that is appropriate for the scripting language you are using. For example, VBScript defines
subroutines with the Sub … End Sub syntax and functions with the Function … End Function syntax.
JScript, on the other hand, supports procedural processing through function calls. For more information
on subroutine processing, see Writing Procedures.
Web applications are, by their very nature, distributed. As clients increase their processing capability, the
degree to which you can distribute processing between the client and server increases. By distributing
some of the processing to the client you will increase your application's responsiveness. Distribution of
processing, however, also increases the complexity of your application design.
You should keep in mind two design goals when you distribute processing between the client and server.
First, you want to minimize communication across the HTTP connection. Regardless how fast the
connection you have established is, local processing will always be faster. You should pass information
between the client and server only when absolutely necessary.
A second design goal is to expose only those server resources to the client that are absolutely necessary
to accomplish the processing task. Each request from the client should be fully qualified so that the server
does not have to respond to the client for further information and thereby increase roundtrips across the
HTTP connection. For example, if a client can completely describe its capabilities to the server when it
makes a request, the server can immediately send a response that matches those capabilities rather than
requesting further information from the client. This design concept can also be applied to the design of
Web applications that support database access. For example, if a client is checking the status of an
order, you should provide the client with a recordset that describes only that particular order, rather than
all the records in the orders table.
? Caching Data: Introduces a technique that you can use to minimize communication across the
HTTP connection.
? Client Capabilities: Describes functionality provides you with a design tool to help make client
requests fully qualified.
? Remote Data Binding with Remote Data Service: Explains a technique that you can use to limit
client access to appropriate data resources.
Caching Data
When clients access your ASP page, there are basically two ways to provide them with the information
they need:
? Your ASP page can either obtain information from server resources, such as from data that has
been persisted to a database, or
? Your ASP page can obtain information from within the application.
Retrieving data from a resource outside the application will require more processing steps, and will
therefore require more time than generating the data from within the application space.
If the data you are going to send to the browser has already been prepared by a previous request, your
application will be able to retrieve that data faster if you store it in a cache. This form of caching is called
output caching. Output caching is particularly suitable when you expect to return the same data in the
same format for many different requests. For example, one common task for developing an input form is
to gather persisted data as members of a drop-down list box. This is preferable to writing the entries
directly into the HTML page, because updates to the persisted data will automatically be reflected in the
form.
The following script is an example of output caching. In this example, the getSportsListBox function
creates a list box from persisted data. The list box is added to the application space so that clients can
access it more quickly than they could if they populated the list box on an individual basis. The example
assumes that a Data Source Name (DSN) called "Sports" is defined on the server.
<INPUT TYPE=submit>
</FORM>
</BODY>
</HTML>
<%
function getSportsListBox()
{
SportsListBox = Application("SportsListBox")
If (SportsListBox != null) return SportsListBox;
crlf = String.fromCharCode(13, 10)
SportsListBox = "<select name=Sports>" + crlf;
SQL = "SELECT SportName FROM Sports ORDER BY SportName";
cnnSports = Server.CreateObject("ADODB.Connection");
cnnSports.Open("Sports", "WebUser", "WebPassword");
rstSports = cnnSports.Execute(SQL);
fldSportName = rstSports("SportName");
While (!rstSports.EOF)
{ SportsListBox = SportsListBox + " <option>" + fldSportName + "</option>" + crlf
SportsListBox = SportsListBox + "</select>"
Application("SportsListBox") = SportsListBox
return SportsListBox;
}
%>
In some circumstances, your application will receive many different requests for the same data, but you
will need to change the presentation of that data for each request. In that case, you use input caching.
With input caching you save the data, but not the presentation of it. You accomplish this by caching the
data with a Dictionary object provided by VBScript, or with an ADO recordset.
The following example demonstrates caching data by adding a connectionless recordset to your
application. ASP scripts within the application space can then access the recordset rather than retrieve
the data from the database. The following two ASP scripts demonstrate this technique.
<% SQL = "SELECT CompanyName, City FROM Customers" Cnn = "DSN=AdvWorks" rsCustomers.Cur
Set myCustomers = Application("rsCustomers").Clone Set CompanyName = myCustomers("Compa
Do Until myCustomers.EOF%><B><%= CompanyName %></B> is located in <B><%= City %></B>.<P>
<%
myCustomers.MoveNext
Loop
%>
The application's Global.asa file creates the recordset and adds it to the application space. The ASP
script then populates the recordset and makes it connectionless by setting the ActiveConnection
property to Nothing. The ASP script then clones this recordset and iterates through its values, which is
much faster than accessing the database itself. This technique is appropriate only if you know that the
data that will be used to populate the recordset is relatively stable.
Client Capabilities
One of the more significant design decisions you will make is how your application will handle differing
client capabilities. For example, one of the most important issues for users is the speed of the connection.
If your application can determine this speed, it can adjust the response to match that capacity. The only
way for your application to be aware of the current connection speed is if the client includes this
information as part of its request.
You can solve the client capabilities problem on either the client side or server side. The client-side
solution relies on Dynamic HTML (DHTML) to include a description of the client's current configuration
as part of the request, as depicted in the graphic below.
There are some situations where client-side scripting will not be feasible. For example, applications that
are exposed on the Internet cannot guarantee that the client will support scripting, which means the
applications may fail for some clients. In addition, server-side resources may not be accessible from the
client side, as the client may reside on a network that does not allow scripting for security reasons.
The server-side approach relies on the Browser Capabilities component. This component reads the User
Agent HTTP header included with the request to determine the client's capabilities. The version of the
Browser Capabilities component that shipped with IIS 3.0 and 4.0 determined client capabilities by
looking them up in a static list. The following graphic shows the sequence of events.
This approach presented difficulties for application designers when the list became out of date. More
importantly, this technique did not cover configurable aspects of a client's capabilities and did not provide
a means of what was actually enabled at the time the request was made.
In IIS 5.0 the Browser Capabilities component has been improved to overcome these earlier design
limitations. The Browser Capabilities component can now be modified for an individual request by the
client returning a cookie describing its capabilities. In addition, if the initial request for an .asp file does
not include a cookie, you can call back to a script that will run on the client to create the cookie. The
following illustration shows the sequence of events.
This improvement to the Browser Capabilities component creates another alternative to the server-side
solution. This technique uses a special status code to call back to the client when a request comes in that
does not include a cookie. You can generate this status code by placing a special meta tag as the first line
in your .asp file. For example:
instructs IIS to send the special status code—an HTTP 449 status code—to Internet Explorer 5.0; it
then tells Internet Explorer 5.0 to run the script in Sendcook.htm, which will generate a cookie describing
the client capabilities. When the server receives this cookie, it will use the cookie in conjunction with the
Browser Capabilities component to determine how to send the response back to the client.
Important If the METADATA meta tag exists in a file that is requested by the client as a result of a
redirection using the Server.Transfer or Server.Execute methods, IIS will ignore the meta tag.
METADATA meta tags in the file that actually contains the redirect, however, will be processed
normally.
For more details on how to use this feature, see Retrieving Browser Capabilities from a Cookie.
For more information on DHTML client capabilities, see the DHTML reference information on the Site
Builder Network. The SBN home page is at www.microsoft.com/sitebuilder/. For an example of the
new Client Capabilities component functionality, see the Browser Capabilities Component and ASP
Samples.
One of the advantages of distributing information over the Internet or an intranet is that you can create
international Web sites that users can access from different countries. Users can request pages that have
been localized into their own language, which they read in localized browser versions.
When you create a Web site that contains pages in different languages, you may need to convert strings
that are passed between the browser and the Web server, or between an ASP script and a COM
component. If all pages on the Web site are written in the default character set used by the Web server,
ASP does the conversion automatically. If you author pages in different character sets, however, you
need to use ASP commands that specify how the strings should be converted. For example, if your site
contains some pages in one of the Japanese character sets and others in one of the Chinese character
sets, you need to specify which character set ASP should use while processing strings for a particular
page.
ASP also provides commands that support the cultural conventions for different locales, such as the
format used for currency, time, and date. As with the string conversion commands, you need to use the
locale commands only if your scripts do not use the default locale for the Web server. For more
information, see the following topics.
? Setting the Code Page for String Conversions: Includes sample code for converting strings used
by ASP.
? Setting the Locale Identifier: Describes how to change the format used for currency, time, and
date.
A code page is an internal table that the operating system uses to map symbols (letters, numerals, and
punctuation characters) to a character number. Different code pages provide support for the character
sets used in different countries. Code pages are referred to by number; for example, code page 932
represents the Japanese character set, and code page 950 represents one of the Chinese character sets.
Active Server Pages, and the script engines it supports, internally use Unicode, a 16-bit fixed-width
character encoding standard. If you author all of your pages in the default code page of the Web server,
ASP automatically converts strings. If your script was not created in the Web server's default code page,
however, you need to specify the code page so that strings are correctly converted as they are passed:
To specify the code page for an ASP page, use the @ CODEPAGE directive. For example, to set the
code page to Japanese, use the following directive:
As ASP processes the content and script on this page, it uses the code page you have specified to
convert characters from your script's character set into Unicode. For example, the value that refers to the
letter "a" in ANSI will be converted into the different value that refers to the letter "a" in Unicode.
Active Server Pages assumes that strings passed between the Web server and the browser, or between
your script and COM components, are in the same code page you have set for your script. If you need
to specify a different code page, you can set the Session.CodePage property to override the
CODEPAGE setting. For example, you may have authored your script in JIS but need to respond to a
client that is using UTF-8 (two different character encodings for the standard Japanese character set).
Session.CodePage defaults to the value of the @ CODEPAGE directive; setting it overrides the current
CODEPAGE setting. For example, to change the code page to one of the Chinese character sets, use
the following command:
If you are temporarily changing the code page for a portion of your script, be sure to set
Session.CodePage back to its original value. The following script shows how to temporarily change the
code page:
A locale is a set of user preference information related to the user's language. The locale determines how
dates and times are formatted, how items are alphabetically sorted, and how strings are compared. The
locale identifier (LCID) is a 32-bit value that uniquely defines a locale. ASP uses the default locale of
the Web server unless you specify a different locale for a particular script.
To set the locale identifier for an ASP page, use the @ LCID directive. For example, to set the locale to
Japanese, use the following locale identifier:
The @ LCID directive tells ASP the locale in which the script was authored. If you need to change the
locale for input to or output from the script, use the Session.LCID property.
The following example demonstrates setting the locale to British English, and using the VBScript
FormatCurrency method to display the value 125 as currency with the £ symbol:
<%
Session.LCID = 2057
Dim curNumb
curNumb = FormatCurrency(125)
Response.Write (curNumb)
%>
The Session.LCID property defaults to the @ LCID directive setting. Setting the value of
Session.LCID in a script overrides the default setting.
For more information on LCIDs see "International Features" in the "Windows Base Services" section.
ASP offers the Web developer flexible, easy-to-use, scalable methods to interact with OLE DB
database providers for Internet or intranet applications. Using ASP and the Microsoft Data Access
Components (MDAC) not only means that you can initially develop a solution using Microsoft Access
and scale up to Microsoft SQL Server 6.5, but that you can access any other databases that have OLE
DB providers. With the additional power of Component Services, you can create highly scalable multi-
tier applications that support Web-based transactions.
ADO Overview
This is preliminary documentation for IIS 5.0 and is subject to change.
ActiveX® Data Objects (ADO) provides a common programming model for any OLE DB data source;
it is essentially a collection of objects that expose the attributes and methods used to communicate with a
data source. ADO uses general OLE DB providers to accesse unique features of specific data sources; it
also uses native OLE DB providers, including a specific OLE DB provider that provides access to Open
Database Connectivity (ODBC) drivers. Designed to replace the need for all other high-level data access
methods, ADO can access relational, Indexed Sequential Access Method (ISAM), or hierarchical
databases, or any type of data source—as long as there is an ODBC-compliant driver.
ADO's ease of use, speed, and low memory overhead make it ideal for server-side scripting. In fact,
ADO is the recommended technology for data access for ASP applications. ADO can be called directly
from server-side scripts or from business components.
Unlike earlier data access methods, ADO does not require navigation through a hierarchy to create
objects; most ADO objects can be created independently, which allows greater flexibility in reusing
objects in different contexts and reduces memory consumption. ADO also takes advantage of ODBC
3.0 connection pooling for ODBC data sources, and session pooling for OLE DB providers. This
eliminates the need to continuously create new Connection objects for each user, which is very resource
intensive.
What ADO cannot do, however, is provide remote data to the client. Once the data has been retrieved
and sent to the browser, the user cannot easily manipulate it or make changes to it within the client
application. Data operations—including filtering and record modifications—must take place on the
server, where the actual data manipulation objects reside. If your application design requirements include
client manipulation of data, see Remote Data Binding with Remote Data Service.
OLE DB, the foundation of Microsoft's Universal Data Access model, is a set of COM interfaces that
provides a standard way for programs to access data. The way your application uses ADO functionality
will be partially determined by whether or not there is an OLE DB provider for the data. ADO is
designed to work with OLE DB, and in most instances your ADO components will communicate with
databases through OLE DB; you can also use ADO to communicate directly with the ODBC driver, if
no OLE DB provider is available. Using ADO through an OLE DB provider has an impact on the
following areas:
? Using Stored Procedures with ADO: Describes several key issues you should consider when
using stored procedures.
? Choosing the Client Networking Library for ADO:Explains the issues surrounding the selection of
a networking library and it's impact on database access speed.
For more information on ADO, see the ADO SDK . For performance information, see Data Access
Performance. To see examples of using ADO, see Database Connectivity under the ASP Script
Examples in ASP Samples.
pooling enabled can present some special considerations. For example, creating temporary stored
procedures for prepared SQL statements is an option that is configurable from the ODBC Data Source
Administrator. The default for this setting is "On" for the SQL Server 2.65 and 3.5 drivers, which means
that when a SQL statement is prepared, a temporary stored procedure is created and compiled. When
the prepared command is called by one of the ADO methods, the temporary stored procedure is
executed, saving the overhead of parsing and compiling the SQL statement. This feature can improve the
performance of your application, if it is used properly. If your SQL statement is going to be executed
more than twice, or if it will be run more than once and contain parameters, the statement should be
prepared. Keep in mind that to prepare a SQL statement it must be compiled the first time you run it,
and that the preparation is lost once you disconnect from the database.
When connection pooling is enabled, you have to decide when temporary stored procedures should be
deleted. With the SQL Server 2.65 driver, stored procedures will be released when the connection is
released. With the SQL Server 3.5 driver, you have the option of deleting them either when the
connection is released, or as appropriate while connected.
There can be storage problems with temporary stored procedures and connection pooling. If you are
using the default setting, you risk of running out of space in TempDB, where temporary stored
procedures are created and stored. When connection pooling is enabled, a connection is made to the
database, but when the client is finished with it and releases it, the connection goes back into the pool.
The connection is not released and the stored procedures are not deleted from the TempDB—even
though they are no longer associated with a client and will never be called again.
Thus, when running the SQL Server 2.65 driver, it may be advisable to disable the creation of stored
procedures on preparation when connection pooling is enabled. With the SQL Server 3.5 driver, the
option to create temporary stored procedures should be disabled or set to "disconnect and as
appropriate" when running connection pooling. Setting this option to "disconnect and as appropriate"
means that the ODBC SQL Server driver will drop the connection when the OLE DB ICommand
object that created the temporary stored procedure is released. If your client code uses ADO, the stored
procedure would be released when the ADODB.Recordset and ICommand object are closed.
When ADO communicates with a database it does so through a networking library. Your selection of a
networking library will be determined by the data provider and system configuration, and can have a
significant impact on database access speed. For example, if you are accessing data from a Microsoft
SQL Server database your access speed, in general, will be faster if you use the TCP/IP networking
library. However, if SQL Server is running on the same computer as IIS, you may find some
performance improvements by using the Named Pipes networking library.
You can set the networking library for a DSN by using the Data Sources (ODBC) option in Control
Panel. Once you set a library for one connection, it will become the default library for all subsequent
connections, as well as for any DSN-less connections that your application may use.
Note If you change the network library from Named Pipes to TCP/IP, be sure not to remove Named
Pipes as one of the options, because SQL Server Enterprise Manager relies on this library.
If your Web application provides clients with the ability to access data, you can distribute the processing
of that data between the client and the server with Remote Data Service (RDS). Client-side RDS
components send queries to the Web server. The server-side RDS components process these requests
and send them to the Database Management System (DBMS) by use of a business object. The DBMS
responds to the request, sending back the data to the Web server. The RDS components on the Web
server transform that data into an ADO Recordset object. The data is parsed for transport to the client
and sent back across the network to the client computer where it may be displayed in data-aware
controls, such as a text or combo box.
The two main objects that you will use to accomplish remote data binding are RDS.DataControl and
RDS.DataFactory. First, create a copy of the RDS.DataControl object on the client computer by
inserting an object tag in an HTML page. For example:
The preceding object tag creates an instance of the RDS.DataControl object and sets the SQL,
Connect, and Server parameters for it. If you add this tag to an HTML page, you could then bind the
data control object to multiple data-aware controls on the HTML page. For example, the following
HTML tags display an HTML table that is bound to the above RDS.DataControl object.
The object on the server that communicates with the RDS.DataControl object is either the
RDS.DataFactory, or a business component. You can instantiate the RDS.DataFactory object by
first creating a RDS.DataSpace object on the client, which then creates an instance of the
DataFactory object on the server with the CreateObject method. The following example script
demonstrates this process.
If your data access needs cannot be served by the RDS.DataFactory object, you can either a create a
custom business component to communicate with the client, or you can use ADO directly from your
ASP script to retrieve the data. In the following example, the custom business component, Inventory,
exposes a method called getQuantityonHand. The RDS.DataControl object creates an instance of
Inventory on the server, and then calls the getQuantityonHand method to retrieve records.
<HTML>
<HEAD>
</HEAD>
<BODY>
<!-- RDS.DataControl -->
<OBJECT classid="clsid:BD96C556-65A3-11D0-983A-00C04FC29E33" ID=ADC1></OBJECT>
<!-- RDS.DataSpace -->
<OBJECT ID="ADS1" WIDTH=1 HEIGHT=1 CLASSID="CLSID:BD96C556-65A3-11D0-983A-00C04FC29E36">
</OBJECT>
<SCRIPT LANGUAGE="VBScript">
Option Explicit
Sub GetRecords()
Dim objInventory, myRS
Set objInventory =
ADS1.CreateObject("Company.Inventory", _
"http://<%=Request.ServerVariables("SERVER_NAME")%>")
' Inventory exposes a method called
' getQuantityonHand that takes connection string and SQL parameters.
Set myRS = objInventory.getQuantityonHand _
("DSN=pubs;UID=sa;PWD=permission;","Select Quantity From Inventory")
' Assign the returned recordset to SourceRecordset.
ADC1.SourceRecordset = myRS
End Sub
</SCRIPT>
</BODY>
</HTML>
The same issues that are described in Component Design Guidelines, in the IIS documentation in the
Platform SDK, apply to any custom data business components you create to communicate with
RDS.DataControl. For example, you should make sure that the component supports either the
Apartment or Both threading model.
Note Remote Data Service (RDS) replaces the Advanced Data Connector (ADC), which is now
considered obsolete. In particular, the ADC remoting functionality (the ability to manipulate and modify
sets of records on the client) has been integrated into ADO as RDS.
Processing Transactions
This is preliminary documentation for IIS 5.0 and is subject to change.
Transaction processing is an approach to application development that divides all processing into
individual units of work, known as transactions. The integration of IIS and Component Services has
made it easy to create Web applications that support transaction processing. If you are designing a Web
application that will support transaction processing, you will face several basic design decisions. This
section outlines the technology that underlies transactional ASP, as well as some fundamental design
issues.
? Designing Transactional Web Applications: Describes the design requirements for transactional
Web applications.
? Transaction Processing Technology: Provides information on Component Services and Message
Queuing Services (MQS).
One of the most important design concepts for transactional Web applications is the distinction between
business processes and physical transactions. Business processes are the day-to-day processes of most
organizations; for example, processing a sales order. A physical transaction corresponds to the actual
updating of the data resources that are used to record the business process. A business process will
usually be made up of more than one physical transaction.
For example, when a sales order is processed, there are at least three distinct steps that need to be
accomplished:
Each of these steps could represent one or more physical transactions, depending on the system design.
The connectionless nature of the Internet mandates that steps be broken into distinct physical
transactions. When a physical transaction is begun, all other users will be prevented from updating the
resources that participate in the transaction until the transaction completes. Imagine what would happen if
the entire sales order process described above was grouped into a single physical transaction. A user
could begin a transaction by indicating his or her interest in a product, which would lock the customer's
account and mark the product as no longer available in the inventory database. The customer could then
leave his or her browser running while attending to other business, but before committing to the sale.
Because the entire order has been treated as one physical transaction, all of the resources are locked
until either the customer commits, or your system throws out the order due to a business rule. Such a
design is not feasible for a transaction processing system that is exposed on the Web.
The design requirements for transactional Web applications will probably always be presented in terms
of business processes. It is important, therefore, to establish some design techniques for breaking
business processes into physical transactions. One important technique is to always limit physical
transactions to a single .asp file.
Note Business processes can span multiple .asp files, but physical transactions should not.
Another design technique is the use of status codes within transactional resources to indicate if a
transaction is pending or committed. By including status codes you can reserve a resource without
actually committing it. When the business process is complete, you can initiate another physical
transaction that commits all pending resources by changing their status code. The Crawford & Sons
Bicycle Company case study illustrates how these two principles affect the implementation of
transactional Web applications.
The Crawford & Sons Custom Bicycle Company is a manufacturer of hand-made bicycles that they
distribute throughout North America. They have decided to begin taking orders for their bicycles through
a Web application. They use Microsoft SQL Server to maintain customer and inventory records and
have already developed data and business-logic components that are registered with Component
Services. Now they need to develop the .asp files that will allow their customers to access these
components within the scope of a single business process. The following diagram illustrates the distinct
physical transactions and the .asp files that make up their Web application design.
The sales order application is made up of four .asp files: Login.asp, Credit.asp, Inventory.asp, and
Commit.asp. Notice that each of the physical transactions is represented by a separate .asp file.
(Each .asp file contains the @Transaction = Required directive.) Login, Credit, and Inventory each
interact with a COM component called Sales Order. Sales Order exposes methods for accomplishing
the three steps of taking an order.
When the customer is ready to commit to the sale (that is, the business process is completed),
Commit.asp groups the entire logical transaction into a single physical transaction which changes all of the
status codes in the data resources from "pending" to "complete." This design accommodates both the
connectionless nature of the Web and the requirement for providing the user with a unified business
process.
For more information on Component Services transactions, see Understanding Transactions . To view
samples of transactional scripting, see ASP Transaction Services in ASP Samples.
The primary technology that makes it possible for an ASP to participate in a transaction is Component
Services. Component Services provides IIS with transaction services and an environment for hosting
component instances. One of the benefits of this environment is the ability to create attributes for
individual component instances. When IIS compiles an ASP script, a new instance of the IIS Web
Application Manager (IISWAM) is created. IISWAM is a COM component that IIS uses to manage
applications. If the ASP script contains the @TRANSACTION directive, the instance of IISWAM will
be declared within the transaction environment with an appropriate transaction property. For example, if
you include @TRANSACTION = Required in your ASP script, you are telling Component Services
that the instance of IISWAM that it creates should be run in a transaction. If the ASP script creates
instances of any other components that have been registered with Component Services, Component
Services will treat them as part of the same transaction. The following diagram illustrates the relationship
between ASP and IISWAM.
Component Services provides transaction services to IIS through two different layers. At the lowest
layer, Component Services interacts with the Microsoft Distributed Transaction Coordinator (MS DTC)
to guarantee that transactions meet the ACID properties (Atomic, Consistent, Isolated, Durable) of a
reliable transaction processing system. Component Services links component instances to MS DTC
through two mechanisms: resource managers and resource dispensers. A resource manager is a system
service that manages durable data. Component Services supports resource managers that implement
either the OLE Transactions protocol, such as Microsoft SQL Server 6.5, or the X/Open DTP XA
standard. Resource dispensers are similar to resource managers in that they work with components to
share state information. However, the information they share is not durable. For example, resource
dispensers can manage pools of database connections for components that use standard ODBC
interfaces. The ODBC 3.0 Driver Manager is the resource dispenser for ODBC connections.
For more information on Component Services transactions, see Understanding Transactions . To view
samples of transactional scripting, see ASP Transaction Services in ASP Samples.
Securing Web sites is a critical issue for Web developers. It is also one of the most potentially confusing.
A secure system requires careful planning, and Web site administrators and programmers must have a
clear understanding of the options for securing their site. In addition, they need to understand how all of
the various security subsystems interact.
This section provides an overview of the security issues faced by ASP, component, and ISAPI
developers.
? Accessing Client Certificates with ASP: Describes the use of server-side scripts to access client
certificates.
? Passing Security Context: Outlines the various security contexts that may play a part in request
processing.
? Additional Security Considerations: Discusses the various issues surrounding security in IIS
applications.
With Active Server Pages (ASP), you can create a server-side script that extracts the contents of a
user's client certificate and saves this information in a text file. By adding this script to SSL-secured Web
pages, you can effectively catalog and manage the client certificates of users accessing your server.
Windows establishes a security context for each logged on user. When IIS receives a request from a
client, it authenticates the request and then impersonates the client. While IIS is impersonating the client,
IIS operates within the confines of the authenticated client's security context. This security context may
change during the various stages of request processing, depending on the nature of the client request. The
following diagram illustrates the various security contexts that may play a part in request processing.
The security context of the IIS process (inetinfo) is known as LocalSystem. However, when IIS is
processing a client request, it will impersonate the context of the client that generated the request. If the
client is authenticated with the Anonymous authentication scheme, the security context will be
IUSR_machinename for in process applications and IWAM_machinename for applications running in
an isolated process. If the client is authenticated with any other authentication scheme, the security
context will map to the individual account of the client.
If you create an instance of a COM component with ASP, the COM component will inherit the security
context of the .asp file that created it. When IIS destroys the component instance, it will also use the
security context of the .asp file in most instances. There is at least one case, however, where this will not
occur. If the COM component has been given session scope (that is, Session("mysesscomp") =
Server.CreateObject("MyComps.Comp1")), and the session times out before the component is
destroyed, IIS will try to destroy the component by using its own security context (LocalSystem) rather
than the context of the client that accessed the .asp file. If the component has accessed secured
resources that it has not released, this scenario can have side effects throughout the system.
Registry Issues
Many IIS applications require resources provided by other software components. For instance, an
ISAPI extension DLL may call an Automation server from a third-party software company, or a CGI
application may launch a program built with Microsoft® Visual Basic®. These components may have
persistent information stored in the registry that they require in order to execute properly. For standard
desktop use of these components, the registry information is read from the profile of the user currently
logged on a computer with Windows. These applications often have problems when launched by IIS
because the profile made available to an IIS application is that of the default user. The default-user profile
is filled with information generic to all users, but is specific to no users. Therefore, a component may run
as expected when User1 executes it on his or her desktop because it is reading information from User1's
profile in the registry. The same application may not run at all from IIS because it will not have access to
User1's profile. This is true even if IIS is impersonating User1's account by using Basic or integrated
Windows authentication.
Desktop Issues
Windows NT 4.0, and Windows 2000 uses the concept of having multiple desktops on the same
computer. A desktop can be thought of as the screen that you view when you are logged on your
computer. Your desktop receives all the mouse and keyboard messages that you send as the user at the
computer, and it allows for applications to interact with one another to a certain extent. For instance, one
application on a desktop can post messages to other applications on the desktop. Support for multiple
desktops implies that there are other desktops running; you just can't see them and you have no way of
sending keyboard or mouse messages to them. This may seem like a futile concept, but, in fact, many
applications that run as Windows services require the capabilities that a desktop provides but don't want
to interact with the interactive user's desktop. Therefore, each service gets its own desktop that won't be
interfered with by the currently logged-on user.
If your IIS application interacts with a desktop in any way (for instance, if it displays a message box),
then it will display that message box on a desktop that cannot be seen on the computer's monitor.
Similarly, an IIS application will not be able to send or post messages to an application on the interactive
desktop. If your IIS application needs to interact with the interactive desktop, then you should use
another form of inter-process communication such as Named Pipes. For more information see
"Interprocess Communication" in the Windows Base Services section of the Platform SDK.
ISAPI filter DLLs, not to be confused with ISAPI extension DLLs, run in the original context of the IIS
service. All services run by default under the Local System account of the computer on which they are
installed. The Local System account has access to almost all resources on the local computer not
specifically denied to it, and no resources on any other computers on the network.
Development Technologies
This is preliminary documentation for IIS 5.0 and is subject to change.
Microsoft Windows Distributed interNet Application (Windows DNA) Architecture is a dynamic set of
technologies that you can use to build Web applications. Microsoft has added several key aspects to the
architecture with Windows 2000.
? Component Services: Describes the services used in component and web development.
? Dynamic HTML: Discusses Dynamic Hypertext Markup Language (DHTML).
? Windows Script Components: Outlines using COM components using scripting languages.
? XML: Describes Extensible Markup Language (XML).
? Active Directory Service Interfaces: Discusses the Active Directory Service Interfaces and their
use with IIS.
Component Services
This is preliminary documentation for IIS 5.0 and is subject to change.
New with Windows 2000, Component Services provides a number of services that make component
and Web application development easier. These services include:
Dynamic HTML
This is preliminary documentation for IIS 5.0 and is subject to change.
Microsoft introduced Dynamic HTML (DHTML) with Internet Explorer 4.0. DHTML allows you to
create much richer HTML that responds to events on the client. By upgrading your HTML pages to take
advantage of DHTML, you will not only enhance the user experience, you will also build Web
applications that use server resources more efficiently.
DHTML controls the appearance of HTML pages by setting properties in the document object model
(DOM). Microsoft has proposed the DOM to the World Wide Web Consortium (W3C) as a standard.
DHTML exposes an event model that allows you to change DOM properties dynamically. The following
simple example demonstrates subdividing an HTML page with <DIV> tags and setting the display style
property to display the division when the user clicks an input button.
Sub showit()
'This subroutine is called when the user clicks a select button.
'It displays text in the hidden DIV.
document.all.cdiv.style.display = ""
End Sub
</SCRIPT>
Windows Script Components provide you with an easy way to create COM components using scripting
languages such as Microsoft® Visual Basic® Scripting Edition (VBScript) and other languages
compatible with the ECMA 262 language specification (such as Microsoft® JScript® 2.0 and JavaScript
1.1). You can use script components as COM components in applications such as Internet Information
Services (IIS), Microsoft Windows Scripting Host (WSH), and any other application that can support
COM components.
Script components are an excellent technology for developing prototypes of COM components. Script
components are like any other COM component in that they can be registered with Component Services
if you intend for them to participate in transactions or to take advantage of the Component Services run-
time environment. Because they are COM components, script components can access the ASP built-in
objects.
For further details on script components, see the Site Builder documentation on
http://microsoft.com/sitebuilder. For further information on building a script component, see Implementing
with Script Components. For specific examples of script components, see Using Components and
Objects.
XML
This is preliminary documentation for IIS 5.0 and is subject to change.
Extensible Markup Language (XML), like HTML, allows you to apply markup, in the form of tags, to a
document. However, unlike HTML, XML is designed to be used as a generalized markup language. In
other words, markup applied to an XML document can be used to convey not only display and
formatting information as with HTML, but semantic and organizational structure for the document. This
flexibility makes XML extremely powerful, and the possible range of applications is impressive.
For more information on Microsoft's work with XML, refer to the Internet Client SDK, Microsoft's
XML Web site at http://msdn.microsoft.com/xml, and the XML articles available on Microsoft Site
Builder Network at http://msdn.microsoft.com/workshop/. For more detailed information about XML
and related standards, see the World Wide Web Consortium at http://www.w3.org.
Microsoft Active Directory Service Interfaces (ADSI) is a COM-based directory service model that
allows ADSI-compliant client applications to access a wide variety of distinct directory protocols,
including Windows® Directory Services, LDAP, and NDS, while using a single, standard set of
interfaces. ADSI shields the client application from the implementation and operational details of the
underlying data store or protocol.
An application called an ADSI provider makes itself available to ADSI client applications. The data
exposed by the provider is organized in a custom namespace, defined by the provider. In addition to
implementing the interfaces defined by ADSI, the provider also can implement the ADSI schema. The
schema is used to provide metadata about the namespace structure and objects that are provided by the
ADSI provider.
For more information about ADSI, refer to the Active Directory Service Interfaces Version 2.0 SDK
and the Active Directory Schema SDK in the Platform SDK.
IIS currently stores most Internet site configuration information in a custom data store called the IIS
metabase. IIS exposes a low-level DCOM interface that allows applications to gain access to, and
manipulate, the metabase. To make it easy to access the metabase, IIS also includes an ADSI provider
that wraps most of the functionality provided by the DCOM interface, and exposes it to any ADSI-
compliant client applications. For more information about using ADSI with IIS, see Using IIS Admin
Objects.
Performance
In the world of single-user desktop software development, the performance requirements are clearly
defined. In that context, it is important that the user does not experience a significant delay when
performing common tasks.
In the early years of the World Wide Web, slow Web pages were commonplace, and for many users a
long wait was tolerated. However, as more and more enterprise Web applications were created, the
requirements for Web application performance began to rival those of the single-user desktop. Today,
with faster communication technologies becoming prevalent, users are demanding greater increases in site
performance.
Scalability
The real issue in Web application design is that while the application appears to the single user as a
traditional desktop application, it is actually a distributed application that could be simultaneously
servicing hundreds or even thousands of users.
Web applications demand performance under a wide range of environment conditions—in other words,
they must be scalable. Certainly, Web applications must perform well, but good performance when being
used by a single user does not necessarily translate into scalability.
There are many different metrics for determining how scalable an application is. Ideally, a truly scalable
Web application should be able to:
? Serve a single user as well as it can serve hundreds or thousands of simultaneous users.
? Perform twice as well when installed on a computer with twice the resources (processors, RAM,
and so on), perform three times as well on a computer with three times the resources, and so on.
Of course, these scalability requirements are ideals. However, the closer your application comes to
fulfilling those ideals, the more successful your application will be when under load.
The most important thing to keep in mind when beginning a Web application development project is that
Web applications are, for the most part, server applications. Historically, server software has been
second only to operating system internals in complexity and programming difficulty. IIS and Windows®
offer a variety of innovative tools that make Web application development much faster and easier, but the
concerns and challenges of server software programming still exist.
? Technology Choices: As with any development platform, Windows offers a number of options
for completing a given task. Making the correct choice of technologies is the first, and often most
important, step in designing a scalable Web application. For example, if a client-side technology
provides the same or similar functionality as provided on the server, the client-side option often
makes more sense; as the application is more scalable because the client handles much of the
processing load. Proper technology choices can also lead to fewer round-trips between the client
and server, further improving performance. For more information, see Web Applications: An
Overview and the Internet Client SDK.
? Language Choices: Choosing a development language impacts your Web application by defining
the range of users who have access to it. For example, including scripting in an application will
exclude users who have browsers that do not support scripting. The following lists some of the
development languages available:
? Windows Script Components
? Visual Basic
? Java
? C++
? Algorithm and Work Flow Design: Even the proper technology, if used improperly, will yield
poor results.
? Multithreading: IIS and Windows provides a multithreaded environment, and in order to create
scalable applications, you must choose the appropriate threading model for your components.
? Resource Contention and Delay: Resource contention and leakage are often major culprits
behind applications that cannot scale.
? "Real-World" Testing: You must be sure to thoroughly test your Web application in an
environment that approximates the actual environment in which the application will be deployed.
A detailed analysis of all of these topics is beyond the scope of this documentation. Instead, in this
section you will find a compilation of notes and procedures, specific to IIS, that will help you create a
scalable Web application.
For more information about designing Web applications, see Design Decisions.
With ASP, you can easily and quickly create Web applications, in a fraction of the time it would take
with a more conventional server-side language, such as C or C++.
However, the ease with which you can create ASP-based applications belies the complexity of the
server processing and client-server interaction required by that application. It is possible that Web
applications that have been created with extensive ASP scripting will not scale well.
To avoid scalability problems, there are two points to keep in mind when developing with ASP:
The first point emphasizes that ASP dovetails with HTML, client-side scripting using DHTML, and XML
to create a powerful platform for interacting with the user. ASP scripting was designed to be used to bind
the user interface to the business logic of the Web application, and ASP was optimized for these sorts of
tasks.
The second point should serve as an important reminder: If you find that most of your business logic is
embedded into the ASP, your application will probably not scale properly. It is true that ActiveX®
scripting languages, hosted by ASP, are capable of accomplishing a great deal of business logic
processing. However, if the business logic required for your Web application is more than trivial, then
that business logic should be folded into a new COM component, rather than embedded in ASP scripts.
Once you have established that your use of ASP is appropriate for the design of your application, and
you have encapsulated the bulk of your business logic into COM components, there are two avenues by
which you can further improve the performance and scalability of your Web application:
For more information about designing Web applications, see Design Decisions.
Code optimization should be performed carefully. In ASP scripting, as in any other programming
language, it is important to determine which areas of the application are consuming the most time and
resources. This information can then be used to efficiently target the critical area for optimization.
Here are several tips that might help minimize performance problems in your ASP scripts:
? Cache Application-scoped objects and data, either by creating the object in Global.asa, or
creating it on-demand in an individual ASP script, and placing it in Application scope.
? Combine output of Response.Write calls by relying on ASP buffering, which is on by default
with IIS 5.0. In order to improve the perceived performance of applications that use buffered
output while performing time-consuming operations, however, your application should periodically
use Reponse.Flush to maintain contact with the user.
If ASP buffering has been disabled for your Web application, performance may be improved if
you minimize the number of separate calls to Response.Write by combining separate output
strings into one larger string. However, if you must perform extensive string manipulations to
accomplish this, the gain in performance is probably offset by the time spent processing the strings.
? Use <OBJECT> tags instead of Server.CreateObject, when instantiating objects at
Application or Session scope. The reason is that IIS delays actually instantiating the object
specified by <OBJECT> tags until the object is actually put to use. If you use <OBJECT> tags,
and your script never uses the object, then your application will not instantiate the object. In
contrast, Server.CreateObject forces IIS to immediately create an instance of the object,
whether the object is used by the script or not.
? Use local variables, avoid public variables. Local variables can be accessed quicker by the
ASP scripting engine than public variables, because the entire namespace doesn't have to be
searched to access the value of a local variable.
? Use client-side validation of user input, where possible, to minimize the HTTP round trips
required. If the browser is full-featured, harness the power of the browser, and free up server-side
resources for more critical tasks. Of course, some integrity checking still should be performed on
the server, depending on the application, as an extra precaution against data corruption.
? Copy individual values from collections into local variables, if you are going to reference the
value more than once. This saves ASP from having to perform lookup processing in the collection
for each and every reference.
? Turn off session state for the entire application, if possible. If your application does not
require the use of IIS sessions, you should use the Internet Information Services snap-in to disable
session state for the entire application. Sessions in IIS remain in memory, and the memory
allocated to the sessions will not be freed until the session has been terminated or timed-out. If
your application is being used by many concurrent users, the server's resources could become
depleted, and performance could be affected. If some parts of your application don't need session
state, you should disable session state for those pages by using the @ENABLESESSIONSTATE
directive.
Turning off session state whenever possible is especially helpful if the page contains a
<FRAMESET> element. Some browsers, including Internet Explorer, will use separate threads to
process the separate frames of the frameset. If session state is turned on for the frameset page, the
client-side performance benefit of these parallel threads will be lost, because IIS will be forced to
serialize the threads processing the separate requests.
? If you do rely on session state, avoid placing large amounts of data into the Session
object, and into session state. Sessions in IIS are persistent, and the memory allocated to the
sessions will not be freed until the session has been terminated or timed-out. If your application is
being used by many concurrent users, the server's resources could become depleted, and
performance could be affected.
? Do not provide empty Session_OnStart or Session_OnEnd.
? Pay close attention to the effects of IIS and ASP configuration changes. See IIS
Configuration Optimization for more details.
? If your ASP page is running as part of an application, designate the application as out-of-
process for application debugging only. Process isolation, which was introduced in IIS 4.0, is
a useful capability. The cross-process marshalling required to support process isolation, however,
can introduce a certain amount of overhead to ASP processing. This difference in overhead is
most significant for simple ASP pages, and is less of a concern for more complex pages. To
maximize scalability and performance, however, consider running the application out-of-process
only until it is sufficiently debugged and stable to be run in-process with IIS.
? Avoid ReDimming arrays, if possible. It is more efficient to simply allocate the full size of the
array when the array is first initialized.
IIS provides several configuration settings that you can adjust to tune the performance and scalability of
your Web applications. These include:
? AppAllowDebugging
? AspAllowSessionState
? AspEnableChunkedEncoding
? AspEnableTypelibCache
? AspProcessorThreadMax
? AspTrackThreadingModel
? AspRequestQueueMax
? AspQueueConnectionTestTime
? AspSessionMax
? AspBufferingOn
? AspScriptEngineCacheMax
? AspSessionTimeout
? AspThreadGateEnabled
Performance tips are provided in the reference page for each property; click a property in preceding list
to see its reference page.
Because you should encapsulate most of your business logic within COM components, it is important
that your components be designed for high performance, in addition to being readily scalable.
default process heap. Each custom heap would then be controlled by a separate, non-
global lock, and lock contention would be reduced.
? Cached Allocation, which involves using custom allocation operations that operate at a
middle layer between the object users and the heap. Calls to the Win32 heap are made
infrequently, and only for large memory blocks. These blocks are then subdivided and
managed by the custom allocator.
? Stack Allocation, using the C run-time function _alloca to allocate memory for your
objects on the stack instead of the heap. This method is feasible only for relatively small
objects, because the space available on the stack is limited. In addition, your newly
allocated object will be available only within the current functions, or functions called by that
function. Once the current function returns, the storage allocated on the stack will be lost.
? Object Encapsulation, accomplished by simply incorporating a buffer as a member data
structure of your component class. This buffer is then used for tasks that would otherwise
require accesses to the Win32 heap.
? Avoid using global locks within your component, if possible. Global locks can often adversely
affect component scalability.
? If your component is running as part of an application, designate the application as out-
of-process for application debugging only. Process isolation, introduced in IIS 4.0. is a useful
capability. The cross-process marshalling required to support process isolation, however, can
introduce a certain amount of overhead to component execution. This difference in overhead is
most significant for simple components, and is less of a concern for more complex components.
To maximize scalability and performance, however, consider running the application out-of-
process only until it is sufficiently debugged and stable to be run in-process with IIS.
? Consider placing your component in a library (in-process) COM+ application. As part of
the Just-In-Time activation feature of Component Services, the component's COM class factory is
cached, and reused for each instantiation request through CreateInstance.
ISAPI is the highest-performance interface for Web applications. If you create an ISAPI extension or
filter, chances are that it will outperform ASP scripts or even components performing similar tasks.
However, the inherent speed of the ISAPI interface does not mean that you can ignore performance and
scalability considerations. Indeed, ISAPI cannot utilize much of the application support services provided
by ASP and COM. If you would like your ISAPI application to maintain session state, for instance,
much of that session-state functionality would have to be implemented by you.
Here are some suggestions for improving the scalability and performance of your ISAPI extensions:
? Avoid ISAPI filters , unless adding an ISAPI filter is absolutely necessary to your application
architecture. You should especially avoid filters that perform processing on raw incoming or
outgoing data. If you determine that a filter is absolutely necessary, be sure to carefully optimize
the main code paths through the filter event notification code.
? Create your own worker thread pool, so that the main I/O threads can be freed to accomplish
other tasks. This option is available only for ISAPI extensions, and not for ISAPI filters. For more
information about how IIS processes requests, see IIS Request Processing. A sample that
demonstrates a worker thread pool, implemented in an ISAPI extension, is available in ISAPI
Examples.
? Consider using asynchronous operations and I/O completion ports, when feasible. IIS
supports asynchronous reading and writing by using the I/O completion ports, available in
Windows NT 4.0, and Windows 2000 or later. Depending on the type of I/O operations being
performed, asynchronous operations can make better use of the CPU time available, and generally
work particularly well when implemented using a worker thread pool. For more information, see
Asynchronous I/O Processing.
? ISAPI extensions should use the Win32 TransmitFile function, exposed by the
HSE_REQ_TRANSMIT_FILE ServerSupportFunction.
? Use Connection: Keep-Alive headers . Keeping persistent HTTP connections will provide
better performance than using non-persistent connections, in most cases. For more details, see
Keep-Alive Connections.
? Minimize need for thread synchronization by maintaining state information with the request
context. If thread synchronization is required, make sure that critical sections are kept short.
? If your ISAPI application uses the heap intensively, consider other heap alternatives.
Intensive use of the Windows® heap can cause resource contention. Several memory allocation
alternatives are worth exploring, including:
? Heap Partitioning, accomplished by creating multiple custom heaps, in addition to the
default process heap. Each custom heap would then be controlled by a separate, non-
global lock, and lock contention would be reduced.
? Cached Allocation, which involves using custom allocation operations that operate at a
middle layer between the object users and the heap. Calls to the Win32 heap are made
infrequently, and only for large memory blocks. These blocks are then subdivided and
managed by the custom allocator.
? Stack Allocation, using the C run-time function _alloca to allocate memory for your
objects on the stack instead of the heap. This method is feasible only for relatively small
objects, because the space available on the stack is limited. In addition, your newly
allocated object will be available only within the current functions, or functions called by that
function. Once the current function returns, the storage allocated on the stack will be lost.
? Object Encapsulation, accomplished by simply incorporating a buffer as a member data
structure of a class. This buffer is then used for tasks that would otherwise require accesses
to the Win32 heap.
? Avoid using global locks within your ISAPI, if possible. Global locks can often adversely
affect scalability.
For more information about ISAPI extensions and filters, see Developing ISAPI Extensions and Filters,
and the ISAPI Reference.
Data access and retrieval is often the most challenging performance area for the Web application
developer.
Many of the scalability and performance concerns that arise around data access are not in your control,
as a Web application developer. However, there are some techniques that you can use to maximize your
performance:
? Cache results from data sources that are stable, or that vary predictably. You can cache
either the recordset returned by a query to the data source, or cache the pure HTML output that
was created using the results of the query.
For instance, if you are using ADO to populate a listbox that will contain the cities in which you
have offices, the first caller to ADO can insert the ADO query results into Application scope.
Subsequent requests for that listbox information could be fulfilled from the Application object,
instead of an expensive call, through ADO, to a data source.
If you wish to cache the resultant recordset directly, you should use a client-side cursor, and
disassociate the recordset from the Command object by setting the ADO ActiveConnection
property to Nothing.
introduced in ADO 2.0, was created to reduce the amount of overhead incurred by ADO, and
thus increase performance and scalability.
? Disable temporary stored procedures, if your data source supports them.
For more information on data access, see Accessing a Data Source and Accessing Data with ASP.
Careful planning and development are necessary for any Web application development project.
However, in order to make a truly scalable Web application, it is important that you rigorously and
regularly test your Web application for scalability problems. It is important to understand that almost all
Web applications encounter some unforeseen scalability problems during development. The only way
these problems can be found and solved is through careful, thorough testing.
In general, the most useful scalability and performance testing stresses the application in a way that
closely parallels the stresses the application would undergo in a "real-world" setting.
Here are a few tools that you can use to perform scalability testing for your Web application:
? InetLoad can be used to generate customizable loads on various Internet services, over a broad
range of Internet protocols, including HTTP, SMTP, POP3, and LDAP. InetLoad can be set to
the exact mix of protocol traffic you expect to be generated, and can be used to simulate hundreds
or even thousands of users.
WCAT is available, along with documentation on how to use it, in the IIS Resource Guide
volume of the Windows 2000 Server Resource Kit. WCAT is also available for Web download
from http://www.microsoft.com/ntserver/web/.
Internet Information Services (IIS) provides powerful programming tools that you can use to access
configuration settings from within a script or application.
? Overview of Programmatic Administration: Describes the metabase, and what you should know
before you create administration applications.
? Using IIS Admin Objects: Explains how you can access the metabase from your scripts or
applications by using an Automation-compatible language of your choice, such as VBScript,
JScript, C++, or Visual Basic.
? Programmatic Administration Reference: Contains reference information for the programmatic
administration objects and interfaces that can be used with IIS.
IIS configuration parameter values are stored in a fast-access, memory-resident data store called the
metabase. The metabase is designed specifically for use with IIS and is faster, more flexible, and more
expandable than the Windows registry.
The metabase is the repository for most IIS 5.0 configuration information.
Metabase Structure
This is preliminary documentation for IIS 5.0 and is subject to change.
Most configuration settings for IIS reside in a storage facility, similar to the Windows registry, called the
metabase. You should become familiar with how the metabase operates, how the information contained
within the metabase is organized, and how you can access that information.
The metabase is organized in a hierarchical structure that mirrors the structure of your IIS installation.
Each node in the metabase structure is called a key, and each key can contain one or more IIS
configuration values, called metabase properties. The IIS metabase keys correspond to the elements of
IIS, and each key contains properties that affect the configuration of its associated element.
Most of the IIS configuration keys and values that were stored in the system registry for earlier versions
of IIS are now stored as properties in the metabase. New keys and values have been added for finer and
more flexible control of IIS. The metabase was designed to allow the same property to be set differently
at different nodes. For example, the MaxBandWidth property setting can be a different value for each
server.
The general structure of IIS is shown in the following figure, which is arranged by key types. The
metabase structure of your IIS installation can consist of a varied number of elements, depending on your
installation choices. Metabase keys associated with IIS elements are addressed by their paths within the
metabase. See Key Names and Paths.
The top-level metabase key, named Computer, contains properties such as MaxBandWidth. These
properties affect the overall execution of IIS on your computer. Two subkeys of the Computer key are
associated with FTP services and Web services, respectively, and contain properties that affect all FTP
and Web servers hosted on that computer.
Subkeys of the FTP service key are associated with individual FTP servers, and contain properties
specific to each FTP server. A subkey of each FTP server key is associated with the root virtual
directory for that server. Other subkeys are added to the root virtual directory key as you add virtual
directories to your FTP servers. Each of these subkeys contains properties that affect the operation or
configuration of the associated virtual directory. The Info key, directly subordinate to the FTP service
key, also contains some properties associated with the FTP service.
Subkeys of the Web service key are associated with individual Web servers, their root virtual directories,
subordinate virtual directories, disk directories, and files. A subkey of the Web service key affects the
configuration of filters used by Web service operations. The Info key, directly subordinate to the Web
service key, also contains some properties associated with the Web service.
Other keys directly subordinate to the top-level key contain properties that affect logging and MIME
mappings. The IISADMIN key is used to record DCOM extensions to IIS.
Keys can also contain references to objects that can be used by the IIS Admin Objects. For example,
the CertMapper key does not contain any metabase properties, but it does provide access to the
IIsCertMapper object and its methods for mapping certificates.
A metabase key is a location in the metabase analogous to a directory in the file system. A metabase
path is a sequence of keys separated by a forward slash (/) that uniquely identifies the location of a key in
the metabase. Key names in the metabase are not unique unless qualified by their metabase paths, just as
different files with the same name can exist in different directories.
You can use the path of a metabase key with the IIS Admin Objects to access the specific IIS Admin
Object associated with that key. The IIS Admin Objects use the Active Directory Service Interfaces
(ADSI) path, called the ADsPath, to refer to the object associated with a key. The path starts with IIS://
and then uses the term LocalHost, or a specific computer name, to refer to the IIsComputer object,
which is associated with the highest key in the metabase.
The paths to objects associated with other metabase keys are an extension of the ADsPath to the
computer key. For example, the ADsPath for the first Web site in your IIS installation would be
IIS://LocalHost/W3SVC/1. You could also use the path IIS://ComputerName/W3SVC/1 to access the
metabase on a different computer.
Each Web site is a server instance, and is referred to in the path by its number. For example,
IIS://LocalHost/MSFTPSVC/3 represents the third FTP server instance, and
IIS://ComputerName/W3SVC/4 represents the fourth Web server instance.
Each Web site has an associated root virtual directory. All other virtual directories and directories
associated with a server instance are subordinate to this root virtual directory. The name of the root
virtual directory is ROOT. IIS://LocalHost/MSFTPSVC/3/ROOT refers to the root virtual directory for
the third FTP server on the local computer, and IIS://LocalHost/W3SVC/4/ROOT refers to the root
virtual directory for the fourth Web server on the same computer.
You can establish the structure below the root virtual directory of a server instance by adding virtual
directories, directories, and files. For FTP servers, metabase properties can be set to the virtual-
directory level. For Web servers, you can set properties to the level of directories and files. For example,
you could use the path IIS://LocalHost/W3SVC/2/ROOT/MyVdir1/Dir1/File1 to set file properties such
as read, write, and execute permissions.
Property Inheritance
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use the property inheritance feature of the metabase to configure your IIS installation with few
settings, and to minimize the amount of memory required for the metabase. Most metabase properties
are inheritable, meaning that they are not explicitly set at a specific key and will inherit values assigned at
higher-level keys. For example, you can set file and directory permissions such as AccessScript,
AccessExecute and AccessWrite at the W3SVC level to apply to all files and directories in all server
instances, or you can set them at the W3SVC/2/ROOT level to apply to all files and directories for the
second Web server only. You can then set different permissions for individual subdirectories and files by
explicitly setting them at lower levels. For example, you might set the AccessExecute permission
property to TRUE for specific directories, virtual directories, or files, such
as ...W3SVC/1/ROOT/VDir1/VDir1a, ...W3SVC/1/ROOT/VDir2/Dir2d,
and ...W3SVC/1/ROOT/VDir2/Dir3/File1, and so on.
The default settings for AccessScript, AccessExecute, and AccessWrite are all FALSE. The way
inheritance works is that wherever you set the value of an inheritable property, all instances of that
property in the remaining subnodes will be set automatically. If you use Internet Services Manager to set
an inheritable property, a dialog box will ask you if you are sure you want to change the value for all the
subnodes. However, if you use a script or the command line to set an inheritable property, the values will
be propagated immediately.
In the following example, AccessScript is set to TRUE at the Web service level (.../W3SVC),
AccessExecute to TRUE at the root level (.../W3SVC/1/ROOT), and AccessWrite to TRUE at the
file level (.../W3SVC/n/ROOT/VDir/Dir/File). The round ball represents where the user sets the
property value and the arrows show the path of inheritance as the value is propagated through the
subnodes.
Most metabase properties are inheritable, except for a few that are used only at specific keys. Some
properties in the metabase are lists of values, such as the ServerBindings property.
Flag properties, such as file access permissions, are often combined into one DWORD by use of
bitmasking. The entire set of flags is stored together and inherits together. For example, if you change one
of the file access permissions, such as AccessExecute for a directory, the entire set of file access
permissions is stored at the metabase key for that directory.
Each metabase property is described in detail in the Administration Property Reference. This reference
includes information about whether each property is inheritable. Also, properties that are stored as part
of a larger set are identified as flags; for example, see the property AccessFlags.
The metabase key values are stored in a disk file, which is named Metabase.bin by default. The
metabase is loaded from disk when IIS starts, stored to disk when IIS shuts down, and saved
periodically while IIS is running. It is important to protect this file from unauthorized use. It is
recommended that you store this file on an NTFS partition and use Windows security to protect it.
Metabase.bin is stored in the Inetsrv directory. You can move or rename the file and change the
Windows registry setting that tells IIS where to find the file on startup. To relocate or rename the
metabase file, you must stop IIS, move or rename the file, and modify the registry key
LOCAL_MACHINE\SOFTWARE\Microsoft\INetMgr\Parameters. Then add a REG_SZ value,
named MetadataFile, to this key. MetadataFile specifies the new complete path of the metabase file,
including the drive letter and file name.
Metabase Reliability
You can implement your own custom backup policy for the metabase, or create specialized backup
tools. Your application can use the methods provided by the IIsComputer object (for IIS Admin
Objects) or IMSAdminBase (for the IIS Admin Base Object) to manage metabase backups. You can
store multiple backup versions in long-term storage, restore the metabase from a backup version of your
choice, and enumerate and delete backups.
Important The metabase backup and restore functionality exists for versioning purposes, not for cross-
machine replication. A metabase backup must be restored only to the same machine on which it was
originally created.
As described in Introduction to the IIS Metabase, the metabase contains most of the configuration
information that IIS needs to operate properly. You can programmatically administer the metabase by
using the IIS Admin Base Object, which also uses the IWamAdmin Interface. Developers can build
applications to use this object; or they can build applications to use the IIS Admin Objects, which
provide a simpler way to implement applications. The following image shows the relationship between the
metabase, the IIS Admin Base Object, and the IIS ADSI Admin Objects layer.
IIS provides two distinct ways to programmatically access the information stored in the metabase:
1. IIS Admin Objects: These objects correspond to the key building blocks of your IIS installation.
Thus, there is an IIS Admin Object named IIsWebServer that exposes properties and methods
that apply to Web servers, another IIS Admin Object named IIsFtpServer that applies to FTP
servers, and so on.
The IIS Admin Objects are most suitable for use with Automation-compatible languages such as
Visual Basic, VBScript, or JScript. For more detailed information, see Using IIS Admin Objects.
2. IIS Admin Base Object: This object provides more advanced development choices. For more
information, see Advanced Programmatic Administration.
The IIS Admin Objects, described in this section, are provided by IIS to make programmatic
administration as straightforward as possible. The IIS Admin Objects are based on Microsoft Active
Directory Service Interfaces (ADSI), are Automation-compatible, and can be easily accessed and
manipulated by any language that supports Automation, such as Microsoft Visual Basic Scripting Edition
(VBScript) or JScript in Active Server Pages (ASP), Visual Basic, Java, or C++.
? IIS Admin Objects Overview: Introduces the IIS Admin Objects and describes what they are and
how they are used.
? Administrative Tasks Using the IIS Admin Objects: Describes how you can use the IIS Admin
Objects for common programmatic administration tasks.
For more information, see IIS Admin Objects Reference, Administration Property Reference, and
Programmatic Administration Examples.
The IIS Admin Objects are COM Automation objects that you can use within ASP pages or custom
applications to change IIS configuration values stored in the IIS metabase. For example, you could set
permissions for the AccessRead, AccessWrite, and AccessExecute properties by writing a script in
an ASP page.
Individual IIS Admin Objects correspond to keys in the metabase and are addressed by their paths
within the metabase. Each object has properties and each property is stored in the metabase. You can
manipulate your IIS configuration by using IIS Admin Objects; you can change properties, add new
virtual directories, add new Web sites, and so on.
Because modifying an IIS Admin Object property changes the value of the corresponding metabase
property, you can configure individual elements of IIS such as the local machine (LM), FTP server
(FTPSVC), or Web server (W3SVC). Because of the hierarchical structure of the metabase and its
property inheritance feature, you can easily configure properties for a single file, a single server, all Web
servers, all FTP servers, or the common properties of many other groups of objects.
? Object Hierarchy: Describes the relationship of the IIS Admin Objects to the metabase and how
you address these objects in your application.
? ADSI Features: Explains how the IIS Admin Objects implement standard ADSI properties and
methods that you can use to administer IIS.
Object Hierarchy
This is preliminary documentation for IIS 5.0 and is subject to change.
The IIS Admin Objects are organized in a hierarchical structure that mirrors the IIS structures defined in
the IIS metabase. Objects contain other objects to create the object structure illustrated in the following
diagram. Details of the IIS structure and the metabase are found in the Metabase Structure topic of the
Introduction to the IIS Metabase section. Most objects will inherit characteristics of the parent object,
but child objects can contain unique characteristics implemented by extending the schema. You can use
this object hierarchy to access configuration settings for specific IIS elements. The structure shown in the
diagram can vary slightly depending on how IIS is installed.
ADSI Features
This is preliminary documentation for IIS 5.0 and is subject to change.
This section discusses ADSI objects and container objects, and how each is implemented and exposed.
The IIS Admin Objects are exposed by IIS as an implementation of ADSI. ADSI provides a standard
syntax for addressing IIS configuration data. The IIS namespace consists of the IIS Admin Objects and
the metabase. The IIS remote administration tool, Internet Service Manager (HTML), uses the IIS
Admin Objects.
? ADSI Objects: Discusses ADSI objects and how they can be used to configure IIS.
? ADSI Container Objects: Describes ADSI container objects and their functionality in IIS.
You can reference IIS Admin Objects by their metabase path. For example, the IIS Admin Object for
the first Web site on the computer named MyComputer would be addressed by the ADSI path
(ADsPath) IIS://MyComputer/W3SVC/1.
The following VBScript code demonstrates how you might use a script to reference the path to the first
Web site (…/1) to open the IIS Admin Object. In the example, this object is associated with the
metabase key for the Web site, which resides on the local machine.
Note You can use the string "LocalHost" instead of the actual machine name.
<%
Dim VSvrObj
Set VSvrObj = GetObject("IIS://LocalHost/W3SVC/1")
Response.Write "Value of ServerComment = " & VSvrObj.ServerComment
%>
ADSI Objects
The IIS Admin Objects each implement the IADs interface defined by the ADSI standard. The IADs
interface for the IIS Admin Objects provides the following basic functionality:
? A simple way to set and retrieve configuration properties on a specific node in the metabase. For
example, you can change permissions (AccessFlags) for a specific Web site.
? A way to retrieve the path of the object's parent container object.
? Binding information that uniquely identifies the object instance in a directory tree.
? A path to the schema definition of the object.
? Identification information that indicates the name and type of the object.
? A way to retrieve namespace properties.
? A simple implicit caching system.
The IIS Admin Objects implement the IADs interface, supporting the Name, ADsPath, Class, GUID,
Parent, and Schema properties in addition to IIS-specific metabase properties. The IADs GetInfo,
SetInfo, Get, Put, GetEx, and PutEx methods are also supported, in addition to others needed for IIS
configuration administration. For more specific information about the ADSI properties and methods
provided by the IIS Admin Objects, see the ADSI Reference.
Any IIS Admin Object that can contain other objects can also implement the IADsContainer interface,
in addition to the IADs interface. Examples of IIS Admin Objects that support IADsContainer include
the following:
? IIsComputer, which can contain IIsWebService and IIsFtpService objects, among others.
? IIsWebVirtualDir object, which can contain IIsWebDirectory and IIsWebFile objects, as
well as additional IIsWebVirtualDir objects.
The IADsContainer interface permits objects to contain other objects, and provides a way to
implement the following tasks:
The IIS Admin Objects that can contain other objects can also implement container object properties
and methods. These objects accomplish this by supporting the IADsContainer interface, the
_NewEnum and Count properties, and the GetObject, Create, and Delete methods. IIS Admin
Objects also support the basic IADs interface properties and methods, and any IIS-specific or extended
properties and methods.
IIS configuration information is stored as binary values in the metabase, also referred to as metabase
properties. You can use the IIS Admin Objects to change these configuration values. These objects can
also be used to configure your IIS installation, create new FTP and Web servers, virtual directories, and
other IIS elements. Individual IIS Admin Objects correspond to specific types of keys in the metabase.
With simple scripts or within ASP pages, you can use the IIS Admin Objects to create applications for
remote administration of your IIS installation.
One example of such an application is the Internet Service Manager (HTML), a remote administration
tool that ships with IIS. This tool was constructed with the techniques demonstrated in this section.
? Manipulating the Metabase: Explains one of the more common programmatic administration tasks
you can do with IIS, manipulating the metabase by using a script.
Other sample command-line scripts are provided in the \Inetpub\AdminScripts directory. For more
examples, see Developer Samples.
The IIS Admin Objects expose a hierarchical namespace of objects where each object has an ADsPath
property. The ADsPath syntax is similar to that of a Uniform Resource Locator (URL), in the form of
IIS://[path], where [path] represents the directory path of the object being accessed. For example,
IIS://MyComputer/W3SVC refers to the IIsWebService object for the machine named MyComputer.
The object associated with MyComputer is the IIsComputer object, which contains all of the other IIS
Admin Objects.
To obtain a reference to a named object, you can use the GetObject function in Visual Basic or
VBScript.
Note Other scripting languages can be used; see the documentation for the scripting language for
details, as well as the ADSI Reference.
For example, you can retrieve the current value of ServerComment by inserting the following VBScript
into an .asp file. In the following example, the string "LocalHost" is used instead of the explicit name
"MyComputer" to access the computer on which IIS is running.
<%
Dim ComputerObj
Dim MaxBW
Set ComputerObj = GetObject("IIS://LocalHost")
MaxBW = ComputerObj.Get("MaxBandwidth")
%>
This could also be implemented using the object.property syntax, as in the following example.
<%
Dim ComputerObj
Dim MaxBW
Set ComputerObj = GetObject("IIS://LocalHost")
MaxBW = ComputerObj.MaxBandwidth
%>
Note ASP pages that access the metabase require administrator privileges on the computer on which
IIS is running; this is also true when running ASP applications out-of-process. When you execute scripts
from a remote computer, you must connect through a secure connection, such as a connection protected
by integrated Windows authentication (also called NTLM authentication). It is suggested that you create
a server or directory for your administrative .asp files and set the authentication method to use integrated
Windows authentication for the server or directory.
For security purposes, out-of-process applications cannot access the metabase unless WamUserName
is recognized as an administrator. It is recommended that you retain this default behavior unless special
circumstances require otherwise.
There are two ways you can modify this out-of-process behavior, but each introduces some security risk:
? You can give the IWAM_machinename account administrator-level access to the metabase,
though this will allow administrator-level access to the metabase for all out-of-process applications
created with this default administrator-level identity.
? Or, you can change the identity of the specific out-of-process package to some other account
identity, and give only that account administrator-level access to the metabase. This method
introduces less potential risk, but it must be implemented for each out-of-process package.
This section contains reference information for the programmatic administration objects and interfaces
that can be used with IIS.
? IIS Admin Objects Reference: Contains a reference page for each of the IIS Admin Objects.
? ADSI Reference: Describes properties and methods that are exposed by the IIS Admin Objects.
? Administration Property Reference: Describes each IIS administration property, including the data
type, default value, inheritance attribute, and provides usage notes.
This topic contains a reference page for each of the IIS Admin Objects. Each page includes ADSI
container information, the ADsPath for the object, the metabase properties accessible by the object,
and any additional methods specific to the object.
Note Each IIS Admin Object has a property called KeyType which specifies exactly what type of IIS
Admin Object a given ADSI object represents. If the key type is not available, or is not valid, then IIS
assigns the generic type IIsObject. You can use KeyType to change the ADSI object to a valid object,
and gain access to other IIS-specific properties and methods.
See Also
IIsCertMapper
This is preliminary documentation for IIS 5.0 and is subject to change.
The IIsCertMapper object maps client certificates to Windows user accounts. IIsCertMapper is an
ADSI object, but not an ADSI container object. See ADSI Features for more information about ADSI
container objects.
ADsPath
IIS://MachineName/W3SVC/N/IIsCertMapper
Syntax
varReturn = IIsCertMapper.Method
Parts
varReturn
A variable that receives the return value from the method.
Method
The object method chosen.
Methods
See Also
CreateMapping
The CreateMapping method of the IIsCertMapper object maps a certificate to a Windows account.
Syntax
Parameters
vCert
Contains the certificate. The certificate is either a string or an array of bytes, usually obtained from
the ClientCertificate collection of the built-in ASP Request Object.
NtAcct
Contains the Windows account string.
NtPwd
Contains the password string for NtAcct.
strName
Contains the friendly name for the account.
IEnabled
Specifies TRUE to enable the mapping, FALSE to disable the mapping.
Code Example
<%
Dim CertObj, vCert
vCert = Request.ClientCertificate("CERTIFICATE")
Set CertObj = GetObject("IIS://..path../IIsCertMapper")
CertObj.CreateMapping vCert, "MYACCT", "MYPASS", "My Name", True
%>
See Also
DeleteMapping
The DeleteMapping method of the IIsCertMapper object deletes an existing certificate mapping.
Four seek methods are available to search for the mapping: by certificate, by name, by Windows
account, and by numeric string index.
Syntax
Parameters
IMethod
Specifies the seek method to use for searching the mappings. Valid seek methods are 1, 2, 3, or
4. Seek method 1 specifies search by certificate, seek method 2 searches by name, method 3
searches by Windows account, and method 4 searches by a 1-based numeric string index (for
example "1," "2," and so on).
vKey
Specifies the key to use in the search specified by IMethod. For seek method 1, vKey specifies a
certificate. For seek method 2, vKey specifies a name. For seek method 3, vKey specifies a
Windows account. For seek method 4, vKey specifies a numeric string index (for example, "1,"
"2," and so on).
Code Example
<%
Dim CertObj
Set CertObj = GetObject("IIS://..path../IIsCertMapper")
'Search by Windows account.
CertObj.DeleteMapping 3, "MYACCT"
%>
See Also
GetMapping
The GetMapping method of the IIsCertMapper object retrieves a certificate and the mapping data
from an existing certificate mapping. Four seek methods are available to search for the mapping: by
certificate, by name, by Windows account, and by numeric string index. The retrieved mapping is
returned in parameter variables you provide.
Syntax
Parameters
IMethod
Specifies the seek method to use for searching the mappings. Valid seek methods are 1, 2, 3, or
4. Seek method 1 specifies search by certificate, seek method 2 searches by name, method 3
searches by Windows account, and method 4 searches by a 1-based numeric string index (for
example, "1," "2," and so on).
vKey
Specifies the key to use in the search specified by IMethod. For seek method 1, vKey specifies a
certificate. For seek method 2, vKey specifies a name. For seek method 3, vKey specifies a
Windows account. For seek method 4, vKey specifies a numeric string index (for example, "1,"
"2," and so on).
vCert
Receives the returned certificate.
NtAcct
Receives the returned Windows account.
NtPwd
Receives the returned Windows account password.
strName
Receives the returned Windows account friendly name.
IEnabled
Receives the returned value TRUE for an enabled mapping, or FALSE for a disabled mapping.
Code Example
<%
Dim CertObj, vCert, NtAcct, NtPwd, strName, IEnabled
Set CertObj = GetObject("IIS://..path../IIsCertMapper")
'Search by Windows account.
CertObj.GetMapping 3, "MYACCT", vCert, NtAcct, NtPwd, strName, IEnabled
%>
See Also
SetAcct
The SetAcct method of the IIsCertMapper object sets a new value for the Windows account string in
an existing certificate mapping. Four seek methods are available to search for the mapping: by certificate,
by name, by Windows account, and by numeric string index.
Syntax
Parameters
IMethod
Specifies the seek method to use for searching the mappings. Valid seek methods are 1, 2, 3, or
4. Seek method 1 specifies search by certificate, seek method 2 searches by name, method 3
searches by Windows account, and method 4 searches by a 1-based numeric string index (for
example, "1," "2," and so on).
vKey
Specifies the key to use in the search specified by IMethod. For seek method 1, vKey specifies a
certificate. For seek method 2, vKey specifies a name. For seek method 3, vKey specifies a
Windows account. For seek method 4, vKey specifies a numeric string index (for example, "1,"
"2," and so on).
NTAcct
Specifies a new value for the Windows account string.
Code Example
<%
Dim CertObj
Set CertObj = GetObject("IIS://..path../IIsCertMapper")
'Search by Windows account.
CertObj.SetAcct 3, "MYACCT", "NewAccount"
%>
See Also
SetEnabled
The SetEnabled method of the IIsCertMapper object enables or disables an existing certificate
mapping. Four seek methods are available to search for the mapping: by certificate, by name, by
Windows account, and by numeric string index.
Syntax
Parameters
IMethod
Specifies the seek method to use for searching the mappings. Valid seek methods are 1, 2, 3, or
4. Seek method 1 specifies search by certificate, seek method 2 searches by name, method 3
searches by Windows account, and method 4 searches by a 1-based numeric string index (for
Code Example
<%
Dim CertObj
Set CertObj = GetObject("IIS://..path../IIsCertMapper")
'Search by Windows account.
CertObj.SetEnabled 3, "MYACCT", True
%>
See Also
SetName
The SetName method of the IIsCertMapper object sets a new value for the name string in an existing
certificate mapping. Four seek methods are available to search for the mapping: by certificate, by name,
by Windows account, and by numeric string index.
Syntax
Parameters
IMethod
Specifies the seek method to use for searching the mappings. Valid seek methods are 1, 2, 3, or
4. Seek method 1 specifies search by certificate, seek method 2 searches by name, method 3
searches by Windows account, and method 4 searches by a 1-based numeric string index (for
example, "1", "2", and so on).
vKey
Specifies the key to use in the search specified by IMethod. For seek method 1, vKey specifies a
certificate. For seek method 2, vKey specifies a name. For seek method 3, vKey specifies a
Windows account. For seek method 4, vKey specifies a numeric string index (for example, "1,"
"2," and so on).
strName
Specifies a new value for the name string.
Code Example
<%
Dim CertObj
Set CertObj = GetObject("IIS://..path../IIsCertMapper")
'Search by Windows account.
CertObj.SetName 3, "MYACCT", "NewName"
%>
See Also
SetPwd
The SetPwd method of the IIsCertMapper object sets a new value for the Windows password string
in an existing certificate mapping. Four seek methods are available to search for the mapping: by
certificate, by name, by Windows account, and by numeric string index.
Syntax
Parameters
IMethod
Specifies the seek method to use for searching the mappings. Valid seek methods are 1, 2, 3, or
4. Seek method 1 specifies search by certificate, seek method 2 searches by name, method 3
searches by Windows account, and method 4 searches by a 1-based numeric string index (for
example, "1," "2," and so on).
vKey
Specifies the key to use in the search specified by IMethod. For seek method 1, vKey specifies a
certificate. For seek method 2, vKey specifies a name. For seek method 3, vKey specifies a
Windows account. For seek method 4, vKey specifies a numeric string index (for example, "1,"
"2," and so on).
strPwd
Specifies a new value for the Windows password string.
Code Example
<%
Dim CertObj
Set CertObj = GetObject("IIS://..path../IIsCertMapper")
'Search by Windows account.
CertObj.SetPwd 3, "MYACCT", "NewPassword"
%>
See Also
IIsCompressionSchemes
This is preliminary documentationfor IIS 5.0 and is subject to change.
IIsCompressionSchemes is an ADSI container object that contains the individual HTTP 1.1
compression schemes that are available to IIS, represented by the ADSI object
IIsCompressionScheme . In addition, all global compression settings for the IIS installation are stored in
IIsCompressionSchemes.
ADsPath
IIS://MachineName/W3SVC/Filters/Compression/Parameters
Syntax
varReturn = object.Method
varReturn = object.Property
Parts
varReturn
A variable that receives the return value from the method.
object
A variable that refers to the IIsCompressionSchemes object, usually as a result of a previous
GetObject operation.
Method or Property
The particular object method or property that you want to use.
Can Contain
IIsCompressionScheme
Properties
Metabase Properties
HcCacheControlHeader HcIoBufferSize
HcCompressionBufferSize HcMaxDiskSpaceUsage
HcCompressionDirectory HcMaxQueueLength
HcDoDiskSpaceLimiting HcMinFileSizeForComp
HcDoDynamicCompression HcNoCompressionForHttp10
HcDoOnDemandCompression HcNoCompressionForProxies
HcDoStaticCompression HcNoCompressionForRange
HcExpiresHeader HcSendCacheHeaders
HcFilesDeletedPerDiskFree
Methods
IIsCompressionScheme
This is preliminary documentation for IIS 5.0 and is subject to change.
The IIsCompressionScheme IIS Admin Object is an ADSI object that contains configuration
information about an individual compression scheme. All instances of the IIsCompressionScheme
object are contained within IIsCompressionSchemes.
ADsPath
IIS://MachineName/W3SVC/Filters/Compression/Scheme
Syntax
varReturn = object.Method
varReturn = object.Property
Parts
varReturn
A variable that receives the return value from the method.
object
Properties
Metabase Properties
HcCompressionDll HcFileExtensions
HcCreateFlags HcMimeType
HcDoDynamicCompression HcOnDemandCompLevel
HcDoStaticCompression HcPriority
HcDoOnDemandCompression HcScriptFileExtensions
HcDynamicCompressionLevel
Methods
IIsComputer
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use the IIsComputer object to set values of global metabase properties that determine how IIS
operates. The IIsComputer object also provides methods to manage metabase backups. You can use
these methods to store multiple backup versions in long-term storage, restore the metabase from a
backup version of your choice, and enumerate and delete backups.
ADsPath
IIS://MachineName
Syntax
varReturn = object.Method
Parts
varReturn
A variable that receives the return value from the method.
object
A variable that contains the IIsComputer object, usually as a result of a previous GetObject
operation.
Method
The object method chosen.
Can Contain
IIsFtpService IIsMimeMap
IIsLogModules IIsWebService
Properties
Metabase Properties
MaxBandwidth MimeMap
MaxBandwidthBlocked
Methods
See Also
Backup
You can use the Backup method of the IIsComputer object to back up the metabase to a location you
specify by providing a backup location name of up to 100 characters in length. Multiple metabase
Syntax
Parameters
BackupLocation
A string of up to 100 characters that specifies the backup location. The storage mechanism will be
determined by IIS. If an empty string is specified, the backup will be stored in the default location.
BackupVersion
Specifies the version number to be assigned to the backup. Must be less than or equal to
MD_BACKUP_MAX_VERSION. Can be set to one of the following values.
MD_BACKUP_HIGHEST_VERSION Overwrite the highest existing backup version
in the specified backup location.
MD_BACKUP_NEXT_VERSION Use the next backup version number available
in the specified backup location.
BackupFlags
One or more of the following flags.
MD_BACKUP_FORCE_BACKUP Force the backup even if the SaveData
operation specified by
MD_BACKUP_SAVE_FIRST fails.
MD_BACKUP_OVERWRITE Back up even if a backup of the same name
and version exists in the specified backup
location, overwriting if necessary.
MD_BACKUP_SAVE_FIRST Perform a SaveData operation before the
backup.
Remarks
IIS determines the backup storage mechanism, so the backup location name you provide does not
necessarily translate to a particular directory, file, or database storage mechanism. As implemented in this
release, metabase backups are stored as files in the system32\inetsrv\MetaBack directory.
Important The metabase backup and restore functionality exists for versioning purposes, not for cross-
machine replication. A metabase backup must be restored only to the same machine from which it was
originally created.
Code Example
<%
Dim ComputerObj, iFlags
Set ComputerObj = GetObject("IIS://LocalHost")
'Backup to next available version number.
'Set flags to save the metabase first and
See Also
DeleteBackup
You can use the DeleteBackup method of the IIsComputer object to delete a metabase backup from
a backup location.
Syntax
Parameters
BackupLocation
A string of up to 100 characters that specifies the backup location. If an empty string is specified,
the backup will be deleted from the default location.
BackupVersion
Specifies the version number of the backup to be deleted from the backup location, or can be the
following constant.
MD_BACKUP_HIGHEST_VERSION Delete the highest existing backup version in
the specified backup location.
Code Example
<%
Dim ComputerObj
Set ComputerObj = GetObject("IIS://LocalHost")
'Delete version 1 backup.
ComputerObj.DeleteBackup "MyBackups", 1
%>
See Also
EnumBackups
You can use the EnumBackups method of the IIsComputer object to enumerate metabase backups
stored in one or more backup locations, retrieving the location, version number, and date of each
backup.
Syntax
Parameters
BkupLocIn
A string of up to 100 characters that specifies the backup location. If an empty string is specified,
all backup locations will be searched.
IndexIn
Specifies the index of the backup to enumerate. Start the index at 0 and increment by 1 until
MD_ERROR_DATA_NOT_FOUND is returned.
BkupVerOut
Receives the version number of the backup enumerated.
BkupLocOut
Receives the backup location of the backup enumerated.
BkupDateTimeOut
Receives the date and time of the backup, in Universal Time Coordinate (UTC), formerly GMT
(Greenwich Mean Time).
Code Example
See Also
Restore
You can use the Restore method of the IIsComputer object to restore the metabase from a backup.
The restore operation stops all services dependent on IISADMIN, including all servers, until the restore
has completed, then restarts all services. Because of this, if you are restoring the metabase by using a
script in an ASP page, you must specify a machine name other than the one on which your script is
executing. You cannot use LocalHost as the machine name. You should be careful to plan for this service
interruption when restoring the metabase from a backup.
Syntax
Parameters
BackupLocation
A string of up to 100 characters that specifies the backup location. If an empty string is specified,
the backup will be retrieved from the default location.
BackupVersion
Specifies the version number of the backup to be restored from the backup location, or can be the
following constant.
MD_BACKUP_HIGHEST_VERSION Restore from the highest existing backup
version in the specified backup location.
BackupFlags
Reserved. Must be zero.
Code Example
<%
Dim ComputerObj, ComputerName
'Restore metabase on a different computer.
ComputerName = "MyOtherComputer"
'You can use LocalHost if running under Windows Script Host.
Set ComputerObj = GetObject("IIS://" & ComputerName)
'Restore the highest number version in MyBackups.
Remarks
You can use the Restore method with LocalHost in scripts running in a command window by using
Cscript.exe. For more information, see the Windows Script Host material in the Windows
documentation.
Important The metabase backup and restore functionality exists for versioning purposes, not for cross-
machine replication. A metabase backup must be restored only to the same machine from which it was
originally created.
See Also
IIsCustomLogModule
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use the IIsCustomLogModule object to configure custom logging information fields. For more
information about custom logging fields, see Setting Metabase Properties for Logging.
ADsPath
IIS://MachineName/Logging/CustomLogging
IIS://MachineName/Logging/CustomLogging/Field
IIS://MachineName/Logging/CustomLogging/FieldGroup
IIS://MachineName/Logging/CustomLogging/FieldGroup/Field
Syntax
varReturn = object.Method
Parts
varReturn
A variable that receives the return value from the method.
object
A variable that contains the IIsComputer object, usually as a result of a previous GetObject
operation.
Method
Properties
Metabase Properties
LogCustomPropertyDataType LogCustomPropertyMask
LogCustomPropertyHeader LogCustomPropertyName
LogCustomPropertyID LogCustomPropertyServicesString
Methods
IIsFilter
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use the IIsFilter object to set metabase properties that affect the operation of ISAPI filters.
You can set filter properties at the Web service level or for an individual Web server.
The IIsFilter object is an ADSI object, but not an ADSI container object.
ADsPath
IIS://MachineName/W3SVC/Filters/FilterName
or
IIS://MachineName/W3SVC/N/Filters/FilterName
where MachineName can be any name or "LocalHost," and N is the number of a Web server.
Syntax
varReturn = object.Method
Parts
varReturn
A variable that receives the return value from the method.
object
A variable that contains the IIsFilter object, usually as a result of a previous GetObject
operation.
Method
The object method chosen.
Properties
Metabase Properties
FilterDescription NotifyNonSecurePort
FilterEnabled NotifyOrderHigh
FilterFlags NotifyOrderLow
FilterPath NotifyOrderMedium
FilterState NotifyPreProcHeaders
NotifyAccessDenied NotifyReadRawData
NotifyAuthentication NotifySecurePort
NotifyEndOfNetSession NotifySendRawData
NotifyEndOfRequest NotifySendResponse
NotifyLog NotifyUrlMap
Methods
IIsFilters
This is preliminary documentation for IIS 5.0 and is subject to change.
The IIsFilters object is an ADSI container object that contains the collection of IIsFilter objects. You
can use the IIsFilters object to set the FilterLoadOrder property to specify the sequence in which
filters are to be loaded, and to enumerate through filters. You can use the IIsFilters object to manage
filters at the Web service level or at an individual Web server.
ADsPath
IIS://MachineName/W3SVC/Filters
or
IIS://MachineName/W3SVC/N/Filters
where MachineName can be any name or "LocalHost," and N is the number of a Web server.
Syntax
varReturn = object.Method
Parts
varReturn
A variable that receives the return value from the method.
object
A variable that contains the IIsFilters object, usually as a result of a previous GetObject
operation.
Method
The object method chosen.
Can Contain
IIsFilter
Properties
Metabase Properties
FilterLoadOrder
Methods
IIsFtpInfo
This is preliminary documentation for IIS 5.0 and is subject to change.
Some metabase properties associated with the FTP service are stored at the Info subkey of the
MSFTPSVC key. You can use the IIsFtpInfo object to set values for these properties.
The IIsFtpInfo object is an ADSI object, but not an ADSI container object.
ADsPath
IIS://MachineName/MSFTPSVC/Info
Syntax
varReturn = object.Method
Parts
varReturn
A variable that receives the return value from the method.
object
A variable that contains the IIsFtpInfo object, usually as a result of a previous GetObject
operation.
Method
The object method chosen.
Properties
Metabase Properties
LogModuleList
Methods
IIsFtpServer
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use the IIsFtpServer object to set metabase properties that apply to a specific FTP server and
to set inheritable metabase properties for FTP virtual directories. Specific methods are also available to
control server operation. FTP servers are identified in the metabase by their index numbers. The first
FTP server is number 1, the second is number 2, and so on.
The IIsFtpServer object is an ADSI container object. For more information on ADSI container
objects, see ADSI Features.
ADsPath
IIS://MachineName/MSFTPSVC/N
Syntax
varReturn = object.Method
Parts
varReturn
A variable that receives the return value from the method.
object
A variable that contains the IIsFtpServer object, usually as a result of a previous GetObject
operation.
Method
The object method chosen.
Can Contain
IIsFtpVirtualDir
Properties
Metabase Properties
A–I
AccessFlags ConnectionTimeout
AccessRead DefaultLogonDomain
AccessWrite DisableSocketPooling
AdminACL DontLog
AllowAnonymous ExitMessage
AnonymousOnly FtpDirBrowseShowLongDate
AnonymousPasswordSync GreetingMessage
AnonymousUserName IPSecurity
AnonymousUserPass
Log...
LogAnonymous LogExtFileTimeTaken
LogExtFileBytesRecv LogExtFileUriQuery
LogExtFileBytesSent LogExtFileUriStem
LogExtFileClientIp LogExtFileUserAgent
LogExtFileComputerName LogExtFileUserName
LogExtFileCookie LogExtFileWin32Status
LogExtFileDate LogFileDirectory
LogExtFileFlags LogFileLocaltimeRollover
LogExtFileHttpStatus LogFilePeriod
LogExtFileMethod LogFileTruncateSize
LogExtFileProtocolVersion LogNonAnonymous
LogExtFileReferer LogOdbcDataSource
LogExtFileServerIp LogOdbcPassword
LogExtFileServerPort LogOdbcTableName
LogExtFileSiteName LogOdbcUserName
LogExtFileTime LogPluginClsId
LogType
M–S
MaxClientsMessage ServerBindings
MaxConnections ServerComment
MaxEndpointConnections ServerListenBacklog
MSDOSDirOutput ServerListenTimeout
Realm ServerSize
ServerAutoStart ServerState
Methods
See Also
Continue
The Continue method of the IIsFtpServer object continues the server operation after it has been
paused.
Syntax
IIsFtpServer.Continue
Code Example
<%
Dim ServerObj
'Continue the second FTP server.
Set ServerObj = GetObject("IIS://LocalHost/MSFTPSVC/2")
ServerObj.Continue
%>
See Also
Pause
The Pause method of the IIsFtpServer object pauses the server operation.
Syntax
IIsFtpServer.Pause
Code Example
<%
Dim ServerObj
'Pause the second FTP server.
Set ServerObj = GetObject("IIS://LocalHost/MSFTPSVC/2")
ServerObj.Pause
%>
See Also
Start
The Start method of the IIsFtpServer object starts the server operation.
Syntax
IIsFtpServer.Start
Code Example
<%
Dim ServerObj
'Start the second FTP server.
Set ServerObj = GetObject("IIS://LocalHost/MSFTPSVC/2")
ServerObj.Start
%>
See Also
Status
The Status method of the IIsFtpServer object returns an integer that indicates the current status of the
server. The possible values are 1 (starting), 2 (started), 3 (stopping), 4 (stopped), 5 (pausing), 6
(paused), or 7 (continuing).
Syntax
IIsFtpServer.Status
See Also
Stop
The Stop method of the IIsFtpServer object stops the server operation.
Syntax
IIsFtpServer.Stop
Code Example
<%
Dim ServerObj
'Stop the second FTP server.
Set ServerObj = GetObject("IIS://LocalHost/MSFTPSVC/2")
ServerObj.Stop
%>
See Also
IIsFtpService
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use the IIsFtpService object to set the metabase property values that control FTP sites and
FTP virtual directories. The DownlevelAdminInstance property indicates the specific FTP server
instance to administer (for IIS 2.0 Internet Server Manager clients performing remote administration of
IIS 5.0).
ADsPath
IIS://MachineName/MSFTPSVC
Syntax
varReturn = object.Method
Parts
varReturn
A variable that receives the return value from the method.
object
A variable that contains the IIsFtpService object, usually as a result of a previous GetObject
operation.
Method
The object method chosen.
Can Contain
IIsFtpServer IIsFtpInfo
Properties
Metabase Properties
A–I
AccessFlags DefaultLogonDomain
AccessRead DirectoryLevelsToScan
AccessWrite DisableSocketPooling
AdminACL DontLog
AllowAnonymous DownlevelAdminInstance
AnonymousOnly ExitMessage
AnonymousPasswordSync FtpDirBrowseShowLongDate
AnonymousUserName GreetingMessage
AnonymousUserPass IPSecurity
ConnectionTimeout
Log...
LogAnonymous LogExtFileUriQuery
LogExtFileBytesRecv LogExtFileUriStem
LogExtFileBytesSent LogExtFileUserAgent
LogExtFileClientIp LogExtFileUserName
LogExtFileComputerName LogExtFileWin32Status
LogExtFileCookie LogFileDirectory
LogExtFileDate LogFileLocaltimeRollover
LogExtFileFlags LogFilePeriod
LogExtFileHttpStatus LogFileTruncateSize
LogExtFileMethod LogNonAnonymous
LogExtFileProtocolVersion LogOdbcDataSource
LogExtFileReferer LogOdbcPassword
LogExtFileServerIp LogOdbcTableName
LogExtFileServerPort LogOdbcUserName
LogExtFileSiteName LogPluginClsId
LogExtFileTime LogType
LogExtFileTimeTaken
M–S
MaxClientsMessage ServerBindings
MaxConnections ServerComment
MaxEndpointConnections ServerListenBacklog
MSDOSDirOutput ServerListenTimeout
Realm ServerSize
ServerAutoStart
Methods
IIsFtpVirtualDir
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use the IIsFtpVirtualDir object to set metabase properties that apply to one or all FTP virtual
directories for an FTP server. If you use this object at the server's root virtual directory (for example,
.../MSFTPSVC/2/ROOT), inheritable property values will apply to all FTP virtual subdirectories of the
root virtual directory of the second FTP server. You can set properties for a specific FTP virtual
directory by using the IIsFtpVirtualDir object for a specific virtual directory (for example,
.../MSFTPSVC/2/ROOT/AVDir).
ADsPath
IIS://MachineName/MSFTPSVC/N/ROOT
IIS://MachineName/MSFTPSVC/N/ROOT/vdirName
Syntax
varReturn = object.Method
Parts
varReturn
A variable that receives the return value from the method.
object
A variable that contains the IIsFtpVirtualDir object, usually as a result of a previous GetObject
operation.
Method
The object method chosen.
Can Contain
IIsFtpVirtualDir
Properties
Metabase Properties
AccessFlags IPSecurity
AccessRead Path
AccessWrite UNCPassword
DontLog UNCUserName
FtpDirBrowseShowLongDate
Methods
IIsIPSecurity
This is preliminary documentation for IIS 5.0 and is subject to change.
The IIsIPSecurity object is a custom ADSI object that you can use to set access permissions by IP
address and domain address.
If GrantByDefault is set to TRUE, then all IP addresses and Internet domains are granted access,
except those you specify to be denied. Use IPDeny and DomainDeny to deny access to specific IP
addresses and domains.
Note IPDeny and DomainDeny are only valid if GrantByDefault is set to TRUE.
If GrantByDefault is set to FALSE, then all IP addresses and domains are denied access by default,
except those you specify to be granted access. Use IPGrant and DomainGrant to grant access to
specific IPs and domains.
Note IPGrant and DomainGrant are only valid if GrantByDefault is set to FALSE.
ADsPath
IIS://MachineName/W3SVVC/N/ROOT
IIS://MachineName/W3SVC/N/ROOT/vdirName
Syntax
varReturn = object.Method
Parts
varReturn
Valid Locations
IIsIPSecurity Properties
Metabase Properties
IPDeny
You can use the IPDeny property of the IIsIPSecurity object to edit lists of IP addresses, held in an
array, that are not allowed access to the server.
Syntax
SecObj.IPDeny "IPAddress,SubnetMask"
Parameters
SecObj
An IIS Admin Object of type IIsIPSecurity.
IPAddress
This is a specific IP address you want to deny access to the server.
SubnetMask
Code Example
<%
Dim SecObj
Dim MyIPSec
Dim IPList, DomainList
Set SecObj = GetObject("IIS://LocalHost/W3SVC/1")
Set MyIPSec = SecObj.IPSecurity
'Test value of MyIPSec.GrantByDefault here.
DomainList = MyIPSec.DomainDeny
IPList = MyIPSec.IPDeny
Redim IPList (Ubound(IPList)+1)
IPList (Ubound(IPList)) = "123.0.0.1,255.255.255.0"
Redim DomainList (Ubound(DomainList)+1)
DomainList (Ubound(DomainList)) = "somedomain.com"
IPSec.DomainDeny = DomainList
IPSec.IPDeny = IPList
Set SecObj.IPSecurity = MyIPSec
DirOjb.Setinfo
%>
See Also
IPGrant
You can use the IPGrant property of the IIsIPSecurity object to edit lists of IP addresses, in an array,
that are not allowed access to the server.
Syntax
SecObj.IPGrant "IPAddress,SubnetMask"
Parameters
SecObj
An IIS Admin Object of type IIsIPSecurity.
IPAddress
This is a specific IP address you want to grant access to the server.
SubnetMask
Code Example
<%
Dim SecObj
Dim MyIPSec
Dim IPList, DomainList
Set SecObj = GetObject("IIS://LocalHost/W3SVC/1")
Set MyIPSec = SecObj.IPSecurity
'Test value of MyIPSec.GrantByDefault here.
DomainList = MyIPSec.DomainGrant
IPList = MyIPSec.IPGrant
Redim IPList (Ubound(IPList)+1)
IPList (Ubound(IPList)) = "123.0.0.1,255.255.255.0"
Redim DomainList (Ubound(DomainList)+1)
DomainList (Ubound(DomainList)) = "somedomain.com"
IPSec.DomainGrant = DomainList
IPSec.IPGrant = IPList
Set SecObj.IPSecurity = MyIPSec
Ojb.Setinfo
%>
See Also
DomainDeny
You can use the DomainDeny property of the IIsIPSecurity object to edit lists of domains that are not
allowed access to the server.
Syntax
SecObj.DomainDeny Domain
Parameters
SecObj
An IIS Admin Object of type IIsIPSecurity.
Domain
This is the domain you want denied access to the server.
Code Example
<%
Dim SecObj
Dim MyIPSec
Dim IPList, DomainList
Set SecObj = GetObject("IIS://LocalHost/W3SVC/1")
Set MyIPSec = SecObj.IPSecurity
'Test value of MyIPSec.GrantByDefault here.
DomainList = MyIPSec.DomainDeny
IPList = MyIPSec.IPDeny
Redim IPList (Ubound(IPList)+1)
IPList (Ubound(IPList)) = "123.0.0.1,255.255.255.0"
Redim DomainList (Ubound(DomainList)+1)
DomainList (Ubound(DomainList)) = "somedomain.com"
IPSec.DomainDeny = DomainList
IPSec.IPDeny = IPList
Set SecObj.IPSecurity = MyIPSec
Ojb.Setinfo
%>
See Also
DomainGrant
You can use the DomainGrant property of the IIsIPSecurity object to edit lists of domains that are
Syntax
SecObj.DomainGrant Domain
Parameters
SecObj
An IIS Admin Object of type IIsIPSecurity.
Domain
This is the domain you want granted access to the server.
Code Example
<%
Dim SecObj
Dim MyIPSec
Dim IPList, DomainList
Set SecObj = GetObject("IIS://LocalHost/W3SVC/1")
Set MyIPSec = SecObj.IPSecurity
'Test value of MyIPSec.GrantByDefault here.
DomainList = MyIPSec.DomainGrant
IPList = MyIPSec.IPGrant
Redim IPList (Ubound(IPList)+1)
IPList (Ubound(IPList)) = "123.0.0.1,255.255.255.0"
Redim DomainList (Ubound(DomainList)+1)
DomainList (Ubound(DomainList)) = "somedomain.com"
IPSec.DomainGrant = DomainList
IPSec.IPGrant = IPList
Set SecObj.IPSecurity = MyIPSec
Ojb.Setinfo
%>
See Also
GrantByDefault
You can use the GrantByDefault property of the IIsIPSecurity object to set how you would like to
specify server access. GrantByDefault is a Boolean property which determines whether the default
setting is grant all with exceptions or deny all with exceptions. If GrantByDefault is TRUE, then all IP
addresses and domains are granted access to the server (with the exception of the list entries of the
DomainDeny and IPDeny methods). If GrantByDefault is FALSE, then all IP addresses and
domains are denied access to the server (with the exception of the list entries of the DomainGrant and
IPGrant methods).
Syntax
SecObj.GrantByDefault Boolean
Parameters
SecObj
An IIS Admin Object of type IIsIPSecurity.
Boolean
This is a value of TRUE or FALSE.
Code Example
<%
Dim SecObj
Set SecObj = GetObject("IIS://LocalHost/W3SVC/1")
'Set permissions to grant access by default.
SecObj.GrantByDefault=TRUE
SecObj.SetInfo
%>
See Also
IIsLogModule
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use the IIsLogModule object to set metabase properties that affect the operation of logging
modules. You can set filter properties at the computer level (IIsComputer), at the FTP and Web
service level, or for an individual FTP or Web server.
The IIsLogModule object is an ADSI object, but not an ADSI container object.
ADsPath
IIS://MachineName/LOGGING/LogModuleName
where MachineName can be any name or "LocalHost," and LogModuleName is the name of a log
module.
Syntax
varReturn = object.Method
Parts
varReturn
A variable that receives the return value from the method.
object
A variable that contains the IIsLogModule object, usually as a result of a previous GetObject
operation.
Method
The object method chosen.
Properties
Metabase Properties
LogModuleId LogModuleUiId
Methods
IIsLogModules
This is preliminary documentation for IIS 5.0 and is subject to change.
The IIsLogModules object is an ADSI container object that contains the collection of IIsLogModule
objects. You can use the IIsLogModules object to manage log modules at the computer level
(IIsComputer).
ADsPath
IIS://MachineName/LOGGING
Syntax
varReturn = object.Method
Parts
varReturn
A variable that receives the return value from the method.
object
A variable that contains the IIsLogModules object, usually as a result of a previous GetObject
operation.
Method
The object method chosen.
Can Contain
IIsLogModule
Properties
Methods
Code Example
<%
'Get log properties for a log module at a server.
Dim LoggingModules, CurrentObj
'Get the object for the first Web server.
Set CurrentObj = GetObject("IIS://LocalHost/W3SVC/1")
'Access the log modules at the computer level.
Set LoggingModules = GetObject("IIS://LocalHost/logging")
'Loop through the installed modules to find the currently
'selected module at this server.
If CurrentObj.LogPluginClsid <> "" Then
For Each LogModule in LoggingModules
If LogModule.LogModuleID = CurrentObj.LogPluginClsid Then
Response.Write LogModule.Name & "<BR>"
End If
Next
'Display a property of the current module.
Response.Write CurrentObj.LogFileDate
End If
%>
IIsMimeMap
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use the IIsMimeMap object to set the inherited Multipurpose Internet Mail Extensions
(MIME) mappings used by the Web servers.
The IIsMimeMap object is an ADSI object, but not an ADSI container object.
ADsPath
IIS://MachineName/MIMEMAP
Syntax
varReturn = object.Method
Parts
varReturn
A variable that receives the return value from the method.
object
A variable that contains the IIsMimeMap object, usually as a result of a previous GetObject
operation.
Method
The object method chosen.
Properties
Metabase Properties
MimeMap
Methods
Code Example
<%
Dim MimeMapObj, aMimeMap, MMType, MMExtension, i, aMimeMapNew()
Const ADS_PROPERTY_UPDATE = 2
'Get the mimemap object.
Set MimeMapObj = GetObject("IIS://LocalHost/MimeMap")
'Get the mappings from the MimeMap property.
aMimeMap = MimeMapObj.GetEx("MimeMap")
' Display the mappings.
ShowMM(MimeMapObj)
' Add a new mapping.
i = UBound(aMimeMap) + 1
Redim Preserve aMimeMap(i)
Set aMimeMap(i) = CreateObject("MimeMap")
aMimeMap(i).Extension = ".jnq"
aMimeMap(i).MimeType = "junque/my-junque"
MimeMapObj.PutEx ADS_PROPERTY_UPDATE, "MimeMap", aMimeMap
MimeMapObj.SetInfo
' Display the mappings.
ShowMM(MimeMapObj)
'Delete a mapping by copying to a new map array.
i = 0
For Each MMItem in aMimeMap
IIsMimeType
This is preliminary documentation for IIS 5.0 and is subject to change.
The MimeMap property contains an array of IISMimeType objects. To add to the array, create a
new IISMimeType object, set its MimeType , create the Extension, add the element to the
MimeMap array, and set it in ADSI.
Syntax
varMimeMap = object.MimeMap
Parts
aMimeMap
A variable that receives the list of IIsMimeType objects.
object
A variable that supports the MimeType property, usually as a result of a previous GetObject
operation.
objMimeType
Can Contain
Properties
Metabase Properties
Object Properties
See Also
IIsMimeMap, MimeMap
MimeType
You can use the MimeType property of the IIsMimeType object to GET and PUT the MIME types
for objects of type IISMimeType .
Syntax
DirObj.MimeType =string
Parameters
DirObj
An IIS Admin Object of type IIsMimeType .
string
This is a string that specifies the MIME type for the object.
Code Example
<%
Dim DirObj
Dim MimeMapNode
Dim MimeMapList
Dim MimeMapEntry
Set Obj = GetObject("IIS://LH/MimeMap")
MimeMapList = DirObj.MimeMap
Redim preserve MimeMapList (Ubound(MimeMapList)+1)
Set MimeMapEntry = CreateObject ("IIsMimeTypeEntry")
MimeMapEntry.MimeType = "Text/Plain"
Mime.Extension = ".log"
Set MimeMapList (Ubound(MimeMapList)) = MimeMapEntry
DirObj.MimeMap = MimeMapList
DirObj.Setinfo
%>
See Also
IIsMimeType , Extension
Extension
Use the Extension property of the IIsMimeType object to specify the MIME type of the file name
extension.
Syntax
DirObj.Extension = String
Parameters
DirObj
An IIS Admin Object of type IIsMimeType .
String
This is the specific file name extension associated with the MIME type specified in the
MimeType property.
Code Example
<%
Dim DirObj
Dim MimeMapNode
Dim MimeMapList
Dim MimeMapEntry
Set Obj = GetObject("IIS://LH/MimeMap")
MimeMapList = DirObj.MimeMap
Redim preserve MimeMapList (Ubound(MimeMapList)+1)
Set MimeMapEntry = CreateObject ("IIsMimeTyepEntry")
MimeMapEntry.MimeMap = "Text/Plain"
Mime.Extension = ".log"
Set MimeMapList (Ubound(MimeMapList)) = MimeMapEntry
DirObj.MimeMap = MimeMapList
DirObj.Setinfo
%>
See Also
MimeType , IIsMimeType
IIsWebDirectory
This is preliminary documentation for IIS 5.0 and is subject to change.
The IIsWebDirectory object is used to set metabase properties that apply to one or more Web
directories for a Web server. When you use the IIsWebDirectory object to set metabase properties for
a Web directory, inheritable properties will apply to all subdirectories and files.
You can also use IIsWebDirectory methods to create and manage Web applications in Web
directories and subdirectories. Applications can also be defined and managed in virtual directories by
using IIsWebVirtualDir.
ADsPath
IIS://MachineName/W3SVC/N/ROOT/vdirName/DirName
Syntax
varReturn = object.Method
Parts
varReturn
A variable that receives the return value from the method.
object
A variable that contains the IIsWebDirectory object, usually as a result of a previous GetObject
operation.
Method
The object method chosen.
Can Contain
IIsWebDirectory IIsWebFile
Properties
Metabase Properties
A – Asp...
AccessExecute AspBufferingOn
AccessFlags AspCodepage
AccessNoRemoteExecute AspEnableApplicationRestart
AccessNoRemoteRead AspEnableAspHtmlFallback
AccessNoRemoteScript AspEnableChunkedEncoding
AccessNoRemoteWrite AspEnableParentPaths
AccessRead AspEnableTypelibCache
AccessScript AspErrorsToNTLog
AccessSSL AspExceptionCatchEnable
AccessSSL128 AspLogErrorRequests
AccessSSLFlags AspProcessorThreadMax
AccessSSLMapCert AspQueueConnectionTestTime
AccessSSLNegotiateCert AspQueueTimeout
AccessSSLRequireCert AspRequestQueueMax
AccessWrite AspScriptEngineCacheMax
AnonymousPasswordSync AspScriptErrorMessage
AnonymousUserName AspScriptErrorSentToBrowser
AnonymousUserPass AspScriptFileCacheSize
AppAllowClientDebug AspScriptLanguage
AppAllowDebugging AspScriptTimeout
AppFriendlyName AspSessionMax
AppIsolated AspSessionTimeout
AppOopRecoverLimit AspThreadGateEnabled
AppPackageID AspThreadGateLoadHigh
AppPackageName AspThreadGateLoadLow
AppRoot AspThreadGateSleepDelay
AppWamClsID AspThreadGateSleepMax
AspAllowOutOfProcComponents AspThreadGateTimeSlice
AspAllowSessionState AspTrackThreadingModel
Auth... – U
AuthAnonymous DirBrowseShowSize
AuthBasic DirBrowseShowTime
AuthFlags DontLog
AuthNTLM EnableDefaultDoc
AuthPersistence EnableDirBrowsing
AuthPersistSingleRequest EnableDocFooter
AuthPersistSingleRequestIfProxy EnableReverseDns
AuthPersistSingleRequestAlwaysIfProxy HttpCustomHeaders
CacheControlCustom HttpErrors
CacheControlMaxAge HttpExpires
CacheControlNoCache HttpPics
CacheISAPI HttpRedirect
ContentIndexed IPSecurity
CpuAppEnabled LogonMethod
CpuCgiEnabled MimeMap
CreateCGIWithNewConsole PoolIDCTimeout
CreateProcessAsUser PutReadSize
DefaultDoc Realm
DefaultDocFooter RedirectHeaders
DefaultLogonDomain ScriptMaps
DirBrowseFlags SSIExecDisable
DirBrowseShowDate UNCAuthenticationPassthrough
DirBrowseShowExtension UploadReadAheadSize
DirBrowseShowLongDate
Methods
See Also
Remarks
Web directories can be nested, and are addressed with the path to the directory, including the directory
name (for example .../vdirName/Dir1/Dir1a/Dir1ab, and so on).
AppCreate
You can use the AppCreate method of the IIsWebDirectory or IIsWebVirtualDir object to create a
Web application definition and mark it as running in-process or out-of-process. If an application already
exists at the specified path, you can use this method to reconfigure the application from in-process to
out-of-process, or the reverse.
Syntax
DirObj.AppCreate InProcFlag
Parameters
DirObj
An IIS Admin Object of type IIsWebDirectory or IIsWebVirtualDir.
InProcFlag
Specifies whether the application being created is to run in-process (TRUE) or out-of-process
(FALSE). If the application already exists and is running in-process, specifying this flag as FALSE
will cause the application definition to be deleted and a new application created to run out-of-
process. If the application already exists and is running out-of-process, specifying this flag as
TRUE will cause the application definition to be deleted and a new application created to run in-
process. If the application exists, and the setting of InProcFlag matches the application's existing
in-process or out-of-process status, then this method will cause no change to the application
definition.
Code Example
<%
Dim DirObj
Const INPROC = True
Const OUTPROC = False
Set DirObj = GetObject("IIS://LocalHost/W3SVC/1/ROOT/MyAppDir")
'Create an application in-process.
DirObj.AppCreate INPROC
%>
See Also
AppCreate2
You can use the AppCreate2 method of the IIsWebDirectory or IIsWebVirtualDir object to create
a Web application definition and mark it as running in-process, out-of-process, or in a process pool. If
an application already exists at the specified path, you can use this method to reconfigure the application
to run in whatever process space you want.
Syntax
DirObj.AppCreate InProcFlag
Parameters
DirObj
An IIS Admin Object of type IIsWebDirectory or IIsWebVirtualDir.
InProcFlag
Binary value that specifies whether the application being created is to run in-process (0), out-of-
process (1), or in a pooled process (2). If the application already exists and is running , changing
the value of this flag will cause the application definition to be deleted and a new application
created to run in the specified process space.
Code Example
<%
Dim DirObj
Const INPROC = 0
Const OUTPROC = 1
Const POOLED = 2
Set DirObj = GetObject("IIS://LocalHost/W3SVC/1/ROOT/MyAppDir")
'Create an application in-process.
DirObj.AppCreate INPROC
%>
See Also
AppDelete
You can use the AppDelete method of the IIsWebDirectory or IIsWebVirtualDir object to delete a
Web application definition from a metabase key. If the application is running, it will be shut down. If the
application is in-process with IIS, all resources associated with the application, such as out-of-process
applications, will be released if the resource is not referenced by another in-process application.
Note Server component DLLs are not released from in-process applications, even if they are not
currently referenced by other applications.
Syntax
DirObj.AppDelete
Parameters
DirObj
An IIS Admin object of type IIsWebDirectory or IIsWebVirtualDir.
Code Example
<%
Dim DirObj
Set DirObj = GetObject("IIS://LocalHost/W3SVC/1/ROOT/MyAppDir")
'Delete the application at this directory.
DirObj.AppDelete
%>
See Also
AppDeleteRecursive
You can use the AppDeleteRecursive method of the IIsWebDirectory or IIsWebVirtualDir object
to delete Web application definitions from a metabase key and all subkeys. If the applications are
running, they will be shut down. If the application is in-process with IIS, all resources associated with the
application, such as out-of-process packages, will be released if the resource is not referenced by
another in-process application.
Note Server component DLLs are not released from in-process applications, even if they aren't
currently referenced by other applications.
Syntax
DirObj.AppDeleteRecursive
Parameters
DirObj
An IIS Admin object of type IIsWebDirectory or IIsWebVirtualDir.
Code Example
<%
Dim DirObj
Set DirObj = GetObject("IIS://LocalHost/W3SVC/1/ROOT/MyAppDir")
'Delete the application at this directory
'and all subdirectories.
DirObj.AppDeleteRecursive
%>
See Also
AppDisable
You can use the AppDisable method of the IIsWebDirectory or IIsWebVirtualDir object to disable
a Web application that is running out-of-process. All of the application's resources are released and the
application's process is terminated. Attempts to access this application will fail. You can use the
AppEnable method to re-enable a disabled application. Both methods are used primarily when moving,
copying, or renaming metabase keys. The AppDisable method has no effect if the application is running
in-process.
Syntax
DirObj.AppDisable
Parameters
DirObj
An IIS Admin object of type IIsWebDirectory or IIsWebVirtualDir.
Code Example
<%
Dim DirObj
Set DirObj = GetObject("IIS://LocalHost/W3SVC/1/ROOT/MyAppDir")
'Disable the application at this directory.
DirObj.AppDisable
%>
See Also
AppDisableRecursive
and at all subordinate keys will be disabled. All of the application resources are released and the
application processes are terminated. Attempts to access this application will fail. You can use the
AppEnableRecursive method to re-enable disabled applications. Both methods are used primarily
when moving, copying, or renaming metabase keys. The AppDisableRecursive method has no effect if
the applications are running in-process.
Syntax
DirObj.AppDisableRecursive
Parameters
DirObj
An IIS Admin Object of type IIsWebDirectory or IIsWebVirtualDir.
Code Example
<%
Dim DirObj
Set DirObj = GetObject("IIS://LocalHost/W3SVC/1/ROOT/MyAppDir")
'Disable the application at this directory
'and at all subdirectories.
DirObj.AppDisableRecursive
%>
See Also
AppEnable
You can use the AppEnable method of the IIsWebDirectory or IIsWebVirtualDir object to reinstate
a Web application definition that was previously disabled with the AppDisable method. If the
application specified was not previously deleted, it will be reregistered with Component Services.
Syntax
DirObj.AppEnable
Parameters
DirObj
An IIS Admin Object of type IIsWebDirectory or IIsWebVirtualDir.
Code Example
<%
Dim DirObj
Set DirObj = GetObject("IIS://LocalHost/W3SVC/1/ROOT/MyAppDir")
'Enable the application at this directory.
DirObj.AppEnable
%>
See Also
AppEnableRecursive
You can use the AppEnableRecursive method of the IIsWebDirectory or IIsWebVirtualDir object
to reinstate Web application definitions that were previously disabled with the AppDisableRecursive
method. If the applications specified were not previously deleted, they will be reregistered with
Component Services.
Syntax
DirObj.AppEnableRecursive
Parameters
DirObj
An IIS Admin Object of type IIsWebDirectory or IIsWebVirtualDir.
Code Example
<%
Dim DirObj
Set DirObj = GetObject("IIS://LocalHost/W3SVC/1/ROOT/MyAppDir")
'Enable the application at this directory
'and at all subdirectories.
DirObj.AppEnableRecursive
%>
See Also
AppGetStatus
You can use the AppGetStatus method of the IIsWebDirectory or IIsWebVirtualDir object to
retrieve the current status of a Web application.
Syntax
vReturn = DirObj.AppGetStatus
Parameters
vReturn
Receives the status of the application.
DirObj
An IIS Admin Object of type IIsWebDirectory or IIsWebVirtualDir.
Return Values
Code Example
<%
Dim DirObj, vStatus
Set DirObj = GetObject("IIS://LocalHost/W3SVC/1/ROOT/MyAppDir")
'Get the status of the application.
vReturn = DirObj.AppGetStatus
%>
See Also
AppUnload
You can use the AppUnload method of the IIsWebDirectory or IIsWebVirtualDir object to unload
a Web application that is running out-of-process. All of the application's resources are released and the
application's process is terminated. If the application is running in-process, the application is released if it
is not being referenced by any other applications.
Note Server component DLLs are not released from in-process applications, even if they aren't
Syntax
DirObj.AppUnload
Parameters
DirObj
An IIS Admin Object of type IIsWebDirectory or IIsWebVirtualDir.
Code Example
<%
Dim DirObj
Set DirObj = GetObject("IIS://LocalHost/W3SVC/1/ROOT/MyAppDir")
'Unload the application at this directory.
DirObj.AppUnload
%>
See Also
AppUnloadRecursive
You can use the AppUnloadRecursive method of the IIsWebDirectory or IIsWebVirtualDir object
to unload Web applications that are running out-of-process. The applications at the specified key and at
all subordinate keys will be unloaded. All of the application resources are released and the application
processes are terminated. If the application is running in-process, the application is released if it is not
being referenced by any other applications.
Note Server component DLLs are not released from in-process applications, even if they aren't
currently referenced by other applications.
Syntax
DirObj.AppUnloadRecursive
Parameters
DirObj
An IIS Admin Object of type IIsWebDirectory or IIsWebVirtualDir.
Code Example
<%
Dim DirObj
Set DirObj = GetObject("IIS://LocalHost/W3SVC/1/ROOT/MyAppDir")
'Unload the application at this directory
'and all subordinate directories.
DirObj.AppUnloadRecursive
%>
See Also
AspAppRestart
You can use the AspAppRestart method of the IIsWebDirectory or IIsWebVirtualDir object to
restart ASP applications. Users can use this method to restart ASP applications without accessing the
Global.asa file or stopping and starting the Web service itself. Essentially, a user can restart the
application on demand.
Syntax
DirObj.AspAppRestart()
Parameters
DirObj
An ASP application object of type IIsWebDirectory or IIsWebVirtualDir.
See Also
IIsWebFile
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use the IIsWebFile object to set metabase key values that apply to a file in a Web directory
for a Web virtual server. Metabase property values set for a specific file will override inherited values
that have been set at a higher level in the metabase hierarchy.
The IIsWebFile object is an ADSI object, but not an ADSI container object.
ADsPath
IIS://MachineName/W3SVC/n/Root/vdirName/DirName/FileName
Syntax
varReturn = object.Method
Parts
varReturn
A variable that receives the return value from the method.
object
A variable that contains the IIsWebFile object, usually as a result of a previous GetObject
operation.
Method
The object method chosen.
Properties
Metabase Properties
AccessExecute CacheControlMaxAge
AccessFlags CacheControlNoCache
AccessNoRemoteExecute CpuAppEnabled
AccessNoRemoteRead CpuCgiEnabled
AccessNoRemoteScript CreateCGIWithNewConsole
AccessNoRemoteWrite CreateProcessAsUser
AccessRead DefaultDocFooter
AccessSource DefaultLogonDomain
AccessScript DontLog
AccessSSL EnableDocFooter
AccessSSL128 EnableReverseDns
AccessSSLFlags HttpCustomHeaders
AccessSSLMapCert HttpErrors
AccessSSLNegotiateCert HttpExpires
AccessSSLRequireCert HttpPics
AccessWrite HttpRedirect
AnonymousPasswordSync IPSecurity
AnonymousUserName LogonMethod
AnonymousUserPass MimeMap
AuthAnonymous PoolIDCTimeout
AuthBasic PutReadSize
AuthFlags Realm
AuthNTLM RedirectHeaders
AuthPersistence ScriptMaps
AuthPersistSingleRequest SSIExecDisable
AuthPersistSingleRequestIfProxy UNCAuthenticationPassthrough
AuthPersistSingleRequestAlwaysIfProxy UploadReadAheadSize
CacheControlCustom
Methods
IIsWebInfo
This is preliminary documentation for IIS 5.0 and is subject to change.
Some metabase properties associated with the Web service are stored at the Info subkey of the
W3SVC key. You can use the IIsWebInfo object to set values for these properties.
The IIsWebInfo object is an ADSI object, but not an ADSI container object.
ADsPath
IIS://MachineName/W3SVC/INFO
Syntax
varReturn = object.Method
Parts
varReturn
A variable that receives the return value from the method.
object
A variable that contains the IIsWebInfo object, usually as a result of a previous GetObject
operation.
Method
The object method chosen.
Properties
Metabase Properties
AdminServer ServerConfigFlags
CustomErrorDescriptions ServerConfigSSL128
LogModuleList ServerConfigSSL40
ServerConfigAutoPWSync ServerConfigSSLAllowEncrypt
Methods
IIsWebServer
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use the IIsWebServer object to set metabase properties that apply to a specific Web virtual
server, and to set inheritable metabase properties for virtual directories, Web directories, and Web files.
Specific methods are also available to control server operation. Web virtual servers are identified in the
metabase by their index numbers. The first Web server is number 1, the second is number 2, and so on.
ADsPath
IIS://MachineName/W3SVC/N
Syntax
varReturn = objWebServer.Method
Parts
varReturn
Specifies result value.
ObjWebServer
Refers to the IIS Admin Object.
Method
Specifies the method called.
Can Contain
IIsCertMapper IIsWebVirtualDir
IIsFilters
Properties
Metabase Properties
A – Asp...
AccessExecute AspAllowOutOfProcComponents
AccessFlags AspAllowSessionState
AccessNoRemoteExecute AspBufferingOn
AccessNoRemoteRead AspCodepage
AccessNoRemoteScript AspEnableApplicationRestart
AccessNoRemoteWrite AspEnableAspHtmlFallback
AccessRead AspEnableChunkedEncoding
AccessSource AspEnableParentPaths
AccessScript AspEnableTypelibCache
AccessSSL AspErrorsToNTLog
AccessSSL128 AspExceptionCatchEnable
AccessSSLFlags AspLogErrorRequests
AccessSSLMapCert AspProcessorThreadMax
AccessSSLNegotiateCert AspQueueConnectionTestTime
AccessSSLRequireCert AspQueueTimeout
AccessWrite AspRequestQueueMax
AdminACL AspScriptEngineCacheMax
AllowKeepAlive AspScriptErrorSentToBrowser
AllowPathInfoForScriptMappings AspScriptFileCacheSize
AnonymousPasswordSync AspScriptLanguage
AnonymousUserName AspSessionMax
AnonymousUserPass AspScriptTimeout
AppAllowClientDebug AspSessionTimeout
AppAllowDebugging AspThreadGateEnabled
AppFriendlyName AspThreadGateLoadHigh
AppIsolated AspThreadGateLoadLow
AppOopRecoverLimit AspThreadGateSleepDelay
AppPackageID AspThreadGateSleepMax
AppPackageName AspThreadGateTimeSlice
AppRoot AspTrackThreadingModel
AppWamClsID
Auth... – I
AuthAnonymous CpuLimitProcStop
AuthBasic CpuLimitsEnabled
AuthFlags CpuLoggingInterval
AuthNTLM CpuLoggingMask
AuthPersistence CpuLoggingOptions
AuthPersistSingleRequest CpuResetInterval
AuthPersistSingleRequestIfProxy CreateCGIWithNewConsole
AuthPersistSingleRequestAlwaysIfProxy CreateProcessAsUser
CacheControlCustom DefaultDoc
CacheControlMaxAge DefaultDocFooter
CacheControlNoCache DefaultLogonDomain
CacheISAPI DirBrowseFlags
CGITimeout DirBrowseShowDate
ConnectionTimeout DirBrowseShowExtension
CpuAppEnabled DirBrowseShowLongDate
CpuCgiEnabled DirBrowseShowSize
CpuEnableActiveProcs DirBrowseShowTime
CpuEnableAllProcLogging DisableSocketPooling
CpuEnableAppLogging DontLog
CpuEnableCgiLogging EnableDefaultDoc
CpuEnableEvent EnableDirBrowsing
CpuEnableKernelTime EnableDocFooter
CpuEnableLogging EnableReverseDns
CpuEnablePageFaults FrontPageWeb
CpuEnableProcType HttpCustomHeaders
CpuEnableTerminatedProcs HttpErrors
CpuEnableTotalProcs HttpExpires
CpuEnableUserTime HttpPics
CpuLimitLogEvent HttpRedirect
CpuLimitPause IPSecurity
CpuLimitPriority
Log...
LogExtFileBytesRecv LogExtFileUriQuery
LogExtFileBytesSent LogExtFileUriStem
LogExtFileClientIp LogExtFileUserAgent
LogExtFileComputerName LogExtFileUserName
LogExtFileCookie LogExtFileWin32Status
LogExtFileDate LogFileDirectory
LogExtFileFlags LogFileLocaltimeRollover
LogExtFileHttpStatus LogFilePeriod
LogExtFileMethod LogFileTruncateSize
LogExtFileProtocolVersion LogOdbcDataSource
LogExtFileReferer LogOdbcPassword
LogExtFileServerIp LogOdbcTableName
LogExtFileServerPort LogOdbcUserName
LogExtFileSiteName LogonMethod
LogExtFileTime LogPluginClsId
LogExtFileTimeTaken LogType
M–U
MaxBandwidth RedirectHeaders
MaxBandwidthBlocked ScriptMaps
MaxConnections SecureBindings
MaxEndpointConnections ServerAutoStart
MimeMap ServerBindings
NetLogonWorkstation ServerComment
NotDeletable ServerListenBacklog
NTAuthenticationProviders ServerListenTimeout
PasswordCacheTTL ServerSize
PasswordChangeFlags ServerState
PasswordExpirePrenotifyDays SSIExecDisable
PoolIDCTimeout UNCAuthenticationPassthrough
ProcessNTCRIfLoggedOn UploadReadAheadSize
PutReadSize UseHostName
Realm
Methods
See Also
Continue
The Continue method of the IIsWebServer object continues the server operation after it has been
paused.
Syntax
IIsWebServer.Continue
Code Example
<%
Dim ServerObj
'Continue the second Web server.
Set ServerObj = GetObject("IIS://LocalHost/W3SVC/2")
ServerObj.Continue
%>
See Also
Pause
The Pause method of the IIsWebServer object pauses the server operation.
Syntax
IIsWebServer.Pause
Code Example
<%
Dim ServerObj
'Pause the second Web server.
Set ServerObj = GetObject("IIS://LocalHost/W3SVC/2"
ServerObj.Pause
%>
See Also
Start
The Start method of the IIsWebServer object starts the server operation.
Syntax
IIsWebServer.Start
Code Example
<%
Dim ServerObj
'Start the second Web server.
Set ServerObj = GetObject("IIS://LocalHost/W3SVC/2"
ServerObj.Start
%>
See Also
Status
The Status method of the IIsWebServer object returns an integer that indicates the current status of the
server. The possible values are 1 (starting), 2 (started), 3 (stopping), 4 (stopped), 5 (pausing), 6
(paused), or 7 (continuing).
Syntax
IIsWebServer.Status
See Also
Stop
The Stop method of the IIsWebServer object stops the server operation.
Syntax
IIsWebServer.Stop
Code Example
<%
Dim ServerObj
'Stop the second Web server.
Set ServerObj = GetObject("IIS://LocalHost/W3SVC/2"
ServerObj.Stop
%>
See Also
IIsWebService
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use the IIsWebService object to set inheritable metabase properties for Web sites and Web
virtual directories. The DownlevelAdminInstance property indicates the specific Web server instance
to administer (for IIS 2.0 Internet Server Manager clients performing remote administration of IIS 5.0).
The IIsWebService object is an ADSI container object. For more information, see ADSI Features.
ADsPath
IIS://MachineName/W3SVC
Syntax
varReturn = object.Method
Parts
varReturn
A variable that receives the return value from the method.
object
A variable that contains the IIsWebServer object, usually as a result of a previous GetObject
operation.
Method
The object method chosen.
Can Contain
IIsFilters IIsWebServer
IIsWebInfo
Properties
Metabase Properties
A – Asp...
AccessExecute AspAllowSessionState
AccessFlags AspBufferingOn
AccessNoRemoteExecute AspCodepage
AccessNoRemoteRead AspEnableApplicationRestart
AccessNoRemoteScript AspEnableAspHtmlFallback
AccessNoRemoteWrite AspEnableChunkedEncoding
AccessRead AspEnableParentPaths
AccessSource AspEnableTypelibCache
AccessScript AspErrorsToNTLog
AccessSSL AspExceptionCatchEnable
AccessSSL128 AspLogErrorRequests
AccessSSLFlags AspProcessorThreadMax
AccessSSLMapCert AspQueueConnectionTestTime
AccessSSLNegotiateCert AspQueueTimeout
AccessSSLRequireCert AspRequestQueueMax
AccessWrite AspScriptEngineCacheMax
AdminACL AspScriptErrorMessage
AllowPathInfoForScriptMappings AspScriptErrorSentToBrowser
AnonymousPasswordSync AspScriptFileCacheSize
AnonymousUserName AspScriptLanguage
AnonymousUserPass AspSessionMax
AppAllowClientDebug AspScriptTimeout
AppAllowDebugging AspSessionTimeout
AppFriendlyName AspThreadGateEnabled
AppIsolated AspThreadGateLoadHigh
AppPackageID AspThreadGateLoadLow
AppPackageName AspThreadGateSleepDelay
AppRoot AspThreadGateSleepMax
AppWamClsID AspThreadGateTimeSlice
AspAllowOutOfProcComponents AspTrackThreadingModel
Auth... – I
AuthAnonymous CpuLimitsEnabled
AuthBasic CpuLoggingInterval
AuthFlags CpuLoggingMask
AuthNTLM CpuLoggingOptions
AuthPersistence CpuResetInterval
AuthPersistSingleRequest CreateCGIWithNewConsole
AuthPersistSingleRequestIfProxy CreateProcessAsUser
AuthPersistSingleRequestAlwaysIfProxy DefaultDoc
CacheControlCustom DefaultDocFooter
CacheControlMaxAge DefaultLogonDomain
CacheControlNoCache DirBrowseFlags
CacheISAPI DirBrowseShowDate
ContentIndexed DirBrowseShowExtension
ConnectionTimeout DirBrowseShowLongDate
CpuAppEnabled DirBrowseShowSize
CpuCgiEnabled DirBrowseShowTime
CpuEnableActiveProcs DirectoryLevelsToScan
CpuEnableAllProcLogging DisableSocketPooling
CpuEnableAppLogging DontLog
CpuEnableCgiLogging DownlevelAdminInstance
CpuEnableEvent EnableDefaultDoc
CpuEnableKernelTime EnableDirBrowsing
CpuEnableLogging EnableDocFooter
CpuEnablePageFaults EnableReverseDns
CpuEnableProcType HttpCustomHeaders
CpuEnableTerminatedProcs HttpErrors
CpuEnableTotalProcs HttpExpires
CpuEnableUserTime HttpPics
CpuLimitLogEvent HttpRedirect
CpuLimitPause InProcessIsapiApps
CpuLimitPriority IPSecurity
CpuLimitProcStop
Log...
LogExtFileBytesRecv LogExtFileUriQuery
LogExtFileBytesSent LogExtFileUriStem
LogExtFileClientIp LogExtFileUserAgent
LogExtFileComputerName LogExtFileUserName
LogExtFileCookie LogExtFileWin32Status
LogExtFileDate LogFileDirectory
LogExtFileFlags LogFileLocaltimeRollover
LogExtFileHttpStatus LogFilePeriod
LogExtFileMethod LogFileTruncateSize
LogExtFileProtocolVersion LogOdbcDataSource
LogExtFileReferer LogOdbcPassword
LogExtFileServerIp LogOdbcTableName
LogExtFileServerPort LogOdbcUserName
LogExtFileSiteName LogonMethod
LogExtFileTime LogPluginClsId
LogExtFileTimeTaken LogType
M–U
MaxConnections ScriptMaps
MaxEndpointConnections ServerAutoStart
MimeMap ServerBindings
NetLogonWorkstation ServerComment
NTAuthenticationProviders ServerListenBacklog
PasswordCacheTTL ServerListenTimeout
PasswordChangeFlags ServerSize
PasswordExpirePrenotifyDays SSIExecDisable
PoolIDCTimeout SSLUseDSMapper
ProcessNTCRIfLoggedOn UNCAuthenticationPassthrough
PutReadSize UploadReadAheadSize
Realm UseHostName
RedirectHeaders WAMUserName
WAMUserPass
Methods
IIsWebVirtualDir
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use the IIsWebVirtualDir object to set metabase properties that apply to one or all virtual
directories for a Web site. If you use the IIsWebVirtualDir object at the server's ROOT directory
(.../W3SVC/2/ROOT), inheritable property values will apply to all virtual subdirectories. You can set
properties for a specific virtual directory by using the IIsWebVirtualDir object for a specific virtual
directory (.../W3SVC/2/ROOT/AVdir).
You can also use IIsWebVirtualDir methods to create and manage Web applications in Web virtual
directories and virtual subdirectories. Applications can also be defined and managed in Web directories.
See IIsWebDirectory.
ADsPath
IIS://MachineName/W3SVC/N/ROOT
IIS://MachineName/W3SVC/N/ROOT/vdirName
Syntax
varReturn = object.Method
Parts
varReturn
A variable that receives the return value from the method.
object
A variable that contains the IIsWebVirtualDir object, usually as a result of a previous
GetObject operation.
Method
The object method chosen.
Can Contain
IIsWebVirtualDir IIsWebFile
IIsWebDirectory
Properties
Metabase Properties
A – Asp...
AccessExecute AspBufferingOn
AccessFlags AspCodepage
AccessNoRemoteExecute AspEnableApplicationRestart
AccessNoRemoteRead AspEnableAspHtmlFallback
AccessNoRemoteScript AspEnableChunkedEncoding
AccessNoRemoteWrite AspEnableParentPaths
AccessRead AspEnableTypelibCache
AccessSource AspErrorsToNTLog
AccessScript AspExceptionCatchEnable
AccessSSL AspLogErrorRequests
AccessSSL128 AspProcessorThreadMax
AccessSSLFlags AspQueueConnectionTestTime
AccessSSLMapCert AspQueueTimeout
AccessSSLNegotiateCert AspRequestQueueMax
AccessSSLRequireCert AspScriptEngineCacheMax
AccessWrite AspScriptErrorMessage
AnonymousPasswordSync AspScriptErrorSentToBrowser
AnonymousUserName AspScriptFileCacheSize
AnonymousUserPass AspScriptLanguage
AppAllowClientDebug AspScriptTimeout
AppAllowDebugging AspSessionMax
AppFriendlyName AspSessionTimeout
AppIsolated AspThreadGateEnabled
AppOopRecoverLimit AspThreadGateLoadHigh
AppPackageID AspThreadGateLoadLow
AppPackageName AspThreadGateSleepDelay
AppRoot AspThreadGateSleepMax
AppWamClsID AspThreadGateTimeSlice
AspAllowOutOfProcComponents AspTrackThreadingModel
AspAllowSessionState
Auth... – U
AuthAnonymous DirBrowseShowTime
AuthBasic DontLog
AuthFlags EnableDefaultDoc
AuthNTLM EnableDirBrowsing
AuthPersistence EnableDocFooter
AuthPersistSingleRequest EnableReverseDns
AuthPersistSingleRequestIfProxy HttpCustomHeaders
AuthPersistSingleRequestAlwaysIfProxy HttpErrors
CacheControlCustom HttpExpires
CacheControlMaxAge HttpPics
CacheControlNoCache HttpRedirect
CacheISAPI IPSecurity
ContentIndexed LogonMethod
CpuAppEnabled MimeMap
CpuCgiEnabled Path
CreateCGIWithNewConsole PoolIDCTimeout
CreateProcessAsUser PutReadSize
DefaultDoc Realm
DefaultDocFooter RedirectHeaders
DefaultLogonDomain ScriptMaps
DirBrowseFlags SSIExecDisable
DirBrowseShowDate UNCAuthenticationPassthrough
DirBrowseShowExtension UNCPassword
DirBrowseShowLongDate UNCUserName
DirBrowseShowSize UploadReadAheadSize
Methods
See Also
Constants
This is preliminary documentation for IIS 5.0 and is subject to change.
The following constants are used with methods and properties of the IIS Admin Objects.
<%
Const ADS_PROPERTY_CLEAR = 1 'PutEx
Const ADS_PROPERTY_UPDATE = 2 'PutEx
Const APPSTATUS_NOTDEFINED = 4 'AppStatus
Const APPSTATUS_RUNNING = 2 'AppStatus
Const APPSTATUS_STOPPED = 3 'AppStatus
Const APPSTATUS_UNLOADED = 1 'AppStatus
Const IIS_ANY_PROPERTY = 0 'GetDataPaths
Const IIS_INHERITABLE_ONLY = 1 'GetDataPaths
Const MD_ERROR_DATA_NOT_FOUND = &H800CC801 'GetDataPaths
Const MD_ERROR_IISAO_INVALID_SCHEMA = &H8800CC810 'GetObject
Const MD_BACKUP_FORCE_BACKUP = 4 'Backup
Const MD_BACKUP_HIGHEST_VERSION = &HFFFFFFFE 'Backup, Delete, Restore
Const MD_BACKUP_MAX_VERSION = 9999 'Limit
Const MD_BACKUP_MAX_LEN = 100 'Limit
Const MD_BACKUP_NEXT_VERSION = &HFFFFFFFF 'Backup
Const MD_BACKUP_OVERWRITE = 1 'Backup
Const MD_BACKUP_SAVE_FIRST = 2 'Backup
Const MD_SERVER_STATE_CONTINUING = 7 'ServerState
Const MD_SERVER_STATE_PAUSING = 5 'ServerState
Const MD_SERVER_STATE_PAUSED = 6 'ServerState
Const MD_SERVER_STATE_STARTING = 1 'ServerState
Const MD_SERVER_STATE_STARTED = 2 'ServerState
Const MD_SERVER_STATE_STOPPING = 3 'ServerState
Const MD_SERVER_STATE_STOPPED = 4 'ServerState
Const NOT_A_VALID_PROPERTY = &H80005006 'Various methods
%>
ADSI Reference
This is preliminary documentation for IIS 5.0 and is subject to change.
The ADSI Reference section describes properties and methods that are exposed by the IIS Admin
Objects. This section contains:
? ADSI Object Properties: Describes the six basic properties that must be implemented by IIS
Admin Objects (Name, ADsPath, Class, GUID, Parent, and Schema).
? ADSI Object Methods: Lists the methods exposed by the IIS Admin Objects.
? ADSI Container Object Properties: Discusses additional attributes implemented by the IIS Admin
Container Object.
? ADSI Container Object Methods: Describes methods, implemented by the ADSI Container
Object, that manipulate IIS Admin Objects and metabase keys.
? ADSI Changes for IIS 5.0: A quick reference to IIS ADSI provider changes in IIS 5.0.
The IIS Admin Objects implement the six basic properties that ADSI objects require. The data type for
all of these properties is string.
The ADSI object properties are read-only and are provided for use with ADSI client programs for
ADSI namespace administration. The following table provides an example of the ADSI properties for the
IIsWebService object. LocalHost is a placeholder for the name of the local computer on which IIS is
running.
GUID {8B645280-7BA4-11CF-B03D-
00AA006E0975}
Parent IIS://LocalHost
Schema IIS://LocalHost/schema/IIsWebService
You can use the ADSI Name property to document the structure of your IIS installation.
You can use the metabase properties supported by the IIS Admin Objects to control the configuration of
your IIS installation. See ADSI Object Methods and the specific metabase properties supported by each
of the individual IIS Admin Objects.
You can use the ADSI methods of the IIS Admin Objects to change metabase property values that
control your IIS configuration. To configure a specific element of IIS, open the IIS Admin Object that
corresponds to the metabase key associated with that element, modify the property values cached in the
object, and direct the object to store the modified values in the metabase.
The following ADSI methods are exposed by the IIS Admin Objects, and can be used to set or query
metabase properties.
Method Description
Get Retrieves a value for a named property from the object.
GetDataPaths Retrieves the paths to all locations of a metabase property subordinate to a
specified starting path.
GetEx Retrieves a value or values for a named single-valued or multivalued
property of the object.
GetInfo Reloads the object with property values that exist in the metabase.
GetPropertyAttribObj Retrieves an object that contains the property's attributes. This object can
then be used to retrieve individual attributes of ADSI properties.
Put Sets the value for a named property of an object.
PutEx Sets the value or values for a named single-valued or multivalued property
of the object.
SetInfo Writes the object property values to the metabase.
The GetInfo method reloads the property values from the metabase into the object. When one of the
IIS Admin Objects is created or opened with the GetObject function, its properties are initialized from
the metabase. You can refresh these values from the metabase by using the GetInfo method, and
overwriting any changes you have made to the property values cached in the object. You then use the
Get or GetEx methods to retrieve the object properties and assign these values to variables, and the
Put and PutEx methods to modify property values in the object.
The IIS Admin Objects also support the object.property syntax when used with languages such as
VBScript or JScript. You can use the SetInfo method to write property values from the object to the
metabase. When you call SetInfo, only the properties that you changed in the object are written back to
the metabase. If you do not call SetInfo, your changes will not be written to the metabase.
Note When you bind to the metabase to modify properties in one of the IIS Admin Objects, the
metabase is not locked while you are changing property values in the object. Other programs can make
changes to values in the metabase after you have retrieved values but before you save them back into the
metabase. Your program should minimize the time between retrieving and saving values.
ADSI properties apply only to the object, and non-ADSI properties apply to the metabase. You must
use the object.property syntax when retrieving ADSI properties, whereas you can use either the
object.property syntax or the ADSI methods such as Get and Put when manipulating metabase
properties.
Example
The following sample VBScript code shows how you can use the ADSI methods of the IIS Admin
Objects to change values in the metabase, and illustrates the use of metabase property inheritance for
efficiency. MyComputer is a placeholder for the name of the computer on which IIS is running.
<%
Dim WebServerObj
Dim VDirObj
Dim WritePerm
'Open the object for the first virtual Web server root.
Set WebServerObj = GetObject("IIS://MyComputer/W3SVC/1/Root")
Get
The ADSI Get method for IIS Admin Objects retrieves a metabase property value from the object and
stores it in a variable. Some languages, such as VBScript, also support the object.property syntax as an
alternative to the Get and Put methods.
Syntax
value = object.Get(property)
or
value = object.property
Parts
value
Receives the returned value of the property.
object
Contains an IIS Admin Object, usually as a result of a previous GetObject operation.
property
A property of the object that has been retrieved from the metabase.
Code Example
<%
Dim IIsObj, vRead, vWrite
Set IIsObj = GetObject("IIS://LocalHost/W3SVC/1/Root")
'Get the value from the object.
vRead = IIsObj.Get("AccessRead")
'Can also use object.property syntax.
vWrite = IIsObj.AccessWrite
'Set the values.
vRead = True
vWrite = False
'Put the values back in the object.
IIsObj.Put "AccessRead", vRead
'Use optional object.property syntax.
IIsObj.AccessWrite = vWrite
'Save the changes back to the metabase.
IIsObj.SetInfo
%>
See Also
GetDataPaths
The ADSI GetDataPaths method can be used with any of the IIS Admin Objects to find the paths to
metabase keys where a specified property is located. This method can be used to find occurrences of a
property that could be preventing subkeys from inheriting values. The path search will start at the key
associated with the object you use GetDataPaths with, and will return the starting path if the property is
located at that key. For example, if you use GetDataPaths with the IIsWebServer object for the third
Web server, the search path would start at IIS://LocalHost/W3SVC/3 and would return the paths
IIS://LocalHost/W3SVC/3, IIS://LocalHost/W3SVC/3/ROOT/VDir1, and
IIS://LocalHost/W3SVC/3/ROOT/VDir1/Dir1/File1, if those were the keys where the property was
found.
A parameter of the method enables you to specify whether to limit your search to seeking only paths of
an inheritable property, or all property paths. You can use GetDataPaths to determine if a property is
inheritable, as well as where occurrences of it are located.
Syntax
Parts
PathList
Receives the list of paths to occurrences of the specified property.
object
Contains an IIS Admin Object, usually as a result of a previous GetObject operation.
property
The name of the property whose paths are to be located.
AttributeFlag
One of the following flags:
IIS_ANY_PROPERTY Retrieve paths regardless of whether the
property is inheritable.
IIS_INHERITABLE_ONLY Retrieve paths only if the property is
inheritable. Return
MD_ERROR_DATA_NOT_FOUND if
property is not inheritable.
Remarks
You can use the For each Path in PathList...Next statement to retrieve individual paths from
PathList.
Code Example
<%
Const IIS_ANY_PROPERTY = 0
Const IIS_INHERITABLE_ONLY = 1
Const MD_ERROR_DATA_NOT_FOUND = &H800CC801
Dim WebSvrObj, PathList, vProperty
GetEx
The ADSI GetEx method retrieves a single-valued or multivalued property value from the object and
puts it into a variant-array variable.
Syntax
value = object.GetEx(property)
Parts
value
Receives the returned property value from the method.
object
Contains an IIS Admin Object, usually as a result of a previous GetObject operation.
property
A property of the object that has been retrieved from the metabase.
Return Values
Code Example
<%
Dim IIsObj, vList
Set IIsObj = GetObject("IIS://LocalHost/W3SVC/Info")
'Get the value from the object.
vList = IIsObj.GetEx("CustomErrorDescriptions")
'Modify the list.
See Also
GetInfo
The ADSI GetInfo method re-initializes the object's properties by using values from the metabase.
Because the object's properties are automatically initialized when the object is created, you need to use
this method only if you want to refresh properties in the object with current values from the metabase.
Syntax
object.GetInfo
Parts
object
Contains an IIS Admin Object, usually as a result of a previous GetObject operation.
Code Example
<%
Dim IIsObj
Set IIsObj = GetObject("IIS://LocalHost/W3SVC/1/Root")
'Make some changes to properties.
' . . .
'Discard changes and refresh property values in the object.
IIsObj.GetInfo
%>
See Also
GetPropertyAttribObj
You can use this method to access information about attributes for individual ADSI properties.
GetPropertyAttribObj works in the following way:
? Returns an object that contains the property's attributes if the property is set at that node or is set
at some parent node and is inheritable.
? Returns an Error if the property is not set at that node, or its parent node and is inheritable.
? Returns an Error if the property is not set at that node, but set at parent and not inheritable.
Syntax
Initializing:
PropAttObj = object.GetPropertyAttribObj(property)
Using:
RetBool = PropAttObj.Attribute
Parts
PropAttObj
Reference to an object that contains the property attributes for the property.
object
Contains an IIS Admin Object, usually as a result of a previous GetObject operation.
property
String that contains the name of the property whose attributes are being requested.
RetBool
Boolean that indicates whether the attribute specified by Attribute is enabled or disabled.
Attribute
Indicates which attribute is being queried. The possible attributes are:
Attribute Description
Inherit Specifies whether the property is inheritable.
PartialPath Indicates whether a partial path is present.
Secure Indicates whether the property is secure.
Reference Specifies if the property was received by a
reference.
Volatile Indicates whether the property is volatile.
IsInherited Specifies whether the property is inherited.
InsertPath Indicates whether a string in a property
contains a special insert value.
AllAttributes Contains all the attributes listed in this table
in one Long.
Remarks
Unlike most other ADSI objects, the property attributes object does not support Get and Set methods.
You must use the object.property syntax to access the individual attributes of the property attribute
object.
Note If a call is made to AppCreate, object path information will be persisted, but you must call
SetInfo before the given object is created. If SetInfo is not called, subsequent calls to the object
created will fail.
Put
The ADSI Put method sets the value for a metabase property in the object. Some languages, such as
VBScript, also support the object.property syntax as an alternative to the Get and Put methods.
Syntax
or
object.property = value
Parts
object
Contains an IIS Admin Object, usually as a result of a previous GetObject operation.
property
A property of the object that has been retrieved from the metabase.
value
The value for the property.
Code Example
<%
Dim IIsObj, vRead, vWrite
Set IIsObj = GetObject("IIS://LocalHost/W3SVC/1/Root")
'Get the value from the object.
vRead = IIsObj.Get("AccessRead")
'Can also use object.property syntax.
vWrite = IIsObj.AccessWrite
' Set the values.
vRead = True
vWrite = False
'Put the values back in the object.
IIsObj.Put "AccessRead", vRead
'Use optional object.property syntax.
IIsObj.AccessWrite = vWrite
'Save the changes back to the metabase.
IIsObj.SetInfo
%>
See Also
PutEx
The ADSI PutEx method sets the value for a single-valued or multivalued metabase property in the
object. You can use PutEx to remove, or clear, a property from a metabase key.
Syntax
Parts
object
Contains an IIS Admin Object, usually as a result of a previous GetObject operation.
controlcode
Specifies whether to update the property, or to remove the property from the object. One of:
ADS_PROPERTY_CLEAR (value 1) to remove the property, or ADS_PROPERTY_UPDATE
(value 2) to update the property.
property
A property of the object that has been retrieved from the metabase.
value
The value for the property. An empty string when removing the property (controlcode =
ADS_PROPERTY_CLEAR).
Remarks
For a metabase property to use inherited data at a key, the property must not already exist at the key; if
it does, you can remove it by using ADS_PROPERTY_CLEAR. (You can use the GetDataPaths
method common to all IIS Admin Objects to locate the keys where a property exists.)
Code Example
<%
Dim IIsObj, vList
Set IIsObj = GetObject("IIS://LocalHost/W3SVC/Info")
'Get the value from the object.
vList = IIsObj.GetEx("CustomErrorDescriptions")
'Modify the list.
See Also
SetInfo
The ADSI SetInfo method saves changed property values from the object to the metabase. After you
have changed some or all of the values in the object properties, you must use the SetInfo method to
save the new values back into the metabase. Only the values you changed will be saved back into the
metabase; unchanged values will not be overwritten.
Syntax
object.SetInfo
Parts
object
Contains an IIS Admin Object, usually as a result of a previous GetObject operation.
Code Example
<%
Dim IIsObj
Set IIsObj = GetObject("IIS://LocalHost/W3SVC/1/Root")
'Make some changes to properties.
' . . .
'Save the changes back to the metabase.
IIsObj.SetInfo
%>
Note If you attempt to create a custom object by calling AppCreate but fail to call SetInfo, any calls
to the custom object will fail because the path exists but the object does not exist. If a call to AppCreate
is made, preliminary information will be persisted, but the object will not be created until SetInfo is
called.
See Also
IIS Admin Objects that can contain other objects also can implement the ADSI container methods and
You can use the ADSI container object methods of the IIS Admin Objects to manipulate keys in the
metabase. You can create, delete, and move keys by creating, deleting, and moving IIS Admin Objects
within container objects. You can also enumerate contained objects such as virtual directories or servers
with container object methods.
These ADSI container object methods manipulate IIS Admin Objects and metabase keys:
Method Description
CopyHere Copies an object into a container.
Create Creates a new object in a container.
Delete Deletes an object from a container.
GetObject Accesses an object in a container.
MoveHere Copies an object into a container and deletes the original object.
Note When one of the IIS Admin Objects is a container object, it retains its own ADSI object
properties and methods as well as any IIS-specific methods and associated metabase properties.
CopyHere
The ADSI container object CopyHere method copies an object into a container.
Syntax
Parts
CopiedObj
Accesses the copied object in the container.
object
Contains an IIS Admin Object, usually as a result of a previous GetObject operation.
SourceName
The name of the object to be copied.
NewName
The new name for the copied object.
Remarks
The CopiedObj variable receives a pointer to the object itself, which remains in the container.
When the contained object to be copied is part of an application, the CopyHere method will remove the
application definition before copying the object. See the AppDelete method of the IIsWebVirtualDir
and IIsWebDirectory objects.
Code Example
<%
Dim ToVDirObj, FromVDirObj, RootVDirObj
'Get the root virtual directory object for a server.
Set RootVDirObj = GetObject("IIS://LocalHost/W3SVC/4/ROOT")
'Copy a virtual directory object.
'Also get a pointer to the new object.
Set ToVdirObj = RootVDirObj.CopyHere("VDir1", "VDir2")
RootVDirObj.SetInfo
%>
See Also
Create
The ADSI container object Create method creates a new object in a container.
Syntax
Parts
NewObj
Accesses the new object created in the container.
object
Contains an IIS Admin Object, usually as a result of a previous GetObject operation.
KeyType
The type of IIS Admin Object to create.
Name
The name for the new object.
Code Example
<%
Dim WebServiceObj, ServerObj
'Get the Web service object, which contains servers.
Set WebServiceObj = GetObject("IIS://LocalHost/W3SVC")
'Create a new Web server object in the container.
Set ServerObj = WebServiceObj.Create("IIsWebServer", "3")
'Add code to configure server and create root virtual directory.
%>
See Also
Delete
The ADSI container object Delete method deletes an object from a container.
Syntax
Parts
object
Contains an IIS Admin Object, usually as a result of a previous GetObject operation.
KeyType
The type of IIS Admin Object to delete.
Name
The name of the object to delete.
Remarks
When the contained object to be deleted is part of an application, the Delete method will remove the
application definition before deleting the object. See the AppDelete method of the IIsWebVirtualDir
and IIsWebDirectory objects.
Code Example
<%
Dim WebServiceObj
'Get the Web service object, which contains servers.
Set WebServiceObj = GetObject("IIS://LocalHost/W3SVC")
'Delete the fourth server.
WebServiceObj.Delete "IIsWebServer", "4"
%>
See Also
GetObject
Syntax
Parts
ChildObj
Accesses the object in the same way as the ASP GetObject function does.
Object
Contains an IIS Admin Object, usually as a result of a previous GetObject operation.
Class
Specifies the class of the object to be accessed.
ChildName
The name of the object to be accessed.
Remarks
The ChildObj variable receives a pointer to the object itself, which remains in the container.
Code Example
<%
Dim WebServiceObj, ServerObj
'Get the Web service object, which contains servers.
Set WebServiceObj = GetObject("IIS://LocalHost/W3SVC")
'Access the object for the third Web server.
Set ServerObj = WebServiceObj.GetObject("IIsWebServer", "3")
%>
See Also
MoveHere
The ADSI container object MoveHere method moves an object into a container and removes the
object from its origin.
Syntax
Parts
MovedObj
Accesses the object moved into the container.
object
Contains an IIS Admin Object, usually as a result of a previous GetObject operation.
SourceName
The name of the object to be moved.
NewName
The name for the moved object.
Remarks
The MovedObj variable receives a pointer to the object itself, which remains in the container.
When the contained object to be moved is part of an application, the MoveHere method will disable
the application definition before moving the object. See the AppDisable method of the
IIsWebVirtualDir and IIsWebDirectory objects.
Code Example
<%
Dim ToVDirObj, FromVDirObj, RootVDirObj
'Get the root virtual directory object for a server.
Set RootVDirObj = GetObject("IIS://LocalHost/W3SVC/3/ROOT")
'Get the object to be moved.
Set FromVDirObj = GetObject("IIS://LocalHost/W3SVC/3/ROOT/VDir1")
'Move the object and give it a new name.
Set ToVdirObj = RootVDirObj.MoveHere("VDir1", "VDir2")
'Release the source object because it has been deleted.
Set FromVDirObj = nothing
%>
See Also
This section contains information about the changes and additions in the ADSI provider for IIS 5.0.
? IIS Performance Features: Describes new performance features for IIS 5.0.
? ADSI Properties Removed from IIS 5.0: Lists any properties that were supported in previous
versions, but which are not valid for IIS 5.0.
? ADSI Properties Added to IIS 5.0: Provides a list of properties new to IIS 5.0, and links to each
property's full reference.
? ADSI Property Key Type Changes for IIS 5.0: Lists any properties whose key type has changed
for IIS 5.0.
? ADSI Properties Changed in IIS 5.0: Lists any properties that have different default behavior for
IIS 5.0.
In IIS 4.0, each Web site was bound to a different IP address. This meant that each site had its own
socket, which was not shared with sites bound to other IP addresses. These sockets are created when
each site starts, and they can consume significant amounts of nonpaged memory (RAM). This memory
consumption limits the number of sites bound to IP addresses that can be created on a machine, because,
after a certain number of sites are started, the machine is out of RAM.
For IIS 5.0, this process has been modified so that sites bound to different IP addresses—but sharing
the same port number—share the same set of sockets. The end result is that more sites can be bound to
an IP address on the same machine than in IIS 4.0. In IIS 5.0, these shared sockets are used flexibly
among all of the started sites, thus reducing resource consumption.
This is now the default behavior for IIS 5.0. In general, this behavior should not be modified. However,
for critical sites that require a dedicated socket, you can set the DisableSocketPooling to TRUE to
revert back to the IIS 4.0 behavior. This change should be made at the site level only, so that other sites
can continue to take advantage of the new socket pooling feature.
AccessSource CPUResetInterval
AspEnableApplicationRestart DisableSocketPooling
AspEnableAspHtmlFallback HcCacheControlHeader
AspEnableChunkedEncoding HcCompressionBufferSize
AspEnableTypelibCache HcCompressionDirectory
AspErrorsToNTLog HcCompressionDll
AspProcessorThreadMax HcCreateFlags
AspQueueConnectionTestTime HcDoDiskSpaceLimiting
AspRequestQueueMax HcDoDynamicCompression
AspSessionMax HcDoOnDemandCompression
AspTrackThreadingModel HcDoStaticCompression
CPUAppEnabled HcDynamicCompressionLevel
CPUCGIEnabled HcExpiresHeader
CPUCGILimit HcFileExtensions
CPUEnableActiveProcs HcFilesDeletedPerDiskFree
CPUEnableAllProcLogging HcIoBufferSize
CPUEnableAppLogging HcMaxDiskSpaceUsage
CPUEnableCGILogging HcMaxQueueLength
CPUEnableEvent HcMimeType
CPUEnableKernelTime HcMinFileSizeForComp
CPUEnablePageFaults HcNoCompressionForHttp10
CPUEnableProcType HcNoCompressionForProxies
CPUEnableTerminatedProcs HcNoCompressionForRange
CPUEnableTotalProcs HcOnDemandCompLevel
CPUEnableUserTime HcPriority
CPULimitLogEvent HcSendCacheHeaders
CPULimitPause LogCustomPropertyDataType
CPULimitPriority LogCustomPropertyHeader
CPULimitProcStop LogCustomPropertyID
CPULimitsEnabled LogCustomPropertyMask
CPULoggingInterval LogCustomPropertyName
CPULoggingMask LogCustomPropertyServicesString
CPULoggingOptions NotDeletable
SSLUseDSMapper
The metabase key types for the following properties have changed since IIS 4.0. To see the full property
reference for a key type, click on the link.
KeyType
FrontPageWeb
CacheISAPI
AspTrackThreadingModel
There is only one property change to list at this time. Check the IIS 5.0 Alphabetical Property List for
detailed information.
Note For items that were implemented after the time of this release, see the Platform SDK.
ScriptMaps property syntax has changed to required-verb inclusion rather than exclusion. (In previous
versions, it was possible to list verb exclusions, but this was not required for valid syntax.) Because of the
change from exclusions to inclusions, verbs are required in the property syntax. See ScriptMaps for
more details.
Administration properties are associated with the values assigned to keys in the metabase. This reference
provides a description of each property, including the data type, default value, inheritance attribute, and
usage notes. For each property, the IIS Admin Objects that can access that property are listed. For
more information about the IIS Admin Objects, see Using IIS Admin Objects.
Note Additional IIS Admin Base Object information is provided for programmers who are
implementing required algorithms at the IIS Admin Base Object level.
AppAllowClientDebug AspLogErrorRequests
AppAllowDebugging AspProcessorThreadMax
AppFriendlyName AspQueueConnectionTestTime
AppIsolated AspQueueTimeout
AppOopRecoverLimit AspRequestQueueMax
AppPackageID AspScriptEngineCacheMax
AppPackageName AspScriptErrorMessage
AppRoot AspScriptErrorSentToBrowser
AppWamClsID AspScriptFileCacheSize
AspAllowOutOfProcComponents AspScriptLanguage
AspAllowSessionState AspScriptTimeout
AspBufferingOn AspSessionMax
AspCodepage AspSessionTimeout
AspEnableApplicationRestart AspThreadGateEnabled
AspEnableAspHtmlFallback AspThreadGateLoadHigh
AspEnableChunkedEncoding AspThreadGateLoadLow
AspEnableParentPaths AspThreadGateSleepDelay
AspEnableTypelibCache AspThreadGateSleepMax
AspErrorsToNTLog AspThreadGateTimeSlice
AspExceptionCatchEnable AspTrackThreadingModel
Auth… – D
AuthAnonymous CpuEnableTerminatedProcs
AuthBasic CpuEnableTotalProcs
AuthFlags CpuEnableUserTime
AuthNTLM CpuLimitLogEvent
AuthPersistence CpuLimitPause
AuthPersistSingleRequest CpuLimitPriority
AuthPersistSingleRequestIfProxy CpuLimitProcStop
AuthPersistSingleRequestAlwaysIfProxy CpuLimitsEnabled
CacheControlCustom CpuLoggingInterval
CacheControlMaxAge CpuLoggingMask
CacheControlNoCache CpuLoggingOptions
CacheISAPI CpuResetInterval
CertCheckMode CreateCGIWithNewConsole
CGITimeout CreateProcessAsUser
ConnectionTimeout CustomErrorDescriptions
ContentIndexed DefaultDoc
CpuAppEnabled DefaultDocFooter
CpuCgiEnabled DefaultLogonDomain
CpuCgiLimit DirBrowseFlags
CpuEnableActiveProcs DirBrowseShowDate
CpuEnableAllProcLogging DirBrowseShowExtension
CpuEnableAppLogging DirBrowseShowLongDate
CpuEnableCgiLogging DirBrowseShowSize
CpuEnableEvent DirBrowseShowTime
CpuEnableKernelTime DirectoryLevelsToScan
CpuEnableLogging DisableSocketPooling
CpuEnablePageFaults DontLog
CpuEnableProcType DownlevelAdminInstance
E-K
EnableDefaultDoc HcExpiresHeader
EnableDirBrowsing HcFileExtensions
EnableDocFooter HcFilesDeletedPerDiskFree
EnableReverseDns HcIoBufferSize
ExitMessage HcMaxDiskSpaceUsage
FilterDescription HcMaxQueueLength
FilterEnabled HcMimeType
FilterFlags HcMinFileSizeForComp
FilterLoadOrder HcNoCompressionForHttp10
FilterPath HcNoCompressionForProxies
FilterState HcNoCompressionForRange
FrontPageWeb HcOnDemandCompLevel
FtpDirBrowseShowLongDate HcPriority
GreetingMessage HcSendCacheHeaders
HcCacheControlHeader HcScriptFileExtensions
HcCompressionBufferSize HttpCustomHeaders
HcCompressionDirectory HttpErrors
HcCompressionDll HttpExpires
HcCreateFlags HttpPics
HcDoDiskSpaceLimiting HttpRedirect
HcDoDynamicCompression InProcessIsapiApps
HcDoOnDemandCompression IPSecurity
HcDoStaticCompression KeyType
HcDynamicCompressionLevel
Log...
LogAnonymous LogExtFileTimeTaken
LogCustomPropertyDataType LogExtFileUriQuery
LogCustomPropertyHeader LogExtFileUriStem
LogCustomPropertyID LogExtFileUserAgent
LogCustomPropertyMask LogExtFileUserName
LogCustomPropertyName LogExtFileWin32Status
LogCustomPropertyServicesString LogFileDirectory
LogExtFileBytesRecv LogFileLocaltimeRollover
LogExtFileBytesSent LogFilePeriod
LogExtFileClientIp LogFileTruncateSize
LogExtFileComputerName LogModuleId
LogExtFileCookie LogModuleList
LogExtFileDate LogModuleUiId
LogExtFileFlags LogNonAnonymous
LogExtFileHttpStatus LogOdbcDataSource
LogExtFileMethod LogOdbcPassword
LogExtFileProtocolVersion LogOdbcTableName
LogExtFileReferer LogOdbcUserName
LogExtFileServerIp LogonMethod
LogExtFileServerPort LogPluginClsid
LogExtFileSiteName LogType
LogExtFileTime
M–R
MaxBandWidth NotifyPreProcHeaders
MaxBandWidthBlocked NotifyReadRawData
MaxClientsMessage NotifySecurePort
MaxConnections NotifySendRawData
MaxEndpointConnections NotifySendResponse
MimeMap NotifyUrlMap
MSDOSDirOutput NTAuthenticationProviders
NetLogonWorkstation PasswordCacheTTL
NotDeletable PasswordChangeFlags
NotifyAccessDenied PasswordExpirePrenotifyDays
NotifyAuthentication Path
NotifyEndOfNetSession PoolIDCTimeout
NotifyEndOfRequest ProcessNTCRIfLoggedOn
NotifyLog PutReadSize
NotifyNonSecurePort Realm
NotifyOrderHigh RedirectHeaders
NotifyOrderLow
NotifyOrderMedium
Script...– Z
ScriptMaps ServerSize
SecureBindings ServerState
ServerAutoStart SSIExecDisable
ServerBindings SSLUseDSMapper
ServerComment UNCAuthenticationPassthrough
ServerConfigAutoPWSync UNCPassword
ServerConfigFlags UNCUserName
ServerConfigSSL128 UploadReadAheadSize
ServerConfigSSL40 UseHostName
ServerConfigSSLAllowEncrypt WAMUserName
ServerListenBacklog WAMUserPass
ServerListenTimeout Win32Error
AccessExecute
When set to TRUE, the AccessExecute file permission property permits execution of ASP scripts and
other executable files. AccessExecute is one of the access permission flags contained in the
AccessFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AccessFlags, AccessScript
AccessFlags
This single property contains the following file access permission flags:
AccessExecute AccessNoRemoteWrite
AccessNoRemoteExecute AccessRead
AccessNoRemoteRead AccessScript
AccessNoRemoteScript AccessWrite
AccessSource
CAUTION Setting both write and execute permissions can be dangerous, because it allows users to
modify internal files and run potentially damaging scripts on the system.
Remote access flags are operative only when the corresponding general access flag is set. For example,
setting AccessNoRemoteRead has no effect unless AccessRead is set as well. If both are set, the
local host can read the file, but the file cannot be read by the remote client.
The AccessSource flag, if set, grants source access to clients, using the HTTP extensions described by
the Web Distributed Authoring and Versioning (WebDAV) standard. For more information on
WebDAV, see the World Wide Web Consortium and Internet Engineering Task Force Web sites.
Note All permissions are applicable to Web services, servers, directories, and files. Only the
AccessRead and AccessWrite permissions are applicable for the FTP services, FTP servers, and FTP
directories.
Access Locations
The following tables list additional information required only for code that uses the IIS Admin Base
Object.
Bitmask Values
AccessNoRemoteExecute
When set to TRUE, this file permission property prohibits the file from being executed by remote clients.
If AccessExecute is set to TRUE, the file can be executed by the Web server.
AccessNoRemoteExecute is one of the access permission flags contained in the AccessFlags
property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AccessFlags
AccessNoRemoteRead
When set to TRUE, this file permission property prohibits the file from being read by remote clients. If
AccessRead is set to TRUE, the file can be read by the Web server. AccessNoRemoteRead is one
of the access permission flags contained in the AccessFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AccessFlags
AccessNoRemoteScript
When set to TRUE, this file permission property prohibits a script file from being executed by remote
clients. If AccessExecute or AccessScript is set to TRUE, the script file can be executed by the Web
server. AccessNoRemoteScript is one of the access permission flags contained in the AccessFlags
property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AccessFlags, AccessScript
AccessNoRemoteWrite
When set to TRUE, this file permission property prohibits the file from being written to by remote clients.
If AccessWrite is set to TRUE, the file can be written to by the Web server. AccessNoRemoteWrite
is one of the access permission flags contained in the AccessFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AccessFlags
AccessRead
When set to TRUE, this file permission property permits the file to be read. AccessRead is one of the
access permission flags contained in the AccessFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AccessFlags
AccessScript
When set to TRUE, this file permission property permits an .asp file to be executed by the ASP engine.
AccessScript is one of the access permission flags contained in the AccessFlags property. The
AccessExecute property allows execution of other types of executable files in addition to .asp files.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AccessFlags
AccessSource
When set to TRUE, this file permission property allows the client full control over the requested
resource. Full control includes full support for the HTTP extensions provided by Web Distributed
Authoring and Versioning (WebDAV). For more information on WebDAV, see the World Wide Web
Consortium and the Internet Engineering Task Force Web sites.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AccessFlags
AccessSSL
When set to TRUE, file access requires Secure Sockets Layer (SSL) file permission processing, with or
without a client certificate. AccessSSL is one of the SSL file permission flags contained in the
AccessSSLFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AccessSSLFlags
AccessSSL128
When set to TRUE, file access requires Secure Sockets Layer (SSL) file permission processing with a
minimum key size of 128 bits, with or without a client certificate. AccessSSL128 is one of the SSL file
permission flags contained in the AccessSSLFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AccessSSLFlags
AccessSSLFlags
This single property contains the following Secure Sockets Layer (SSL) file permission flags:
AccessSSL AccessSSLNegotiateCert
AccessSSL128 AccessSSLRequireCert
AccessSSLMapCert
Data type Long
Default value 0 (no SSL permissions)
Inheritance Inheritable
Access Locations
/LM/W3SVC/N/ROOT/WebVirtualDir/WebDirectory/WebFile IIsWebFile
The following tables list additional information required only for code that uses the IIS Admin Base
Object.
Values
Default Value
0x00000000 (No SSL protocols required)
Constant Value Description
MD_ACCESS_SSL 0x00000008 SSL permissions required.
MD_ACCESS_NEGO_CERT 0x00000020 Client certificate optional.
MD_ACCESS_REQUIRE_CERT 0x00000040 Client certificate required.
MD_ACCESS_MAP_CERT 0x00000080 Server will map client
certificate to Windows
account.
MD_ACCESS_SSL128 0x00000100 SSL permissions with 128-
bit key required.
See Also
AccessFlags
AccessSSLMapCert
When set to TRUE, this property indicates that Secure Sockets Layer (SSL) file permission processing
will map a client certificate to a Windows account. The AccessSSLNegotiateCert property must also
be set to TRUE for the mapping to occur. AccessSSLMapCert is one of the SSL file permission flags
contained in the AccessSSLFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AccessSSLFlags
AccessSSLNegotiateCert
When set to TRUE, Secure Sockets Layer (SSL) file access processing will request a certificate from
the client. If AccessSSLRequireCert is FALSE, access will continue if the client does not have a
certificate. Note that some versions of Internet Explorer will close the connection if the server requests a
certificate and one is not available, even if AccessSSLRequireCert is also set to TRUE.
AccessSSLNegotiateCert is one of the SSL file permission flags contained in the AccessSSLFlags
property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AccessSSLFlags
AccessSSLRequireCert
When set to TRUE, Secure Sockets Layer (SSL) file access processing will request a certificate from
the client. If no certificate is provided by the client, the connection will be closed.
AccessSSLNegotiateCert must also be set to TRUE when using AccessSSLRequireCert. This
property is one of the SSL file permission flags contained in the AccessSSLFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AccessSSLFlags
AccessWrite
When set to TRUE, this file permission property permits writing to the file. AccessWrite is one of the
access permission flags contained in the AccessFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AccessFlags
AdminACL
The AdminACL property contains a Microsoft Windows discretionary access control list (DACL) that
can be used to control access to any metabase subtree. This property can be used to grant read access,
restricted write access, or unrestricted write access.
Access Locations
The following tables list additional information required only for code that uses the IIS Admin Base
Object.
Values
Default Value
0x00000000 (no SSL protocols required)
Constant Value Description
MD_ACR_READ 0x00000001 Enable read access to all
properties.
MD_ACR_WRITE 0x00000002 Enable write access to all
properties.
MD_ACR_ENUM_KEYS 0x00000008 Enable key enumeration.
MD_ACR_RESTRICTED_WRITE 0x00000020 See Remarks, following this
table.
Remarks
AdminACL AppIsolated
Path AccessFlags
AnonymousUserName AnonymousUserPass
MaxBandWidth MaxBandWidthBlocked
SecureBindings ServerBindings
AdminServer
This property identifies the Web server instance being administered by the remote administration
program. This property is read-only.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AllowAnonymous
This property specifies whether the FTP or Web server will allow anonymous access.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AllowKeepAlive
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AllowPathInfoForScriptMappings
This property indicates whether clients are permitted to specify path information in script-mapped
requests.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AnonymousOnly
This property specifies whether the service or server restricts access to anonymous FTP users. If the
value is TRUE, only anonymous users will be allowed to log on to the FTP server. If the value is FALSE,
users will be allowed to log on by using a valid user name, as well as anonymously.
Note If the value of AnonymousOnly is set to TRUE, and the value of the metabase property
AllowAnonymous is set to FALSE, no users will be permitted to log on to the FTP server.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AnonymousPasswordSync
This property indicates whether IIS should handle the user password for anonymous users attempting to
access resources. For anonymous access to function properly, if the value of
AnonymousPasswordSync is FALSE the administrator must set the password in the
AnonymousUserPass property. If the value of AnonymousPasswordSync is TRUE, no anonymous
user password is required.
Note If the value of AnonymousPasswordSync is set to TRUE, and the value of the metabase
property AllowAnonymous is set to FALSE, no users will be permitted to log on to the FTP server.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See also
AnonymousUserName , AnonymousUserPass
AnonymousUserName
The server associates a user name and password with every server action. This value specifies the name
of the registered local user that will be used for anonymous users. See also AnonymousUserPass and
AnonymousPasswordSync.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AnonymousUserPass
The server associates a user name and password with every server action. This value specifies the
password of the registered local user that will be used for anonymous users. See also
AnonymousUserName and AnonymousPasswordSync.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AnonymousUserPass, AnonymousPasswordSync
AppAllowClientDebug
This flag specifies whether ASP client-side debugging is enabled. This property is independent of
AppAllowDebugging, which applies to server-side debugging.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AppAllowDebugging
This flag specifies whether ASP debugging is enabled on the server. This property is independent of the
AppAllowClientDebug property, which applies to client-side debugging.
Tip If server-side debugging is enabled, IIS application threads will be serialized: Only one thread at a
time will be allowed to execute, for each application. On busy sites, this could adversely affect server
performance.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AppFriendlyName
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AppPackageName
AppIsolated
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
InProcessIsapiApps
AppOopRecoverLimit
This property specifies the maximum number of times an out-of-process application will be restarted
after a failure. The server will not service requests from components that have exceeded this limit.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
InProcessIsapiApps
AppPackageID
This property provides the COM+ application identifier (ID) for a transaction. This property is read-
only. This ID is used in all transactions managed by Component Services.
Access Locations
/LM/W3SVC/N/ROOT/WebVirtualDir/WebDirectory IIsWebDirectory
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AppPackageName
AppPackageName
This property provides the COM+ application name for a transaction. This property should be
considered read-only.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AppPackageID, AppFriendlyName
AppRoot
This property provides the URL for the ROOT directory of the application name space. This property
should be considered read-only. To mark a node as an application root, use the application management
methods of the IIsWebVirtualDir and IIsWebDirectory objects.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AppWamClsID
This property provides the class ID for the application's Web Application Management (WAM)
interface. This property should be treated as read-only.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspAllowOutOfProcComponents
This property specifies whether an ASP script is allowed to call out-of-process components, which are
executables that are launched from within an application. If set to TRUE at the Web service level
(/LM/W3SVC), all in-process applications will be able to launch out-of-process components. If set to
TRUE at the root of a specific application, only that application can launch out-of-process components.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspAllowSessionState
This property enables session state persistence for the ASP application. If the value is TRUE, the server
will create a new Session object for each connection. Session state will be accessible, session storage
will be allowed, the Session_OnStart and Session_OnEnd will occur, and the ASPSessionID cookie
will be sent to the client. If the value is FALSE, state access and storage are not allowed, events are not
processed, and no cookie is sent.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspBufferingOn
This property specifies whether output from an ASP application will be buffered. If the value is TRUE
(default), all output from the application is collected in the buffer before the buffer is flushed to the client
browser. If this property is set to FALSE, output from ASP scripts will be written to client browser as it
becomes available.
With buffering on, the ASP application will have to completely process the ASP script before any output
is received by the client browser. For this reason, applications for which buffering has been turned on
could seem slower to users than those applications for which buffering is turned off, even though the total
time taken for the buffered script is less. Therefore, if buffering is turned on, you should consider using
the Response.Flush method to pass the user pieces of content as the script is being processed.
Note If buffering is turned off, any methods that modify existing HTTP headers, or generate new
headers, must be executed before the content body is sent to the client browser. If buffering is turned on,
this restriction is unnecessary.
Important If you installed IIS 5.0 by upgrading from a previous version of IIS, the default setting for
this property will be FALSE, not TRUE.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspCodepage
This property specifies the default code page for an application. This setting can be overridden at the
page level by using the @CODEPAGE directive.
Access Locations
/LM/W3SVC/N/ROOT/WebVirtualDir/WebDirectory IIsWebDirectory
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspEnableApplicationRestart
This metabase property determines whether an ASP application can be automatically restarted.
There are two ways in which an application can be restarted. IIS 4.0 can call the application's Global.asa
file; this will immediately cause the application to restart if the AspEnableApplicationRestart property
is set to TRUE.
Important When this property if toggled from FALSE to TRUE, the application will automatically and
immediately be restarted.
IIS 5.0 also provides an ADSI method, AspAppRestart, which can be used to restart the application.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AspAppRestart
AspEnableAspHtmlFallback
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AspAppRestart
AspEnableChunkedEncoding
This metabase property specifies whether HTTP 1.1 chunked transfer encoding is enabled for the Web
service.
Note Even if chunked transfer encoding is enabled, it will be used only with browsers that support, and
have enabled, HTTP 1.1.
The Web service setting for this property is applicable to all in-process application nodes, at all levels.
Metabase settings at the Web server level or lower will be ignored for in-process applications. However,
settings at the Web server level or lower will be used if that node is isolated as an out-of-process
application.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspEnableParentPaths
This property specifies whether an ASP page can allow paths relative to the current directory (using
the ..\ notation). If set to TRUE, it constitutes a potential security risk because an include path could
access critical or confidential files outside the application's root directory.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspEnableTypelibCache
This metabase property specifies whether type libraries will be cached on the server.
The Web service setting for this property is applicable to all in-process application nodes, at all levels.
Metabase settings at the Web server level or lower will be ignored for in-process applications. However,
settings at the Web server level or lower will be used if that node is isolated as an out-of-process
application.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspErrorsToNTLog
This metabase property specifies whether IIS scripting errors will be written to the Windows Event Log.
The IIsWebService setting for this property is applicable to all in-process application nodes, at all
levels. Metabase settings at the IIsWebServer level or lower will be ignored for in-process applications
unless that IIsWebServer node is isolated as an out-of-process application.
If AspLogErrorRequests is TRUE and AspErrorsToNTLog is FALSE, then the ASP errors will be
sent to the IIS log. If these errors are serious or logging to IIS log previously failed, then each error will
also be sent to the Windows Event Log.
If AspLogErrorRequests is FALSE, then these errors will only be sent to the IIS Log, and not to the
Windows Event Log.
If AspLogErrorRequests is TRUE and AspErrorsToNTLog is TRUE, then all ASP related errors
will go to the Windows Event Log and the IIS log.
Note To completely prevent ASP errors from being logged in the IIS log file, you must disable logging
altogether. To accomplish this see the DontLog and LogType properties.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspExceptionCatchEnable
This value specifies whether exceptions thrown by components are trapped by ASP pages. If FALSE
(disabled), Microsoft Script Debugger will not catch exceptions sent by the component you are
debugging.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspLogErrorRequests
This property controls whether the Web server writes unsuccessful client requests to the Windows Event
Log file. If AspLogErrorRequests is TRUE, a standard set of ASP error requests are logged. For a list
of these errors see ASP Error List.
If AspLogErrorRequests is TRUE and AspErrorsToNTLog is FALSE, then the ASP errors will be
sent to the IIS log. If these errors are serious or logging to IIS log previously failed, then each error will
also be sent to the Windows Event Log.
If AspLogErrorRequests is FALSE, then these errors will only be sent to the IIS Log, and not to the
Windows Event Log.
If AspLogErrorRequests is TRUE and AspErrorsToNTLog is TRUE, then all ASP related errors
will go to the Windows Event Log and the IIS log.
Note To completely prevent ASP errors from being logged in the IIS log file, you must disable logging
altogether. To accomplish this see the DontLog and LogType properties.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
This table contains a list of ASP errors that will be logged by the Windows Event Log if
AspLogErrorRequests is set to TRUE.
See Also
AspErrorsToNTLog
AspProcessorThreadMax
This metabase property specifies the maximum number of worker threads per processor that IIS will
create.
Tip This setting can dramatically influence the scalability of your Web applications, and the performance
of your server in general. The optimal setting for your IIS installation depends on what types of
applications and content you are serving.
If this metabase property is changed, the Web server instance must stopped and restarted in order for
the change to take effect. The Web service setting for this property is applicable to all in-process
application nodes, at all levels. Metabase settings at the Web server level or lower will be ignored for in-
process applications. However, settings at the Web server level or lower will be used if that node is
isolated as an out-of-process application.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspQueueConnectionTestTime
IIS places all ASP requests into a queue. If the request has been queued for longer than the number of
seconds specified by the AspQueueConnectionTestTime metabase property, then ASP will check to
determine whether the client is still connected before executing the request. If the client is no longer
connected, the request will not be processed, and will be deleted from the queue.
Tip Users often will not wait very long for ASP pages to be processed. Although the maximum waiting
time varies from user to user, the generally accepted maximum is approximately 10 seconds. You can
use the AspQueueConnectionTestTime metabase property to make sure that IIS does not waste time
processing a request that has been abandoned by the user.
Note that this metabase identifier is useful for making ASP processing efficient only up to the point at
which ASP begins to process the script. Once the script is being executed, however, your application
should continue to check for client connection at appropriate times during the script's execution, by using
the ASP method IResponse::IsClientConnected.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspQueueTimeout
This property specifies the amount of time, in seconds, that an ASP script request will wait in the queue
for execution. When requests are pulled from the queue for execution, they are checked to see if they
have expired (have waited longer than the value of this parameter). Expired requests are rejected with a
message indicating the server is too busy.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspRequestQueueMax
This metabase property specifies the maximum number of concurrent ASP requests that will be permitted
into the queue. Any client browsers attempting to request ASP files when the queue is full will be given an
HTTP 500 "Server Too Busy" error.
The Web service setting for this property is applicable to all in-process application nodes, at all levels.
Metabase settings at the Web server level or lower will be ignored for in-process applications. However,
settings at the Web server level or lower will be used if that node is isolated as an out-of-process
application.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspScriptEngineCacheMax
This property specifies the maximum number of scripting engines that ASP pages will keep cached in
memory.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspScriptErrorMessage
This property specifies the error message that will be sent to the browser if specific debugging errors are
not sent to the client (if AspScriptErrorSentToBrowser is FALSE).
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AspScriptErrorSentToBrowser
AspScriptErrorSentToBrowser
This property specifies whether the Web server writes debugging specifics (file name, error, line number,
description) to the client browser in addition to logging them to the Windows Event Log. The
AspScriptErrorMessage property provides the error message to be sent if this property is FALSE.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AspScriptErrorMessage
AspScriptFileCacheSize
This property specifies the number of precompiled script files to cache. If 0, no script files will be
cached. If -1, all script files requested will be cached. This property can be used to tune performance,
depending on the amount of memory available and the amount of script file traffic.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspScriptLanguage
This property specifies the default script language for all ASP applications for the Web server. This
default language will be used within the script language delimiters (<% and %>) unless specifically
overridden by the following directive.
<%
@ LANGUAGE = ScriptingLanguage
%>
Access Locations
/LM/W3SVC/N/ROOT/WebVirtualDir IIsWebVirtualDir
/LM/W3SVC/N/ROOT/WebVirtualDir/WebDirectory IIsWebDirectory
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspScriptTimeout
This property specifies the default length of time in seconds that ASP pages will allow a script to run
before terminating and writing an event to the Windows Event Log. The script can override this default
value by using the Server.ScriptTimeout property. The ScriptTimeout property allows your ASP
application to set a higher script timeout value. For example, you might use this setting to adjust the
timeout once a particular user has established a valid session by logging in or ordering a product.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See also
ScriptTimeout, AspSessionTimeout
AspSessionMax
This metabase property specifies the maximum number of concurrent sessions that IIS will permit. If a
client attempts to establish a new session with IIS once this limit is reached, the client will receive an error
(HTTP 500 "Server Too Busy").
Tip ASP incurs a certain amount of memory overhead for each session maintained. Although you could
use AspSessionMax to limit this memory overhead, it is generally more appropriate to manage the
lifetime of session objects within IIS by using the AspSessionTimeout property, so that client browsers
will be rejected once the limit is reached.
If an incoming request doesn't have an ASP session cookie, or has a session cookie that doesn't match
an existing session, it is considered a new session request.
The Web service setting for this property is applicable to all in-process application nodes, at all levels.
Metabase settings at the Web server level or lower will be ignored for in-process applications. However,
settings at the Web server level or lower will be used if that node is isolated as an out-of-process
application.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See also
AspSessionTimeout
AspSessionTimeout
This property specifies the default amount of time in minutes a Session object will be maintained after the
last request associated with the object is made. This can be overridden in script by using the
Session.Timeout method.
Tip AspSessionTimeout can be used to tune your ASP applications. Because Session objects
consume some memory resources, limiting the lifetime of an individual Session timeout with this property
will make your applications more scalable.
The Web service setting for this property is applicable to all in-process application nodes, at all levels.
Metabase settings at the Web server level or lower will be ignored for in-process applications. However,
settings at the Web server level or lower will be used if that node is isolated as an out-of-process
application.
Access Locations
/LM/W3SVC/N/ROOT/WebVirtualDir/WebDirectory IIsWebDirectory
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See also
Timeout, AspScriptTimeout
AspThreadGateEnabled
Important IIS performs thread gating to dynamically control the number of concurrently executing
threads, in response to varying load conditions. The default settings for this property, and the other
thread gating properties, are designed to be appropriate for the majority of server configurations and
traffic conditions. Changing these properties can lead to significant performance degradation.
The Web service setting for this property is applicable to all in-process application nodes, at all levels.
Metabase settings at the Web server level or lower will be ignored for in-process applications. However,
settings at the Web server level or lower will be used if that node is isolated as an out-of-process
application.
Access Locations
/LM/W3SVC/N/ROOT/WebVirtualDir IIsWebVirtualDir
/LM/W3SVC/N/ROOT/WebVirtualDir/WebDirectory IIsWebDirectory
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspThreadGateLoadHigh
This metabase property specifies the minimum CPU load, as a percentage of the total, at which the CPU
is considered under high load conditions. This information will be used by IIS to perform thread gating, in
an attempt to maintain CPU load between the percentages specified in AspThreadGateLoadLow and
AspThreadGateLoadHigh.
Important IIS performs thread gating to dynamically control the number of concurrently executing
threads, in response to varying load conditions. The default settings for this property, and the other
thread gating properties, are designed to be appropriate for the majority of server configurations and
traffic conditions. Changing these properties can lead to significant performance degradation.
The Web service setting for this property is applicable to all in-process application nodes, at all levels.
Metabase settings at the Web server level or lower will be ignored for in-process applications. However,
settings at the Web server level or lower will be used if that node is isolated as an out-of-process
application.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspThreadGateLoadLow
This metabase property specifies the maximum CPU load, as a percentage of the total, at which the CPU
is still considered under low load conditions. This information will be used by IIS to perform thread
gating, in an attempt to maintain CPU load between the percentages specified in
AspThreadGateLoadLow and AspThreadGateLoadHigh.
Important IIS performs thread gating to dynamically control the number of concurrently executing
threads, in response to varying load conditions. The default settings for this property, and the other
thread gating properties, are designed to be appropriate for the majority of server configurations and
traffic conditions. Changing these properties can lead to significant performance degradation.
The Web service setting for this property is applicable to all in-process application nodes, at all levels.
Metabase settings at the Web server level or lower will be ignored for in-process applications. However,
settings at the Web server level or lower will be used if that node is isolated as an out-of-process
application.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspThreadGateSleepDelay
This metabase property specifies how long to defer thread requests, before the request is rechecked by
the IIS thread gating mechanism.
Important IIS performs thread gating to dynamically control the number of concurrently executing
threads, in response to varying load conditions. The default settings for this property, and the other
thread gating properties, are designed to be appropriate for the majority of server configurations and
traffic conditions. Changing these properties can lead to significant performance degradation.
The Web service setting for this property is applicable to all in-process application nodes, at all levels.
Metabase settings at the Web server level or lower will be ignored for in-process applications. However,
settings at the Web server level or lower will be used if that node is isolated as an out-of-process
application.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspThreadGateSleepMax
This metabase property specifies the maximum number of times a specific request can be put to sleep
(deferred) while IIS performs thread gating.
Important IIS performs thread gating to dynamically control the number of concurrently executing
threads, in response to varying load conditions. The default settings for this property, and the other
thread gating properties, are designed to be appropriate for the majority of server configurations and
traffic conditions. Changing these properties can lead to significant performance degradation.
The Web service setting for this property is applicable to all in-process application nodes, at all levels.
Metabase settings at the Web server level or lower will be ignored for in-process applications. However,
settings at the Web server level or lower will be used if that node is isolated as an out-of-process
application.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspThreadGateTimeSlice
This metabase property specifies how often the thread gating mechanism in IIS checks the CPU load.
Important IIS performs thread gating to dynamically control the number of concurrently executing
threads, in response to varying load conditions. The default settings for this property, and the other
thread gating properties, are designed to be appropriate for the majority of server configurations and
traffic conditions. Changing these properties can lead to significant performance degradation.
The Web service setting for this property is applicable to all in-process application nodes, at all levels.
Metabase settings at the Web server level or lower will be ignored for in-process applications. However,
settings at the Web server level or lower will be used if that node is isolated as an out-of-process
application.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AspTrackThreadingModel
This metabase property specifies whether IIS will check the threading model of any components that
your application instantiates.
Important It is usually best to leave this metabase property set to its default value (FALSE), so that
ASP will not use system resources to track the threading model. and your ASP application will usually
provide the best possible performance. If this property is set to FALSE, and you give Application scope
to components that you create, those components must aggregate the free-threaded marshaler. If you do
not aggregate the free-threaded marshaler, ASP will generate an error when you try to instantiate the
component. For more information about this topic, see Building Components for ASP.
Tip Another reason to leave this property at its default setting (FALSE), is that any objects instantiated
in your ASP application that lack the OnStartPage or OnEndPage method will be released earlier than
they would be otherwise. This should improve your application's scalability.
For more details on improving performance, see Developing Scalable ASP Applications .
Note In IIS 4.0, the default for this metabase property was TRUE.
The Web service setting for this property is applicable to all in-process application nodes, at all levels.
Metabase settings at the Web server level or lower will be ignored for in-process applications. However,
settings at the Web server level or lower will be used if that node is isolated as an out-of-process
application.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
AuthAnonymous
This property specifies anonymous authentication as one of the possible Windows authentication
schemes returned to clients as being available. AuthAnonymous is one of the authentication scheme
flags contained in the AuthFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AuthFlags
AuthBasic
This property specifies Basic authentication as one of the possible Windows authentication schemes
returned to clients as being available. AuthBasic is one of the authentication scheme flags contained in
the AuthFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AuthFlags
AuthFlags
This single property contains the settings for the Windows authentication schemes that will be returned to
clients as being available.
This single property contains the following file access permission flags:
Authanonymous
AuthBasic
AuthNTLM
Access Locations
The following tables list additional information required only for code that uses the IIS Admin Base
Object.
Bitmask Values
AuthNTLM
NTLM authentication) as one of the possible Windows authentication schemes returned to clients as
being available. AuthNTLM is one of the authentication scheme flags contained in the AuthFlags
property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AuthFlags
AuthPersistence
If the AuthPersistSingleRequest is set to TRUE, then authentication persists only for a single request.
If AuthPersistSingleRequestIfProxy is set to TRUE, then authentication persists only for a single
request if it is a proxy request and the request is not handled by Microsoft Proxy Server. (That is, if
Proxy Server and IIS are running on the local computer, and the request is targeted to a remote server.)
If AuthPersistSingleRequestAlwaysIfProxy is set to TRUE, then authentication is valid for a single
request if the request is by proxy.
Note Only one sub-flag of AuthPersistence can be TRUE at one time. The subflags are
AuthPersistSingleRequest, AuthPersistSingleRequestIfProxy, and
AuthPersistSingleRequestAlwaysIfProxy. When one of these three properties is set to TRUE, the
other two properties are automatically set to FALSE. The value of AuthPersistence always equals the
value of the sub-flag that is set to TRUE.
This single property contains the following file access permission flags. All permissions are applicable to
the Web service, servers, directories, and files. Only the AccessRead and AccessWrite permissions
are applicable for the FTP service, FTP servers, and FTP directories.
AuthPersistSingleRequest AuthPersistSingleRequestAlwaysIfProxy
AuthPersistSingleRequestIfProxy
Access Locations
The following tables list additional information required only for code that uses the IIS Admin Base
Object.
Bitmask Values
AuthPersistSingleRequest
This property specifies authentication will persist only across single requests on a connection. IIS will
reset the authentication at the end of each request, and force re-authentication on the next request of the
session.
All permissions are applicable to the Web service, servers, directories, and files. Only the AccessRead
and AccessWrite permissions are applicable for the FTP service, FTP servers, and FTP directories.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AuthPersistence
AuthPersistSingleRequestIfProxy
This property specifies authentication will persist only across single requests on a connection if the
connection is by proxy. IIS will reset the authentication at the end of the request if the current
authenticated request is by proxy and it is not the special case where IIS is running MSPROXY.
All permissions are applicable to the Web service, servers, directories, and files. Only the AccessRead
and AccessWrite permissions are applicable for the FTP service, FTP servers, and FTP directories.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AuthPersistence
AuthPersistSingleRequestAlwaysIfProxy
This property specifies that authentication is valid for a single request if by proxy. IIS will reset the
authentication at the end of the request and force re-authentication on the next request if the current
authenticated request is by proxy of any type.
All permissions are applicable to the Web service, servers, directories, and files. Only the AccessRead
and AccessWrite permissions are applicable for the FTP service, FTP servers, and FTP directories.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AuthPersistence
CacheControlCustom
This property specifies custom HTTP 1.1 cache control directives. Multiple directives can be specified if
they are separated by carriage return/line feed (CRLF) pairs. There should not be a trailing carriage
return/line feed after the final directive.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
CacheControlMaxAge
This property specifies the HTTP 1.1 cache control maximum age value. The range is 0 to
&HFFFFFFFF (-1 or unlimited) , measured in seconds.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
CacheControlNoCache
This property specifies the HTTP 1.1 directive to prevent caching of content.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
CacheISAPI
This property indicates whether ISAPI extensions are cached in memory after use. If the value of this
property is TRUE, the .dll file will remain in the cache until the server is stopped. If the value is FALSE,
extensions are unloaded from memory once the extension .dll is no longer in use.
ISAPI extensions are cached or not cached based on the value of this property at the time they were
loaded into memory for use. Thus, if this property is changed after an extension has been loaded and
cached, the change will have no effect on that extension.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
CertCheckMode
This property is used to enable or disable Certificate Revocation List (CRL) checking. When
CertCheckMode is set to zero (0) the CRL is not searched for certificates that have been revoked.
When CertCheckMode is greater than zero (CertCheckMode>0) the CRL will be searched for
certificates that have been revoked.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
CGITimeout
This property specifies the timeout in seconds for CGI applications. Its range is 10 to &H80000000 (2.1
million seconds).
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
ConnectionTimeout
This property specifies the time in seconds the server will wait before disconnecting an inactive
connection.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
ContentIndexed
This property specifies whether the content under this directory tree should be indexed by the installed
content indexer.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
CpuAppEnabled
This metabase property specifies whether process accounting and throttling should be performed for
ISAPI extensions and ASP applications. To perform process accounting on CGI applications, use the
property CpuCgiEnabled.
Note Because process accounting in IIS uses Windows Job Objects to monitor CPU times for an
entire process, process accounting will log and throttle only applications that are isolated in a separate
process from IIS.
Process throttling and process accounting are independently controlled by several other metabase
properties. In order to enable process accounting you must set CpuEnableLogging (which is a member
of CpuLoggingMask) to TRUE, and set at least one other CpuLoggingMask property to TRUE. It is
also necessary to set at least one member flag of the CpuLoggingOptions, set CpuLoggingInterval to
a nonzero value, and set either CpuAppEnabled or CpuCgiEnabled, as appropriate, to TRUE.
To properly activate process throttling, CpuLimitsEnabled must be set to TRUE, and at least one of
the following properties should be set to TRUE: CpuLimitLogEvent, CpuLimitPriority,
CpuLimitProcStop, CpuLimitPause.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
CpuCgiEnabled
This metabase property indicates whether IIS should perform process accounting for CGI applications.
To effectively throttle CGI applications, use the CgiTimeout property. To use process accounting for
ISAPI and ASP applications, use CpuAppEnabled.
Note Because process accounting in IIS uses Windows Job Objects to monitor CPU times for an
entire process, process accounting will log and throttle only applications that are isolated in a separate
process from IIS.
Process throttling and process accounting are independently controlled by several other metabase
properties. In order to enable process accounting you must set CpuEnableLogging (which is a member
of CpuLoggingMask) to TRUE, and set at least one other CpuLoggingMask property to TRUE. It is
also necessary to set at least one member flag of the CpuLoggingOptions, set CpuLoggingInterval to
a nonzero value, and set either CpuAppEnabled or CpuCgiEnabled, as appropriate, to TRUE.
To properly activate process throttling, CpuLimitsEnabled must be set to TRUE, and at least one of
the following properties should be set to TRUE: CpuLimitLogEvent, CpuLimitPriority,
CpuLimitProcStop, CpuLimitPause.
Access Locations
/LM/W3SVC/N/ROOT/WebVirtualDir/WebDirectory/WebFile IIsWebFile
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
CpuCgiLimit
When set to a value other than zero, this property limits the time in seconds that a CGI script is allowed
to be in process. When set to zero, the process time is unlimited.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
ScriptTimeout
CpuEnableActiveProcs
This property indicates whether the total number of active processes is recorded when process
accounting is performed.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
CpuLoggingMask
CpuEnableAllProcLogging
This property indicates whether IIS should log total CPU times for all out-of-process ISAPI extensions
and ASP and CGI applications. For more information, see CpuLoggingOptions.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
CpuLoggingOptions
CpuEnableAppLogging
This property indicates whether IIS should log out-of-process ISAPI extensions and ASP applications.
For more information, see CpuLoggingOptions.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
CpuLoggingOptions
CpuEnableCgiLogging
This property indicates whether IIS should log total CPU times for CGI applications. For more
information, see CpuLoggingOptions.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
CpuLoggingOptions
CpuEnableEvent
This property indicates whether the event that triggered the creation of a log record is specified in the log
record itself. For more information, see CpuLoggingMask.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
CpuLoggingMask
CpuEnableKernelTime
This property indicates whether total kernel-mode CPU time is recorded when process accounting is
performed. For more information, see CpuLoggingMask.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
CpuLoggingMask
CpuEnableLogging
This property specifies whether process accounting is enabled for the Web service or server. Process
accounting can log the amount of CPU time that is taken by a Web server or service, as well as any
process throttling events that might occur. For more information, see CpuLoggingMask.
Note Because process accounting in IIS uses Windows Job Objects to monitor CPU times for an
entire process, process accounting will log and throttle only applications that are isolated in a separate
process from IIS.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
CpuLoggingMask
CpuEnablePageFaults
This property indicates whether the total number of page faults is recorded when process accounting is
performed. For more information, see CpuLoggingMask.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
CpuLoggingMask
CpuEnableProcType
This property indicates whether process type is recorded when process accounting is performed. For
more information, see CpuLoggingMask.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
CpuLoggingMask
CpuEnableTerminatedProcs
This property indicates whether the total number of terminated processes is recorded when process
accounting is performed. For more information, see CpuLoggingMask.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
CpuLoggingMask
CpuEnableTotalProcs
This property indicates whether the total number of processes is recorded when process accounting is
performed. For more information, see CpuLoggingMask.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
CpuLoggingMask
CpuEnableUserTime
This property indicates whether total user-mode CPU time is recorded when process accounting is
performed. For more information, see CpuLoggingMask.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
CpuLoggingMask
CpuLimitLogEvent
This metabase property specifies the percentage of CPU time, in 1/1000ths of a percent, that all isolated
processes on the Web server are allowed to occupy during a given process accounting interval (specified
by CpuResetInterval). If the processes attempt to occupy more CPU time than specified in
CpuLimitLogEvent, a note will be made in the Windows Event Log that the processes have exceeded
the limits. If process accounting is enabled, the limit overrun will also be entered into the IIS log.
If CpuLimitLogEvent is set to 0, or a value greater than 100,000 (100 percent), IIS will not log any
events against the process. However, one of the other process throttling properties, such as
CpuLimitPriority, CpuLimitProcStop, or CpuLimitPause, could generate a response from IIS if a
CPU limit is exceeded.
Note Because process accounting in IIS uses Windows Job Objects to monitor CPU times for an
entire process, process accounting will log and throttle only applications that are isolated in a separate
process from IIS.
Process throttling and process accounting are independently controlled by several other metabase
properties. In order to enable process accounting, you must set CpuEnableLogging (which is a
member of CpuLoggingMask) to TRUE, and set at least one other CpuLoggingMask property to
TRUE. It is also necessary to set at least one flag of CpuLoggingOptions, set CpuLoggingInterval to
a nonzero value, and set either CpuAppEnabled or CpuCgiEnabled, as appropriate, to TRUE.
To properly activate process throttling, CpuLimitsEnabled must be set to TRUE, and at least one of
the following properties should be set to TRUE: CpuLimitLogEvent, CpuLimitPriority,
CpuLimitProcStop, or CpuLimitPause.
Important Applications that do not have process throttling enabled do not contribute to the total CPU
time for the purposes of calculating CPU limit overruns.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
CpuLimitPause
This metabase property specifies the percentage of CPU time, in 1/1000ths of a percent, that all isolated
processes on the Web server can occupy during a given process accounting interval (specified by
CpuResetInterval). If the processes attempt to occupy more CPU time than specified in
CpuLimitPause, IIS will pause the entire site, and any new client requests will receive a custom error
indicating that the server is out of resources. The site will remain in a paused state until the current reset
interval has ended. Any limit overrun will be recorded in the Windows Event Log, and, if process
accounting is enabled, in the IIS log as well.
If CpuLimitPause is set to 0, or a value greater than 100,000 (100 percent), IIS will not pause the site.
However, one of the other process throttling properties, such as CpuLimitLogEvent,
CpuLimitPriority, or CpuLimitProcStop, could generate a response from IIS if a CPU limit is
exceeded.
Note Because process accounting in IIS uses Windows Job Objects to monitor CPU times for an
entire process, process accounting will log and throttle only applications that are isolated in a separate
process from IIS.
Process throttling and process accounting are independently controlled by several other metabase
properties. In order to enable process accounting you must set CpuEnableLogging (which is a member
of CpuLoggingMask) to TRUE, and set at least one other CpuLoggingMask property to TRUE. It is
also necessary to set at least one member flag of the CpuLoggingOptions, set CpuLoggingInterval to
a nonzero value, and set either CpuAppEnabled or CpuCgiEnabled, as appropriate, to TRUE.
To properly activate process throttling, CpuLimitsEnabled must be set to TRUE, and at least one of
the following properties should be set to TRUE: CpuLimitLogEvent, CpuLimitPriority,
CpuLimitProcStop, or CpuLimitPause.
Important Applications that do not have process throttling enabled do not contribute to the total CPU
time for the purposes of calculating CPU limit overruns.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
CpuLimitPriority
This metabase property specifies the percentage of CPU time, in 1/1000ths of a percent, that all isolated
processes on the Web server can occupy during a given process accounting interval (specified by
CpuResetInterval). If the processes attempt to occupy more CPU time than specified in
CpuLimitPriority, all processes for that server will be set to Idle Class priority until the next process
accounting reset. Any new processes on that server will also be set to Idle Class priority. Any limit
overrun will be recorded in the Windows Event Log, and, if process accounting is enabled, in the IIS log
as well.
If CpuLimitPriority is set to 0, or a value greater than 100,000 (100 percent), IIS will take change the
priority of any of the process' threads. However, one of the other process throttling properties, such as
CpuLimitLogEvent, CpuLimitProcStop, or CpuLimitPause, could generate a response from IIS if a
Note Because process accounting in IIS uses Windows Job Objects to monitor CPU times for an
entire process, process accounting will log and throttle only applications that are isolated in a separate
process from IIS.
Process throttling and process accounting are independently controlled by several other metabase
properties. In order to enable process accounting you must set CpuEnableLogging (which is a member
of CpuLoggingMask) to TRUE, and set at least one other CpuLoggingMask property to TRUE. It is
also necessary to set at least one member flag of the CpuLoggingOptions, set CpuLoggingInterval to
a nonzero value, and set either CpuAppEnabled or CpuCgiEnabled, as appropriate, to TRUE.
To properly activate process throttling, CpuLimitsEnabled must be set to TRUE, and at least one of
the following properties should be set to TRUE: CpuLimitLogEvent, CpuLimitPriority,
CpuLimitProcStop, or CpuLimitPause.
Important Applications that do not have process throttling enabled do not contribute to the total CPU
time, for the purposes of calculating CPU limit overruns.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
CpuLimitProcStop
This metabase property specifies the percentage of CPU time, in 1/1000ths of a percent, that all isolated
processes on the Web server may occupy during a given process accounting interval (specified by
CpuResetInterval). If the isolated processes attempt to occupy more CPU time than specified in
CpuLimitProcStop, IIS halts all isolated processes on that site affected by Process Throttling.
Processes terminated due to limit overruns will not be allowed to restart until the next CPU interval reset.
Any limit overrun will be recorded in the Windows Event Log, and, if process accounting is enabled, in
the IIS log as well.
If CpuLimitProcStop is set to 0, or a value greater than 100,000 (100 percent), IIS will not stop the
process. However, one of the other process throttling properties, such as CpuLimitLogEvent,
CpuLimitPriority, or CpuLimitPause, could generate a response from IIS if a CPU limit is exceeded.
Note Because process accounting in IIS uses Windows Job Objects to monitor CPU times for an
entire process, process accounting will log and throttle only applications that are isolated in a separate
process from IIS.
Process throttling and process accounting are independently controlled by several other metabase
properties. In order to enable process accounting you must set CpuEnableLogging (which is a member
of CpuLoggingMask) to TRUE, and set at least one other CpuLoggingMask property to TRUE. It is
also necessary to set at least one member flag of the CpuLoggingOptions, set CpuLoggingInterval to
a nonzero value, and set either CpuAppEnabled or CpuCgiEnabled, as appropriate, to TRUE.
To properly activate process throttling, CpuLimitsEnabled must be set to TRUE, and at least one of
the following properties should be set to TRUE: CpuLimitLogEvent, CpuLimitPriority, or
CpuLimitProcStop, CpuLimitPause.
Important Applications that do not have process throttling enabled do not contribute to the total CPU
time, for the purposes of calculating CPU limit overruns.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
CpuLimitsEnabled
This metabase property specifies whether process throttling is enabled, Process throttling can be enabled
for an individual virtual server, or for the Web service overall, to limit the amount of CPU time used.
Note Because process accounting in IIS uses Windows Job Objects to monitor CPU times for an
entire process, process accounting will log and throttle only applications that are isolated in a separate
process from IIS.
Process throttling and accounting are independently controlled by several other metabase properties. In
order to enable process accounting you must set CpuEnableLogging (which is a member of
CpuLoggingMask) to TRUE, and set at least one other CpuLoggingMask property to TRUE. It is
also necessary to set at least one member flag of the CpuLoggingOptions, set CpuLoggingInterval to
a nonzero value, and set either CpuAppEnabled or CpuCgiEnabled, as appropriate, to TRUE.
To properly activate process throttling, CpuLimitsEnabled must be set to TRUE, and at least one of
the following properties should be set to TRUE: CpuLimitLogEvent, CpuLimitPriority,
CpuLimitProcStop, or CpuLimitPause.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
CpuLoggingInterval
This metabase property specifies the logging interval for process accounting and throttling activity, in
minutes. If process accounting is enabled and activated, IIS will write a summary of the process
accounting information to the log file at the end of each interval specified by CpuLoggingInterval.
Important For process accounting to work properly, you must be sure to set the property
CpuLoggingInterval to a value less than that specified by CpuResetInterval. If
CpuLoggingInterval is greater than CpuResetInterval, IIS will reset counters and the logging timer
before the logging interval has elapsed, and process accounting will never occur.
Note Because process accounting in IIS uses Windows Job Objects to monitor CPU times for an
entire process, process accounting will log and throttle only applications that are isolated in a separate
process from IIS.
Process throttling and process accounting are independently controlled by several other metabase
properties. In order to enable process accounting you must set CpuEnableLogging (which is a member
of CpuLoggingMask) to TRUE, and set at least one other CpuLoggingMask property to TRUE. It is
also necessary to set at least one member flag of the CpuLoggingOptions, set CpuLoggingInterval to
a nonzero value, and set either CpuAppEnabled or CpuCgiEnabled, as appropriate, to TRUE.
To properly activate process throttling, CpuLimitsEnabled must be set to TRUE, and at least one of
the following properties should be set to TRUE: CpuLimitLogEvent, CpuLimitPriority, or
CpuLimitProcStop, CpuLimitPause.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
CpuLoggingMask
This metabase property specifies which process accounting and throttling fields should be written to the
IIS log file. All enabled fields will be written on every process accounting log. All values logged are for
the reset interval in which the logging occurs.
Note Because process accounting in IIS uses Windows Job Objects to monitor CPU times for an
entire process, process accounting will log and throttle only applications that are isolated in a separate
process from IIS.
CpuEnableLogging CpuEnableProcType
CpuEnableActiveProcs CpuEnableTerminatedProcs
CpuEnableEvent CpuEnableTotalProcs
CpuEnableKernelTime CpuEnableUserTime
CpuEnablePageFaults
You can also change the logging mask flags by directly manipulating the flags contained in
CpuLoggingMask by using the hexadecimal values described in the following tables.
Process throttling and process accounting are independently controlled by several other metabase
properties. In order to enable process accounting you must set CpuEnableLogging (which is a member
of CpuLoggingMask) to TRUE, and set at least one other CpuLoggingMask property to TRUE. It is
also necessary to set at least one member flag of the CpuLoggingOptions, set to a nonzero value, and
set either CpuAppEnabled or CpuCgiEnabled, as appropriate, to TRUE.
To properly activate process throttling, CpuLimitsEnabled must be set to TRUE, and at least one of
the following properties should be set to TRUE: CpuLimitLogEvent, CpuLimitPriority,
CpuLimitProcStop, or CpuLimitPause.
Access Locations
The following tables list additional information required only for code that uses the IIS Admin Base
Object.
MD_CPU_ENABLE_PROC_TYPE
MD_CPU_ENABLE_USER_TIME
MD_CPU_ENABLE_KERNEL_TIME
MD_CPU_ENABLE_PAGE_FAULTS
MD_CPU_ENABLE_TOTAL_PROCS
MD_CPU_ENABLE_ACTIVE_PROCS
MD_CPU_ENABLE_TERMINATED_PROCS
Default bitmask value 0x800000FF
Bitmask Values
CpuLoggingOptions
This metabase property contains flags that specify how IIS should log CPU times for services, servers,
or applications. You can use this property to configure IIS to sum the CPU times of CGI applications
only, of ISAPI extensions and ASP applications only, or of all applications.
Note Because process accounting in IIS uses Windows Job Objects to monitor CPU times for an
entire process, process accounting will log and throttle only applications that are isolated in a separate
process from IIS.
You can also directly manipulate the bit flags within CpuLoggingOptions by using the hexadecimal
values in the following Bitmask Values table.
Process throttling and process accounting are independently controlled by several other metabase
properties. In order to enable process accounting you must set CpuEnableLogging (which is a member
of CpuLoggingMask) to TRUE, and set at least one other CpuLoggingMask property to TRUE. It is
also necessary to set at least one member flag of the CpuLoggingOptions, set CpuLoggingInterval to
a nonzero value, and set either CpuAppEnabled or CpuCgiEnabled, as appropriate, to TRUE.
To properly activate process throttling, CpuLimitsEnabled must be set to TRUE, and at least one of
CpuEnableAppLogging CpuEnableAllProcLogging
CpuEnableCgiLogging
Access Locations
The following tables list additional information required only for code that uses the IIS Admin Base
Object.
Bitmask Values
CpuResetInterval
This metabase property specifies the reset period for process accounting and process throttling limits on
the server or service. When the number of minutes elapsed since the last process accounting reset equals
the number specified by this property, IIS will reset the CPU timers for both the logging and limit
intervals.
Important If you want IIS to log process accounting information to a log file, you must be sure to set
the property CpuLoggingInterval to a value less than that specified by CpuResetInterval. If
CpuLoggingInterval is greater than CpuResetInterval, IIS will reset counters and the logging timer
before the logging interval has elapsed, and process accounting will never occur.
Note Because process accounting in IIS uses Windows Job Objects to monitor CPU times for an
entire process, process accounting will log and throttle only applications that are isolated in a separate
process from IIS.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
CreateCGIWithNewConsole
This property indicates whether a CGI application runs in its own console. If the value is TRUE, each
CGI application creates a new console when started. A value of FALSE indicates that CGI applications
should run without a console.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
CreateProcessAsUser
This property specifies whether a CGI process will be created in the system context or in the context of
the requesting user.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
CustomErrorDescriptions
This property contains a list of custom error messages. Each string in the list specifies an error code and
subcode for the custom message; what the specific error text and subcode error text is to be; and
whether the custom message is supported by file or URL, or just by file only. Each string is in the format
ErrorCode, ErrorSubcode, ErrorText, ErrorSubcodeText, followed by another comma and either a 0
for file and URL support, or a 1 for file support only.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
HttpErrors
DefaultDoc
This property contains one or more file names of default documents that will be returned to the client if no
file name is included in the client's request. The default document will be returned if the
EnableDefaultDoc property is TRUE for the directory. This property can contain a list of default
document file names separated by a comma and a space, for example Default1.htm, Default2.htm.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
Remarks
If the EnableDefaultDoc flag is not set in the DirBrowseFlags property, the server will not search for
a default document.
See Also
DirBrowseFlags
DefaultDocFooter
This value specifies the custom footer that is appended to files returned to the client. The custom footer
will be sent only if the EnableDocFooter property is TRUE. The footer can be a string such as "This is a
custom footer," or a reference to a file such as C:\Wwwroot\Footers\Footer.htm.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
Remarks
If the EnableDefaultDoc flag is not set in the DirBrowseFlags identifier, the server will not search for
a default document.
See Also
EnableDocFooter
DefaultLogonDomain
This property specifies the default domain for logon. If this value is not specified, the default domain will
be the domain name controlled by the computer, if the computer is a domain controller. If the computer
is not a domain controller, the default domain will be the computer name.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
DirBrowseFlags
This property contains flags that control whether directory browsing is enabled, how much directory and
file information is provided if browsing is enabled, and whether there is a default page in the directory.
Note If a client accesses the directory and does not provide a file name, and the EnableDefaultDoc
flag is set to TRUE, the server will look for the file specified in the property DefaultDoc. If the default
file does not exist in the directory, and the EnableDirBrowsing flag is set to TRUE, then directory
browsing is enabled.
DirBrowseShowDate DirBrowseShowTime
DirBrowseShowExtension EnableDefaultDoc
DirBrowseShowLongDate EnableDirBrowsing
DirBrowseShowSize
Access Locations
/LM/W3SVC/N/ROOT/WebVirtualDir/WebDirectory IIsWebDirectory
The following tables list additional information required only for code that uses the IIS Admin Base
Object.
MD_DIRBROW_SHOW_TIME
MD_DIRBROW_SHOW_SIZE
MD_DIRBROW_SHOW_EXTENSION
MD_DIRBROW_LOADDEFAULT
Default bitmask value 0x4000001E
Bitmask Values
DirBrowseShowDate
This property specifies that date information will be displayed when browsing directories.
DirBrowseShowDate is one of the settings contained in the DirBrowseFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
DirBrowseFlags
DirBrowseShowExtension
This property specifies that file name extensions will be displayed when browsing directories.
DirBrowseShowExtension is one of the settings contained in the DirBrowseFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
DirBrowseFlags
DirBrowseShowLongDate
This property specifies that date information will be displayed in extended format when displaying
directories. DirBrowseShowLongDate is one of the settings contained in the DirBrowseFlags
property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
DirBrowseFlags
DirBrowseShowSize
This property specifies that file size information will be displayed when browsing directories.
DirBrowseShowSize is one of the settings contained in the DirBrowseFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
DirBrowseFlags
DirBrowseShowTime
This property specifies that file time information will be displayed when displaying directories.
DirBrowseShowTime is one of the settings contained in the DirBrowseFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
DirBrowseFlags
DirectoryLevelsToScan
This property specifies the number of virtual directory levels to scan in the metabase from the top of the
tree (that is, the root virtual directory for a server) to build a list of directories to be monitored for file
system changes. The valid range is 0 to 0xFFFFFFFF (unlimited). If a virtual directory is not included in
the list, then the IIS cache will not be flushed when a file change occurs in the directory. This list is also
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
DisableSocketPooling
This property specifies whether socket pooling is used for sites distinguished by IP address (rather than
port number or host header name, for example). If DisableSocketPooling is set to FALSE, then socket
pooling is enabled and sockets are shared between sites that use the same socket number (but different
IP addresses). If DisableSocketPooling is set to TRUE, then there is no socket sharing for sites based
on IP address.
In IIS version 4.0, each Web site was bound to a different IP address, which meant that each site had its
own socket that was not shared with sites bound to other IP addresses. These sockets are created when
the site starts, and they consume significant nonpaged memory (RAM). This memory consumption limits
the number of sites bound to IP addresses that can be created on a single machine.
By default, socket pooling is enabled. In general, this behavior should not be modified. If changed, the
change should be made at the site level only so that other sites can continue to take advantage of the
socket pooling feature.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
DontLog
This property specifies whether client requests should be written to the log file. By default (FALSE),
requests are written to the file. You can set this value to TRUE to turn logging off.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogType
DownlevelAdminInstance
This property indicates the server instance for remote administration clients.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AdminServer
EnableDefaultDoc
This property specifies that the default document (specified by the DefaultDoc property) for a directory
will be loaded when the directory is being browsed. EnableDefaultDoc is one of the settings contained
in the DirBrowseFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
DirBrowseFlags
EnableDirBrowsing
This property specifies that directory browsing is enabled. EnableDirBrowsing is one of the settings
contained in the DirBrowseFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
DirBrowseFlags
EnableDocFooter
This property enables or disables custom footers specified by the DefaultDocFooter property. Higher
performance will be achieved if custom footers are disabled.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
DefaultDocFooter
EnableReverseDns
This property enables or disables reverse Domain Name Server (DNS) lookups (reverse lookups
involve finding the domain name from an IP address). Reverse DNS lookups can use significant
resources and time.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
ExitMessage
This property specifies the message text an FTP server will transmit to a client when the client sends a
quit command.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
FilterDescription
This property holds a string, which serves as the description for the corresponding filter.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
FilterEnabled
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
FilterFlags
This property contains flags that indicate which events the ISAPI filter has registered to be notified for.
This property, and all its component flags, should be considered read-only. For more information, see
Developing ISAPI Filters .
Access Locations
The following tables list additional information required only for code that uses the IIS Admin Base
Object.
Bitmask Values
FilterLoadOrder
This property, a comma-delimited list, specifies the order in which filters are to be loaded, such as
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
FilterPath
This property specifies the full path to a filter DLL; for example C:\Wwwroot\Bin\Filter.dll.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
FilterState
This property indicates whether the filter is loaded (value 1) or unloaded (value 4). This property is read-
only.
Access Locations
The following tables list additional information required only for code that uses the IIS Admin Base
Object.
Bitmask values
FrontPageWeb
This property indicates whether this server instance will be targeted by Microsoft® FrontPage ®. Setting
this value to TRUE causes the FrontPage Manager to create the files required for FrontPage Server
Extensions. Setting this value to FALSE causes these files to be deleted.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
FtpDirBrowseShowLongDate
This property indicates whether or not to display two-digit or four-digit years when browsing directories.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
GreetingMessage
This property contains a greeting message (in a multiple-line string) that can be sent to new clients from
an FTP server.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HcCacheControlHeader
This metabase property specifies the directive that IIS will add to the Cache-Control header. This
header, along with the Expires header specified by HcExpiresHeader, is sent with every compressed
file that is sent to a client browser.
This property specifies a header that overrides the HTTP Expires header specified by
HcExpiresHeader, and is included to ensure that older clients and proxy servers will not attempt to
cache compressed files.
The Web service must be restarted before any changes to this property take effect.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HcCompressionBufferSize
This metabase property specifies the size of the buffer, in bytes, that IIS will use for receiving
compressed data. This buffer is used for both on-demand compression of static content, as well dynamic
content compression. A larger buffer will yield slightly faster compression performance, but at the cost of
additional memory usage.
The Web service must be restarted before any changes to this property take effect.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HcCompressionDirectory
This metabase property specifies the directory where compressed versions of static files are temporarily
cached. If compression is enabled for IIS, every time IIS receives a request for a static file (such as
an .htm or .txt file), the server searches the compression directory for an already-compressed version of
the static file being requested.
To force IIS to recompress all outgoing static files, erase all files found in the compression directory
specified by HcCompressionDirectory.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
HcDoOnDemandCompression
HcCompressionDll
This metabase property specifies the fully qualified file system path and file name of the compression
DLL associated with the compression scheme.
The Web service must be restarted before any changes to this property take effect.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HcCreateFlags
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HcDoDiskSpaceLimiting
This metabase property allows you to limit the amount of disk space that compressed files (stored in the
compression directory specified by HcCompressionDirectory) can occupy. If this property is set to
TRUE, then IIS will not occupy more than the number of bytes specified by HcMaxDiskSpaceUsage
with compressed files. Once the limit is reached, compressed files are removed from the compression
directory on a least-recently used (LRU) basis. If HcDoDiskSpaceLimiting is set to FALSE, IIS
enforces no limit to the amount of disk space that the files in the compression directory can occupy.
Tip Limiting the use of disk space has a significant impact on performance because additional overhead
is required to check for the limit. Use this feature only if it is necessary.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HcDoDynamicCompression
This property specifies whether compression of responses to requests for dynamic content, such as the
output of ASP scripts and ISAPI extensions, is enabled. At the global level,
HcDoDynamicCompression indicates that all dynamic content will be compressed as it is requested.
Important Because dynamic content is by definition changeable, IIS does not cache compressed
versions of dynamic output. Thus, if dynamic compression is enabled, each and every response to
requests for dynamic content will have to be compressed each time. Dynamic compression consumes
considerable CPU time and memory resources, and it should only be used on servers that have slow
networks, but CPU power to spare.
If you change the value of this property at the individual compression scheme level, the Web service will
need to be restarted for the change to take effect.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HcDoOnDemandCompression
This metabase property specifies whether static files, such as .htm and .txt files, will be compressed if no
compressed version of the file exists in the compression directory specified by
HcCompressionDirectory.
At a global level, if this property is set to TRUE, and IIS receives a request for static content, IIS will
check the compression directory. If no corresponding compressed version of the requested file is found,
IIS will send an uncompressed version of the requested file to the client browser while a background
thread compresses the file. The newly compressed file will then be stored in the compression directory,
and subsequent responses to requests for that file will be serviced directly from the directory. If
HcDoOnDemandCompression is set to FALSE at a global level, however, IIS will not compress
static content files for which it finds no corresponding compressed version in the compression directory.
In other words, an uncompressed version of the file will be returned for every request unless a
compressed version of the file already exists in the compression directory.
If you change the value of this property at the individual compression scheme level, the Web service will
need to be restarted for the change to take effect.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HcDoStaticCompression
This metabase property specifies whether responses to requests for static content will be compressed by
IIS. At the global level, HcDoStaticCompression indicates that IIS will respond to requests for static
content (such as .htm and .txt files) first by checking the compression directory specified by
HcCompressionDirectory. If a compressed version of the static file is found in the directory, it will be
sent to the client browser. Otherwise, if on-demand compression is enabled with
HcDoOnDemandCompression, IIS will send the requested file in uncompressed form, and add that
file to the background compression queue.
At the individual compression scheme level, HcDoStaticCompression indicates whether the individual
compression scheme supports compression of static files.
If you change the value of this property at the individual compression scheme level, the Web service must
be restarted for the change to take effect.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HcDynamicCompressionLevel
This metabase property specifies the compression level for the compression scheme, when the scheme is
compressing dynamic content. Low compression levels produce slightly larger compressed files, but with
lower overall impact on CPU and memory resources. Higher compression levels generally result in
smaller compressed files but higher CPU and memory usage.
The Web service must be restarted for any changes to this property take effect.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HcExpiresHeader
This metabase property specifies the content of the HTTP Expires header that is sent with all requested
compressed files, along with the Cache-Control header discussed in HcCacheControlHeader.
The combination of HcExpiresHeader and HcCacheControlHeader ensure that older clients and
proxy servers will not attempt to cache compressed files.
The Web service must be restarted for any changes to this property take effect.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HcFileExtensions
This property indicates which file name extensions are supported by the compression scheme. Only static
files with the specified file extensions will be compressed by IIS. If this setting is empty, then the scheme
supports all file name extensions.
The Web service must be restarted for any changes to this property take effect.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
HcScriptFileExtensions
HcFilesDeletedPerDiskFree
This metabase property specifies the number of compressed files that are deleted from the compression
directory when IIS determines that the compression directory has grown beyond its limits. IIS will delete
a number of files equal to the setting of this property, starting with the least-recently used files.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HcIoBufferSize
This metabase property specifies the size of the buffer, in bytes, that IIS will use to read uncompressed
files. A larger buffer will yield slightly faster compression performance, but at the cost of additional
memory usage.
The Web service must be restarted before any changes to this property take effect.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HcMaxDiskSpaceUsage
This metabase property specifies whether IIS will limit the number of bytes of disk space occupied by
compressed file in the compression directory.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HcMaxQueueLength
IIS performs on-demand compression of static content in the background. When a static file is
requested, and IIS has determined that a previously compressed version of the requested file does not
already exist in the compression directory, the request is put into a simple FIFO (first in, first out) queue.
HcMaxQueueLength specifies how many concurrent background compression requests can be in the
queue. If the queue is full, additional compression requests are ignored until there is room in the queue.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HcMimeType
This property indicates which MIME types are supported by the compression scheme. Only static files
with the specified MIME type will be compressed by IIS. If this setting is empty, then the scheme
supports all MIME types.
The Web service must be restarted before any changes to this property take effect.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HcMinFileSizeForComp
This property allows you to specify the minimum number of bytes a file must contain for it to be
compressed using on-demand compression. Very small files do not compress well, and in some cases
compression may even make the file larger than it was initially.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HcNoCompressionForHttp10
This metabase property disables compression for requests containing an HTTP 1.0 version number.
HTTP 1.0, as described in RFC 1945, provides a minimal level of support for certain types of
compression. However, some confusion exists around HTTP 1.0 compression, especially with regard to
proxy servers. In order to minimize the chance of inappropriately returning a compressed file to a client
that cannot decompress the file, you can use this metabase property to disable compression in
questionable scenarios.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HcNoCompressionForProxies
This metabase property allows you to disable the HTTP 1.1 response for compression requests that
have come through proxy servers. Certain HTTP proxy servers, including some advertised as HTTP
1.1-compliant, do not handle the caching of compressed objects correctly.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HcNoCompressionForRange
This metabase property specifies how IIS handles HTTP Range requests. The HTTP 1.1 RFC, RFC
2068, is ambiguous about whether Range requests should apply to the compressed or uncompressed
version of a file. It is possible that some browsers could be unprepared for compressed Range
responses, so IIS defaults to not sending compressed responses to Range requests, to avoid problems
with browser misbehavior.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HcOnDemandCompLevel
This metabase property specifies the compression level for the compression scheme, when the scheme is
to compress static content on demand. Low compression levels produce slightly larger compressed files,
but with lower overall impact on CPU and memory resources. Higher compression levels generally result
in small compressed files but higher CPU and memory usage.
The Web service must be restarted before any changes to this property take effect.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
HcDynamicCompressionLevel
HcPriority
This metabase property specifies the priority rating assigned to a particular compression scheme. If your
installation of IIS has multiple compression schemes installed, and a client browser indicates (in the
Accept-Encoding header) that it can handle multiple compression schemes, IIS uses the priority numbers
specified in HcPriority to determine which scheme to use for the request. In that case, IIS will use the
matching scheme that has the highest priority number.
Valid priority numbers can be from 1 to 10. In general, if you have multiple compression schemes
installed with IIS, you should assign each compression scheme a different priority number.
The Web service must be restarted before any changes to this property take effect.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HcSendCacheHeaders
This metabase property specifies whether the headers specified by HcCacheControlHeader and
HcExpiresHeader are sent with each compressed response. If this property is set to TRUE, Cache-
Control and Expires headers are sent with all compressed responses. If this property is set to FALSE,
however, only the HTTP 1.1 Vary header will be sent with the compressed response.
Important In general, the Cache-Control and Expires HTTP headers are included with compressed
responses to prevent inappropriate caching of compressed files, especially by proxy servers and older
browsers. If you choose to disable these headers, it is recommended that you also set
HcNoCompressionForProxies and HcNoCompressionForHttp10 to TRUE.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HcScriptFileExtensions
This property indicates which file name extensions are supported by the compression scheme. Only
dynamic files with the specified file extensions will be compressed by IIS. If this setting is empty, then the
scheme supports all file name extensions.
The Web service must be restarted for any changes to this property take effect.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
HcFileExtensions
HttpCustomHeaders
This property contains custom headers that are sent to the client in addition to the default header of the
HTML file. Each string in this property is formatted as a key name and value pair: Keyname, Value.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HttpErrors
This property specifies the custom error string to be sent to clients in response to HTTP 1.1 errors. Each
string in the list specifies the HTTP error code and subcode, indicates whether the handler will be a URL
or a file, and specifies which URL or file the client will be sent. Each string can be in either format. To
send a URL to the client, use HTTPErrorCode, HTTPErrorSubcode, URL, HandlerURL. To send a
file, use HTTPErrorCode, HTTPErrorSubcode, FILE, Filename.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
CustomErrorDescriptions
HttpExpires
This property specifies the expiration of HTML document content by returning the value to the browser
in the HTML file header. The browser compares the value of this property with the current date to
determine whether to display a cached page or to request an updated page from the server. This
property can be made relative, or dynamic, by using the format D,#SecondsUntilExpiration (with
0xFFFFFFFF indicating no expiration date). It can also be absolute, with the format
S,ValidGMTString.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HttpPics
This property specifies the World Wide Web Consortium (W3C) Platform for Internet Content
Selection (PICS) rating header. For more information on PICS, see the W3C Web site.
Access Locations
/LM/W3SVC/N/ROOT/WebVirtualDir/WebDirectory IIsWebDirectory
/LM/W3SVC/N/ROOT/WebVirtualDir/WebDirectory/WebFile IIsWebFile
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
HttpRedirect
This property specifies the directory or URL to which a client is redirected when the client attempts to
access a specific resource. There are two general forms that the value for this property can take.
The simple format is Destination, Flag, where Destination can specify either a URL or a virtual path to
a file. Flag can have one of three values: EXACT_DESTINATION indicates that the value provided for
Destination should be considered an absolute target location; CHILD_ONLY indicates that the value
should be added to the beginning of the file name of the request to be redirected; and PERMANENT
indicates that this redirection will be permanent for this resource.
The more complex form of specification for this property involves the use of wildcards. The format is *;
Wildcard1; Destination1; Wildcard2; Destination2, Flag. Each Wildcard; Destination pair indicates
that requests matching the wildcard are redirected to the specified destination. Flag can have the same
values as the simple string format.
Access Locations
/LM/W3SVC/N/ROOT/WebVirtualDir IIsWebVirtualDir
/LM/W3SVC/N/ROOT/WebVirtualDir/WebDirectory IIsWebDirectory
/LM/W3SVC/N/ROOT/WebVirtualDir/WebDirectory/WebFile IIsWebFile
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
InProcessIsapiApps
This property specifies a list of ISAPI filters and extensions that must be run in the Web server process.
The string format is either Fullpath\Appname.dll, or just Appname.dll. ISAPI DLL entries without a
qualifying path will match any ISAPI request that contains the DLL name, regardless of the physical path
specified in the request.
For example, any of the following would be a valid list for the property: "D:\winnt\system32
\inetsrv\ssinc.dll" "D:\winnt\system32\inetsrv\httpodbc.dll" "author.dll" "shtml.dll" "admin.dll."
ssinc.dll
Inheritance Inheritable
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
Remarks
This property indicates only which ISAPI applications are required to run in-process. The inclusion of an
application in this list does not imply that the application is automatically run at server startup. Note that
there can be significant performance issues if too many applications are forced to run outside of the
server process.
See Also
AppIsolated
IPSecurity
This property specifies the IP access restrictions for a URL. It can be used to grant or deny access to
browsers based on either their IP address or DNS host name.
Note For a more detailed explanation for this object, see IIsIPSecurity.
Access Locations
/LM/W3SVC/N/ROOT IIsWebVirtualDir
/LM/W3SVC/N/ROOT/WebVirtualDir IIsWebVirtualDir
/LM/W3SVC/N/ROOT/WebVirtualDir/WebDirectory IIsWebDirectory
/LM/W3SVC/N/ROOT/WebVirtualDir/WebDirectory/WebFile IIsWebFile
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
IIsIPSecurity
KeyType
The KeyType property specifies the type of a metabase key, and the IIS Admin Object that relates to
that key. The KeyType property is used to specify the class of the object associated with the key, such
as IIsWebServer or IIsWebVirtualDir. The KeyType determines the set of properties accessible at
the key.
Remarks
The KeyType property is accessible by all IIS Admin Objects. The value is the name of the IIS Admin
Object accessed, and is the same as the ADSI Class property.
LogAnonymous
This property specifies whether anonymous requests are logged to the event log.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
LogCustomPropertyDataType
This property indicates the data type of a custom logging field to which this property applies. The
constants used to specify the data type are listed in the following table:
For more information about custom logging fields, see Setting Metabase Properties for Logging.
Access Locations
The following tables list additional information required only for code that uses the IIS Admin Base
Object.
Bitmask Values
LogCustomPropertyHeader
The LogCustomPropertyHeader property indicates which header string will be written to the log file
for the custom logging field to which this property applies.
For more information about custom logging fields, see Setting Metabase Properties for Logging.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
LogCustomPropertyID
This property specifies the identifier of the metabase property that will be used to determine if logging is
enabled or disabled for the specific logging field in question. To get the identifier for a given property, you
must first determine what the underlying metabase identifier constant is for the administration property in
question. You can then refer to the header file iiscnfg.h to determine the identifier for that constant.
For instance, the ADSI administration property named LogExtFileFlags refers to the underlying
When a logging module is called to log custom information fields, the logging module will access the
property specified by LogCustomPropertyID, and check the individual flag bits, specified by
LogCustomPropertyMask, to determine if that particular field is currently enabled or disabled.
For more information about custom logging fields, see Setting Metabase Properties for Logging.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
LogCustomPropertyMask
This property specifies the bitmask that can be used against the metabase property, specified by
LogCustomPropertyID, to determine whether the particular logging field is currently enabled or
disabled.
When a logging module is asked to log custom information fields, the logging module will access the
property specified by LogCustomPropertyID, and check the individual flag bits, specified by
LogCustomPropertyMask, to determine if that particular field is currently enabled or disabled.
For more information about custom logging fields, see Setting Metabase Properties for Logging.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
LogCustomPropertyName
This property specifies the name of the custom logging information field. This name generally should be
the name used in the user interface for the logging module.
For more information about custom logging fields, see Setting Metabase Properties for Logging.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
LogCustomPropertyServicesString
This property specifies to which services the custom logging fields will apply.
For more information about custom logging fields, see Setting Metabase Properties for Logging.
MSFTPSVC
SMTPSVC
NNTPSVC
Inheritance Inheritable
Access Locations
/LM/Logging/CustomLogging/FieldGroup/Field IIsCustomLogModule
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
LogExtFileBytesRecv
This property indicates whether the total number of bytes received is written to the log file during logging
events. This property is one of the flags contained in the LogExtFileFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogExtFileFlags
LogExtFileBytesSent
This property indicates whether the total number of bytes sent is written to the log file during logging
events. This property is one of the flags contained in the LogExtFileFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogExtFileFlags
LogExtFileClientIp
This property indicates whether the client's IP address is written to the log file during logging events. This
property is one of the flags contained in the LogExtFileFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogExtFileFlags
LogExtFileComputerName
This property enables the name of the local machine to be logged during logging events. This property is
one of the flags contained in the LogExtFileFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogExtFileFlags
LogExtFileCookie
This property indicates whether information from the client cookie is written to the log file during logging
events. This property is one of the flags contained in the LogExtFileFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogExtFileFlags
LogExtFileDate
This property indicates whether the date is included in the information written to the log file during a
logging event. This property is one of the flags contained in the LogExtFileFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogExtFileFlags
LogExtFileFlags
This property contains flags that indicate to Windows 2000 Server which categories of information are
written to the log file (or ODBC data source) during logging events. The following individual flags are
included in this property:
Access Locations
The following tables list additional information required only for code that uses the IIS Admin Base
Object.
MD_EXTLOG_TIME
MD_EXTLOG_METHOD
MD_EXTLOG_URI_STEM
MD_EXTLOG_HTTP_STATUS
Default bitmask value 0x 00000586
Bitmask Values
LogExtFileHttpStatus
This property indicates whether HTTP status information is written to the log file during a logging event.
This property is one of the flags contained in the LogExtFileFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogExtFileFlags
LogExtFileMethod
This property indicates whether the logging method is written to the log file during a logging event. This
property is one of the flags contained in LogExtFileFlags.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogExtFileFlags
LogExtFileProtocolVersion
This property indicates whether the client/server protocol version is written to the log file during a logging
event. This property is one of the flags contained in LogExtFileFlags.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogExtFileFlags
LogExtFileReferer
This property indicates whether the referrer field, sent by the client, is written to the log file during a
logging event. This property is one of the flags contained in the LogExtFileFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogExtFileFlags
LogExtFileServerIp
This property indicates whether the server's IP address is written to the log file during a logging event.
This property is one of the flags contained in the LogExtFileFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogExtFileFlags
LogExtFileServerPort
This property indicates whether the active server port is written to the log file during a logging event. This
property is one of the flags contained in the LogExtFileFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogExtFileFlags
LogExtFileSiteName
This property indicates whether the site name is written to the log file during a logging event. This
property is one of the flags contained in the LogExtFileFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogExtFileFlags
LogExtFileTime
This property indicates whether the time is written to the log file during a logging event. This property is
one of the flags contained in the LogExtFileFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogExtFileFlags
LogExtFileTimeTaken
This property enables writing into the log file, during logging events, the total time taken for a request to
be completed. This property is one of the flags contained in the LogExtFileFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogExtFileFlags
LogExtFileUriQuery
This property indicates whether the Universal Resource Identifier (URI) query information is written to
the log file during logging events. The URI query usually consists of parameters passed to the URL by
using the URL?Parameters format. This property is one of the flags contained in the LogExtFileFlags
property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogExtFileFlags
LogExtFileUriStem
This property indicates whether the Universal Resource Identifier (URI) stem information is written to the
log file during logging events. The URI stem usually consists of the actual resource being requested. This
property is one of the flags contained in the LogExtFileFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogExtFileFlags
LogExtFileUserAgent
This property indicates whether the contents of the user agent field, sent by the client, are written to the
log file during a logging event. This property is one of the flags contained in the LogExtFileFlags
property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogExtFileFlags
LogExtFileUserName
This property indicates whether the user's name is written to the log file during logging events. This
property is one of the flags contained in the LogExtFileFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogExtFileFlags
LogExtFileWin32Status
This property indicates whether the current Microsoft ® Win32® error status is written to the log file
during a logging event. This property is one of the flags contained in the LogExtFileFlags property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogExtFileFlags
LogFileDirectory
This property specifies the default logging directory, in which the log file and logging-related support files
are stored.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
LogFileLocaltimeRollover
This property specifies IIS log file rollover behavior for W3C Extended logging. If the property is set to
FALSE, the default rollover behavior will be in effect: A new log file will be created based on the
Universal Time Coordinate (UTC), not local time. If this property is set to TRUE, a new log file will be
created based on local time, not UTC. (UTC was formerly called Greenwich Mean Time, or GMT.)
Note Regardless of the setting of this property, the time stamp for each W3C Extended Logging log
record will be UTC-based.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
LogFilePeriod
This property specifies how often Microsoft Windows should create a new log file. This property can be
set to the following values: 1 (daily), 2 (weekly), 3 (monthly), or 4 (hourly). If this property is set to 0, a
new file will be created when the maximum size designated in LogFileTruncateSize is reached.
Access Locations
The following tables list additional information required only for code that uses the IIS Admin Base
Object.
Bitmask values
See Also
LogFileTruncateSize
LogFileTruncateSize
This property specifies the maximum size of the log file, in bytes. A new log file is created if a logging
event causes the original log file to exceed the size specified in this property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
LogModuleId
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogModuleUiId
LogModuleList
This property specifies a string that contains a comma-delimited list that names the available logging
modules.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
LogModuleUiId
This property specifies the CLSID for the logging module's user interface.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
LogModuleId
LogNonAnonymous
This property specifies whether non-anonymous hits are logged to the event log.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
LogOdbcDataSource
This property specifies the name of the ODBC data source to which Microsoft Windows will write data
during logging events.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
Remarks
The logging module's CLSID determines whether Microsoft Windows will log to an ODBC data source,
or to the file system.
LogOdbcPassword
This property specifies the ODBC database password to be used when writing information to the
database during logging events.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
LogOdbcTableName
This property specifies the name of the ODBC database table to which Microsoft Windows will write
information during logging events.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
LogOdbcUserName
This property specifies the ODBC database user name to be used when writing information to the
database during logging events.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
LogonMethod
This property specifies the logon method for clear-text logons. Valid settings are: interactive (value set to
0), batch (1), and network (2). Each user attempting to log on to the server must have access
permissions corresponding to the appropriate logon method.
Access Locations
Bitmask values
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
LogPluginClsid
This property specifies the order of precedence for the logging modules.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
LogType
This property indicates whether logging is enabled. A value of 0 indicates that logging is disabled, and a
value of 1 indicates that logging is enabled. This property is read-only.
Access Locations
The following tables list additional information required only for code that uses the IIS Admin Base
Object.
Bitmask values
See Also
DontLog
MaxBandWidth
This property specifies the maximum network bandwidth used for IIS. You can use this setting to help
prevent overloading the network with IIS activity. This is not an inheritable property, but the value set at
the machine level is globally available to all server instances. MaxBandWidth can be set individually so
that specific server instances are used instead of the global value, and can exceed the global setting
established at the machine level. A server instance must be stopped and restarted for a changed
MaxBandWidth value to take effect.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
MaxBandWidthBlocked
This property specifies the maximum number of asynchronous requests to be queued in the outstanding
idle queue when the maximum bandwidth of the server is exceeded. The value range for this property is 0
to &HFFFFFFFF (unlimited).
This is not an inheritable property, but the value set at the machine level is globally available to all server
instances.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
MaxClientsMessage
This property contains the text of a message to send to clients when the current connection exceeds the
maximum connections established by the MaxConnections property. The message is a single line of
text.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
MaxConnections
MaxConnections
This property specifies the maximum number of simultaneous connections to a server. The valid range is
0 to 0xFFFFFFFF (unlimited). The MaxClientsMessage property can be used to send a message to
clients when this value has been exceeded.
Access Locations
The following tables list additional information required only for code that uses the IIS Admin Base
Object.
See Also
MaxClientsMessage
MaxEndpointConnections
This property specifies the maximum number of "listen" sockets that will be aggregated on a network
endpoint. For example, if this value is set to 15, then a maximum of 15 total connections can be made to
a single port, even if more than one domain is bound to the port.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
MimeMap
This property provides a list of the file name extensions for Multipurpose Internet Mail Extensions
(MIME) mappings. The MimeMap key at the local machine level of the metabase establishes the
default list, which can be overridden at the Web service and Web server level keys. See the
IIsMimeMap object for details on managing this property.
Access Locations
/LM/W3SVC/N/ROOT/WebVirtualDir/WebDirectory IIsWebDirectory
/LM/W3SVC/N/ROOT/WebVirtualDir/WebDirectory/WebFile IIsWebFile
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
MSDOSDirOutput
This property specifies the style of directory output for a list operation request from an FTP client. If the
value is TRUE, the format is in MS-DOS® style, if FALSE, it is produced in UNIX style.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
NetLogonWorkstation
This property indicates the criteria that will be used by the domain controller for domain logon restrictions
from computers running Windows 2000 Professional. If NetLogonWorkstation is set to a value of 0,
logon restrictions are based on domain and the Windows Professional client information. If
NetLogonWorkstation is set to a value of 1, logon restrictions are based on the client's IP address.
And if NetLogonWorkstation is set to a value of 2, logon restrictions are based on the client's DNS
name.
Access Locations
The following tables list additional information required only for code that uses the IIS Admin Base
Object.
Bitmask values
NotDeletable
This metabase property indicates whether Internet Service Manager (HTML) can delete a server. If this
property is set to TRUE, any attempt to delete the affected server instance will result in an error.
This metabase property is not examined by the Internet Information Services snap-in administration tool.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
NotifyAccessDenied
This property specifies whether the filter has registered to be notified of access-denial messages. If the
value is TRUE, the filter will be notified when the server is about to send the "401 Access Denied" error
message. If the value is FALSE, the filter ignores access-denied messages. This property is one of the
flags contained in the property FilterFlags, and is read-only.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
FilterFlags
NotifyAuthentication
This property indicates whether the filter has registered to be notified of authentication events. If the value
is TRUE, the filter will be notified when the server is initially authenticating the client. This property is one
of the flags contained in the property FilterFlags, and should be considered read-only.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
FilterFlags
NotifyEndOfNetSession
This property indicates whether the filter has registered to be notified of network sessions that are ending.
This property is one of the flags contained in the property FilterFlags, and should be considered read-
only.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
FilterFlags
NotifyEndOfRequest
This property indicates whether the filter has registered to be notified at the end of every client request.
This property is one of the flags contained in the property FilterFlags, and should be considered read-
only.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
FilterFlags
NotifyLog
This property indicates whether the filter has registered to be notified when the server is writing to the
log. This property is one of the flags contained in the property FilterFlags, and should be considered
read-only.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
FilterFlags
NotifyNonSecurePort
This property indicates whether the filter has registered to be notified only for sessions on nonsecure
ports. This property is one of the flags contained in the FilterFlags property, and should be considered
read-only.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
FilterFlags
NotifyOrderHigh
This property indicates whether the filter has registered as high priority. When a notification occurs, if the
filter has registered for that notification, high priority filters are processed first. If other filters have also
registered as high priority, then the filters will be processed in the order they appear in the
FilterLoadOrder property.
This property is one of the flags contained in the FilterFlags property, and should be considered read-
only.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
FilterFlags
NotifyOrderLow
This property indicates whether the filter has registered as low priority. When a notification occurs, if the
filter has registered for that notification, low priority filters are processed last. If other filters have also
registered as low priority, then the filters will be processed in the order they appear in the
FilterLoadOrder property.
This property is one of the flags contained in the FilterFlags property, and should be considered read-
only.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
FilterFlags
NotifyOrderMedium
This property indicates whether the filter has registered as medium priority. When a notification occurs, if
the filter has registered for that notification, medium priority filters are processed after high priority filters,
but before low priority filters. If other filters have also registered as low priority, then the filters will be
processed in the order they appear in the FilterLoadOrder property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
FilterFlags
NotifyPreProcHeaders
This property indicates whether the filter has registered to be notified when the server has preprocessed
the headers of a request. This property is one of the flags contained in the FilterFlags. This is a read-
only property.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
FilterFlags
NotifyReadRawData
This property indicates whether the filter has registered to be given raw data as input, before any
processing has taken place. This property is one of the flags contained in the FilterFlags property, and
should be considered read-only.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
FilterFlags
NotifySecurePort
This property indicates whether the filter has registered to be notified only for sessions on secure ports.
This property is one of the flags contained in the FilterFlags property, and should be considered read-
only.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
FilterFlags
NotifySendRawData
This property indicates whether the filter has registered to be notified when the server is sending raw data
back to the client. This property is one of the flags contained in the FilterFlags property, and should be
considered read-only.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
FilterFlags
NotifySendResponse
This property indicates whether the filter has registered to be notified when the server is sending a
response to the client. This property is one of the flags contained in the FilterFlags property, and should
be considered read-only.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
FilterFlags
NotifyUrlMap
This property indicates whether the filter has registered to be notified when the server maps a URL to a
physical path. This property is one of the flags contained in the FilterFlags property, and should be
considered read-only.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
FilterFlags
NTAuthenticationProviders
This property contains a comma-delimited list of Windows authentication providers, such as integrated
Windows authentication (also known as NTLM).
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
PasswordCacheTTL
This property is used for password types of security authentication schemes. The value specifies the
amount of time in seconds that an expired password will be held in the memory cache.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
PasswordExpirePrenotifyDays
PasswordChangeFlags
This property specifies the flags that control password expiration and password change processing
between the server and client. A value of 0 (default) indicates that an SSL connection is required, 1
indicates that changing is allowed on nonsecure ports, 2 indicates that changing is disabled, and 4
indicates that password expiration notification is disabled.
Access Locations
The following tables list additional information required only for code that uses the IIS Admin Base
Object.
Bitmask values
See Also
PasswordExpirePrenotifyDays
PasswordExpirePrenotifyDays
This property specifies the number of days remaining before the client's password will expire, and is used
to indicate when a password prenotification message will be sent.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
Remarks
When working with the IIS Admin Base Object, password expiration notification can be turned off by
setting the MD_AUTH_ADVNOTIFY_DISABLE flag in the property
MD_AUTH_CHANGE_FLAGS.
See Also
PasswordChangeFlags
Path
This property specifies the physical path associated with a virtual directory.
Access Locations
/LM/W3SVC/N/ROOT/WebVirtualDir IIsWebVirtualDir
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
PoolIDCTimeout
This property specifies the timeout value (in seconds) for Internet database connection pooling. A value
of zero specifies that no pooling will be implemented.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
ProcessNTCRIfLoggedOn
This property enables processing of integrated Windows (NTLM) authentication even if a user has
already logged on using an alternate authentication scheme.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
PutReadSize
This property specifies the chunk size (in bytes) to be sent to the client in the HTTP 1.1 Transfer
Encoding header field. Normal values for this property are in the range of 1 KB to 64 KB. Intranet
applications may benefit from values for this property at the upper end of the range. For Internet
applications, values at the lower end of the range are more appropriate.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
Realm
This property specifies the realm when the server requests that a client authenticate itself because the
client was denied access to a resource when using Basic (clear-text) authentication. This value appears in
the browser's user name–password prompt.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
RedirectHeaders
This property specifies additional redirection headers. Multiple headers can be specified if they are
separated by carriage return/line feed (CRLF) pairs. Do not put a trailing carriage return/line feed after
the final header.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
ScriptMaps
This property specifies the file name extensions of applications for script processor mappings. The List
string requires Extension, ScriptProcessor, Flags, IncludedVerbs. Where Extension is the file name
extension (such as .htm), ScriptProcessor is the full path to the DLL, Flags is the integer value
corresponding to the requested behavior described below, and IncludedVerbs is a list of the verbs for
this ISAPI DLL to handle.
Note In IIS version 4.0 and earlier, the syntax was to list excluded verbs rather than included verbs.
In version 5.0, if no verbs are listed, a value of "all verbs" is assumed. It is recommended that you list the
verbs you want your ISAPI filter or extension to handle.
Three possible flags are allowed for each extension mapping, so one of three possible values can be
assigned to the Flags attribute.
For example, to specify the file extension for the ISAPI "Test.dll" with a file extension of ".htm", you
might provide the following List (string):
Access Locations
The following tables list additional information required only for code that uses the IIS Admin Base
Object.
Bitmask value
SecureBindings
This property specifies a string that is used by IIS to determine which secure network endpoints are used
by the server instance. The string format is IP:Port.
Note The IP component of each string is optional. If it is not provided, IIS assumes that any IP address
is allowable (wildcard).
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
ServerBindings
ServerAutoStart
This property indicates if the server instance should start automatically when the service is started.
This property is reset automatically when a server instance is stopped or restarted, to maintain state
across service restarts. For example, if a server is stopped, the value of this property is set to FALSE so
that if the service is stopped and restarted, the server will remain stopped. Likewise, if a server is started,
this property is set to TRUE, allowing the server to remain running whenever the service is running.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
ServerBindings
This property specifies a string that is used by IIS to determine which network endpoints are used by the
server instance. The string format is IP:Port:Hostname.
Note Both the IP and Hostname parameter of the string are optional. Any unspecified parameters
default to an all-inclusive wildcard.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
SecureBindings
ServerComment
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
ServerConfigAutoPWSync
This property is a flag that participates in the ServerConfigFlags server configuration property. A value
of TRUE indicates that the server can perform automatic anonymous user password synchronization
between the Web authentication manager (WAM) and the Microsoft Windows authentication manager.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
ServerConfigFlags
ServerConfigFlags
This property contains flags that specify the server configuration established at startup. The flags
contained in this property are individually defined in the following properties:
ServerConfigAutoPWSync ServerConfigSSL128
ServerConfigSSLAllowEncrypt ServerConfigSSL40
Access Locations
The following tables list additional information required only for code that uses the IIS Admin Base
Object.
Bitmask values
ServerConfigSSL128
This property is a flag that participates in the ServerConfigFlags server configuration specification
property. A value of TRUE indicates that 128-bit Secure Sockets Layer (SSL) processing is installed.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
ServerConfigFlags
ServerConfigSSL40
This property is a flag that participates in the ServerConfigFlags server configuration specification
property. A value of TRUE indicates that 40-bit Secure Sockets Layer (SSL) processing is installed.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
ServerConfigFlags
ServerConfigSSLAllowEncrypt
This property is a flag that participates in the ServerConfigFlags server configuration specification
property. A value of TRUE indicates that the locality allows encryption.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
ServerConfigFlags
ServerListenBacklog
This property specifies the number of outstanding sockets that can be queued. The value is based on the
AcceptEx operating system parameter and the server size specified in the ServerSize property. Valid
values for this property range from 5 to 500.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
ServerSize
ServerListenTimeout
This property specifies the amount of time in seconds the server should wait before disconnecting a client
that has connected but has not sent any data.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
ServerSize
This property specifies the general size of the server, in terms of number of client requests processed per
day. A value of 0 indicates a small Web site that would expect to receive fewer than 10,000 requests per
day, a value of 1 indicates a medium site handling between 10,000 and 100,000 requests a day, and a
value of 2 designates a large site processing more than 100,000 requests a day. The value of this
Access Locations
The following tables list additional information required only for code that uses the IIS Admin Base
Object.
Bitmask values
See Also
ServerListenBacklog
ServerState
This property presents the current state of the server instance. The states, and the corresponding state
codes, are as follows: 1 (starting), 2 (started), 3 (stopping), 4 (stopped), 5 (pausing), 6 (paused), or 7
(continuing).
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
Bitmask values
Remarks
To send commands to the server, when working with the IIS Admin Base Object, use the
MD_SERVER_COMMAND property.
SSIExecDisable
This property specifies whether server-side include (SSI) #exec directives are disabled under this path.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
SSLUseDSMapper
This property specifies whether IIS is to use the Windows Directory Service certificate mapper or IIS
certificate mapper. If SSLUseDSMapper is set to FALSE, then IIS will use the IIS certificate mapper.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
AccessSSLFlags
UNCAuthenticationPassthrough
This property enables user authentication passthrough for Universal Naming Convention (UNC) virtual
root access (for authentication schemes that support delegation).
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
UNCPassword
This property specifies the encrypted password used to gain access to Universal Naming Convention
(UNC) virtual roots.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
UNCUserName
This property specifies the user name for Universal Naming Convention (UNC) virtual roots.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
UncPassword, Path
UploadReadAheadSize
This property establishes the number of bytes a Web server will read into a buffer and pass to an ISAPI
extension. This occurs once per client request. The ISAPI extension receives any additional data directly
from the client. The range is 0 to &HFFFFFFFF (4GB).
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
UseHostName
This property specifies whether the server returns its DNS host name (the computer name, by default)
when doing redirects. If the value of this property is FALSE, then the host's IP address is returned
instead of a host name.
Note If the client sends the host header, the server will use the value specified in the host header for the
UseHostName property, regardless of the server's own internal setting.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
WAMUserName
This property specifies the account user name that IIS uses by default as the COM+ application identity
for newly created IIS out-of-process applications. The values of this property and its companion
property, WAMUserPass, are set when IIS is installed, and match the user name and password values
in the Microsoft Windows user account established at the same time. It is recommended that you do not
change the value of this property. If you do, change it to a valid Windows user account, and change
WAMUserPass to the corresponding password for the new account.
Note Changes to the value of this property and WAMUserPass may disrupt the operation of existing
IIS out-of-process applications. You can synchronize application identities by using Component Services
to edit the user name and password values found on the Identity tab of the property sheet for each
package. See WAMUserPass for additional information. In-process applications are not affected by
these property values.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
WAMUserPass
WAMUserPass
This property specifies the password for the account that IIS uses by default as the COM+ application
identity for newly created IIS out-of-process applications. The values of this property and its companion
property, WAMUserName , are set when IIS is installed, and match the password and user name
values in the Microsoft Windows user account (IWAM_MachineName, where MachineName is the
name of the machine on which IIS is installed) established at the same time. It is recommended that you
do not change the value of this property. If you do, the Windows account password must be changed to
the identical value, and you must also synchronize existing IIS out-of-process application identities by
using Component Services to edit the user name and password values found on the Identity tab of the
property sheet for each package. In-process application packages are not affected by these property
values.
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
See Also
WAMUserName
Win32Error
Access Locations
The following table lists additional information required only for code that uses the IIS Admin Base
Object.
The ADSI property data types can be used at the scripting level, whereas the IIS Admin Base Object
data types are used only when writing code that uses the IIS Admin Base Object. The difference stems
from the fact that scripting languages such as Microsoft® JScript® and Visual Basic® Scripting Edition
(VBScript) have dissimilar data type implementations when compared to languages such as C and C++.
Use the following table as a reference for ADSI data types, to find the corresponding data type for the
IIS Admin Base Object.
Active Server Pages (ASP) implements classes that enable your component to access the properties and
methods of the ASP built-in objects. The ObjectContext object exposes methods that return an
interface to one of the ASP built-in objects. Your component can use these interfaces to access the
methods and properties of the built-in objects.
Class Use to
Application Calls the methods and properties of the Application object.
ASP Error Object Calls the methods and properties of the ASP Error object.
ObjectContext Returns the built-in objects and provide methods used in
transaction processing.
Request Calls the methods and properties of the Request object.
Response Calls the methods and properties of the Response object.
To use the ObjectContext and built-in objects in a Visual Basic component, you must include a
reference to the Microsoft ® ASP Object Library in your Visual Basic project.
For more information about the built-in objects see the Built-in Object Reference.
Application Object
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use the Application object to share information among all users of a given application. An
ASP-based application is defined as all the .asp files in a virtual directory and its subdirectories. Because
the Application object can be shared by more than one user, there are Lock and Unlock methods to
ensure that multiple users do not try to alter a property simultaneously.
Syntax
Application.method
Collections
Contents Contains all of the items that have been added to the
application through script commands.
StaticObjects Contains all of the objects added to the session with
the <OBJECT> tag.
Methods
Events
Application_OnEnd
Application_OnStart
Scripts for the preceding events are declared in the Global.asa file. For more information about these
events and the Global.asa file, see the Global.asa Reference.
Remarks
You can store values in the Application Collections. Information stored in the Application collections is
available throughout the application and has application scope. The following script demonstrates storage
of two types of variables.
<%
Application("greeting") = "Welcome to My Web World!"
Application("num") = 25
%>
You can also assign a component instance to a variable that has application scope. If you assign a
component instance to a variable with the Server.CreateObject method, the variable will be a member
of the Application.Contents collection. If the variable is assigned with the <OBJECT> tag, the variable
will be a member of the Application StaticObjects Collection.
You should be careful about assigning component instances to variables with application scope, because
some components are not designed to be given application scope. For more information, see the
Platform SDK.
If you assign a component instance to a variable in the Application Contents Collection, and use Visual
Basic® Scripting Edition (VBScript) as your primary scripting language, you must use the Set keyword.
This is illustrated in the following script.
You can then reference the methods and properties of MyComponent on subsequent Web pages by
using this script
<%
Set MyLocalObj1 = Application("Obj1")
MyLocalObj1.MyObjMethod
%>
Another way to create objects with application scope is by using the <OBJECT> tag in the Global.asa
file. For more information, see the Global.asa Reference.
You cannot store a built-in object in the Application object. For example, each of the following lines
returns an error.
<%
Set Application("var1") = Session
Set Application("var2") = Request
Set Application("var3") = Response
Set Application("var4") = Server
Set Application("var5") = Application
Set Application("var6") = ObjectContext
%>
You should be aware of the threading model used by any components you give application scope. The
threading model used to develop the component will have a significant impact on whether a component
instance should be assigned to a variable in one of the Application collections. For more information,
see Component Design Guidelines.
If you store an array in an Application object, you should not attempt to alter the elements of the stored
array directly. For example, the following script does not work:
This is because the Application object is implemented as a collection. The array element StoredArray
(3) does not receive the new value. Instead, the value would be included in the Application object
collection, and would overwrite any information that had previously been stored at that location.
It is strongly recommended that if you store an array in the Application object, you retrieve a copy of
the array before retrieving or changing any of the elements of the array. When you are done with the
array, you should store the array in the Application object again, so that any changes you made are
saved. This is demonstrated in the following scripts.
---file1.asp---
<%
'Creating and initializing the array.
dim MyArray()
Redim MyArray(5)
MyArray(0) = "hello"
MyArray(1) = "some other string"
Server.Transfer("file2.asp")
%>
---file2.asp---
<%
'Retrieving the array from the Application Object
Example
The following example uses the application variable NumVisits to store the number of times that a
particular page has been accessed. The Lock method is called to ensure that only the current client can
access or alter NumVisits. Calling the Unlock method then enables other users to access the
Application object.
<%
Application.Lock
Application("NumVisits") = Application("NumVisits") + 1
Application.Unlock
%>
You can see a working sample .asp file that uses the Application object in the Building ASP
Applications section of the ASP Samples.
Application Collections
? Contents
? StaticObjects
The Contents collection contains all the items that have been added to the application through a script
command. You can use the Contents collection to obtain a list of items that have been given application
scope, or to specify a particular item to be the target of an operation. You can also remove items from
Syntax
Application.Contents(Key)
Parameters
Key
Specifies the name of the item to retrieve.
Methods
Remarks
The Application.Contents collection contains those items that have been declared at the application
level without using the <OBJECT> tags. This would include both objects created with
Server.CreateObject as well as scalar variables established through an Application declaration. In the
following script, for example, both strHello and objCustom would be members of the
Application.Contents collection:
<%
Application("strHello") = "Hello"
Set Application("objCustom") = Server.CreateObject("MyComponent") %>
The Application.Contents collection supports For...Each and For...Next iteration. The following
script illustrates each of these methods of iterating through the Application.Contents collection:
<%
Application("strText1") = "1234567890"
Application("strText2") = "ABCDEFGHIJ"
Application("strText3") = "A1B2C3D4E5"
%>
<%
For Each Key in Application.Contents
Response.Write Key + " = " + Application(Key) + "<BR>"
Next
%>
<%
For intItem = 1 to Application.Contents.Count
Response.Write CStr(intItem) + " = "
Response.Write Application.Contents(intItem) + "<BR>"
Next
%>
You can see a working sample .asp file that uses the Application.Contents collection in the Building
ASP Applications section of the ASP Samples.
The StaticObjects collection contains all of the objects created with the <OBJECT> tags within the
scope of the Application object. You can use the collection to determine the value of a specific property
for an object, or iterate through the collection and retrieve all properties for all static objects.
Syntax
Application.StaticObjects(Key)
Parameters
Key
Specifies the name of the item to retrieve.
Remarks
You can use an iterating control structure to loop through the keys of the StaticObjects collection. This
is demonstrated in the following example.
<%
Dim strKey
Application Methods
? Contents.Remove
? Contents.RemoveAll
? Lock
? Unlock
Contents.Remove
Syntax
Application.Contents.Remove(name|index)
Parameters
name
The identifier for the item to remove.
index
An index offset indicating which item in the list to remove.
Remarks
The Contents.Remove method takes either a string or an integer as an input parameter. If the input
parameter is a string, the method will search the contents collection for an item with that name and
remove it. If the input parameter is an integer, the method counts that number of items from the start of
the collection, and removes the corresponding item.
Example
The following example adds two items to the Application.Contents collection and removes the second
one.
<%
Application("strFirst")=("First thing")
Application("strSecond")=("Second thing")
Application.Contents.Remove(strFirst)
%>
See Also
Contents.RemoveAll
Contents.RemoveAll
The Application.Contents.RemoveAll method removes all items that have been added to the
Application.Contents collection.
Syntax
Application.Contents.RemoveAll ()
See Also
Contents.Remove
Lock
The Lock method blocks other clients from modifying the variables stored in the Application object,
ensuring that only one client at a time can alter or access the Application variables. If you do not call the
Unlock method explicitly, the server unlocks the locked Application object when the .asp file ends or
times out.
Syntax
Application.Lock
Example
<%
Application.Lock
Application("NumVisits") = Application("NumVisits") + 1
Application("datLastVisited") = Now()
Application.Unlock
%>
In the preceding example the Lock method prevents more than one client from accessing the variable
NumVisits at a time. If the application had not been locked, two clients could try to increment the
variable NumVisits simultaneously.
Applies To
Application Object
See Also
Unlock
Unlock
The Unlock method enables other clients to modify the variables stored in the Application object after it
has been locked using the Lock method. If you do not call this method explicitly, the Web server
unlocks the Application object when the .asp file ends or times out.
Syntax
Application.Unlock
Example
<%
Application.Lock
Application("NumVisits") = Application("NumVisits") + 1
Application("datLastVisited") = Now()
Application.Unlock
%>
In the preceding example the Unlock method releases the locked object so that the next client can
increment NumVisits.
Note The application Lock method is cumulative, meaning if the same script calls Lock several times, it
must also call Unlock the same number of times to fully release the application. If this does not occur, the
application lock will be held until the script is finished running.
Applies To
Application Object
See Also
Lock
ASPError Object
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use the ASPError object to obtain information about an error condition that has occurred in an
ASP script. The ASPError object is returned by the Server.GetLastError method. The ASPError
object exposes read-only properties.
Syntax
ASPError.property
Properties
FileName Indicates the name of the .asp file that was being
processed when the error occurred.
LineNumber Indicates the line within the .asp file that generated
the error.
Description Returns a short description of the error.
ASPDescription Returns a more detailed description of the error if
it is an ASP-related error.
Remarks
When IIS encounters an error with either compiling or running an .asp file it will generate a 500;100
custom error. By default all Web sites and applications will transfer processing of a 500;100 custom
error to the file 500-100.asp which is installed by default to windir\Help\iisHelp\common. After a
500;100 custom error is generated, IIS will also create an instance of the ASPError object which
describes the error condition. The file 500-100.asp uses the properties of this object to display a page
describing the error condition. You can develop additional error processing by either modifying 500-
100.asp or by creating a new .asp file for processing errors.
Example
The following example is extracted from the file 500-100.asp and demonstrates writing the information
exposed by the ASPError object to a table.
<TABLE>
<TR><TD><font style="font:9pt/12pt verdana; color:black">ASP Code <TD><font style="
<TR><TD><font style="font:9pt/12pt verdana; color:black">Number <TD><font style="
<TR><TD><font style="font:9pt/12pt verdana; color:black">Source <TD><font style="
<TR><TD><font style="font:9pt/12pt verdana; color:black">FileName <TD><font style="
<TR><TD><font style="font:9pt/12pt verdana; color:black">LineNumber <TD><font style="
<TR><TD><font style="font:9pt/12pt verdana; color:black">Description <TD><font style="
<TR><TD><font style="font:9pt/12pt verdana; color:black">ASP Description <TD><font style="
</TABLE>
See Also
Server.GetLastError
ASPCode
The ASPCode property returns a string that contains an error code generated by IIS.
Syntax
ASPError.ASPCode ()
Applies To
ASPError Object
Number
The Number property returns a long integer that contains the error code returned by a COM
component. This will be a standard COM error code.
Syntax
ASPError.Number ()
Applies To
ASPError Object
Source
The Source property returns a string indicating if the error was generated by IIS, a scripting language, or
a component.
Syntax
ASPError.Source ()
Applies To
ASPError Object
FileName
The FileName property returns a string that indicates the .asp file that generated the error.
Syntax
ASPError.FileName ()
Applies To
ASPError Object
LineNumber
The LineNumber property returns a long integer indicating the number of the line within the .asp file that
generated the error.
Syntax
ASPError.LineNumber ()
Applies To
ASPError Object
Description
Syntax
ASPError.Description ()
Applies To
ASPError Object
ASPDescription
The ASPDescription property returns a string providing a more complete description of the error, if
available.
Syntax
ASPError.ASPDescription ()
Applies To
ASPError Object
ObjectContext Object
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use the ObjectContext object to either commit or abort a transaction, managed by Component
Services, that has been initiated by a script contained in an ASP page.
When an .asp file contains the @TRANSACTION directive, the page runs in a transaction and does not
finish processing until the transaction either succeeds completely or fails.
Syntax
ObjectContext.method
Methods
SetAbort The SetAbort method declares that the transaction initiated by the script
has not completed and the resources should not be updated.
SetComplete The SetComplete method declares that the script is not aware of any
reason for the transaction not to complete. If all components participating
in the transaction also call SetComplete, the transaction will complete.
Events
OnTransactionAbort
OnTransactionCommit
Remarks
ObjectContext implements two methods of the COM ObjectContext object. The SetAbort method
explicitly aborts the transaction. This causes Component Services to prevent any updates to resources
that were contacted during the first phase of the transaction. When the transaction aborts, the script's
OnTransactionAbort event will be processed.
Calling the SetComplete method does not necessarily mean that the transaction is complete. The
transaction will only complete if all of the transactional components called by the script call
SetComplete. In most instances, you will not need to call SetComplete within the script, as the script is
ObjectContext exposes methods in addition to SetAbort and SetComplete. These other methods are
not available to scripts in ASP scripts; however, they are available to components called by the script.
Example
The following example uses the SetAbort and SetComplete methods. The Sales.htm file obtains data
required to process a sales request. The second file, SalesVerify.asp contains a script that uses two
objects, Inventory and Sales, to process the sale. SetAbort is called if Inventory returns an error
code indicating that there is not sufficient inventory on hand to process the sale. If the Inventory object
does not return the error code, SetComplete is called and the sale is processed.
Sales.htm
<HTML>
<HEAD>
<TITLE>Sales Order</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF"><FONT FACE="ARIAL,HELVETICA">
<H2>Sales Order Form </H2>
SalesVerify.asp file
CheckQuantity = Request("QuantityToBuy")
CheckProduct = Request("ProductCode")
QuantityStatus = CurrentQOH.CheckQOH(CheckQuantity,CheckProduct)
If QuantityStatus = None
ObjectContext.SetAbort
Response.Write "Sorry, there is not sufficient quantity on hand to
process your sale."
Else
ObjectContext.SetComplete
Account = Request("AccountIn")
Saleupdate = CurrentSales.PostIt(AccountIn)
End If
%>
ObjectContext Methods
? SetAbort
? SetComplete
SetAbort
Syntax
ObjectContext.SetAbort
Applies To
ObjectContext Object
SetComplete
The SetComplete method overrides any previous SetAbort method that has been called in a script.
Syntax
ObjectContext.SetComplete
Applies To
ObjectContext Object
ObjectContext Events
? OnTransactionAbort
? OnTransactionCommit
OnTransactionAbort
The OnTransactionAbort event occurs if the transaction is aborted. When the OnTransactionAbort
event occurs, IIS will process the script's OnTransactionAbort subroutine, if it exists.
Example
The following example sends a response to the client with the transaction aborts:
Applies To
ObjectContext Object
OnTransactionCommit
The OnTransactionCommit event occurs after a transactional script's transaction commits. When the
OnTransactionCommit event occurs, IIS will process the script's OnTransactionCommit subroutine,
if it exists.
Example
The following example sends a response to the client with the transaction commits:
%>
Applies To
ObjectContext Object
Request Object
This is preliminary documentation for IIS 5.0 and is subject to change.
The Request object retrieves the values that the client browser passed to the server during an HTTP
request.
Syntax
Request[.collection|property|method](variable)
Collections
ClientCertificate The values of fields stored in the client certificate that is sent in the
HTTP request.
Cookies The values of cookies sent in the HTTP request.
Form The values of form elements in the HTTP request body.
QueryString The values of variables in the HTTP query string.
ServerVariables The values of predetermined environment variables.
Properties
TotalBytes Read-only; specifies the total number of bytes the client is sending in
the body of the request.
Methods
BinaryRead Retrieves data sent to the server from the client as part of a POST
request.
Variable parameters are strings that specify the item to be retrieved from a collection or to be used as
input for a method or property. For more information about the variable parameter, see the individual
collection descriptions.
Remarks
If the specified variable is not in one of the preceding five collections, the Request object returns
EMPTY.
All variables can be accessed directly by calling Request(variable) without the collection name. In this
case, the Web server searches the collections in the following order.
1. QueryString
2. Form
3. Cookies
4. ClientCertificate
5. ServerVariables
If a variable with the same name exists in more than one collection, the Request object returns the first
instance that the object encounters.
It is strongly recommended that when referring to members of a collection the full name be used. For
example, rather than Request.(AUTH_USER) use Request.ServerVariables(AUTH_USER). This
will allow the server to locate the item more quickly.
See Also
Response Object
Request Collections
? ClientCertificate
? Cookies
? Form
? QueryString
? ServerVariables
ClientCertificate
The ClientCertificate collection retrieves the certification fields (specified in the X.509 standard) from a
request issued by the Web browser.
If a Web browser uses the SSL3.0/PCT1 protocol (in other words, it uses a URL starting with https://
instead of http://) to connect to a server and the server requests certification, the browser sends the
certification fields.
Before you can use the ClientCertificate collection, you must configure your Web server to request
client certificates.
Syntax
Request.ClientCertificate( Key[SubField] )
Parameters
Key
Specifies the name of the certification field to retrieve. A client certificate consists of the following
fields.
Value Meaning
Certificate A string containing the binary stream of the entire certificate content in
ASN.1 format.
Flags A set of flags that provide additional client certificate information. The
following flags may be set:
Note To use the preceding flags you must include the client-certificate
include file in your ASP page. If you are using VBScript, include
cervbs.inc. If you are using JScript, include cerjavas.inc. These files are
installed in the \Inetpub\ASPSamp\Samples directory.
Issuer A string that contains a list of subfield values containing information about
the issuer of the certificate. If this value is specified without a SubField,
the ClientCertificate collection returns a comma-separated list of
subfields. For example, C=US, O=Verisign, and so on.
SerialNumber A string that contains the certification serial number as an ASCII
representation of hexadecimal bytes separated by hyphens (-). For
example, 04-67-F3-02.
Subject A string that contains a list of subfield values. The subfield values contain
information about the subject of the certificate. If this value is specified
without a SubField, the ClientCertificate collection returns a comma-
separated list of subfields. For example, C=US, O=Msft, and so on.
ValidFrom A date specifying when the certificate becomes valid. This date follows
VBScript format and varies with international settings. For example, in the
U.S., 9/26/96 11:59:59 PM. The year value is displayed as a four-digit
number.
ValidUntil A date specifying when the certificate expires. The year value is displayed
as a four-digit number.
SubField
An optional parameter you can use to a retrieve an individual field in either the Subject or Issuer
keys. This parameter is added to the Key parameter as a suffix. For example, IssuerO or
SubjectCN. The following table lists some common SubField values.
Value Meaning
C Specifies the name of the country of origin.
CN Specifies the common name of the user. (This subfield is only used with the
Subject key.)
GN Specifies a given name.
I Specifies a set of initials.
L Specifies a locality.
O Specifies the company or organization name.
OU Specifies the name of the organizational unit.
S Specifies a state or province.
T Specifies the title of the person or organization.
SubField values other than those listed in the preceding table can be identified by their ASN.1 identifier.
The format of the ASN.1 identifier is a list of numbers separated by a period (.). For example,
3.56.7886.34.
Remarks
You can iterate through the keys of the ClientCertificate collection. This is demonstrated in the
following example.
<%
For Each strKey in Request.ClientCertificate
Response.Write strkey & " = " & Request.ClientCertificate(strkey) & "<BR>")
Next
%>
Example
The following example uses the Subject key to test whether a client certificate has been presented.
<%
If Len(Request.ClientCertificate("Subject")) = 0
Response.Write("No client certificate was presented")
End if
%>
The following example retrieves the common name of the company that issued the client certificate.
The following example checks the organization name of the subject of the client certification.
<%
If (Request.ClientCertificate("Subject")="Msft")
Response.Write("Good Choice!")
End if
%>
The following example displays the expiration date of the client certificate.
The following example uses the Flags key to test whether the issuer of the certificate is known. The
include statement in the first line enables this script to use the named flag ceUnrecognizedIssuer.
Applies To
Request Object
See Also
Cookies
The Cookies collection enables you to retrieve the values of the cookies sent in an HTTP request.
Syntax
Request.Cookies(cookie)[(key)|.attribute]
Parameters
cookie
Specifies the cookie whose value should be retrieved.
key
An optional parameter used to retrieve subkey values from cookie dictionaries.
attribute
Specifies information about the cookie itself. The attribute parameter can be the following.
Name Description
HasKeys Read-only. Specifies whether the cookie contains keys.
Remarks
You can access the subkeys of a cookie dictionary by including a value for key. If a cookie dictionary is
accessed without specifying key, all of the keys are returned as a single query string. For example, if
MyCookie has two keys, First and Second, and you do not specify either of these keys in a call to
Request.Cookies, the following string is returned.
First=firstkeyvalue&Second=secondkeyvalue
If two cookies with the same name are sent by the client browser, Request.Cookies returns the one
with the deeper path structure. For example, if two cookies had the same name but one had a path
attribute of /www/ and the other of /www/home/, the client browser would send both cookies to
the /www/home/ directory, but Request.Cookies would only return the second cookie.
To determine whether a cookie is a cookie dictionary (whether the cookie has keys), use the following
script.
If myCookie is a cookie dictionary, the preceding value evaluates to TRUE. Otherwise, it evaluates to
FALSE.
You can iterate through all the cookies in the Cookie collection, or all the keys in a cookie. However,
iterating through keys on a cookie that does not have keys will not produce any output. You can avoid
this situation by first checking to see whether a cookie has keys by using the .HasKeys syntax. This is
demonstrated in the following example:
<%
For Each strKey In Request.Cookies
Response.Write strKey & " = " & Request.Cookies(strKey) & "<BR>"
If Request.Cookies(strKey).HasKeys Then
For Each strSubKey In Request.Cookies(strKey)
Response.Write "->" & strKey & "(" & strSubKey & ") = " & _
Request.Cookies(strKey)(strSubKey) & "<BR>"
Next
End If
Next
%>
Example
Note Cookies are described in detail in the HTTP state management specification, which is available at
WWW.W3.ORG.
Applies To
Request Object
See Also
Form
The Form collection retrieves the values of form elements posted to the HTTP request body by a form
using the POST method.
Syntax
Request.Form(element)[(index)|.Count]
Parameters
element
Specifies the name of the form element from which the collection is to retrieve values.
index
An optional parameter that enables you to access one of multiple values for a parameter. It can be
any integer in the range 1 to Request.Form(parameter).Count.
Remarks
The Form collection is indexed by the names of the parameters in the request body. The value of
Request.Form(element) is an array of all of the values of element that occur in the request body. You
can determine the number of values of a parameter by calling Request.Form(element).Count. If a
parameter does not have multiple values associated with it, the count is 1. If the parameter is not found,
the count is 0.
To reference a single value of a form element that has multiple values, you must specify a value for index.
The index parameter may be any number between 1 and Request.Form(element).Count. If you
reference one of multiple form parameters without specifying a value for index, the data is returned as a
comma-delimited string.
When you use parameters with Request.Form, the Web server parses the HTTP request body and
returns the specified data. If your application requires unparsed data from the form, you can access it by
calling Request.Form without any parameters.
You can iterate through all the data values in a form request. For example, if a user filled out a form by
specifying two values, Chocolate and Butterscotch, for the FavoriteFlavor element, you could retrieve
those values by using the following script.
<%
For i = 1 To Request.Form("FavoriteFlavor").Count
Response.Write Request.Form("FavoriteFlavor")(i) & "<BR>"
Next
%>
Chocolate
Butterscotch
You can use this technique to display the parameter name, as shown in the following script.
<%
For i = 1 to Request.Form("FavoriteFlavor").count %>
Request.Form(FavoriteFlavor) = <%= Request.Form("FavoriteFlavor")(i)_
%> <BR>
<% Next %>
Request.Form(FavoriteFlavor) = Chocolate
Request.Form(FavoriteFlavor) = Butterscotch
Example
firstname=James&flavor=Rocky+Road
Note If your form includes multiple objects with the same name (for example, HTML SELECT tags),
the item in the form collection will be a comma-delimited list of all the selected values.
Applies To
Request Object
See Also
QueryString
The QueryString collection retrieves the values of the variables in the HTTP query string. The HTTP
query string is specified by the values following the question mark (?). Several different processes can
generate a query string. For example, the anchor tag
generates a variable named string with the value "this is a sample." Query strings are also generated by
sending a form, or by a user typing a query into the address box of the browser.
Syntax
Request.QueryString(variable)[(index)|.Count]
Parameters
variable
Specifies the name of the variable in the HTTP query string to retrieve.
index
An optional parameter that enables you to retrieve one of multiple values for variable. It can be
Remarks
To reference a QueryString variable in one of multiple data sets, you specify a value for index. The
index parameter can be any value between 1 and Request.QueryString(variable).Count. If you
reference one of multiple QueryString variables without specifying a value for index, the data is
returned as a comma-delimited string.
When you use parameters with Request.QueryString, the server parses the parameters sent to the
request and returns the specified data. If your application requires unparsed QueryString data, you can
retrieve it by calling Request.QueryString without any parameters.
You can use an iterator to loop through all the data values in a query string. For example, if the following
request is sent
http://localhost/script/directory/NAMES.ASP?Q=Fred&Q=Sally
---NAMES.ASP---
<%
For Each item In Request.QueryString("Q")
Response.Write Request.QueryString("Q")(item) & "<BR>"
Next
%>
Fred
Sally
The preceding script could also have been written using Count.
<%
For i = 1 To Request.QueryString("Q").Count
Response.Write Request.QueryString("Q")(i) & "<BR>"
Next
%>
Example
/scripts/directory-lookup.asp?name=fred&age=22
name=fred&age=22.
The QueryString collection would then contain two members, name and age. You can then use the
following script:
Applies To
Request Object
See Also
ServerVariables
Syntax
Parameters
Remarks
If a client sends a header other than those specified in the preceding table, you can retrieve the value of
that header by prefixing the header name with HTTP_ in the call to Request.ServerVariables. For
example, if the client sent the header
SomeNewHeader:SomeNewValue
You can iterate through each server variable name. For example, the following script prints out all of the
server variables in a table:
<TABLE BORDER="1">
<TR><TD><B>Server Variable</B></TD><TD><B>Value</B></TD></TR>
<% For Each strKey In Request.ServerVariables %>
<TR><TD> <%= strKey %> </TD><TD> <%= Request.ServerVariables(strKey) %> </TD></TR>
<% Next %>
</TABLE>
Example
The following example uses the Request object to display several server variables:
<HTML>
<!-- This example displays the content of several ServerVariables. -->
ALL_HTTP server variable =
<%= Request.ServerVariables("ALL_HTTP") %> <BR>
CONTENT_LENGTH server variable =
<%= Request.ServerVariables("CONTENT_LENGTH") %> <BR>
CONTENT_TYPE server variable =
<%= Request.ServerVariables("CONTENT_TYPE") %> <BR>
QUERY_STRING server variable =
<%= Request.ServerVariables("QUERY_STRING") %> <BR>
SERVER_SOFTWARE server variable =
<%= Request.ServerVariables("SERVER_SOFTWARE") %> <BR>
</HTML>
The next example uses the ServerVariables collection to insert the name of the server into a hyperlink.
Applies To
Request Object
See Also
Request Properties
? TotalBytes
TotalBytes
The TotalBytes property specifies the total number of bytes the client sent in the body of the request.
This property is Read-only.
Syntax
Counter = Request.TotalBytes
Parameters
Counter
Specifies a variable to receive the total number of bytes that the client sends in the request.
Example
The following script sets a variable equal to the total number of bytes included in a request object.
<%
Dim bytecount
bytecount = Request.TotalBytes
%>
Applies To
Request Object
See Also
BinaryRead
Request Methods
? BinaryRead
BinaryRead
The BinaryRead method retrieves data sent to the server from the client as part of a POST request.
This method retrieves the data from the client and stores it in a SafeArray. A SafeArray is an array that
contains information about the number of dimensions and the bounds of its dimensions.
Syntax
variant = Request.BinaryRead(count)
Parameters
variant
Contains an array of unsigned bytes returned by this method. This parameter will be of type
VT_ARRAY | VT_UI1, which is a variant array of unsigned one byte characters.
count
Before execution, specifies how many bytes to read from the client. After this method returns,
count will contain the number of bytes successfully read from the client. The total number of bytes
that will actually be read is less than or equal to Request.TotalBytes.
Remarks
The BinaryRead method is used to read the raw data sent by the client as part of a POST request. This
method is used for low-level access to this data, as opposed to, for example, using the Request.Form
collection to view form data sent in a POST request. Once you have called BinaryRead, referring to
any variable in the Request.Form collection will cause an error. Conversely, once you have referred to
a variable in the Request.Form collection, calling BinaryWrite will cause an error. Remember, if you
access a variable in the Request collection without specifying which subcollection it belongs to, the
Request.Form collection may be searched, bringing this rule into force.
Example
The following example uses the BinaryRead method to place the content of a request into a safe array.
<%
Dim vntPostedData, lngCount
lngCount = Request.TotalBytes
vntPostedData = Request.BinaryRead(lngCount)
%>
Applies To
Request Object
See Also
Response Object
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use the Response object to send output to the client.
Syntax
Response.collection|property|method
Collections
Cookies Specifies cookie values. Using this collection, you can set cookie
values.
Properties
Pics Set the value for the pics-label response header, to indicate the PICS
content rating.
Status The value of the status line returned by the server.
Methods
See Also
Request Object
Response Collections
? Cookies
Cookies
The Cookies collection sets the value of a cookie. If the specified cookie does not exist, it is created. If
the cookie exists, it takes the new value and the old value is discarded.
Syntax
Response.Cookies(cookie)[(key)|.attribute] = value
Parameters
cookie
The name of the cookie.
key
An optional parameter. If key is specified, cookie is a dictionary, and key is set to value.
attribute
Specifies information about the cookie itself. The attribute parameter can be one of the following.
Name Description
Domain Write-only. If specified, the cookie is sent only to requests to this
domain.
Expires Write-only. The date on which the cookie expires. This date must be
set in order for the cookie to be stored on the client's disk after the
session ends. If this attribute is not set to a date beyond the current
date, the cookie will expire when the session ends.
HasKeys Read-only. Specifies whether the cookie contains keys.
Path Write-only. If specified, the cookie is sent only to requests to this path.
If this attribute is not set, the application path is used.
Secure Write-only. Specifies whether the cookie is secure.
Value
Specifies the value to assign to key or attribute.
Remarks
<%
Response.Cookies("mycookie")("type1") = "sugar"
Response.Cookies("mycookie")("type2") = "ginger snap"
%>
Set-Cookie:MYCOOKIE=TYPE1=sugar&TYPE2=ginger+snap
A subsequent assignment to myCookie without specifying a key, would destroy type1 and type2. This
is shown in the following example.
In the preceding example, the keys type1 and type2 are destroyed and their values are discarded. The
myCookie cookie now has the value chocolate chip.
Conversely, if you call a cookie with a key, it destroys any non-key values the cookie contained. For
example, if after the preceding code you call Response.Cookies with the following
The value chocolate chip is discarded and newType would be set to peanut butter.
You can use an iterator to set cookie attributes. For example, to set all of the cookies to expire on a
particular date, use the following syntax.
<%
For Each cookie in Response.Cookies
Response.Cookie(cookie).ExpiresAbsolute = #July 4, 1997#
Next
%>
You can also iterate through the values of all the cookies in a collection, or all the keys in a cookie.
However, if you try to iterate through the values for a cookie that does not have keys, nothing will be
returned. To avoid this, you can first use the .HasKeys syntax to check whether a cookie has any keys.
This is demonstrated in the following example.
<%
If Not cookie.HasKeys Then
'Set the value of the cookie.
Response.Cookies(cookie) = ""
Else
'Set the value for each key in the cookie collection.
For Each key in Response.Cookies(cookie)
Response.Cookies(cookie)(key) = ""
Next
%>
Example
The following examples demonstrate how you can set a value for a cookie and assign values to its
attributes.
<%
Response.Cookies("Type") = "Chocolate Chip"
Response.Cookies("Type").ExpiresAbsolute = "July 31, 2001"
Response.Cookies("Type").Path = "/"
%>
Applies To
Response Object
See Also
Request.Cookies
Response Properties
? Buffer
? CacheControl
? Charset
? ContentType
? Expires
? ExpiresAbsolute
? IsClientConnected
? PICS
? Status
Buffer
The Buffer property indicates whether to buffer page output. When page output is buffered, the server
does not send a response to the client until all of the server scripts on the current page have been
processed, or until the Flush or End method has been called.
The Buffer property cannot be set after the server has sent output to the client. For this reason, the call
to Response.Buffer should be the first line of the .asp file.
Syntax
Response.Buffer [= flag]
Parameters
flag
Specifies whether or not to buffer page output. It can be one of the following values.
Value Description
FALSE No buffering. The server sends output to the client as it is processed.
This is the default value for versions of IIS up to and including 4.0. For
version 5.0 and later, the default value is True.
TRUE The server does not send output to the client until all of the ASP scripts
on the current page have been processed, or until the Flush or End
method has been called.
Remarks
If the current .asp file has buffering set to TRUE and does not call the Flush method, the server will
honor Keep-Alive requests made by the client. This saves time because the server does not have to
create a new connection for each client request.
However, buffering prevents any of the response from being displayed to the client until the server has
finished all script processing for the current page. For long scripts, this may cause a perceptible delay.
You can use the ASPBufferingOn property in the metabase to set the default value for script buffering.
For more information about using the metabase, see Using IIS Admin Objects.
Applies To
Response Object
See Also
Flush, End
CacheControl
The CacheControl property overrides the Private default value. When you set this property to Public,
proxy servers can cache the output generated by ASP.
Syntax
Parameters
Value Description
Private Only private caches may cache this page. This
is the default value. Most proxy servers will
not cache pages with this setting.
Remarks
Setting CacheControl to public may improve the perceived performance of your .asp files. If your .asp
file generates custom HTML for every request, you will not improve performance by setting
CacheControl to public. The values for Private and Public are strings, and must be enclosed in quotation
marks (" ").
Applies To
Response Object
Charset
The Charset property appends the name of the character set (for example, ISO-LATIN-7) to the
content-type header in the response object.
Syntax
Response.Charset(CharsetName)
Parameters
CharsetName
A string that specifies a character set for the page. The character set name will be appended to
the content-type header in the Response object.
Example
For an ASP page that did not include the Response.Charset property, the content-type header would
be
content-type:text/html
content-type:text/html; charset=ISO-LATIN-7
Remarks
This function inserts any string in the header, regardless of whether it represents a valid character set or
not.
If a single page contains multiple tags containing Response.Charset, each Response.Charset will
replace the previous CharsetName. As a result, the character set will be set to the value specified by the
last instance of Response.Charset in the page.
On Macintosh computers, the default U.S. character set is not ISO-LATIN-1. When serving up
documents, Personal Web Server for Macintosh automatically converts from the Macintosh character set
to ISO-Latin-1. In the U.S. version, all pages are assumed to be in the U.S. Macintosh character set
unless the Response.Charset is used. If Response.Charset is used to change the character set,
Personal Web Server for Macintosh does not convert the character set.
Applies To
Response Object
ContentType
The ContentType property specifies the HTTP content type for the response. If no ContentType is
specified, the default is text/HTML.
Syntax
Response.ContentType [= ContentType ]
Parameters
ContentType
A string describing the content type. This string is usually formatted type/subtype where type is
the general content category and subtype is the specific content type. For a full list of supported
content types, see your Web browser documentation or the current HTTP specification.
Example
The following example sets the content type to Channel Definition Format (CDF).
The following examples set the ContentType property to other common values.
Applies To
Response Object
Expires
The Expires property specifies the length of time before a page cached on a browser expires. If the user
returns to the same page before it expires, the cached version is displayed.
Syntax
Response.Expires [= number]
Parameters
number
The time in minutes before the page expires.
Remarks
When your .asp file calls Response.Expires, IIS creates an HTTP header indicating the time on the
server. If the system time on the client is earlier than the system time on the server (due to either the client
or server having an inaccurate time setting, or time-zone differences) setting the parameter to 0 will not
have the effect of expiring the page immediately. You can use the Response.ExpiresAbsolute property
to achieve immediate expiration of a page. In addition, you can use a negative number for the Expires
property. For example
<%Response.Expires = -1 %>
If there are multiple calls to Response.Expires on a single page, the server will use the shortest time
period.
Applies To
Response Object
See Also
ExpiresAbsolute
ExpiresAbsolute
The ExpiresAbsolute property specifies the date and time at which a page cached on a browser
expires. If the user returns to the same page before that date and time, the cached version is displayed. If
a time is not specified, the page expires at midnight of that day. If a date is not specified, the page expires
at the given time on the day that the script is run.
Syntax
Parameters
date
Specifies the date on which the page will expire. The value sent in the expires header conforms to
the RFC-1123 date format.
time
Specifies the time at which the page will expire. This value is converted to GMT before an Expires
header is sent.
Remarks
If this property is set more than once on a page, the earliest expiration date or time is used.
Example
The following example specifies that the page will expire 15 seconds after 1:30 PM on May 31, 2001.
Applies To
Response Object
See Also
Expires
IsClientConnected
The IsClientConnected property is a read-only property that indicates if the client has disconnected
from the server.
Syntax
Response.IsClientConnected ( )
Remarks
This property allows you greater control over circumstances where the client may have disconnected
from the server. For example, if a long period of time has elapsed between when a client request was
made and when the server responded, it may be beneficial to make sure the client is still connected
before continuing to process the script.
Example
<%
'Check to see if the client is connected.
If Not Response.IsClientConnected Then
'Get the sessionid to send to the shutdown function.
Shutdownid = Session.SessionID
'Perform shutdown processing.
Shutdown(Shutdownid)
End If
%>
Applies To
Response Object
PICS
Syntax
Response.PICS(PICSLabel)
Parameters
PICSLabel
A string that is a properly formatted PICS label. The value specified by PICSLabel will be
appended to the pics-label response header.
Example
<%
Response.PICS("(PICS-1.1 <http://www.rsac.org/ratingv01.html> labels on " & chr(34) & "199
%>
Remarks
The PICS property inserts any string in the header, whether or not it represents a valid PICS label.
If a single page contains multiple tags containing Response.PICS, each instance will replace the PICS
label set by the previous one. As a result, the PICS label will be set to the value specified by the last
instance of Response.PICS in the page.
Because PICS labels contain quotes, you must replace each quote with " & chr(34) & ".
Applies To
Response Object
Status
The Status property specifies the value of the status line returned by the server. Status values are defined
in the HTTP specification.
Syntax
Response.Status = StatusDescription
Parameters
StatusDescription
A string that consists of both a three-digit number that indicates a status code and a brief
explanation of that code. For example, 310 Move Permanently.
Remarks
Use this property to modify the status line returned by the server.
Example
Applies To
Response Object
Response Methods
? AddHeader
? AppendToLog
? BinaryWrite
? Clear
? End
? Flush
? Redirect
? Write
AddHeader
The AddHeader method adds an HTML header with a specified value. This method always adds a new
HTTP header to the response. It will not replace an existing header of the same name. Once a header
has been added, it cannot be removed.
If another Response method will provide the functionality you require, it is recommended that you use
that method instead.
Syntax
Parameters
name
The name of the new header variable.
value
The initial value stored in the new header variable.
Remarks
To avoid name ambiguity, name should not contain any underscore (_) characters. The
ServerVariables collection interprets underscores as dashes in the header name. For example, the
following script causes the server to search for a header named MY-HEADER.
Because the HTTP protocol requires that all headers be sent before content, in general you must modify
all outgoing headers before your ASP script generates any output. In IIS 4.0, this meant that you had to
call AddHeader in your script before any output (such as that generated by HTML code or the Write
method) was sent to the client.
However, with IIS 5.0, response buffering (enabled by the metabase property AspBufferingOn) is on
by default. Therefore, you can call the AddHeader method at any point in the script, as long as it
precedes any calls to Flush.
<HTML>
Here's some text on your Web page.
<% Response.AddHeader "WARNING", "Error Message Text" %> Here's some more interesting and
<% Response.Flush %>
<% Response.Write("some string") %>
</HTML>
In the preceding example, because the page is buffered by default, the server will not send output to the
client until all the scripts on the ASP page have been processed or until the Flush method is called. With
buffered output, calls to AddHeader can appear anywhere the script, so long as they precede any calls
to Flush. If the call to AddHeader appeared below the call to Flush in the preceding example, the
script would generate a run-time error.
You can use this method to send multiple copies of the same header with different values, as with
WWW-Authenticate headers.
Example
The following example uses the AddHeader method to request that the client use Basic authentication.
Note The preceding script merely informs the client browser which authentication to use. If you use this
script in your Web applications, you should ensure that the Web server has Basic authentication enabled.
Applies To
Response Object
See Also
AppendToLog
The AppendToLog method adds a string to the end of the Web server log entry for this request. You
can call it multiple times in one section of script. Each time the method is called it appends the specified
string to the existing entry.
Syntax
Response.AppendToLog string
Parameters
string
The text to append to the log file. Because fields in the log are comma-delimited, this string cannot
contain any comma characters (,).
Remarks
In order for the specified string to be recorded in the log file, you must enable the URI Stem option of
the Extended Properties property sheet for the site whose activity you wish to log.
Example
The following example adds the text "content updated" to the log file.
Applies To
Response Object
BinaryWrite
The BinaryWrite method writes the specified information to the current HTTP output without any
character conversion. This method is useful for writing non-string information such as binary data
required by a custom application.
Syntax
Response.BinaryWrite data
Parameters
data
The data to write to the HTTP output. This parameter will be of type VT_ARRAY | VT_UI1,
Example
If you have an object that generates an array of bytes, you can use the following call to BinaryWrite to
send the bytes to a custom application.
<%
Set objBinaryGen = Server.CreateObject("MyComponents.BinaryGenerator")
vntPicture = objBinaryGen.MakePicture
Response.BinaryWrite vntPicture
%>
Applies To
Response Object
See Also
Write
Clear
The Clear method erases any buffered HTML output. However, the Clear method erases only the
response body; it does not erase response headers. You can use this method to handle error cases. Note
that this method will cause a run-time error if Response.Buffer has not been set to TRUE.
Syntax
Response.Clear
Applies To
Response Object
See Also
End, Flush
End
The End method causes the Web server to stop processing the script and return the current result. The
remaining contents of the file are not processed.
Syntax
Response.End
Remarks
If Response.Buffer has been set to TRUE, calling Response.End will flush the buffer. If you do not
want output returned to the user, you should call Response.Clear first.
<%
Response.Clear
Response.End
%>
Applies To
Response Object
See Also
Buffer, Clear
Flush
The Flush method sends buffered output immediately. This method will cause a run-time error if
Response.Buffer has not been set to TRUE.
Syntax
Response.Flush
Remarks
If the Flush method is called on an ASP page, the server does not honor Keep-Alive requests for that
page.
Applies To
Response Object
Redirect
The Redirect method causes the browser to attempt to connect to a different URL.
Syntax
Response.Redirect URL
Parameters
URL
The Uniform Resource Locator that the browser is redirected to.
Remarks
Any response body content set explicitly in the page is ignored. However, this method does send other
HTTP headers set by this page to the client. An automatic response body containing the redirect URL as
a link is generated. The Redirect method sends the following explicit header, where URL is the value
passed to the method.
Example
The following example redirects the user to Microsoft’s primary Web site.
Applies To
Response Object
Write
The Write method writes a specified string to the current HTTP output.
Syntax
Response.Write variant
Parameters
variant
The data to write. This parameter can be any data type supported by the Visual Basic Scripting
Edition VARIANT data type, including characters, strings, and integers. This value cannot contain
the character combination %>; instead you should use the escape sequence %\>. The Web server
Example
The following examples use the Response.Write method to send output to the client.
The following example adds an HTML tag to the Web page output. Because the string returned by the
Write method cannot contain the character combination %>, the escape %\> has been used instead.
The following script
Applies To
Response Object
See Also
BinaryWrite
Server Object
This is preliminary documentation for IIS 5.0 and is subject to change.
The Server object provides access to methods and properties on the server. Most of these methods and
properties serve as utility functions.
Syntax
Server.property|method
Properties
ScriptTimeout The amount of time that a script can run before it times out.
Methods
Server Properties
? ScriptTimeout
ScriptTimeout
The ScriptTimeout property specifies the maximum amount of time a script can run before it is
terminated.
The timeout will not take effect while a server component is processing.
Syntax
Server.ScriptTimeout = NumSeconds
Parameters
NumSeconds
Specifies the maximum number of seconds that a script can run before the server terminates it. The
default value is 90 seconds.
Remarks
A default ScriptTimeout can be set for a Web service or Web server by using the AspScriptTimeout
property in the metabase. The ScriptTimeout property cannot be set to a value less than that specified
in the metabase. For example, if NumSeconds is set to 10, and the metabase setting contains the default
value of 90 seconds, scripts will time out after 90 seconds. However, if NumSeconds were set to 100,
the scripts would time out after 100 seconds.
For more information about using the metabase, see Using IIS Admin Objects.
Example
The following example causes scripts to time out if the server takes longer than 100 seconds to process
them:
The following example retrieves the current value of the ScriptTimeout property and stores it in the
variable TimeOut.
Applies To
Server Object
See Also
AspScriptTimeout
Server Methods
? CreateObject
? Execute
? GetLastError
? HTMLEncode
? MapPath
? Transfer
? URLEncode
CreateObject
The CreateObject method creates an instance of a server component. If the component has
implemented the OnStartPage and OnEndPage methods, the OnStartPage method is called at this
time. For more information about server components, see Installable Components for ASP.
Syntax
Server.CreateObject( progID )
Parameters
progID
Specifies the type of object to create. The format for progID is [Vendor.]Component[.Version].
Remarks
By default, objects created by the Server.CreateObject method have page scope. This means that they
are automatically destroyed by the server when it finishes processing the current ASP page.
To create an object with session or application scope, you can either use the <OBJECT> tag in the
Global.asa file and set the SCOPE attribute to SESSION or APPLICATION, or store the object in a
session or application variable.
For example, an object stored in a session variable, as shown in the following script, is destroyed when
the Session object is destroyed. That is, when the session times out, or the Abandon method is called.
You can also destroy the object by setting the variable to Nothing or setting the variable to a new value,
as shown below. The first example releases the object ad. The second replaces ad with a string.
You cannot create an object instance with the same name as a built-in object. For example, the following
returns an error.
Example
The preceding example creates a server component, MyAd, as a MSWC.AdRotator component that
can be used to automate rotation of advertisements on a Web page.
For more information about server components, see Building Components for ASP.
Applies To
Server Object
Execute
The Execute method calls an .asp file and processes it as if it were part of the calling ASP script. The
Execute method is similar to a procedure call in many programming languages.
Syntax
Server.Execute( Path )
Parameters
Path
A string specifying the location of the .asp file to execute. If an absolute path is specified for this
parameter then it must be for an .asp file within the same application space.
Remarks
The Server.Execute method provides a way of dividing a complex application into individual modules.
By employing the Server.Execute method, you can develop a library of .asp files that you can call as
needed. This approach is an alternative to server-side includes.
After IIS processes the .asp file specified in the input parameter to Server.Execute, the response is
returned to the calling ASP script. The executed .asp file may modify HTTP headers. However, as with
any .asp file, if the executed .asp file attempts to modify HTTP headers after it sends a response to the
client, it will generate an error.
The path parameter may be for either an absolute or a relative path. If the path is absolute, it must map to
an ASP script in the same application as the calling .asp file.
If either the calling or called .asp file contains a transaction directive, the status of the transaction will
apply to the .asp file which contains the directive. For example, if ASP1 below calls ASP2 and the
transaction is aborted while ASP2 is being processed, ASP2's OnTransactionAbort (if present) will be
called. After ASP2 completes processing, ASP1's OnTransactionAbort (if present) will be called.
ASP1:
<%@ Transaction=Required%>
<%
Server.Execute ("Page22.asp")
Sub OnTransactionAbort
Sub OnTransactionCommit
%>
Asp2.asp:
<%@
Transaction=Required
Sub OnTransactionAbort
Sub OnTransactionCommit
%>
Example
The following example demonstrates executing an .asp file that returns some text. The output from these
two scripts is:
I am going to ASP2
Here I am
ASP1
ASP2
Applies to
Server Object
See Also
GetLastError
The GetLastError method returns an ASPError Object describing the error condition that occurred.
This method is available only before the .asp file has sent any content to the client.
Syntax
Server.GetLastError ()
Remarks
If a 500;100 custom error has been defined for an ASP application, it may refer to an .asp file. In this
case, when an error occurs during the running of an .asp file within the application, the server will
automatically transfer to this ASP page via the Server.Transfer method. All of the state information
from the executing ASP application will be available to the .asp file that is handling the error. In addition,
the ASPError Object will be available, so you can expose the properties of the error through the .asp
file that you set up to handle the error.
The default Web site is configured to use the file \iishelp\common\500-100.asp. You can either use this
file for processing ASP errors, or create your own. If you want to change the .asp file for processing the
500;100 custom errors you can use the Internet Information Services snap-in.
Note A 500;100 custom error will be generated if IIS encounters an error while processing either
an .asp file or the application's Global.asa file.
Example
The following three examples demonstrate different sorts of errors that will generate a 500;100 custom
error. The three types of errors are:
? Pre-processing errors
? Script compiling errors
? Run-time errors
The first example demonstrates a pre-processing error, which IIS will generate when it tries to include
the file. This error will be generated because the include statement is missing the file parameter for the
include statement. The second example demonstrates a script compiling error. The scripting engine will
not compile this script because it is missing the keyword "next" in a For...Next loop. The third example
demonstrates a run-time error that will be caught because the script attempts to divide by 0.
Example 1
Example 2
<%
dim I
for i=1 to 1
nxt
%>
Example 3
<%
dim i,j
dim sum
sum=0
j=0
for i=1 to 10
sum=sum+1
next
sum=sum/j
%>
Applies To
Server Object
See Also
ASPError Object
HTMLEncode
Syntax
Server.HTMLEncode( string )
Parameters
string
Specifies the string to encode.
Example
If you view source, or open the page as a text file, you will be able to see the encoded HTML.
Applies To
Server Object
See Also
URLEncode
MapPath
The MapPath method maps the specified relative or virtual path to the corresponding physical directory
on the server.
Syntax
Server.MapPath( Path )
Parameters
Path
Specifies the relative or virtual path to map to a physical directory. If Path starts with either a
forward (/) or backward slash (\), the MapPath method returns a path as if Path is a full virtual
path. If Path doesn't start with a slash, the MapPath method returns a path relative to the
directory of the .asp file being processed.
Remarks
The MapPath method does not check whether the path it returns is valid or exists on the server.
Because the MapPath method maps a path regardless of whether the specified directories currently
exist, you can use the MapPath method to map a path to a physical directory structure, and then pass
that path to a component that creates the specified directory or file on the server.
You can use the relative path syntax for the Path parameter if the AspEnableParentPaths property is set
to TRUE (which is the default value). If you are concerned about allowing scripts to access the physical
directory structure, you can disable this feature by setting the AspEnableParentPaths property to
FALSE. You can accomplish this with either the Internet Information Services snap-in or with a script.
Example
For the examples below, the file data.txt is located in the directory, C:\Inetpub\Wwwroot\Script, as is the
test.asp file that contains the following scripts. The C:\Inetpub\Wwwroot directory is set as the server's
home directory.
The following example uses the server variable PATH_INFO to map the physical path of the current file.
The following script
<%= server.mappath(Request.ServerVariables("PATH_INFO"))%><BR>
c:\inetpub\wwwroot\script\test.asp<BR>
Because the path parameters in the following examples do not start with a slash character, they are
mapped relative to the current directory, in this case C:\Inetpub\Wwwroot\Script. The following scripts
<%= server.mappath("data.txt")%><BR>
<%= server.mappath("script/data.txt")%><BR>
c:\inetpub\wwwroot\script\data.txt<BR>
c:\inetpub\wwwroot\script\script\data.txt<BR>
The next two examples use the slash characters to specify that the path returned should be looked up as
complete virtual paths on the server. The following scripts
<%= server.mappath("/script/data.txt")%><BR>
<%= server.mappath("\script")%><BR>
c:\inetpub\wwwroot\script\data.txt<BR>
c:\inetpub\wwwroot\script<BR>
The following examples demonstrate how you can use either a forward slash (/) or a backslash (\) to
return the physical path to the home directory. The following scripts
<%= server.mappath("/")%><BR>
<%= server.mappath("\")%><BR>
c:\inetpub\wwwroot<BR>
c:\inetpub\wwwroot<BR>
Applies To
Server Object
See Also
AspEnableParentPaths
Transfer
The transfer method sends all of the information that has been assembled for processing by one .asp
Syntax
Server.Transfer (path)
Parameters
Path
The location of the .asp file to which control should be transferred.
Remarks
When you call Server.Transfer the state information for all the built-in objects will be included in the
transfer. This means that any variables or objects that have been assigned a value in the current page,
during the current session, or within the current application-state, will be maintained. In addition, all of the
current contents for the request collections will be available to the .asp file receiving the transfer.
If the path you specify in the input parameter is for an .asp file in another application, the .asp file will
execute as if it were in the application that contains the Server.Transfer command. In other words, all
variables and objects that have been given application scope either by other .asp files in the application
or by the application's Global.asa file will be available to the called .asp file.
Example
The following example demonstrates transferring from one .asp file to another .asp file, and sending the
session identifier to the client.
A session ID
I am going to ASP2
ASP1
ASP2
<HTML>
Applies To
Server Object
See Also
URLEncode
The URLEncode method applies URL encoding rules, including escape characters, to a specified string.
Syntax
Server.URLEncode( string )
Parameters
string
Specifies the string to encode.
Example
<%Response.Write(Server.URLEncode("http://www.microsoft.com")) %>
https%3A%2F%2Ffanyv88.com%3A443%2Fhttp%2Fwww%2Emicrosoft%2Ecom
Applies To
Server Object
See Also
HTMLEncode
Session Object
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use the Session object to store information needed for a particular user-session. Variables
stored in the Session object are not discarded when the user jumps between pages in the application;
The Web server automatically creates a Session object when a Web page from the application is
requested by a user who does not already have a session. The server destroys the Session object when
the session expires or is abandoned.
One common use for the Session object is to store user preferences. For example, if a user indicates
that they prefer not to view graphics, you could store that information in the Session object. For more
information on using the Session object, see Managing Sessions in the ASP Applications section.
Note Session state is only maintained for browsers that support cookies.
Syntax
Session.collection|property|method
Collections
Contents Contains the items that you have added to the session with script
commands.
StaticObjects Contains the objects created with the <OBJECT> tag and given session
scope.
Properties
CodePage The code page that will be used for symbol mapping.
LCID The locale identifier.
SessionID Returns the session identification for this user.
Timeout The timeout period for the session state for this application, in minutes.
Methods
Abandon This method destroys a Session object and releases its resources.
Contents.Remove This method deletes an item from the Contents collection.
Contents.RemoveAll This method deletes all items from the Contents collection.
Events
Scripts for the following events are declared in the Global.asa file.
Session_OnEnd
Session_OnStart
For more information about these events and the Global.asa file, see the Global.asa Reference.
Remarks
You can store values in the Session object. Information stored in the Session object is available
throughout the session and has session scope. The following script demonstrates storage of two types of
variables.
<%
Session("username") = "Janine"
Session("age") = 24
%>
However, if you store an object in the Session object and use VBScript as your primary scripting
language, you must use the Set keyword. This is illustrated in the following script.
You can then call the methods and properties exposed by MyComponent.class1 on subsequent Web
pages, by using the following.
<%
Set MyLocalObj1 = Session("Obj1")
MyLocalObj1.MyObjMethod
%>
Another way to create objects with session scope is to use the <OBJECT> tags in the Global.asa file.
You cannot, however, store a built-in object in a Session object. For example, each of the following
lines would return an error.
<%
Set Session("var1") = Session
Set Session("var2") = Request
Set Session("var3") = Response
Set Session("var4") = Server
Set Session("var5") = Application
%>
Before you store an object in the Session object, you should know what threading model it uses. Only
objects marked as both can be stored in the Session object without locking the session to a single
thread.
If you store an array in a Session object, you should not attempt to alter the elements of the stored array
directly. For example, the following script will not work:
This is because the Session object is implemented as a collection. The array element StoredArray(3)
does not receive the new value. Instead, the value is indexed into the collection, overwriting any
information stored at that location.
It is strongly recommended that if you store an array in the Session object, you retrieve a copy of the
array before retrieving or changing any of the elements of the array. When you are done with the array,
you should store the array in the Session object again so that any changes you made are saved. This is
demonstrated in the following example:
---file1.asp---
<%
'Creating and initializing the array
Dim MyArray()
Redim MyArray(5)
MyArray(0) = "hello"
MyArray(1) = "some other string"
Response.Redirect("file2.asp")
%>
---file2.asp---
<%
'Retrieving the array from the Session Object
'and modifying its second element.
LocalArray = Session("StoredArray")
LocalArray(1) = " there"
Example
The following code assigns the string MyName to a session variable called name, assigns a value to a
session variable called year, and assigns an instance of the some.Obj component to a variable called
myObj.
Session("name") = "MyName"
Session("year") = 96
Set Session("myObj") = Server.CreateObject("someObj")
%>
Session Collections
? Contents
? StaticObjects
The Session.Contents collection contains all of the items that have been established for a session
without using the <OBJECT> tag. The collection can be used to determine the value of a specific session
item, or to iterate through the collection and retrieve a list of all items in the session.
Syntax
Session.Contents( Key )
Parameters
Key
The name of the property to retrieve.
Remarks
You can use an iterating control structure to loop through the keys of the Contents collection. This is
demonstrated in the following example.
anArray(0)="one"
anArray(1)="second"
anArray(2)="third"
Session("anArray")=anArray
Session("scalar")="1234567890ABCDEFG"
set objConn=server.createobject("adodb.connection")
set Session("object")=objConn
The StaticObjects collection contains all of the objects created with the <OBJECT> tag within the
scope of the session object. The collection can be used to determine the value of a specific property for
an object, or to iterate through the collection and retrieve all properties for all objects.
Syntax
Session.StaticObjects( Key )
Parameters
Key
The property to retrieve.
Remarks
You can use an iterating control structure to loop through the keys of the StaticObjects collection. This
is demonstrated in the following example.
<%
Dim objProp
For Each objProp in Session.StaticObjects
If IsObject(Session.StaticObjects(objProp)) Then
Response.write(objProp & " : Session object cannot be displayed."&_
"<BR>")
Else
Response.write(objprop & " : " & Session.StaticObjects(objprop) &_
"<BR>")
End if
Next
%>
Session Properties
? CodePage
? LCID
? SessionID
? Timeout
CodePage
The CodePage property determines the code page that will be used to display dynamic content.
Syntax
Session.CodePage(=Codepage)
Parameters
Codepage
An unsigned integer that represents a valid code page for the system that is running the scripting
engine.
Remarks
A code page is a character set that can include numbers, punctuation marks, and other glyphs. Different
languages and locales may use different code pages. For example, ANSI code page 1252 is used for
American English and most European languages; OEM code page 932 is used for Japanese Kanji.
A code page can be represented in a table as a mapping of characters to single-byte values or multibyte
values. Many code pages share the ASCII character set for characters in the range 0x00 – 0x7F.
Applies To
Session Object
LCID
The LCID property determines the location identifier that will be used to display dynamic content.
Syntax
Session.LCID(=LCID)
Parameters
LCID
A valid locale identifier.
Remarks
An LCID specifies the locale identifier, which is a standard international abbreviation that uniquely
identifies one of the system-defined locales. If an LCID has been set using the @LCID directive
Session.LCID will override the value set by the directive.
Example
The following example demonstrates setting the locale to British English and using the VBScript
FormatCurrency method to display the value 125 as currency with the £ symbol:
<%
Session.LCID = 2057
Dim curNumb
curNumb = FormatCurrency(125)
Response.Write (curNumb)
%>
Applies To
Session Object
For more information, see Accommodating International Clients and Locale Identifiers.
SessionID
The SessionID property returns the session identifier, a unique identifier that is generated by the server
when the session is created. The session ID is returned as a LONG data type.
Syntax
Session.SessionID
Remarks
You should not use the SessionID property to generate primary key values for a database application.
This is because if the Web server is restarted, some SessionID values may be the same as those
generated before the server was stopped. Instead, you should use an auto-increment column data type,
such as IDENTITY with Microsoft® SQL Server, or COUNTER with Microsoft ® Access.
Applies To
Session Object
Timeout
The Timeout property specifies the timeout period assigned to the Session object for this application, in
minutes. If the user does not refresh or request a page within the timeout period, the session ends.
Syntax
Session.Timeout [ = nMinutes]
Parameters
nMinutes
Specifies the number of minutes that a session can remain idle before the server terminates it
automatically. The default is 10 minutes.
Applies To
Session Object
See Also
Abandon
Session Methods
? Abandon
? Contents.Remove
? Content.RemoveAll
Abandon
The Abandon method destroys all the objects stored in a Session object and releases their resources. If
you do not call the Abandon method explicitly, the server destroys these objects when the session times
out.
Syntax
Session.Abandon
Remarks
When the Abandon method is called, the current Session object is queued for deletion, but is not
actually deleted until all of the script commands on the current page have been processed. This means
that you can access variables stored in the Session object on the same page as the call to Abandon, but
not in any subsequent Web pages.
For example, in the following script, the third line prints the value Mary. This is because the Session
object is not destroyed until the server has finished processing the script.
<%
Session.Abandon
Session("MyName") = "Mary"
Reponse.Write(Session("MyName"))
%>
If you access the variable MyName on a subsequent Web page, it is empty. This is because MyName was
destroyed with previous Session object when the page containing the above example finished
processing.
The server creates a new Session object when you open a subsequent Web page after abandoning a
session. You can store variables and objects in this new Session object.
Example
The following example causes the session state to be released when the server finishes processing the
current page.
Applies To
Session Object
See Also
Timeout
Contents.Remove
The Remove method deletes a specific item from the Session object's Contents collection.
Syntax
Session.Contents.Remove( Item|Index )
Parameter
Item
The name of the member to remove from the collection.
Index
The index entry for the member to remove from the collection.
Remarks
The Contents.Remove method takes either a string or an integer as an input parameter. If the input
parameter is a string, the method will search the contents collection for an item with that name and
remove it. If the input parameter is an integer, the method counts that number of items from the start of
the collection, and removes the corresponding item.
Example
The following example adds and removes a variable called myName to the Session.Contents
collection.
<%
Session("myName") = " "
Session.Collection.Remove("myName")
%>
Applies To
Session Object
See Also
Session.Contents.RemoveAll
Contents.RemoveAll
The RemoveAll method deletes all items that have been added to the Session object's Contents
collection.
Syntax
Session.Contents.RemoveAll ()
Example
The following example removes all items that have been added to the Session.contents collection:
<%Session.Contents.RemoveAll()%>
Applies To
Session Object
See Also
Session.Contents.Remove
You can create dynamic, interactive Web pages by using the server components included with Active
Server Pages (ASP) in your scripts. This reference section contains information about and examples of
these components.
For information on server scripting with ASP, see Developing Web Applications. For more information
on the built-in objects supplied with the ASP, see Visual Basic Object Model.
Note The examples in this reference use Microsoft® Visual Basic® Scripting Edition (VBScript) as the
primary scripting language. However, ASP scripts can be written in any supported scripting language.
For information on how to change the primary scripting language, see Working with Scripting Languages.
Ad Rotator Component
This is preliminary documentation for IIS 5.0 and is subject to change.
The Ad Rotator component creates an Ad Rotator object that automates the rotation of advertisement
images on a Web page. Each time a user opens or reloads the Web page, the Ad Rotator component
displays a new advertisement based on the information you specify in a Rotator Schedule File.
You can record how many users click each advertisement by setting the URL parameter in the Rotator
Schedule file to direct users to the Redirection File. When you specify this parameter, each jump to an
advertiser's URL is recorded in the Web server activity logs.
File Names
Syntax
Parameters
AdRotator
Specifies the name of the AdRotator object created by the call to Server.CreateObject.
Properties
Methods
Example
The following example displays a different advertisement each time a user views the Web page.
The following HTML is generated by the GetAdvertisement method and is added to the page's output,
displaying the next advertisement in the Rotator Schedule file.
<A HREF="http://www.msn.com/isapi/adredir.asp?http://www.company.com/">
<IMG SRC="http://msnnt3web/ads/homepage/chlogolg.gif"
ALT="Check out the new Technology Center"
WIDTH=440 HEIGHT=60 BORDER=1></A>
The Rotator Schedule file contains information that the Ad Rotator component uses to manage and
display the various advertisement images. In it you can specify the details for the advertisements, such as
the size of the advertisement space, the image files to use, and the percentage of time that each file should
be displayed.
The Rotator Schedule file has two sections. The first section sets parameters that apply to all
advertisement images in the rotation schedule. The second section specifies file and location information
for each individual advertisement and the percentage of display time that each advertisement should
receive. The two sections are separated by a line containing only an asterisk (*).
In the first section there are four global parameters, each consisting of a keyword and a value. All are
optional. If you do not specify values for the global parameters, the Ad Rotator uses default values. In
this case, the first line of the file must contain only an asterisk (*).
Syntax
[REDIRECT URL]
[WIDTH numWidth]
[HEIGHT numHeight]
[BORDER numBorder]
adURL
adHomePageURL
Text
impressions
Parameters
URL
Specifies the path to the dynamic-link library (.dll) or application (.asp) file that implements
redirection. This path can be specified either fully (http://MyServer/MyDir/redirect.asp) or relative
to the virtual directory (/MyDir/redirect.asp).
numWidth
Specifies the width of the advertisement on the page, in pixels. The default is 440 pixels.
numHeight
Specifies the height of the advertisement on the page, in pixels. The default is 60 pixels.
numBorder
Specifies the thickness of the hyperlink border around the advertisement, in pixels. The default is a
1-pixel border. Set this parameter to 0 for no border.
adURL
The location of the advertisement image file.
adHomePageURL
The location of the advertiser's home page. If the advertiser does not have a home page, put a
hyphen (-) on this line to indicate that there is no link for this ad.
Text
Alternate text that is displayed if the browser does not support graphics, or has its graphics
capabilities turned off.
impressions
A number between 0 and 10000 that indicates the relative weight of the advertisement.
For example, if a Rotator Schedule file contains three ads with impressions set to 2, 3, and 5, the
first advertisement is displayed 20 percent of the time, the second 30 percent of the time, and the
third 50 percent of the time.
Remarks
If the sum of the impressions parameters for all items exceeds 10000, an error will be generated the first
time the Rotator Schedule file is accessed by a call to the GetAdvertisement method.
Example
The following script demonstrates how you can use a rotator schedule file to display a variety of
advertisements and how to include a redirection file.
---Adrot.txt---
REDIRECT /scripts/adredir.asp
WIDTH 440
HEIGHT 60
BORDER 1
*
http://kabaweb/ads/homepage/chlogolg.gif
http://www.bytecomp.com/
Check out the ByteComp Technology Center
20
http://kabaweb/ads/homepage/gamichlg.gif
-
Sponsored by Flyteworks
20
http://kabaweb/ads/homepage/ismodemlg.gif
http:// www.proelectron.com/
28.8 internal PC modem, only $99
80
http://kabaweb/ads/homepage/spranklg.gif
http://www.clocktower.com/
The #1 Sports site on the net
10
Redirection File
The Redirection file is a file that you create. It usually includes script to parse the query string sent by the
AdRotator object and to redirect the user to the URL associated with the advertisement that the user
clicked on.
You can also include script in the Redirection file to count the number of users that have clicked on a
particular advertisement, and save this information to a file on the server.
Example
The following example redirects the user to the advertiser's home page.
---Adredir.asp---
<% Response.Redirect(Request.QueryString("url")) %>
Ad Rotator Properties
This is preliminary documentation for IIS 5.0 and is subject to change.
Border
The Border property enables you to specify whether to display the advertisements with a surrounding
border.
Syntax
Border = size
Parameters
size
Specifies the thickness of the border that surrounds the displayed advertisement. The default is the
value set in the header of Rotator Schedule file.
Example
<%
Set ad = Server.CreateObject("MSWC.AdRotator")
ad.Border = 0
%>
<%= ad.GetAdvertisement("/ads/adrot.txt") %>
See Also
Clickable, TargetFrame
Clickable
The Clickable property enables you to specify whether the advertisements are displayed as hyperlinks.
Syntax
Clickable = value
Parameters
value
Specifies whether the advertisement should be a hyperlink. This parameter can be one of the
following values. The default value is TRUE.
Value Description
TRUE Display the advertisements as hyperlinks.
FALSE Do not display the advertisements as hyperlinks.
Example
The following example displays the advertisements as images only, not as hyperlinks.
<%
Set ad = Server.CreateObject("MSWC.AdRotator")
ad.Clickable = FALSE
%>
<%= ad.GetAdvertisement("/ads/adrot.txt") %>
See Also
Border, TargetFrame
TargetFrame
The TargetFrame property specifies the target frame into which the link should be loaded. This
property fulfills the same function as the TARGET parameter in an HTML anchor statement.
Syntax
TargetFrame = frame
Parameters
frame
Specifies the name of the frame in which to display the advertisement. This parameter can also be
one of the HTML frame-keywords, such as _TOP, _NEW, _CHILD, _SELF, _PARENT, or
_BLANK. The default value is NO FRAME.
Example
<%
Set ad = Server.CreateObject("MSWC.AdRotator")
ad.TargetFrame = AdFrame
%>
<%= ad.GetAdvertisement("/ads/adrot.txt") %>
See Also
Border, Clickable
Ad Rotator Methods
This is preliminary documentation for IIS 5.0 and is subject to change.
GetAdvertisement
The GetAdvertisement method retrieves the next advertisement from the Rotator Schedule file. Each
time the script is run, such as when a user opens or refreshes a page, the method retrieves the next
scheduled advertisement.
Syntax
GetAdvertisement( rotationSchedulePath )
Parameters
rotationSchedulePath
Specifies the location of the Rotator Schedule file relative to the virtual directory. For example, if
the physical path was C:\Inetpub\Wwwroot\Ads\Adrot.txt (where Wwwroot is the "/" virtual
directory) you would specify the path \Ads\Adrot.txt.
Return Values
Example
The following example gets an advertisement from the Adrot.txt file in the /Ads/ virtual directory.
The Browser Capabilities component creates a BrowserType object that provides your scripts with a
description of the capabilities of the client's Web browser.
When a browser connects to the Web server, it automatically sends an HTTP User Agent header. This
header is an ASCII string that identifies the browser and its version number. The BrowserType object
compares the header to entries in the Browscap.ini file.
If it finds a match, the BrowserType object assumes the properties of the browser listing that matched
the User Agent header.
If the object does not find a match for the header in the Browscap.ini file, it searches for the closest
match using the * and ? wildcards. If a match can not be found using wildcards, the object will use the
default browser settings if they have been specified in the Browscap.ini file. If the object does not find a
match and default browser settings have not been specified in the Browscap.ini file, the object sets every
property to the string "UNKNOWN."
You can add properties or new browser definitions to this component simply by updating the
Browscap.ini file.
File Names
Syntax
Parameters
BrowserType
Specifies the name of the BrowserType object created by the call to Server.CreateObject.
Example
The following example uses the BrowserType object to display a table showing some of the capabilities
of the current browser.
Browscap.ini File
You can declare property definitions for any number of browsers in the Browscap.ini file. You can also
set default values to use if the client's browser is not one of the listed definitions.
For each browser definition, you provide an HTTP User Agent header and the properties and values you
wish to associate with that header. For more information on the format of the HTTP User Agent header,
refer to the HTTP specification available at http://www.w3.org.
Syntax
[; comments]
[HTTPUserAgentHeader]
[parent = browserDefinition]
[property1 = value1]
...
[propertyN = valueN]
[defaultProperty1 = defaultValue1]
...
[defaultPropertyN = defaultValueN]
Parameters
comments
Any line that starts with a semicolon (;). Comments, which are ignored by the BrowserType
object, can occur anywhere in the Browscap.ini file.
HTTPUserAgentHeader
Specifies the HTTP User Agent header to associate with the browser-property value statements
specified in propertyN. The Browscap.ini file may contain multiple browser definitions, each one
starting with a unique HTTPUserAgentHeader value.
You can use the asterisk (*) character as a wildcard character in the HTTPUserAgentHeader to
replace zero or more characters and the (?) character as a wildcard to replace a single character.
Note The BrowserType object first attempts to match exactly the User Agent header to a value of
HTTPUserAgentHeader. If that fails, it attempts to make a match that uses wildcard characters.
If more than one browser definition containing wildcard characters matches the User Agent header, the
BrowserType object returns the properties of the definition which most closely matches the User Agent
header. The closest match is the match which replaces the fewest characters.
browserDefinition
An optional parameter specifying the HTTP User Agent header-string of a browser to use as the
parent browser. The current browser's definition will inherit all of the property values declared in
the parent browser's definition. This helps define properties for a new version of a browser,
because new versions usually retain most of the properties of the previous release. These inherited
property values can be overwritten by explicitly setting a new value for the property by using the
syntax propertyN = valueN.
propertyN
An optional parameter specifying the name of the browser property to set. It must start with an
alphabetic character and cannot be longer than 255 characters. Each browser definition in the
Browscap.ini file can contain as many statements of property values as needed. For example, if
your application only needed to know whether or not a user's browser supported VBScript, you
would only need one property statement for each browser definition.
Property Description
ActiveXControls Specifies whether the browser supports ActiveX® controls.
Backgroundsounds Specifies whether the browser supports background sounds.
Beta Specifies whether the browser is beta software.
Browser Specifies the name of the browser.
Cdf Specifies whether the browser supports the Channel Definition
Format for Webcasting.
Cookies Specifies whether the browser supports cookies.
Frames Specifies whether the browser supports frames.
Javaapplets Specifies whether the browser supports Java applets.
Javascript Specifies whether the browser supports JScript.
Platform Specifies the platform that the browser runs on.
Tables Specifies whether the browser supports tables.
Vbscript Specifies whether the browser supports VBScript.
Version Specifies the version number of the browser.
valueN
An optional parameter specifying the value of propertyN. This value is a string by default. To
specify an integer, prefix the value with a number sign (#). To specify a Boolean value, use TRUE
or FALSE.
defaultPropertyN
An optional parameter specifying the name of the browser property to which to assign a default
value if none of the defined HTTPUserAgentHeader values match the HTTP User Agent header
sent by the browser.
defaultValueN
An optional parameter specifying the value of defaultPropertyN. This value is a string by default.
To specify an integer, prefix the value with a number sign (#). To specify a Boolean value, use
TRUE or FALSE.
Example
In the following example, the parent tag allows the second browser definition to inherit from the first, so
that the Microsoft® Internet Explorer 5.x definition inherits all the properties of Microsoft® Internet
Explorer 5.0 definition (for example, frames=TRUE, tables=TRUE, and cookies=TRUE). It adds
platform-specific information by adding the line, platform=WinNT, and overwrites the version
information in the line, version=4.0.
;;ie 5.0
[IE 5.0]
browser=IE
Version=5.0
majorver=#5
minorver=#0
frames=TRUE
tables=TRUE
cookies=TRUE
backgroundsounds=TRUE
vbscript=TRUE
javascript=TRUE
javaapplets=True
ActiveXControls=TRUE
Win16=False
beta=False
AK=False
SK=False
AOL=False
;;ie 5.x
[Mozilla/4.0 (compatible; MSIE 5.*; Windows NT)]
parent=IE 5.0
version=5.0
minorver=0
platform=WinNT
; Default Browser
[Default Browser Capability Settings]
browser=Default
frames=FALSE
tables=TRUE
cookies=FALSE
backgroundsounds=FALSE
vbscript=FALSE
javascript=FALSE
A new way of determining client capabilities was added in IIS 5.0. If the client sends a cookie describing
their capabilities as part of the request, your ASP page can create an instance of the Browser
Capabilities Component that adds the name value pairs specified by the cookie as properties.
For example, if the client sent a cookie that contained a name-value pair of userLanguage=Spanish, the
Browser Capabilities component would add a userLanguage property and set the value for this property
to Spanish.
Important If the METADATAmetatag exists in a file that is requested by the client as a result of a
redirection using the Server.Transfer or Server.Execute methods, the metatag will be ignored by IIS.
METADATA metatags in the file that actually contains the redirect, however, will be processed
normally.
The following example demonstrates using a cookie to determine browser capabilities. Two files are
required:
? Sendcook.htm runs on the client and uses DHTML to determine a list of properties that have been
Sendcook.htm
<HTML XMLNS:IE>
<HEAD>
<STYLE>
IE\:clientcaps {behavior:url(#default#clientcaps)}
</STYLE>
<SCRIPT language="JavaScript">
function stopAllErrors()
{
// No errors should be presented to the user if they occur.
return true;
}
window.onerror = stopAllErrors;
function window.onload ()
{
bcString = "width= " + oClientCaps.width;
bcString += "&height= " + oClientsCaps.height;
bcString += "&bufferDepth= " + oClientCaps.bufferDepth;
bcString += "&colorDepth= " + oClientCaps.colorDepth;
bcString += "&cookies= " + oClientCaps.cookies;
bcString += "&platform= " + oClientCaps.platform;
document.cookie = "BrowsCap= " + bcString;
}
</SCRIPT>
</HEAD>
<BODY>
<IE:clientcaps ID="oClientCaps" />
</BODY>
<HTML>
Checkcap.asp
<HTML>
<BODY>
<!--METADATA TYPE="Cookie" NAME="BrowsCap" SRC="sendcook.htm"-->
<% Set myBrowsCap = Server.CreateObject("MSWC.BrowserType") %>
<%
Response.write(width= " +myBrowsCap.width + "<BR>"
Response.write(height= " +myBrowsCap.height + "<BR>"
Response.write(bufferDepth= " +myBrowsCap.bufferDepth + "<BR>"
Response.write(colorDepth= " +myBrowsCap.colorDepth + "<BR>"
Response.write(cookies= " +myBrowsCap.cookies + "<BR>"
Response.write(platform= " +myBrowsCap.platform + "<BR>"
%>
</BODY>
</HTML>
For more information on the design implications for determining browser capabilities, see Client
Capabilities.
The Content Linking component creates a Nextlink object that manages a list of URLs so that you can
treat the pages in your Web site like the pages in a book. You can use the Content Linking component to
automatically generate and update tables of contents and navigational links to previous and subsequent
Web pages. This is ideal for applications such as online newspapers and forum message listings.
The Content Linking component references a Content Linking List file that contains the list of the linked
Web pages. This list is stored on the Web server.
File Names
Syntax
Parameters
NextLink
Specifies the name of the object created by the call to Server.CreateObject.
Methods
GetListCount Counts the number of items linked in the Content Linking List file.
GetListIndex Gets the index of the current page in the Content Linking List file.
GetNextDescription Gets the description of the next page listed in the Content Linking
List file.
GetNextURL Gets the URL of the next page listed in the Content Linking List
file.
GetNthDescription Gets the description of the Nth page listed in the Content Linking
List file.
GetNthURL Gets the URL of the Nth page listed in the Content Linking List
file.
GetPreviousDescription Gets the description line of the previous page listed in the Content
Linking List file.
GetPreviousURL Gets the URL of the previous pages listed in the Content Linking
List file.
Example
<OL>
<%
Set NextLink = Server.CreateObject ("MSWC.NextLink")
count = NextLink.GetListCount ("/data/nextlink.txt")
I = 1
%>
<UL>
<% Do While (I <= count) %>
<LI><A HREF=" <%= NextLink.GetNthURL ("/data/nextlink.txt", I) %> ">
<%= NextLink.GetNthDescription ("/data/nextlink.txt", I) %> </A>
<%
I = (I + 1)
Loop
%>
</UL>
</OL>
The following script adds the next-page and previous-page buttons to an HTML file.
<%
Set NextLink = Server.CreateObject ("MSWC.NextLink")
If (NextLink.GetListIndex ("/data/nextlink.txt") > 1)
Then
%>
Previous Page</A>
<% End If %>
<A HREF=" <%= NextLink.GetNextURL ("/data/nextlink.txt") %> ">Next Page</A>
The Content Linking List file contains one line of text for each URL in the list. Each line ends in a carriage
return and each item on a line is separated by a TAB character.
Syntax
Values
Web-page-URL
The virtual or relative URL of the Web page in the format filename or directory\filename.
Absolute URLs, those that start with "http:", "//", or "\\", are not supported and will not be
processed by methods such as GetNextURL and GetListIndex. When building your content
path, you should ensure that no collisions or infinite loops can occur.
text-description
A value containing text that describes Web-page-URL.
comment
Explanatory text that is not processed by the component.
Example
The following text file creates a list of URLs that can be used by the Content Linking component.
---Nextlink.TXT---
Story1.htm Highlights From the Hockey Playoffs
Story2.htm Congress Passes New Welfare Initiative
Story3.htm Cider Recipes to Warm Long Winter Nights
Story4.htm Winter Storm to bring more snow to East
Story5.htm Reducing Stress on the Job
Sain.htm Return to the table of contents
? GetListCount
? GetListIndex
? GetNextDescription
? GetNextURL
? GetNthDescription
? GetNthURL
? GetPreviousDescription
? GetPreviousURL
GetListCount
The GetListCount method retrieves the total number of Web pages listed in the Content Linking List
file.
Syntax
GetListCount( listURL )
Parameters
listURL
The location of the Content Linking List file.
Return Values
See Also
GetListIndex
GetListIndex
The GetListIndex method retrieves the index number of the current item in the Content Linking List file.
Syntax
GetListIndex( listURL )
Parameters
listURL
The location of the Content Linking List file.
Return Values
The GetListIndex method returns an integer index value specifying the current page's position on the file
list. The index number of the first item is 1. The method returns 0 if the current page is not in the Content
Linking List file.
See Also
GetListCount
GetNextDescription
The GetNextDescription method retrieves the text description of the next item in the Content Linking
List file.
Syntax
GetNextDescription( listURL )
Parameters
listURL
The location of the Content Linking List file.
Return Values
The GetNextDescription method returns an ASCII string describing the next item in the Content
Linking List file. If the current page is not found in the list file, GetNextDescription returns the string
description of the last page on the list.
See Also
GetNextURL
The GetNextURL method retrieves the URL of the next item in the Content Linking List file.
Syntax
GetNextURL( listURL )
Parameters
listURL
The location of the Content Linking List file.
Return Values
This method returns the URL of the next page specified in the Content Linking List file. If the current
page is not specified in the Content Linking List file, GetNextURL returns the URL of the last page on
the list.
Example
The following example uses the GetNextURL method to embed a link to the next page in the Content
Linking List file. The advantage of using GetNextURL is that when you change the order or number of
the content pages, you only have to update the list in Content Linking List file and do not need to update
the navigational links on each page.
See Also
GetNthDescription
The GetNthDescription method retrieves a text description of the Nth item in the Content Linking List
file.
Syntax
GetNthDescription( listURL, i )
Parameters
listURL
The location of the Content Linking List file.
i
The index number of an item in the Content Linking List file.
Return Values
See Also
GetNthURL
The GetNthURL method returns the URL of the Nth item in the Content Linking List file.
Syntax
GetNthURL( listURL, i )
Parameters
listURL
The location of the Content Linking List file.
i
The index number of an item in the Content Linking List file.
Return Values
See Also
GetPreviousDescription
The GetPreviousDescription method retrieves a text description of the previous item in the Content
Linking List file.
Syntax
GetPreviousDescription( listURL )
Parameters
listURL
The location of the Content Linking List file.
Return Values
This method returns a string describing either the previous item in the Content Linking List file or, if the
current page is not in the file, the first item on the list.
See Also
GetPreviousURL
The GetPreviousURL method returns the URL of the previous item in the Content Linking List file.
Syntax
GetPreviousURL( listURL )
Parameters
listURL
The location of the Content Linking List file.
Return Values
This method returns a string containing the URL of the previous item in the Content Linking List file. If the
current page is not specified in the Content Linking List file, GetPreviousURL returns the URL of the
first page in the file.
See Also
The Content Rotator component creates a ContentRotator object that automatically rotates HTML
content strings on a Web page. Each time a user requests the Web page, the object displays a new
HTML content string based upon information that you specify in a Content Schedule File.
Because the content strings can contain HTML tags, you can display any type of content that HTML can
represent: text, images, or hyperlinks. For example, you can use this component to rotate through a list of
daily quotations or hyperlinks, or to change text and background colors each time the Web page is
opened.
Syntax
Parameters
oVar
Specifies the name of the ContentRotator object created by the call to Server.CreateObject.
Methods
Remarks
Because the ContentRotator object uses a random generator to select which of the weighted content
strings is displayed, a string may be repeated. This is most likely to occur if there are few entries in the
Content Schedule file, or if one entry is weighted much higher than the others.
Example
The following example displays a different tip of the day each time a user views the Web page.
<%
Set Tip = Server.CreateObject("MSWC.ContentRotator")
Tip.ChooseContent("/tips/tiprot.txt")
%>
The Content Schedule file contains information that the ContentRotator object uses to manage and
display the specified content.
In this file you include any number of HTML content string entries. Each entry consists of two parts: a
line that begins with double percentage signs (%%) and contains both the relative weight and any
comments, and a second part that contains the HTML content string itself.
Syntax
%% [#Weight] [//Comments]
ContentString
Parameters
Weight
This optional parameter specifies a number between 0 and 10000 that indicates the relative weight
of the HTML content string. The probability of a particular content string being displayed by the
ContentRotator object can be expressed as the Weight of that content string divided by the sum
of Weight values for all entries in the Content Schedule file.
For example, if a Content Schedule file contained three content strings with respective weights of
1, 3, and 4, the Content Rotator displays the first content string one-eighth of the time, the second
string three-eighths of the time, and the third string half of the time.
If the sum of all weight values exceeds 10000, an error will be generated when the schedule file is
accessed by a call to either the GetAllContent or ChooseContent methods.
Comments
This optional parameter contains comments about the entry. These comments are for development
use only and are not displayed to the user. If you require more than one line of comments, you
must start each additional comment line with a line delimiter (%%) followed by a comment
delimiter (//).
ContentString
The HTML content that the ContentRotator object displays. For example, you can present a
line of text, an image, or a sound.
ContentString may include one or more lines. The ContentRotator object treats everything
between blocks of double percent signs (%%) as a single HTML content string.
Example
The following is an example of a Content Schedule file. Note that because the content strings can contain
HTML tags, you can display any type of content that can be represented with HTML, including text,
images, and hyperlinks.
-------------Content.txt--------------------
%% // Because no value is set for Weight, the default value is 1.
Don't run with scissors.
%%
Here's the <A HREF="secret.asp">secret link.</A>
ChooseContent
This is preliminary documentation for IIS 5.0 and is subject to change.
The ChooseContent method retrieves an HTML content string from the Content Schedule file and
displays it on the current page. The method retrieves a new content string each time the script is run, such
as when a user opens or reloads a page.
Syntax
ChooseContent( content-schedule-path )
Parameters
content-schedule-path
Specifies the location of the Content Schedule file.
This parameter can be specified either as a relative or virtual path. For example, if the Content
Schedule file, Content.txt, and the .asp file that called ChooseContent both resided in the
directory /MyApp/Tips/, where MyApp is a virtual directory on the server, then either the full
virtual path (/MyApp/Tips/Content.txt) or the relative path (Content.txt) could be specified for
content-schedule-path.
The ContentRotator object calls the Server.MapPath method to map the specified path to a
physical directory. For more information, see the Server Object reference pages.
Return Value
Remarks
Because the ContentRotator object uses a random generator to select which of the weighted content
strings is displayed, a string may be repeated. This is most likely to occur if there are few entries in the
Content Schedule file, or if one entry is weighted much higher than the others.
Example
The following example gets a new tip from the content.txt file in the /Tips/ virtual directory.
<%
Set NextTip = Server.CreateObject("MSWC.ContentRotator")
NextTip.ChooseContent("/Tips/Content.txt")
%>
GetAllContent
This is preliminary documentation for IIS 5.0 and is subject to change.
The GetAllContent method retrieves all of the HTML content strings from the Content Schedule file
and writes them directly to the Web page as a list with an <HR> tag after each entry.
This method is typically used during authoring, to proofread the Content Schedule file.
Syntax
GetAllContent( content-schedule-path )
Parameters
content-schedule-path
Specifies the location of the Content Schedule file.
This parameter can be specified either as a relative or virtual path. For example, if the Content
Schedule file, content.txt, and the .asp file that called GetAllContent both resided in the
directory /MyApp/Tips/, where MyApp is a virtual root on the server, then either the full virtual
path (/MyApp/Tips/content.txt) or the relative path (content.txt) could be specified for content-
schedule-path.
The ContentRotator object calls the Server.MapPath method to map the specified path to a
physical directory. For more information, see the Server Object Reference pages.
Return Values
None.
Remarks
The Content Rotator component uses the Response.Write method to write output directly to the .asp
page that called the GetAllContent method. For more information, see the Response Object reference
page.
Example
The following example uses the GetAllContent method to display all of the entries in the Content
Schedule file.
<H1>smile</H1>
be your umbrella.
</FONT>
<HR>
<IMG SRC="/images/happy.gif">
<HR>
Counters Component
This is preliminary documentation for IIS 5.0 and is subject to change.
The Counter component creates a Counters object that can create, store, increment, and retrieve any
number of individual counters.
A counter is a persistent value that contains an integer. You can manipulate a counter with the Get,
Increment, Set, and Remove methods of the Counters object. Once you create the counter, it
persists until you remove it.
Counters do not automatically increment on an event like a page hit. You must manually set or increment
counters using the Set and Increment methods.
Counters are not limited in scope. Once you create a counter, any page on your site can retrieve or
manipulate its value. For example, if you increment and display a counter named hits in a page called
Page1.asp, and you increment hits in another page called Page2.asp, both pages will increment the same
counter. If you hit Page1.asp, and increment hits to 34, hitting Page2.asp will increment hits to 35. The
next time you hit Page1.asp, hits will increment to 36.
All counters are stored in a single text file, Counters.txt, which is located in the same directory as the
ounters.dll file.
Syntax
Create the Counters object one time on your server by adding the following to the Global.asa file:
<OBJECT
RUNAT=Server
SCOPE=Application
ID=Counter
PROGID="MSWC.Counters">
</OBJECT>
Remarks
Only create one Counters object in your site. This single Counters object can create any number of
individual counters.
Note For Internet Information Services on Windows® 95 or later, a Counters component has already
been specified in the Global.asa file in the default virtual directory. You can work with the Counters
object the component creates as if it were a built-in object by calling Counters.Get,
Counters.Increment, Counters.Remove, and Counters.Set. You should not create another instance
of the Counters object.
Methods
Example
Create an instance of the Counters object in the Global.asa file with the ID attribute set to Counter:
You can then use that Counters object on one page to create all the counters you need:
Then on another page you can increment the counter in the following manner:
Get
This is preliminary documentation for IIS 5.0 and is subject to change.
The Get method takes the name of a counter and returns the current value of the counter. If the counter
doesn't exist, the method creates it and sets it to 0.
Syntax
Counters.Get(CounterName)
Parameters
CounterName
A string containing the name of the counter.
Example
Display the value a counter with <%= Counters.Get(CounterName) %>. Assign the value of the
counter to a variable with <% countervar = Counters.Get(CounterName) %>.
The following script displays the vote tally from a poll about favorite colors.
<%
If colornumber = "1" Then
Counters.Increment("greencounter")
Else
If colornumber = "2" Then
Counters.Increment("bluecounter")
Else
If colornumber = "0" Then
Counters.Increment("redcounter")
End If
End If
End If
%>
<P>Current vote tally:
<P>red: <% =Counters.Get("redcounter") %>
<P>green: <% = Counters.Get("greencounter") %>
<P>blue: <% = Counters.Get("bluecounter") %>
See Also
Increment
This is preliminary documentation for IIS 5.0 and is subject to change.
The Increment method takes the name of a counter, adds 1 to the current value of the counter, and
returns the counter's new value. If the counter doesn't exist, the method creates it and sets its value to 1.
Syntax
Counters.Increment(CounterName)
Parameters
CounterName
A string containing the name of the counter.
Example
Increment the value of a counter with <% Counters.Increment(CounterName) %>. Increment and
display the value of a counter with <%= Counters.Increment(CounterName) %>.
To retrieve the value of a counter, use Counters.Get. To set a counter to a specific value, use
Counters.Set.
<P>There have been <%= Counters.Increment("hits") %> visits to this Web page. </P>
In this example, Counters.Increment increases the counter by one each time the client requests the
page from the server.
See Also
Remove
This is preliminary documentation for IIS 5.0 and is subject to change.
The Remove method takes the name of a counter, removes the counter from the Counters object, and
deletes the counter from the Counters.txt file.
Syntax
Counters.Remove( CounterName )
Parameters
CounterName
A string containing the name of the counter.
Example
The following code removes the counter hitscounter from the ounters.txt file.
See Also
Set
This is preliminary documentation for IIS 5.0 and is subject to change.
The Set method takes the name of a counter and an integer, sets the counter to the value of the integer,
and returns the new value. If the counter doesn't exist, Counters.Set creates it and sets it to the value of
the integer.
Syntax
Counters.Set(CounterName, int)
Parameters
CounterName
A string containing the name of the counter.
int
The new integer value for CounterName.
Example
See Also
The Database Access component uses ActiveX® Data Objects (ADO) to access information stored in a
database or other tabular data structure.
For information about ADO see http://www.microsoft.com/data/ or the Microsoft Data Access SDK in
the Platform SDK.
Note To use the constants specified in the ADO Reference, you must either include a file that contains
information about the ADO constants or include a reference to the ADO type library in your Global.asa
file. Using a type library is generally a better option. The following example demonstrates using the ADO
type library to access constants.
Instead of:
You would include the following type library declaration in the Global.asa file for the application.
For more information about type libraries and constants, see Using Variables and Constants. For more
information about data access, see Accessing a Data Source and Accessing Data with ASP.
The File Access component exposes methods and properties you can use to access a computer's file
system. You can use the File Access Component to create a FileSystemObject object which provides
the methods properties and collections you use to access the file system.
Logging Utility
This is preliminary documentation for IIS 5.0 and is subject to change.
The IIS Log component is used to create an IISLog object, which enables your applications to read
from the IIS log. This component allows you to quickly create, for example, ASP scripts or VB
components that programmatically walk through daily log files so that certain types of information can be
extracted.
Important The user accessing the ASP script that instantiates the IISLog component must be
authenticated as an Administrator or Operator on the server on which IIS is running. If the user is only
anonymous, the IIS Log component will not function properly.
File Names
Syntax
Parameters
oVar
Specifies the name that can be used as a reference to the IISLog component.
Methods
Properties
Remarks
The following steps are necessary to use the IIS Log component effectively:
1. Use the OpenLogFile method to specify from which log file or files the IISLog component
should read.
2. Use the ReadLogRecord to read the appropriate log records.
3. Use the IIS Log component properties to retrieve specific information from the log records.
Important Only log files created by logging modules that support log file reading will be accessible
through this component. The four built-in logging modules that come with IIS support log-file reading, but
if you are using a custom or third-party logging module, you will need to enhance the logging module. See
Extending IIS Logging Capabilities for more information.
AtEndOfLog
This method indicates whether there are any more records available in the log file. It only returns TRUE
after an attempt to read past the end of the file.
Syntax
AtEndOfLog()
Return Values
Returns TRUE if there are no more records available in the log file for reading. Otherwise, returns
FALSE.
CloseLogFiles
This method causes the IISLog component to close open log files.
Syntax
CloseLogFiles( IOMode )
Parameters
IOMode
A Long that indicates which log file or files should be closed. It can take one of the following
values:
Constant Value Description
ForReading 1 Closes log files that have been
opened for reading.
ForWriting 2 Closes log files that have been
opened for writing.
AllOpenFiles 32 Closes all open log files.
OpenLogFile
This method allows you to open a log file for reading or writing.
Syntax
Parameters
FileName
Name of the log file to open.
IOMode
Optional parameter indicating whether the log file is opened for reading or writing. This parameter
can take one of the following values:
Constant Value Description
ForReading 1 Opens the specified log file for
reading.
ForWriting 2 Opens the specified log file for
writing.
Optional parameter indicating the logging modules should only return records matching this server
instance.
OutputLogFileFormat
Optional parameter indicating the format for log files opened for writing.
ReadFilter
This method allows you to read log records between a date and time range.
Syntax
Parameters
startDateTime
Optional parameter indicating date and time after which log records are to be read.
endDateTime
Optional parameter indicating date and time before which log records are to be read.
ReadLogRecord
This method allows you to read the next available log record.
Syntax
ReadLogRecord()
See Also
AtEndOfLog
WriteLogRecord
This method allows you to write new log records that have been read from another IISLog object.
Syntax
WriteLogRecord( IISLog )
Parameters
IISLog
The object indicating where the log file records are read.
BytesReceived
This property enables you to retrieve the number of bytes received during the operation from the current
log record.
Syntax
count = BytesReceived
Parameters
count
The number of bytes received.
BytesSent
This property enables you to retrieve the number of bytes sent during the operation referred to by the
current log record.
Syntax
count = BytesSent
Parameters
count
The number of bytes sent.
ClientIP
This property allows you to retrieve the client's IP address for the operation referred to by the current log
record.
Syntax
var = ClientIP
Parameters
var
The client's IP address.
Cookie
Syntax
var = Cookie
Parameters
var
The cookie.
CustomFields
This property allows you to retrieve any extra HTTP headers that were included in the HTTP operation
referred to by the current log record. The extra headers returned are contained within a two-dimensional
array, consisting of key-value pairs.
Syntax
var = CustomFields
Parameters
var
A two-dimensional array of variants. Each pair of variants forms a key-value pair that describes an
HTTP header.
Remarks
CustomFields can be used to retrieve any custom or special fields that were logged by IIS.
DateTime
This property allows you to retrieve the date and time from the current log record.
Syntax
var = DateTime
Parameters
var
The date and time.
Method
This property enables you to extract the HTTP operation type from the current log record.
Syntax
var = Method
Parameters
var
The HTTP operation type such as GET or PUT.
ProtocolStatus
This property allows you to determine the HTTP protocol status code for the HTTP operation referred
to by the current log record.
Syntax
var = ProtocolStatus
Parameters
var
The HTTP protocol status code.
ProtocolVersion
This property allows you to retrieve the protocol version string from the current log record.
Syntax
var = ProtocolVersion
Parameters
var
The protocol version string.
Referer
Syntax
var = Referer
Parameters
var
The referrer URL.
ServerIP
This property allows you to retrieve the server's IP address for the operation referred to by the current
log record.
Syntax
var = ServerIP
Parameters
var
The server's IP address.
ServerName
This property permits you to retrieve the name of the computer for the operation referred to by the
current log record.
Syntax
var = ServerName
Parameters
var
The computer's name.
ServerPort
This property allows you to retrieve the port number that was used in the operation referred to by the
current log record.
Syntax
var = ServerPort
Parameters
var
The port number.
ServiceName
This property allows you to extract the name of the service from the current log record. The
ServiceName includes the server instance.
Syntax
var = ServiceName
Parameters
var
The service name and server instance (such as "W3SVC1000" or "MSFTPSVC1").
TimeTaken
This property allows you to determine the total processing time required for the operation referred to by
the current log record.
Syntax
var = TimeTaken
Parameters
var
The total time for processing.
URIQuery
This property enables you to extract any HTTP request parameters (also known as the query string) that
were passed during the HTTP operation referred to by the current log record.
Syntax
var = URIQuery
Parameters
var
The HTTP request parameters.
URIStem
This property allows you to extract the target URL from the current log record.
Syntax
var = URIStem
Parameters
var
The target URL string.
UserAgent
This property allows you to examine the browser user agent string.
Syntax
var = UserAgent
Parameters
var
The user agent string.
UserName
This property enables you to discover the user name for non-anonymous clients that participated in the
operation referred to by the current log record.
Syntax
var = UserName
Parameters
var
The client's user name.
Win32Status
This property allows you to determine the Win32 status code from the current log record.
Syntax
var = Win32Status
Parameters
var
The Win32 status code.
MyInfo Component
This is preliminary documentation for IIS 5.0 and is subject to change.
The MyInfo component creates a MyInfo object that keeps track of personal information, such as the
site administrator's name, address, and display choices. Typically, the administrator types this information
directly into the Web server interface. However, you can set the values of the properties directly using a
script in an ASP page.
Each property of a MyInfo object returns a string. If a MyInfo property has no value set, the property
returns an empty string.
The MyInfo object can have properties in addition to the ones documented here. The properties listed
in the table below are implemented by Personal Web Server to keep track of information entered into
the Personal Web Services interface. If you use MyInfo on IIS, these properties will not be
implemented.
You can create new MyInfo properties by simply assigning a string value to them. For example:
<%
MyInfo.DogName = "Snoopy"
MyInfo.DogBreed = "Beagle"
%>
creates the new properties DogName and DogBreed. These new properties are stored persistently along
with the other MyInfo properties.
Create new MyInfo properties for values that remain consistent throughout a site.
The values of MyInfo properties are stored in a single text file, Myinfo.xml. MyInfo.xml is installed to
the \winnt\system32 directory on Windows 2000, and to the root directory on Windows95 or later.
File Names
Syntax
Create a MyInfo object once in the Global.asa file by adding the following:
<OBJECT
RUNAT=Server
SCOPE=Session
ID=MyInfo
PROGID="MSWC.MyInfo">
</OBJECT>
Remarks
Note For Personal Web Server for Windows® 95, the <OBJECT> declaration that creates MyInfo
has already been included in the Global.asa file in the default virtual directory. You can work with
MyInfo as if it were a built-in object.
Syntax
MyInfo.property
The Page Counter component creates a PageCounter object that counts and displays the number of
times a Web page has been opened. At regular intervals the object writes the number of hits to a text file
so that in the event of a server shutdown, the data is not lost. The Page Counter component uses an
internal Central Management object to record how many times each page in the application has been
opened.
When an instance of the PageCounter object is created on a page by using the Server.CreateObject
method, the object retrieves the current hit count for the specified Web page from the Central
Management object. The object can then be manipulated with the methods it exposes.
Syntax
Parameters
oVar
Specifies the name of the PageCounter object created by the call to Server.CreateObject.
Registry Entries
The Page Counter adds the key MSWC.PageCounter to the registry when the object is compiled or
registered. The key is added under HKEY_CLASSES_ROOT and contains the following named values.
Methods
Hits Displays the number of times that a specified URL has been
opened.
PageHit Increments the Hit Count.
Reset Sets the hit count for a specified page to 0.
Example
The following example uses the PageCounter object to track the number of visitors to the page and
sends a special message to the one millionth visitor.
<%
Set MyPageCounter = Server.CreateObject("MSWC.PageCounter")
HitMe = MyPageCounter.Hits
If HitMe = 1000000 Then
%>
You are the lucky 1,000,000th Customer!!! <BR>
<% Else %>
Sorry, you are customer #<%= HitMe %> <BR>
<% End If %>
The Hit Count Data file is a text file on the server to which the Central Management object
periodically saves the hit count data. Editing this file is not recommended; errors in the format will prevent
the PageCounter object from properly loading the hit count information.
Hits
The Hits method returns the number of times that a specified Web page has been opened.
Syntax
Object.Hits( [pathInfo] )
Parameters
pathInfo
Optional parameter that specifies the PATH_INFO of the Web page using the
format /virtualdirectoryname/filename.asp. If this parameter is not specified, the hit count for
the current page is displayed.
Return Values
A LONG indicating the number of times that the specified Web page has been opened.
Examples
The following example uses the Hits method to display the number of times that the current Web page
has been opened.
This Web page has been viewed <%= MyPageCount.Hits %> times.
<P>
Page Myscript.asp has been viewed <%= MyPageCounter.Hits("/VirtualDir1/Myscript.asp") %> t
See Also
Reset, PageHit
PageHit
The PageHit method increments the hit count for the current Web page.
Syntax
Object.PageHit()
Example
The following example uses the PageHit method to increment the number of times that the current Web
page has been opened.
<%
Set MyPageCounter = Server.CreateObject("MSWC.PageCounter")
MyPageCounter.PageHit
%>
This Web page has been viewed <%= MyPageCount.Hits %> times.
See Also
Reset, Hits
Reset
The Reset method sets the hit count for a specified Web page to 0.
Syntax
Reset([pathInfo])
Parameters
pathInfo
Optional parameter that specifies the PATH_INFO of the Web page using the
format /virtualdirectoryname/filename.asp. If this parameter is not specified, the hit count for
the current page is reset.
Examples
The following example resets the page counters for the current Web page and Mypage.asp.
<%
Set MyPageCounter = Server.CreateObject("MSWC.PageCounter")
MyPageCounter.Reset
MyPageCounter.Reset("/VirtualDir1/Mypage.asp")
%>
See Also
Hits, PageHit
The Permission Checker component creates a PermissionChecker object that uses the password
authentication protocols provided in Microsoft ® Internet Information Services (IIS) to determine whether
a Web user has been granted permissions to read a file.
You can use the Permission Checker component to customize an ASP-based page for different types of
users. For example, if a Web page contains hyperlinks, you can use the Permission Checker component
to test whether the user has permissions for the target Web pages. If the user does not have the proper
permissions, you can then omit or alter the hyperlinks to those pages the user may not access.
Syntax
Parameters
oVar
Specifies the name of the PermissionChecker object created by the call to
Server.CreateObject.
Methods
Examples
The following example uses the HasAccess method to test whether the current user has access to a
specified file. Note that you can specify either a physical or virtual path.
Remarks
IIS supports the following three types of password authentication in any combination:
? Anonymous
? Basic
? Integrated Windows authentication
When Anonymous authentication is enabled, all users are initially logged on under the IIS anonymous
user account. Because anonymous users all share the same account, the Permissions Checker
component cannot authenticate individual users when anonymous access is allowed.
For applications where all users have individual accounts, such as intranet-only Web sites, it is
recommended that you disable anonymous authentication so that the Permissions Checker component
can authenticate individual users.
For applications where some pages must be available to anonymous users and other pages need to be
secure, such as mixed Internet and intranet Web sites, you should enable anonymous authentication and
at least one other password authentication method, either integrated Windows authentication or Basic.
Then if you deny anonymous access to a specific page, the server will attempt to authenticate the user by
using either integrated Windows authentication or Basic password authentication.
You can use either of the following two methods to deny anonymous access to a specific page.
? Set the Access Control List for the ASP-based file to exclude the anonymous user account.
? In the ASP script, check for the anonymous user account (if the LOGON_USER server variable
is empty) and set Response.Status to the 401 Unauthorized error message. This will cause
IIS to attempt to identify the user by using NTLM or Basic authentication.
<%
If Request("LOGON_USER") = "" Then
Response.Status = "401 Unauthorized"
End if
%>
If all the files in your application must be available to anonymous users, the Permission Checker
component will not able to distinguish individual user accounts. You can still use it, however, to ensure
that the specified Web page exists and test whether the anonymous user account has access permissions
for that page.
Note NTLM password authentication is currently supported only by Microsoft Internet Explorer, and
may not work over a proxy server. Thus, if users connect to your site with browsers other than Internet
Explorer or through a proxy server and your application requires a non-anonymous user context, you
must also enable Basic password authentication.
HasAccess
This is preliminary documentation for IIS 5.0 and is subject to change.
The HasAccess method tests whether a user has permission to access a specified file.
Syntax
HasAccess( FilePath )
Parameters
FilePath
A string that specifies the path and name of the file; this can be either a physical or virtual path.
Return Values
Returns a BOOLEAN value that indicates whether the Web user has access to the specified file. If the
file does not exist, the PermissionChecker object returns False.
Examples
The following example uses the PermissionChecker object to test whether the Web user has access to
the file C:\pages\private\default.htm. If the user has access, the script creates a hyperlink to that file;
otherwise it writes a message. This example uses a virtual path.
<%
Set pmck = Server.CreateObject("MSWC.PermissionChecker")
UserHasAccess = pmck.HasAccess("/private/default.htm")
If UserHasAccess
%>
<A HREF="/private/default.htm">Go to the Clubhouse!</A>
<% Else %>
Sorry, you are not a member.
<% End If %>
The following example repeats the preceding one but uses a physical path to determine the user’s
permissions.
<%
Set pmck = Server.CreateObject("MSWC.PermissionChecker")
UserHasAccess = pmck.HasAccess("c:\pages\private\default.htm")
If UserHasAccess
%>
<A HREF="/private/default.htm">Go to the Clubhouse!</A>
<% Else %>
Sorry, you are not a member.
<% End If %>
Status Component
This is preliminary documentation for IIS 5.0 and is subject to change.
The Status component creates a Status object that has properties that contain server status information.
Currently this server status is only available on Personal Web Server for Macintosh.
File Names
Syntax
Parameters
Status
Specifies the name of the Status object created by the call to Server.CreateObject.
Remarks
Currently, the Status object only returns server status information for Personal Web Server for
Macintosh. For all Windows platforms, the properties of the Status object currently all return the string
"unavailable."
The only time you may need to include a Status object is when you are running ASP scripts that were
developed on Macintosh and use Status properties.
Note The following table describes the Status properties as they are implemented on Macintosh.
Properties
Tools Component
This is preliminary documentation for IIS 5.0 and is subject to change.
The Tools component creates a Tools object that provides utilities that enable you to easily add
sophisticated functionality to your Web pages.
File Names
Syntax
Parameters
Tools
Specifies the name of the Tools object created by the call to Server.CreateObject.
Remarks
In Personal Web Server for Windows® 95 or Windows 98, the Tools object has already been included
in the Global.asa file in the default virtual directory. You can work with the Tools object as if it were a
built-in object by calling Tools.FileExists, Tools.ProcessForm, and Tools.Random.
Methods
FileExists
This is preliminary documentation for IIS 5.0 and is subject to change.
The FileExists method checks the existence of a file. It returns –1 if the specified URL exists within a
published directory. If the file does not exist, it returns 0.
Syntax
Tools.FileExists(URL)
Parameters
URL
A string that specifies the relative URL of the file you are checking.
Remarks
FileExists only checks the existence of files published on your site. Therefore, it takes a relative URL
rather than an absolute URL.
Example
The following example demonstrates using the FileExists property to create a link if a particular file is
present.
See Also
ProcessForm, Random
Owner
This is preliminary documentation for IIS 5.0 and is subject to change.
The Owner method checks whether the current user is the site administrator. It returns -1 if the name
and password submitted in the request header matches the Administrator name and password set in the
Personal Web Services interface. It returns 0 if there is not a match.
Syntax
Tools.Owner
Remarks
Currently, Owner only works properly on Personal Web Server for Macintosh.
See Also
PluginExists
This is preliminary documentation for IIS 5.0 and is subject to change.
The PluginExists method checks whether the specified Macintosh server plug-in exists. It returns -1 if
the specified Macintosh server plug-in name is currently registered. It returns 0 if the plug-in is not
registered.
Syntax
Tools.PluginExists(PluginName)
Parameters
PluginName
A string that specifies the name of the server plug-in.
Remarks
Server plug-ins are only used on Macintosh. For IIS and Personal Web Server for Windows95 or later,
PluginExists always returns 0.
See Also
ProcessForm
This is preliminary documentation for IIS 5.0 and is subject to change.
The ProcessForm method processes the contents of a form that has been submitted by a visitor to the
Web site.
Syntax
Parameters
OutputFileURL
A string containing the relative URL of the file to which the processed data is written.
TemplateURL
A string containing the relative URL of the file that contains the template, or instructions, for
processing the data.
InsertionPoint
An optional parameter indicating where in the output file to insert the process data. This parameter
has not been implemented. If you include a value for this parameter it will be ignored.
Remarks
The template files can contain ASP scripts. A script between <% and %> delimiters is treated just like
other text in the template and copied into the output file. If the output file is an ASP document, the script
will run when the output file is accessed. Scripts in template files can also be put between special <%%
and %%> delimiters which cause the script to execute while Tools.ProcessForm is executing. Since
these scripts are executed before the template data is saved in the output file, the results get saved in the
output file, usually as standard text.
If the specified output file does not exist, the server creates it.
If the InsertionPoint parameter does not exist, Tools.ProcessForm replaces the entire output file. If the
InsertionPoint parameter exists, and does not begin with an asterisk (*), Tools.ProcessForm finds the
InsertionPoint string in the output file and inserts the data immediately after it. If the InsertionPoint
string begins with an asterisk (*), Tools.ProcessForm finds the InsertionPoint string in the output file
and inserts the data immediately before it. If the InsertionPoint string exists, but is not found in the
output file, the data is appended to the end of the file.
Example
<%
Tools.processform("/$Received Messages/default.asp","MessageInsert.process","<SPAN>*
%>
See Also
FileExists, Random
Random
This is preliminary documentation for IIS 5.0 and is subject to change.
Syntax
Tools.random
Remarks
To get a random integer below a specific value, use the Mod function.
Example
<% = Tools.Random %> will display a random integer between –32768 to 32767. For example,
<% = ( Abs( Tools.Random ) ) %> will display a positive random integer. For example, 23054
<% = ( Abs( Tools.Random ) ) Mod 100 %> will display a random integer between 0 and 99. Fo
See Also
FileExists, ProcessForm
Script Reference
This is preliminary documentation for IIS 5.0 and is subject to change.
This section contains reference information for building ASP pages. The following topics are included:
? JScript Reference
? VBScript Reference
? @ Directives Reference
? Global.asa Reference
JScript Reference
This is preliminary documentation for IIS 5.0 and is subject to change.
VBScript Reference
This is preliminary documentation for IIS 5.0 and is subject to change.
@ Directives Reference
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use @ processing directives in your scripts to send information to IIS about how to process
an .asp file. For example, the following script uses the @LANGUAGE processing directive to set the
scripting language to VBScript.
<%@LANGUAGE=VBScript
Dim myvar
Application("myvar") = This is my var
Response.Write(myvar)
%>
The following five @ directives are supported by Active Server Pages (ASP) in IIS 5.0.
? @CODEPAGE
? @ENABLESESSIONSTATE
? @LANGUAGE
? @LCID
? @TRANSACTION
@CODEPAGE
You can use the @CODEPAGE directive to set the code page to be used for the .asp file. A code page
is a character set, which can include numbers, punctuation marks, and other glyphs. Different languages
and locales may use different code pages. For example, ANSI code page 1252 is used for American
English and most European languages; OEM code page 932 is used for Japanese Kanji.
A code page can be represented in a table as a mapping of characters to single-byte values or multibyte
values. Many code pages share the ASCII character set for characters in the range 0x00–0x7F.
You can override the code page that has been set by the @CODEPAGE directive with the
Session.CodePage property. Doing so, however, only applies to script running within the scope of the
session.
Syntax
Parameters
codepage
An unsigned integer that represents a valid code page for the system that is running the ASP
scripting engine.
See Also
Session.CodePage
@ENABLESESSIONSTATE
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use the @ENABLESESSIONSTATE directive to turn off session tracking for a page. Session
tracking maintains information about a set of requests that are issued by a single client. If your page does
not rely on session information, turning off session tracking may decrease the time it takes for IIS to
process the script.
Syntax
Remarks
@LANGUAGE
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use the @LANGUAGE directive to set the language that will be used to interpret the
commands in a script. You can set your scripting language to any scripting engine that has been installed
in IIS. The default scripting language is VBScript, so if you do not include a @LANGUAGE directive in
your script, the script will be interpreted by the VBScript engine.
Syntax
Parameters
Scriptengine
The script engine that should compile the script. IIS ships with two script engines, VBScript and
JScript.
Remarks
You can change the default scripting language with the IIS Admin Objects AspScriptLanguage property.
You can apply this property to a Web Service, Web Server, Virtual Directory or Web Directory. For
more information, see Using IIS Admin Objects.
@LCID
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use the @LCID directive to set the locale identifier (LCID) for a script. The LCID is a
DWORD containing the language identifier in the lower word and a reserved value in the upper word.
The identifier supplied in an LCID is a standard international numeric abbreviation. This LCID has the
components necessary to uniquely identify one of the installed system-defined locales. There are two
predefined LCID values. LOCALE_SYSTEM_DEFAULT is the system default locale, and
LOCALE_USER_DEFAULT is the current user's locale.
Syntax
Parameters
localeidentifier
A valid locale identifier.
See Also
@TRANSACTION
This is preliminary documentation for IIS 5.0 and is subject to change.
You can use the @TRANSACTION directive to indicate that the script should be treated as a
transaction. If a script is treated as a transaction, Component Services will create a transaction to
coordinate the updating of resources.
Syntax
Parameters
Value
A string that indicates the type of transaction support. Possible values are:
Value Meaning
Required The script will initiate a transaction
Requires_New The script will initiate a transaction
Supported The script will not initiate a transaction
Not_Supported The script will not initiate a transaction
Remarks
If a script contains the @TRANSACTION directive, it must be the very first line in the .asp file,
otherwise an error is generated. You must add the directive to each page that should be run under a
transaction. The current transaction ends when the script finishes processing.
If the script containing the @TRANSACTION directive has been called by either the Server.Transfer
or Server.Execute method, and the value is specified as Required the script will continue the transaction
of the calling asp if the calling asp was transacted. If the calling asp was not transacted, the called asp will
create a new transaction.
For example, the following two scripts would be considered one transaction.
ASP
<%
Server.CreateObject("Mytransactedcomponent.Closeout")
%>
See Also
ObjectContext
Global.asa Reference
This is preliminary documentation for IIS 5.0 and is subject to change.
The Global.asa file is an optional file in which you can specify event scripts and declare objects that have
session or application scope. It is not a content file displayed to the users; instead it stores event
information and objects used globally by the application. This file must be named Global.asa and must be
stored in the root directory of the application. An application can only have one Global.asa file.
? Application Events
? Session Events
? <OBJECT> Declarations
? TypeLibrary Declarations
If you include script that is not enclosed by <SCRIPT> tags, or that defines an object that does not have
session or application scope, the server returns an error. The server ignores both tagged script that the
application or session events do not use, as well as any HTML in the file.
The scripts contained in the Global.asa file may be written in any supported scripting language. If multiple
event or object scripts use the same scripting language, they can be combined inside a single set of
<SCRIPT> tags.
When you save changes to the Global.asa file, the server finishes processing all of the current application
requests before it recompiles the Global.asa file. During that time, the server refuses additional requests
and returns an error message stating that the request cannot be processed while the application is being
restarted.
After all of the current user requests have been processed, the server deletes all active sessions, calling
the Session_OnEnd event for each session it deletes, closes the application, and calls the
Application_OnEnd event. The Global.asa file is then recompiled. Subsequent user requests will start
the application and create new sessions, and trigger the Application_OnStart and Session_OnStart
events.
Procedures declared in the Global.asa file can only be called from one or more of the scripts associated
with the Application_OnStart, Application_OnEnd, Session_OnStart, and Session_OnEnd events.
They are not available to the ASP pages in the ASP-based application.
To share procedures across an application, you can declare the procedures in a separate file, and then
use server-side include (SSI) statements to include the file in the ASP pages that call the procedures.
Note The examples in this document use Microsoft® Visual Basic® Scripting Edition (VBScript) as the
primary scripting language. However, ASP scripts can be written in any supported scripting language,
such as JScript®. For more information on how to change the primary language, see Working with
Scripting Languages.
Application Events
This is preliminary documentation for IIS 5.0 and is subject to change.
An ASP-based application is made up of all the files in its root directory and in any subdirectories. An
application starts the first time that a user opens one of the Web pages in the application and ends when
the server shuts down. The application has two events, an Application_OnStart event and an
Application_OnEnd event.
You can specify script for these events in the Global.asa file. When the application starts, the server
looks in the Global.asa file and processes the Application_OnStart event script. When the application
ends, the server processes the Application_OnEnd event script.
Application_OnStart
The Application_OnStart event occurs before the first new session is created, that is, before the
Session_OnStart event. Only the Application and Server built-in objects are available. Referencing the
Session, Request, or Response objects in the Application_OnStart event script causes an error.
Syntax
</SCRIPT>
Parameters
ScriptLanguage
Specifies the scripting language used to write the event script. It may be any supported scripting
language, such as VBScript or JScript. If more than one event uses the same scripting language,
they can be combined under a single set of <SCRIPT> tags.
Examples
Sub Application_OnStart
Application("NumberofVisitors") = 0
End Sub
See Also
Application_OnEnd, Session_OnStart
Application_OnEnd
The Application_OnEnd event occurs when the application quits, after the Session_OnEnd event.
Only the Application and Server built-in objects are available.
Syntax
</SCRIPT>
Parameters
ScriptLanguage
Specifies the scripting language used to write the event script. It may be any supported scripting
language, such as VBScript or JScript. If more than one event uses the same scripting language,
they can be combined under a single set of <SCRIPT> tags.
Remarks
See Also
Application_OnStart, Session_OnEnd
Session Events
This is preliminary documentation for IIS 5.0 and is subject to change.
The Web server automatically creates a session when a user, who did not previously have a session,
opens a Web page in the application. The server destroys the session either when it times out or when
the server calls the Abandon method.
The session has two events, a Session_OnStart event and a Session_OnEnd event.
You can specify script for these events in the global file, Global.asa. When the session starts, the server
looks in the Global.asa file and processes the Session_OnStart event script. This script is processed
before the Web page that the user requested is processed. When the session ends, the server processes
the Session_OnEnd event script.
Note Session tracking on by default. If you do not want to track sessions, you can disable sessions
with the @ENABLESESSIONSTATE directive.
See Also
Session Object
Session_OnStart
The Session_OnStart event occurs when the server creates a new session. The server processes this
script prior to executing the requested page. The Session_OnStart event is a good time for you to set
any session-wide variables, because they will be set before any pages are accessed. All the built-in
objects (Application, ObjectContext, Request, Response, Server, and Session) are available and can be
referenced in the Session_OnStart event script.
Syntax
</SCRIPT>
Parameters
ScriptLanguage
Specifies the scripting language used to write the event script. It may be any supported scripting
language, such as VBScript or JScript. If more than one event uses the same scripting language,
they can be combined under a single set of <SCRIPT> tags.
Example
Although the Session object persists if the Session_OnStart event contains a call to the Redirect or
End methods, the server stops processing the script in both the Global.asa file and in the file that
triggered the Session_OnStart event.
You can call the Redirect method in the Session_OnStart event, for example, to ensure that users
always start a session at a particular Web page. When the user enters the application, the server creates
a session for that user and processes the Session_OnStart event script. You can include script in this
event to check whether the page opened by the user is the starting page and, if not, direct the user to the
starting page by calling the Response.Redirect method. This is demonstrated in the following example.
startPage = "/MyApp/StartHere.asp"
currentPage = Request.ServerVariables("SCRIPT_NAME")
If strcomp(currentPage,startPage,1) then
Response.Redirect(startPage)
End If
End Sub
</SCRIPT>
The preceding example only works for browsers that support cookies. Because a noncookie browser
does not return the SessionID cookie, the server creates a new session each time the user requests a
page. Thus for each request, the server processes the Session_OnStart script and redirects the user to
the starting page. If you use the script below, it is recommended that you put a notice on your starting
page to inform users that the site requires a cookie-enabled browser.
Remarks
You should note that any Session_OnStart event script that follows a call to the Redirect method is not
executed. For this reason, you should call the Redirect method last in your event script. This is
demonstrated in the following example.
</SCRIPT>
In the preceding example the Redirect method hides any text displayed to the client during the session-
initialization script.
See Also
Session_OnEnd, Application_OnStart
Session_OnEnd
The Session_OnEnd event occurs when a session is abandoned or times out. Of the server built-in
objects, only the Application, Server, and Session objects are available.
Syntax
</SCRIPT>
Parameters
ScriptLanguage
Specifies the scripting language used to write the event script. It may be any supported scripting
language, such as VBScript or JScript. If more than one event uses the same scripting language,
they can be combined under a single set of <SCRIPT> tags.
Remarks
See Also
Session_OnStart, Application_OnEnd
<OBJECT> Declarations
This is preliminary documentation for IIS 5.0 and is subject to change.
You can create objects with session or application scope in the Global.asa file by using the extended
<OBJECT> tag. This tag is self-contained and is outside of any <SCRIPT> tags.
The objects declared in the Global.asa file are not created until the server processes a script that calls
that object. This saves resources by creating only the objects that are needed.
The server does not call the OnStartPage and OnEndPage methods for objects created with application
scope. For more information on component scope see Setting Object Scope and Determining Object
Scope.
Syntax
</OBJECT>
Parameters
Scope
Specifies the scope of the object. In the Global.asa file, Scope will be set to either Session or
Application.
Identifier
Specifies a name for the object instance.
ProgID
An identifier associated with a class identifier. Either ProgID or ClassID must be specified in the
<OBJECT> tag. The format for ProgID is [Vendor.]Component[.Version].
ClassID
Specifies a unique identifier for an COM class object. Either ProgID or ClassID must be
specified in the <OBJECT> tag.
Examples
The first of the following examples creates an object of session scope named MyConnection by using
the ProgID parameter. The second example uses the ClassID parameter.
Remarks
The objects declared in the Global.asa file can be used by any script in the application. For example, if
---GLOBAL.ASA---
<OBJECT RUNAT=Server SCOPE=Session ID=MyAd PROGID="MSWC.AdRotator">
</OBJECT>
You could reference the object MyAd from any page in the application:
---SOME.ASP---
<%= MyAd.GetAdvertisement("/ads/adrot.txt") %>
TypeLibrary Declarations
This is preliminary documentation for IIS 5.0 and is subject to change.
A type library is a file that contains information about objects and types supported by a COM
component. It is very common for a COM component to describe any constants that it supports in a
type library. If your Web application relies on COM objects that have declared data types in type
libraries, you can declare the type libraries in Global.asa. Doing so will make it possible to refer to the
constants declared in the type libraries from any script within the application boundary.
For more information about using constants in ASP, see Using Variables and Constants.
Syntax
<!--METADATA TYPE="TypeLib"
FILE="file"
UUID="typelibraryuuid"
VERSION="majorversionnumber.minorversionnumber"
LCID="localeid"
-->
Parameters
file
Absolute path to a type library. If this parameter and the typelibraryuuid parameter are provided,
file is used to identify the type library. Either the file parameter or the typelibraryuuid parameter
is required.
typelibraryuuid
Universally unique identifier for the type library. Either the file parameter or the typelibraryuuid
parameter is required.
majorversionnumber
Used for selecting version. If the requested version is not found, then the most recent version is
used (optional).
minorversionnumber
Used for selecting version. If the requested version is not found, then the most recent version is
used (optional).
localeid
The locale identifier to be used for the type library. If the requested locale is not found, then the
System locale identifier will be used. (optional)
Error Values
Error Description
ASP 0222 Invalid type library specification. The METADATA tag contains an
invalid type library specification.
ASP 0223 Type library not found. The METADATA tag contains a type library
specification that does not match any registry entry.
ASP 0224 Type library cannot be loaded. ASP cannot load the type library
specified in the METADATA tag.
ASP 0225 Type library cannot be wrapped. ASP cannot create a Type Library
Wrapper object from the type libraries specified in the METADATA
tag.
Remarks
It is recommended that METADATA tags appear near the top of the Global.asa file. However, these
tags can appear anywhere inside of the Global.asa file, including both inside and outside the SCRIPT
tags.
You can avoid ambiguous references to constants by adding the type library name as a prefix for the
constant. For example, ADODB.adErrItemNotFound would be less ambiguous than
adErrItemNotFound.
If you use Microsoft Visual InterDev to create your Global.asa file, the METADATA tags will include
the optional STARTSPAN and ENDSPAN keywords. These keywords are ignored by IIS.
If you do not specify a locale identifier for the type library, the default locale identifier for the system will
be used. If the system locale identifier can not be used, and you have not specified a locale identifier, the
locale identifier for the Type Library will be set to 0.
Example
MyComponent in the following example was developed with Visual Basic 5.0. MyComponent defines the
constant MyError with the following statement.
The type library is contained in mycomponent.lib, which you have installed in the following directory.
C:\MyComponent
The following METADATA tag is included in the Global.asa file for the MyApp application.
<!--METADATA TYPE="TypeLib"
FILE="MyComponent.tlb"
-->
Any .asp file in the MyApp application can now include the following script:
<%
Dim MyVar
Set MyVar = Server.CreateObject("MyComponent.MyClass")
Currentreturn = MyVar.MyMethod
If Currentreturn = False
Response.Write(MyError)
End If
%>
ASP Samples
This is preliminary documentation for IIS 5.0 and is subject to change.
Welcome to the ASP samples. Through these clear and simple examples, this section exposes you to the
power and extensibility of Internet Information Services (IIS), one step at a time. Included are sample
ASP scripts and Windows® Scripting Host (WSH) administrative scripts.
? ASP Script Examples: Features a wide variety of scripts, provided in both Microsoft ® Visual
Basic® Scripting Edition (VBScript) and JScript®. Beginners can learn what scripting is all about,
while more experienced users can quickly review ASP fundamentals and move on to more
advanced applications. To see the sample scripts in action, you can run them immediately without
exiting this documentation.
? Programmatic Administration Examples: Provides samples that use the IIS programmatic
interfaces. Here you will find Windows Scripting Host (WSH) scripts, written in VBScript and
JScript, that access the IIS metabase by using the ADSI interface.
For information about overall application development, see Developing Web Applications.
Important These samples are provided for educational purposes only. They are not intended to be
used in a production environment, have not been tested in a production environment, and Microsoft will
not provide technical support for them.
Active Servers Pages (ASP) is one of the features that make IIS the premier Web server. Never before
has it been so easy to create useful, interactive, Web-based applications, even if you have relatively little
experience with programming. If you are a more advanced user, ASP provides a way to rapidly create
sophisticated and robust Web applications without dedicating the often substantial resources required for
development in a more conventional programming language environment, such as C++ or Java.
This section provides an overview of the capabilities of server-side scripting in general, and ASP in
particular, while at the same time providing more advanced examples for experienced developers who
want to discover what ASP can do for them.
Sample scripts provided in this documentation are divided into several categories:
? Simple Scripts: Learn the basics of script syntax, flow control, functions, and procedures.
? Building ASP Applications: Study samples that demonstrate the structure and function of a Web-
based application.
? Web Interactivity using ASP: Discover how to make your application more useful and versatile by
incorporating cookies, client-side scripting, and other techniques.
? Using Installable Components: Learn how to leverage the functionality provided by the Active
Server Pages components that are installed with IIS.
? Database Connectivity: Explore examples that illustrate the power of the bundled database access
component, ActiveX® Data Objects (ADO).
? ASP Transaction Services: Study samples that demonstrate the alliance between Component
Services and ASP scripts.
Although the samples in this section are provided as an educational resource, this is not a tutorial on ASP
scripting or application creation. For more information, see Active Server Pages and Developing Web
Applications.
Simple Scripts
This is preliminary documentation for IIS 5.0 and is subject to change.
The following scripts illustrate the fundamental techniques used in ASP scripting. If you're a newcomer to
application development, or a programmer who has never scripted before, this is a good starting place.
Variables
This is preliminary documentation for IIS 5.0 and is subject to change.
Overview
Every application ever written, regardless of the programming language, has used variables of some sort,
and ASP scripts are no exception. Both VBScript and JScript allow you to create and manage variables
simply and easily.
Each language deals with variable declaration differently. Both JScript and VBScript are quite flexible
about variables and their declaration. In VBScript, any variable is automatically considered to be of the
Variant type when it is initially declared with the Dim statement. Each variable eventually is assigned a
subtype, such as Numeric and Array. JScript is similar; the variable is initially declared with the var
statement. Both languages, in general, try to perform much of the data type management, including type
conversion, automatically. In fact, you don't even have to use the Dim or var statements at all to use a
new variable; they are optional in their respective languages.
Code Tour
This sample declares several different kinds of variables, performs simple operations on them, and then
displays them to the client browser using the special <% = ...%> script delimiters. An integer is assigned
to the variable intVariable, added to itself, and the sum sent to the client browser. StrVariable is set to
equal to the first name, is added to Smith, and sent to the client browser. Booleans and dates are
likewise declared or created, initialized, manipulated, and displayed.
Remarks
Of particular interest is the final step in the date variable demonstration. In VBScript, the variable is first
assigned a literal date string, and displayed. It is then reset, and assigned the value that is returned by the
VBScript Now function, which returns the current system time. The JScript example uses the JScript
Date function to set both the initial literal by passing parameters to the function, and then to set the
variable equal to the current system time by passing no parameters to the function.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\simple\Variables_VBScript.asp and ...\asp\simple\Variables_JScript.asp.
Looping
This is preliminary documentation for IIS 5.0 and is subject to change.
Overview
Looping is one of the most important flow-control mechanisms in a programming language. Looping
constructs provide the foundation for any application that must repetitively perform a task, such as adding
1 to a variable, reading a text file, or processing an e-mail message and sending it.
Code Tour
VBScript and JScript provide several looping mechanisms. This sample demonstrates the three most
commonly used looping statements, For ... Next, Do ... Loop, and While ... Wend. These three
statements are subtly different, and the scripting situation will frequently dictate which of the three would
work best. For the purpose of this sample, however, each type of looping statement is used to
accomplish the same task, which is to print a greeting five times using progressively larger font sizes. For
each looping statement, the variable i is initialized, and the test condition for the loop is defined such that i
will never be greater than 5. The variable is then incremented by 1 for each iteration of the loop.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\simple\Looping_VBScript.asp and ...\asp\simple\Looping_JScript.asp.
Conditional Operators
This is preliminary documentation for IIS 5.0 and is subject to change.
Overview
Conditional operators, together with variables and looping constructs, form the fundamental building
blocks of programming languages and, therefore, applications. The Web-based applications you
implement with ASP scripts can take advantage of both the flow control provided by conditional
operators and the interactivity and sophistication of HTML.
Code Tour
This sample demonstrates the If ... Then, or if ... else statements in both VBScript and JScript, as well
as the more complicated Select ... Case and switch ... case statements. Each statement demonstration
performs the same task, sending a page to the client browser that consists of the current time and date
and a greeting. The text of the greeting will be either "Good Morning" or "Good Evening," depending on
whether the system clock reads A.M. or P.M.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\simple\Conditional_VBScript.asp and ...\asp\simple\Conditional_JScript.asp.
Arrays
This is preliminary documentation for IIS 5.0 and is subject to change.
Overview
Arrays are essentially variables that can hold more than one value. Both VBScript and JScript support
arrays for most data types. This sample demonstrates how you can create and use arrays in ASP scripts.
Each element of an array is accessed by using an index. Thus, in the array A, A(0) refers to the first
element, A(1) refers to the second element, and so on. Note that array elements in both VBScript and
JScript are numbered starting at 0.
Arrays can be fixed-size, or dynamically sizable. In both VBScript and JScript, the variable name must
be declared, and storage space must be allocated for a new array. This is accomplished by using the
Dim statement in VBScript, and the new statement in JScript. If a specific size is explicitly stated, then
the array is fixed-size; but if a specific size is omitted from the declaration, then the array is considered
dynamically sizable.
Code Tour
This sample creates two arrays, aFixed, which is fixed-size, and aColors, which is dynamically sizable.
The script then assigns specific string values to each element in the arrays, using the index notation
ArrayName(Index) to access the appropriate element. The script then loops through each array by using
a For loop, and displays the results in a table.
Note that dynamically sizable arrays are implicitly expanded in JScript, so as to include the highest
element indexed in an assignment. VBScript, in contrast, requires that you explicitly resize the dynamic
array with the ReDim statement.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\simple\Arrays_VBScript.asp and ...\asp\simple\Arrays_JScript.asp.
Server-Side Includes
This is preliminary documentation for IIS 5.0 and is subject to change.
Overview
Modularity and reusability of code can be very useful in your development of ASP scripts. For example,
if you want to display copyright information on the bottom of each of your HTML pages and ASP pages,
ASP provides a solution to this problem: server-side includes, which are directives to the server to
include a certain file, which can be a text file, graphical image, or an ASP function. The copyright notice
can exist as one file, and be included into the rest of your Web site's files. And if the copyright notice
changes, you only have to change one file instead of 50 or 500.
The PathType parameter consists of a keyword, either FILE or VIRTUAL, which indicates whether the
Name string specified is a physical or virtual path.
Code Tour
This example uses the #include directive to include the file HeaderInfo.asp. When this script is executed,
ASP loads the script line by line, character by character, until it gets to the #include directive, at which
point it loads the contents of the designated file, line by line. Then the remainder of the sample script is
loaded; once this is finished the script is executed, included file and all.
Note If the file that your ASP script includes contains a large number of functions and variables that are
not used by the including script, the extra resources occupied by these unused structures can adversely
affect performance, and ultimately decrease the scalability of your Web application. Therefore, it is
generally advisable to break your include files into multiple smaller files, and include only those files
required by your ASP script, rather than include one or two larger include files that may contain
unneeded information.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\simple\Includes_VBScript.asp and ...\asp\simple\Includes_JScript.asp.
Overview
Functions and procedures provide a way to avoid rewriting the same block of code every time you want
to perform a particular task. Both VBScript and JScript allow you to call a function or procedure from
any point in a script. This sample demonstrates how you can create and use these tools with ASP.
If you don't have any functions in your ASP page, the ASP engine simply processes your entire file, start
to finish, each time it is requested by a client browser. Functions and procedures, however, are executed
only when called, not inline with the rest of the code.
You can denote functions and procedures in VBScript or JScript by using the Function statement. In
addition, VBScript makes a distinction between a function that returns a value and a function that does
not; a function that returns a value is denoted with the Sub statement, indicating that it is a subroutine.
Code Tour
This sample defines one function, PrintOutMsg, which takes as parameters a message, and a number
that specifies how many times the message is to be written to the client browser with the
Response.Write method. The function, for the purposes of this sample, simply returns to the client
browser the number of times the message was printed.
Remarks
It is important to note the RUNAT attribute of the <SCRIPT> tag. If the RUNAT attribute is not
included, ASP will assume that the script is client-side scripting, and will pass the code back to the
browser for processing. ASP would then not recognize the PrintOutMsg function call, return an error,
and abort.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\simple\Functions_VBScript.asp and ...\asp\simple\Functions_JScript.asp.
ASP makes it easy for you to develop Web-based applications. With the tools and services ASP
provides, you can create an integrated, powerful application quickly and easily.
Here you will find examples that show some of the basic application features in action.
? Session Variables: Demonstrates the use of the Session object to retain state during a client
browser's session in an application.
? Application Variables: Illustrates the use of the Application object to store information for the life
of an application.
Session Variables
This is preliminary documentation for IIS 5.0 and is subject to change.
Overview
You can use the Session object to store variables that will remain available for the length of the session,
and, therefore, have session scope. For instance, if you have created an online shopping application, you
could define Session object variables that allow you to track how much merchandise the shopper has
purchased or how much money is owed.
Code Tour
This example uses the variable SessionCount to store the number of times you have clicked the Click
here to visit it again link.
Remarks
If you visit this sample several times, then visit other sections of this documentation before visiting this
sample again, the count will pick up where you left off. This is because the server's Session object that is
associated with your particular Web session will not be destroyed until your session has timed out.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\applications\Session_VBScript.asp and ...\asp\applications\Session_JScript.asp.
Application Variables
This is preliminary documentation for IIS 5.0 and is subject to change.
Overview
You can use the built-in Application object to store developer-defined global application information
that is persistent for the life of the application.
Code Tour
This example demonstrates this storage ability by implementing a simple counter. The total number of
times that client browsers visit the sample script is stored in the application variable AppPageCount, and
incremented each time the script is accessed.
Note Because the Application object for a given application is available to many client browsers
simultaneously, the object must be locked before a property or value is changed, and unlocked after the
change. Locking is not necessary if the value or property is simply being queried.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\applications\Application_VBScript.asp and ...\asp\applications\Application_JScript.asp.
With ASP, you can easily create useful Web-based applications. The following examples demonstrate
some of the techniques used in creating an interactive ASP application.
? User Form Input with POST: Illustrates techniques you can use to obtain form values by using the
Request.Form collection.
? HTTP Server Variables: Demonstrates techniques you can use to access server variable
information from an ASP script.
? Using Cookies: Illustrates how your script can set and read cookies by using the
Response.Cookies collection.
? Setting Expiration Information: Shows how you can set the expiration date for a resource by using
the Response.Expires and Response.ExpiresAbsolute properties.
? Client-Side Scripting: Demonstrates simple tasks you can perform with a combination of ASP and
client-side scripting.
? Populating Fields: Illustrates techniques you can use to populate form fields by using ASP.
Overview
The most basic form of interactivity on the Web is probably the HTML form. It is important to note that
ASP does not replace forms, but rather enhances them, and makes them easier for you to implement and
manage.
The HTML <FORM> tag specifies what method the form will use to convey information to the
processing script. The POST method attribute indicates that information from the form will be passed to
the processing script or program through a separate HTTP connection. The processing script or program
can parse the information and do whatever task is required, and return output to the client browser.
Code Tour
This example demonstrates how to implement a simple form by using the HTML POST method
attribute, as well as one key benefit of creating forms with ASP: the ability to combine the form and the
actual processing code into the same file. This sample creates a small form with two text input boxes, one
for the user's first name (fname) and one for his or her last name (lname). The Request.Forms
collection is accessed to get the value of the fname and lname variables from the request, and the results
are displayed at the bottom of the page.
The first time you run this script, no text will be displayed below the horizontal line. This is because no
form information was available to pass to this script when it started, and ASP ignores searches of
Request.Forms for information that does not exist. However, if you press the Submit button, the page is
reloaded and the information you entered into the text boxes is available to the script.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\interaction\Form_VBScript.asp and ...\asp\interaction\Form_JScript.asp.
Overview
Each HTTP transaction that takes place between a client browser and a server involves the exchange of
a great deal of potentially useful information. This sample demonstrates one way you can access this
information, by accessing server variables. Using server variables, you can, determine the server's name
with the SERVER_NAME variable, or the HTTP headers with the ALL_HTTP variable.
Code Tour
The sample's structure is simple: form a two-column table, and fill each table row with a name, value
variable pair. Each individual server variable is retrieved by using the name as a key, such as
Request.ServerVariables("ALL_HTTP"). In addition, because ServerVariables is a collection, you
can use a For Each ... Next loop to iterate through all variables found in the collection.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\interaction\ServerVariables_VBScript.asp and ...\asp\interaction\ServerVariables_JScript.asp.
Using Cookies
This is preliminary documentation for IIS 5.0 and is subject to change.
Overview
You can use cookies to store information about a particular client, session, or application. You can then
use this information to customize and streamline a client browser's session.
Code Tour
This sample illustrates how your application can query the value of a particular cookie. IIS makes
cookies available to ASP scripts through the Request.Cookies collection. This example first queries the
cookie CookieVBScript or CookieJScript by using the standard collection-access format,
object.collection(keyname). It then resets that cookie to the current date and time.
If the initial query yields a null string, that indicates the client browser has never visited the page in
question before, and a first-time welcome message is displayed. If a value is returned by the initial query
of CookieVBScript or CookieJScript, however, it indicates not only that the client browser has visited
before, but when that last visit took place.
Note IIS sends all HTTP headers required for a given Web page or script before any HTML is sent to
the client browser. Therefore, all statements and methods that modify the HTTP headers of the response,
including setting of the Response.Cookies collection members, must be located before the <HTML>
tag in your script. If your script attempts to modify the HTTP headers after the server has begun sending
HTML content back to the client browser, the script will generate an error.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\interaction\Cookie_VBScript.asp and ...\asp\interaction\Cookie_JScript.asp.
Overview
You can give every page or script on the server an expiration date. The expiration date can either be in
the form of an absolute date, such as January 1, 2000, or a relative date, such as 600 minutes from the
time the page was first downloaded by the client browser. If a client browser requests that same page
again before the expiration date and time, then the client browser uses its own cached copy.
Code Tour
This example illustrates how your script can set the expiration date for a file. The Response.Expires
property is used to set the relative expiration date. The unit of measurement is minutes, so if this property
is set to 10, as in the example, then the page will expire after 10 minutes.
Note IIS sends all HTTP headers required for a given Web page or script before any HTML is sent to
the client browser. Therefore, all statements and methods that modify the HTTP headers of the response,
including setting the Response.Expires and Response.ExpiresAbsolute properties, must be located
before the <HTML> tag in your script. If your script attempts to modify the HTTP headers after the
server has begun sending HTML content back to the client browser, the script will generate an error.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\interaction\Expire_VBScript.asp and ...\asp\interaction\Expire_JScript.asp.
Client-Side Scripting
This is preliminary documentation for IIS 5.0 and is subject to change.
Overview
ASP is a server-side scripting environment. Client-side scripting complements ASP nicely, allowing for a
number of enhancements, such as ActiveX® controls, that can make your application more powerful and
user-friendly.
Code Tour
This example demonstrates how you can include a client-side script in your preferred scripting language.
This script defines a subroutine called DoIt within the <SCRIPT> tags. Note that there is no
RUNAT=SERVER attribute present, which indicates that the script is an ASP subroutine. The page
provides one button for the user that, when clicked, executes the DoIt subroutine on the client browser.
This sample demonstrates a very useful advantage to combining ASP scripts with client-side scripting.
When ASP encounters the <SCRIPT> tags, it does not simply ignore everything within that block. It
continues to search for, parse, and execute script elements, specified with delimiters (<% ... %>), that
are meant for the server. This example, therefore, returns within a client-side script the session
information returned from the Session.SessionID method.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\interaction\ClientScript_VBScript.asp and ...\asp\interaction\ClientScript_JScript.asp.
Populating Fields
This is preliminary documentation for IIS 5.0 and is subject to change.
Overview
You can use forms to collect input from users, but you can also use them to display information as well.
For example, if a client browser accesses your phone-directory search engine, you will want to show the
results of their search. Your search script (which can be implemented in ASP as well) accepts input,
accesses the database, and sends the results in a query string to your display form. This sample is a
simple demonstration of how that display form would look.
Code Tour
For the purposes of this sample, the data is hard-coded into the script, but obviously the information
could come from an interactive form, database, or text file. This sample starts by initializing the variables.
It then creates a form with the HTML <FORM> tags and defines four text boxes. Using the server-side
script delimiters <%= ... %>, the script then fills the text boxes with the values set in the initialization.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\interaction\PopulateForm_VBScript.asp and ...\asp\interaction\PopulateForm_JScript.asp.
There are a number of components installed with IIS that your application can call upon to perform a
wide variety of tasks to enhance your Web site. However, the real advantage of using these components
is that, because they run on the server and send to the client browser only normal HTML, any reasonably
current Web browser will be able to display the results. The examples below demonstrate how to access
these components, and show some simple situations in which they can be used.
For more information about working with the installable Active Server components, as well as detailed
descriptions of each individual component, see Installable Components for ASP.
Ad Rotator
This is preliminary documentation for IIS 5.0 and is subject to change.
Overview
The Ad Rotator component creates an AdRotator object, which automates the rotation of
advertisement images on a Web page. The component is designed to display a new advertisement each
Code Tour
This sample demonstrates how to use the Ad Rotator component. The script itself is simple, creating an
instance of the AdRotator object and calling the GetAdvertisement method each time the page is
loaded. GetAdvertisement returns a single ad entry from the Ad Rotator schedule file, adrot.txt in this
example, and the special script delimiter <% = ... %> displays the results to the client browser.
The schedule file for this sample, adrot.txt, is relatively straightforward. The four lines above the asterisk
(*) are global file settings that affect all schedule entries in the file. The most interesting and useful global
setting is the redirection specification. In this sample, if a user clicks on the advertisement, no matter
which particular entry is currently displayed, the user will be transported to the .asp file indicated. These
scripts, or DLLs, usually count how many hits a given ad has received, collect user information, and then
extract the URL from the request and redirect the client browser once again to the URL that was
originally requested.
Each of the entries that occurs below the asterisk consist of four lines, denoting the image to be
displayed, hyperlink, alternate text, and the relative probability that that particular entry will be displayed
on any given visit to that Web page. Thus, the Microsoft® Internet Information Services image has an 80
percent chance of being displayed with each hit on that page, while the Microsoft Internet Explorer image
will be displayed for only 20 percent of the hits.
Note If an advertisement entry in the schedule file does not have a corresponding URL, the hyperlink
line of the entry must contain a hyphen (-) or the Ad Rotator component will return an error.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\components\AdRotator_VBScript.asp and ...\asp\components\AdRotator_JScript.asp.
Browser Capabilities
This is preliminary documentation for IIS 5.0 and is subject to change.
Overview
Not all browsers have the same capabilities. To make the task of accounting for differences easier, ASP
provides the Browser Capabilities component. This component provides your scripts with a description
of the capabilities of the client browser by use of the BrowserType object.
Code Tour
First, an instance of the BrowserType object must be created and assigned to an object variable, bc.
Then, each property is requested, in turn, from the object by using the object.property syntax. Run the
example, and see what your browser can do.
If you are using Internet Explorer version 5.0 or later, the list of capabilities you will see include those
capabilities that are determined using the new client capabilities cookies, described in Client Capabilities.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\components\BrowserCap_VBScript.asp and ...\asp\components\BrowserCap_JScript.asp.
Database Connectivity
This is preliminary documentation for IIS 5.0 and is subject to change.
If you are creating a Web-based application, your application is probably going to have forms. And it
will probably also require some kind of database. ActiveX® Data Objects (ADO) provides you with a
set of powerful tools for accessing and manipulating data sources.
The samples in this section illustrate the techniques required to use ADO effectively, and how you can
best put its functionality to use in a Web-based application.
? Simple Query: Illustrates how you can use ADO and ASP together to perform simple database
queries.
? Limit Query Results: Shows how your scripts, using ASP and ADO, can limit the number of rows
returned in a recordset.
? Scrollable Query: Demonstrates a multidirectional, scrollable query with ADO.
? Add/Delete Records: Illustrates the techniques you need to use to add and delete records from a
data source by using ASP and ADO.
? Update Records: Shows how your application can use ADO to update existing records.
? Executing Stored Procedures: Illustrates how your ASP scripts can use ADO to execute stored
database procedures.
For more information on ADO, and Microsoft data access tools in general, refer to the Microsoft Data
Access documentation.
Simple Query
This is preliminary documentation for IIS 5.0 and is subject to change.
Overview
Although databases can be very complicated systems, and data access tools must be powerful and
responsive, it is equally important that simple database access tasks be easy to accomplish. This sample
demonstrates how ADO provides an easy way to perform such a task.
Code Tour
The goal of this sample application is to retrieve a small recordset from a Microsoft® Access database,
and print the results. The first step is to create an instance of the Connection object, using the
Server.CreateObject method. The sample uses the Connection object instance to open the OLE DB
data provider, then uses the Connection instance again to execute a SQL SELECT command to
retrieve all the records from the Authors table. The script finishes by iterating through the returned
recordset collection and displaying the results. Afterwards, both the recordset and OLE DB data source
Important OLE DB must be properly configured on the server for this sample to run properly.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\database\SimpleQuery_VBScript.asp and ...\asp\database\SimpleQuery_JScript.asp.
Overview
In an Internet environment, it is often desirable to limit the amount of information that a database query
returns to a client browser. This example demonstrates how a script, using ASP and ADO, can limit the
number of rows returned.
Code Tour
The sample first creates an instance of the Connection object, and opens the OLE DB connection with
this object's Open method. CreateObject is used again to instantiate an empty Recordset object. The
ActiveConnection property of the new Recordset object is set to point at the open OLE DB
connection, an SQL source string is assigned, and cursor type specified. The key to limiting the results
lies with the Recordset object's PageSize property. For this example, the value is set to 10, which
indicates that ADO is to return at most 10 records. Finally, the Open method is called, and ADO
searches for the first 10 records that fulfill the SQL search string.
When ADO has returned and placed the results of the search into the Recordset object, the script loops
through the page, displaying all fields of each record in a table. The script then performs the typical
housecleaning operations, closing both the recordset and the connection.
It is important to realize that if the SQL query had returned more than 10 records, this script would not
display them. Instead, the extra records would be deposited on one or more additional, logical pages.
The property PageCount indicates how many logical pages of data were returned.
Important OLE DB must be properly configured on the server for this sample to run properly.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\database\LimitRows_VBScript.asp and ...\asp\database\LimitRows_JScript.asp.
Scrollable Query
This is preliminary documentation for IIS 5.0 and is subject to change.
Overview
When you design application for an Internet environment, you will often want to limit the amount of
information that a database query returns to a client browser. This example demonstrates how a script,
using ASP and ADO, can limit the number of rows passed to the client browser in any one chunk, but
still allow the user to browse through all the results of the query.
Code Tour
The script consists of several code sections that all work together to accomplish this task. First, the
database is accessed as usual, creating a Connection object and Recordset object. The Recordset
object's PageSize property is set to 4, and the recordset is opened and populated with the query results
from the database table Authors. The first logical page of four result records are displayed in a table.
Two buttons, PgUp and PgDn, are provided so that the user can view other pages of the recordset.
If a user clicks on a button, the page is accessed again, this time using the POST method to pass some
variables to the next copy of itself. The variable PageNo is used to store what page the user is currently
viewing, while the Mv variable is used to pass the scrolling direction to the next form. If a user clicks on
PgDn, for instance, the page is accessed again, with Mv set to PgDn and PageNo set to 1. The script
would use that information to add 1 to the current page number, and AbsolutePage could then be used
to display the next page of results.
Important OLE DB must be properly configured on the server for this sample to run properly.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\database\MultiScrolling_VBScript.asp and ...\asp\database\MultiScrolling_JScript.asp.
Add/Delete Records
This is preliminary documentation for IIS 5.0 and is subject to change.
Overview
This sample illustrates the techniques you need to know in order to use ASP and ADO to add and delete
records from a database.
Code Tour
First, CreateObject is used to create an instance of the Connection object, which in turn is used to
open a connection to the OLE DB data provider. CreateObject is used again, this time to create an
empty Recordset object. The ActiveConnection property is set to refer to the new Connection
object.
Although the ADO Recordset object provides the AddNew method to add new records to a database,
you may be able to achieve better scalability by sending SQL INSERT commands directly to the
database engine. This sample uses the Recordset.Execute command, with the appropriate SQL
command string, to insert information for a new author.
At this point, another Recordset object instance is created and opened with another SQL command.
The record just added is selected, then deleted by passing the SQL DELETE command directly to the
database engine. The script then terminates.
Important OLE DB must be properly configured on the server for this sample to run properly.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\database\AddDelete_VBScript.asp and ...\asp\database\AddDelete_JScript.asp.
Update Records
This is preliminary documentation for IIS 5.0 and is subject to change.
Overview
This example demonstrates how your application can use ADO to update existing records.
Code Tour
CreateObject is used to create an instance of the Connection object, which in turn is used to open a
connection to the OLE DB data provider. CreateObject is used again, this time to create an empty
Recordset object. The ActiveConnection property is set to refer to the new Connection object.
The new recordset is then configured. The Recordset.Execute method takes a SQL command string as
a parameter. This sample uses a SQL UPDATE command string to efficiently perform the update to the
appropriate database records.
Important OLE DB must be properly configured on the server for this sample to run properly.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\database\Update_VBScript.asp and ...\asp\database\Update_JScript.asp.
Overview
Stored procedures, such as those provided by Microsoft ® SQL Server, are the keys to making large,
mission-critical database applications function smoothly and efficiently. This example demonstrates how
you can access this functionality by using ADO from within an ASP script.
Code Tour
This script first creates an instance of the Connection object and uses it to open an OLE DB connection
with the sample database, pubs. A special object, called a Command object, is created next. The
Command object's CommandText property is set to the string of the command you want to issue,
which for this sample is the name of a stored procedure, ByRoyalty. The Command object Parameters
property provides a collection of Parameter objects, and this script uses the Append method to add a
new parameter to the collection.
Once CreateParameter has been used to name and configure the parameter instance, the parameter
name assigned can be used to access the value of that parameter directly, as if the Command object
itself were a collection. Thus
oCmd("@Percentage") = 75
assigns the value 75 to the parameter that the script has labeled as @Percentage. The Command
object's Execute method is invoked, and the resulting recordset is assigned to the object variable oRs
defined earlier in the script. The first record of the resultant recordset is displayed.
Important SQL Server must be installed, and configured properly, on the same machine on which IIS
is running in order for this sample to work correctly.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\database\StoredProcedures_VBScript.asp
and ...\asp\database\StoredProcedures_JScript.asp.
Transaction management is a required component for any serious Web-based application. Answering
that need, ASP and Component Services provide reliable, robust transaction services to your
applications. With ASP and Component Services, most of the technical details of transaction
management are taken care of behind the scenes.
Some of the features of ASP and Component Services are illustrated in the following sample.
? Basic Transaction: Demonstrates the basics of ASP and Component Services, including commits
and the OnTransactionCommit and OnTransactionAbort events.
Basic Transaction
This is preliminary documentation for IIS 5.0 and is subject to change.
Overview
Using ASP, you can easily take advantage of the reliability provided by Component Services. You only
need to include the @TRANSACTION directive in your script. This directive tells Component Services
that any changes that occur in that page, such as database manipulation or Message Queuing Services
(MQS) message transmission, should be considered transactions. A change that is being managed by
transaction services can be either committed, making it permanent; or aborted, which would result in the
state of the database or queue being rolled back to its previous state, before the changes were made.
Code Tour
In this sample, the entire page has been declared a transaction by use of the @TRANSACTION
directive. The sample provides some scripting commands for two other procedures that are called to
perform additional completion or clean-up tasks. OnTransactionCommit is called when either the
script has successfully completed, or the ObjectContext.SetComplete method has been called.
Likewise, OnTransactionAbort is called when the script either encounters some kind of processing
error, or the ObjectContext.SetAbort method has been called.
This sample commits, by default, because it simply prints a small message and then exits. Because the
directive declared the script to be a transaction, exiting successfully automatically commits changes made
in the script (although in this case there are none), and triggers the OnTransactionCommit procedure,
which prints a message.
Important The @TRANSACTION directive must be on the first line of the .asp file, or an error will
be generated.
Location
The VBScript and JScript versions of this script are available in the IIS samples directory,
at ...\asp\transactional\SimpleTransaction_VBScript.asp
and ...\asp\transactional\SimpleTransaction_JScript.asp.
The samples presented here demonstrate how you can create scripts that use the ADSI interfaces
provided by IIS to administer the IIS installation.
Scripting languages, such as Microsoft® Visual Basic® Scripting Edition (VBScript) and JScript®, can
be used to automate time-consuming administrative tasks. This section provides some simple example
scripts designed to run on your local machine, written in VBScript and JScript, and executed by the
Windows Scripting Host (WSH). The samples provided here illustrate basic techniques for
accomplishing common tasks.
The general format for invoking a WSH script is either Cscript.exe ScriptName to execute the script at
the command line, or Wscript.exe ScriptName to execute the script in a window. You can also create a
batch file that will execute Cscript.exe or Wscript.exe and your script. For more information about
WSH, please refer to the Windows Scripting Host documentation.
Important WSH must be locally installed to execute these sample scripts. In addition, most of these
scripts access functionality provided by IIS, and therefore require that IIS and WSH be installed locally.
Overview
Multiple logging modules can lead to multiple problems if you aren't prepared. This sample tool illustrates
some techniques you can use to create logging management tools of your own.
This sample tool serves two separate functions. If it is invoked without command-line arguments, then it
simply lists all logging modules that currently have entries in the metabase on your server. But if an
ADsPath is given, such as IIS://LocalHost/W3SVC/3, then the tool will try to determine what is
considered the active logging module for that metabase node, and will give you information about that
logging module.
Code Tour
To list the available logging modules, the GetObject method is invoked to gain access to the
IIS://LocalHost/Logging node of the metabase. A For ... Each loop is then used to enumerate the
modules that are founded in that node.
Gathering information about a specific server's logging module is a bit more involved. Because the only
property at the server level that indicates what logging module is currently in use by the server is the
LogPluginClsId property, this value must be compared to each and every module listed at
the //LocalHost level until a match is found.
GetObject is used to gain access to the list of logging modules provided at the //LocalHost level. The
CLSID of the logging module is compared to the CLSID of each logging module provided in this main
list until a match is found. When a match is found, the script tells you all it can about the logging module; if
no match is found between the CLSIDs, the script aborts with an error.
Location
Overview
The IIS metabase is a large and complicated structure, and has much vital information about your
Internet sites. So that you can easily protect that important data, backing up the metabase has been made
into a relatively easy task. This tool demonstrates how you can create a tool that makes backing up the
metabase even easier.
Code Tour
All metabase backup functionality is provided at the IIS://LocalHost level, so this string is passed to
GetObject to get a reference to the local machine object. The Backup method is then invoked with
several parameters, including a number of flags, a location, and a version number.
The location parameter refers to a name that you give to your set of backup versions. Backup
implementation will probably change in future releases, but at the time of this writing, all backups are
stored in the same directory. Therefore, it might be helpful to think of location as the name of a series of
backup snapshots.
The backup version parameter can be explicit, or you can use one of several special values, the most
important being &HFFFFFFFF. This value, which equals -1 in VBScript, indicates that the Backup
method should assign a version number to this backup that is one higher than the highest version number
found for that location.
Location
Overview
If you have backed up your metabase, and then somehow corrupted the configuration on all of your
Web sites, you will need to retrieve your metabase backup. This tool is provided for just such a situation.
Code Tour
The method to restore the metabase is simply called Restore , and is accessed at the same
IIS://LocalHost node of the metabase that the Backup method was. Restore takes several parameters,
including the location string and the version number. Again, there are several constants that can be used
in place of an explicit version number. This sample uses as a default one of those constants,
&HFFFFFFFE (-2 decimal), which indicates that the server should look for, and restore from, the
highest numbered version of the specified backup location.
Location
Overview
Server creation, deletion, stopping, starting, configuring: These are all tasks that can keep you very busy,
especially if you are an administrator of a large Internet or intranet Web site. This sample tool
demonstrates how you can automate many of those tasks.
Code Tour
This sample script provides a simple interface through which you can create a new Web server. Several
steps are required to accomplish this, starting with invoking GetObject on the IIS://LocalHost/W3SVC
node. The IIsWebService object's ADSI method Create is used to create a new IIsWebServer
object. The server object is then configured, and the new information written back to the metabase with
the SetInfo method.
At this point in the script, the server is not a fully functional Web site. It now has a node in the metabase,
but it is not running, nor does it have a root directory in which to store anything. To finish creating the
Web site, the tool creates an instance of the IIsWebVirtualDir ADSI object, then configures that
object to be the new root directory for the new server. SetInfo is once again called to save the
information to the metabase, and finally, if all has gone well up to this point, the server object's Start
method is invoked.
Remarks
Note that almost every major statement group in this sample has its own set of error-code checking. This
is important when creating any tool in general, but especially for tools that use the IIS metabase.
Location