Built-in ASP Objects Reference

The Active Server Pages (ASP) framework provides six built-in objects:

  • Application
  • ObjectContext
  • Request
  • Response
  • Server
  • Session

The built-in objects are special because they are built into ASP pages and do not need to be created before you can use them in scripts.

This reference provides information about the built-in objects and their properties, methods, and events. For more information on server scripting with ASP pages, see Web Applications. For information about server components, see Installable Components for ASP.

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 more information on how to change the primary language, see Working with Scripting Languages.


Application Object

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

Lock | The Lock method prevents other clients from modifying Application object properties.
Unlock | The Unlock method allows other clients to modify Application object properties.

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
%>

Each of these variables would be members of the Application Contents Collection.

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., as some components are not designed to be given application scope. For more information, see Determining Component Scope in the Creating Components for ASP section of the Programmer's Reference.

If you assign a component instance to a variable in the Application Contents Collection, and use Visual Basic® Scripting Edition as your primary scripting language, you must use the Set keyword. This is illustrated in the following script.

<% Set Application("Obj1") = Server.CreateObject("MyComponent") %>

You can then reference the methods and properties of MyComponent on subsequent Web pages by using this script

<% Application("Obj1").MyObjMethod %>

or by extracting a local copy of the object and using the following

<%
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 a Application object, you should not attempt to alter the elements of the stored array directly. For example, the following script does not work

<% Application("StoredArray")(3) = "new value" %>

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 all over 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"

'Storing the array in the Application object
Application.Lock
Application("StoredArray") = MyArray
Application.Unlock

Response.Redirect("file2.asp")
%>

---file2.asp---
<%
'Retrieving the array from the Application Object
'and modifying its second element
LocalArray = Application("StoredArray")
LocalArray(1) = " there"

'printing out the string "hello there"
Response.Write(LocalArray(0)&LocalArray(1))

'Re-storing the array in the Application object
'This overwrites the values in StoredArray with the new values
Application.Lock
Application("StoredArray") = LocalArray
Application.Unlock
%>

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
%>

This application page has been visited
<%= Application("NumVisits") %> times!


Application Collections

The Application object supports these collections:

  • Contents
  • StaticObjects


Application Contents Collection

The Contents collection is a group all of 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.

Syntax

Application.Contents(Key)

Parameters

Key
Specifies the name of the item to retrieve.

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 MyVar and MyObj would be members of the Application.Contents collection:

<%
   Application("MyVar") = "Hello"
   Set Application("MyObj") = Server.CreateObject("MyComponent") %>

The Application.Contents collection supports For...Each and For...Next iteration. The following two scripts illustrate each of these methods of iterating through the Application.Contents collection.

<%
For Each Key in Application.Contents
  Response.Write ("Key")
Next Key
%>
<%
For i = 1 to Application.Contents.Count
  Response.Write ("Key")
Next Key
%>


Application StaticObjects Collection

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 to 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 ObjProp

For Each ObjProp in Application.StaticObjects
  Response.write(ObjProperty & " : " & Application.StaticObjects(ObjProp) & "<BR>")
Next ObjProp
%>


Application Methods

The Application object has the following methods.

  • Lock
  • Unlock


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.Unlock
%>

This application page has been visited
<%= Application("NumVisits") %>  times!

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.Unlock
%>

This application page has been visited
<%= Application("NumVisits") %>  times!

In the preceding example the Unlock method releases the locked object so that the next client can increment NumVisits.

Applies To

Application Object

See Also

Lock


ObjectContext Object

You can use the ObjectContext object to either commit or abort a transaction, managed by Microsoft Transaction Server (MTS), that has been initiated by a script contained in an ASP page.

When an ASP 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

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.
SetAbort | The SetAbort method declares that the transaction initiated by the script has not completed and the resources should not be updated.

Events

OnTransactionCommit
OnTransactionAbort

Remarks

ObjectContext implements two methods of the MTS ObjectContext object. The SetAbort method explicitly aborts the transaction. This causes MTS 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 assumed to be complete if it finishes processing without calling SetAbort.

ObjectContext exposes six methods in addition to SetAbort and SetComplete. These other methods are not available to ASP scripts, however, they are available to components called by the script.

Example

The following example uses the SetAbort and SetCommit 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
<!DOCTYPE HTML PUBLIC "-//IETF//DTD HTML//EN">

<HTML>
<HEAD>
<TITLE>Sales Order</TITLE>
</HEAD>
<BODY BGCOLOR="#FFFFFF"><FONT FACE="ARIAL,HELVETICA">
<H2>Sales Order Form </H2>

<FORM METHOD=POST ACTION="SalesVerify.asp">
<P>Please enter the product code, quantity, and your account number.
<INPUT TYPE=TEXT NAME=QuantityToBuy>
<INPUT TYPE=TEXT NAME=ProductCode>
<INPUT TYPE=TEXT NAME=AccountIn>
<P>
<INPUT TYPE=SUBMIT>
</FONT>
</BODY>
</HTML>
SalesVerify.asp file
<%@ Transaction = Required %>
<%
  Set CurrentQOH = Server.CreateObject("Mycomp.Inventory")
  Set CurrentSales = Server.CreateObject("Mycomp.Sales")

  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
%>

See Also

Creating Transactional Scripts in Web Applications


ObjectContext Methods

The ObjectContext object has the following methods.

SetAbort

SetComplete


SetAbort

The SetAbort method aborts a transaction initiated by an ASP.

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

The following events can occur after a ObjectContext method:

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.


OnTransactionCommit

The OnTransactionCommit event occurs after a transacted script's transaction commits. When the OnTransactionCommit event occurs, IIS will process the script's OnTransactionCommit subroutine, if it exists.


Request Object

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 the ServerVariables collection the full name be used. For example, rather than Request.(AUTH_USER) use Request.ServerVariables(AUTH_USER).

See Also

Response Object


Request Collections

The Request object has the following 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.

If no certificate is sent, the ClientCertificate collection returns EMPTY.

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:

ceCertPresent - A client certificate is present.

ceUnrecognizedIssuer - The last certification in this chain is from an unknown issuer.

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 hexidecimal bytes separated by hyphens (-). For example, 04-67-F3-02.
Subject | A string that contains a list of subfield values that themselves 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.
ValidUntil | A date specifying when the certificate expires.

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 use an iterator to loop through the keys of the ClientCertificate collection. This is demonstrated in the following example.

<%
For Each key in Request.ClientCertificate
  Response.Write( key & ": " & Request.ClientCertificate(key) & "<BR>")
Next
%>

Examples

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.

<%= Request.ClientCertificate("IssuerCN") %>

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.

This certification will expire on
<%= Request.ClientCertificate("ValidUntil") %>

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.

<!--#include file="cervbs.inc" -->
<%
If Request.ClientCertificate("Flags") and ceUnrecognizedIssuer then
  Response.Write "Unrecognized issuer"
End If
%>

Applies To

Request Object

See Also

Cookies, Form, QueryString, ServerVariables


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.

<%= Request.Cookies("myCookie").HasKeys %>

If myCookie is a cookie dictionary, the preceding value evaluates to TRUE. Otherwise, it evaluates to FALSE.

You can use an iterator to cycle 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.

<%
'Print out the entire cookie collection.
For Each cookie in Request.Cookies
  If Not cookie.HasKeys Then
    'Print out the cookie string
%>
    <%= cookie %> = <%= Request.Cookies(cookie)%>
<%
Else
  'Print out the cookie collection
  For Each key in Request.Cookies(cookie)
%>
  <%= cookie %> (<%= key %>) = <%= Request.Cookies(cookie)(key)%>
<%
  Next
End If
Next
%>

Examples

The following example prints the value of myCookie in a Web page.

Here is the value of the cookie named myCookie:
<%= Request.Cookies("myCookie") %>

Applies To

Request Object

See Also

ClientCertificate, Form, QueryString, ServerVariables


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 use an iterator to loop 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 parameter, you could retrieve those values by using the following script.

<%
For Each item In Request.Form("FavoriteFlavor")
  Response.Write item & "<BR>"
Next
%>

The preceding script would display the following.

Chocolate
Butterscotch

The same output can be generated with a For...Next loop, as shown in the following script.

<%
For i = 1 To Request.Form("FavoriteFlavor").Count
  Response.Write Request.Form("FavoriteFlavor")(i) & "<BR>"
Next
%>

You can use this iterator to display the parameter name, as shown in the following script.

<% For Each x In Request.Form %>
Request.Form( <%= x %> ) = <%= Request.Form(x) %> <BR>
<% Next %>

This script displays the following on the browser.

FavoriteFlavor = Chocolate
FavoriteFlavor = Butterscotch

Example

Consider the following form.

<FORM ACTION = "/scripts/submit.asp" METHOD = "post">
<P>Your first name: <INPUT NAME = "firstname" SIZE = 48>
<P>What is your favorite ice cream flavor: <SELECT NAME = "flavor">
<OPTION>Vanilla
<OPTION>Strawberry
<OPTION>Chocolate
<OPTION>Rocky Road</SELECT>
<p><INPUT TYPE = SUBMIT>
</FORM>

From that form, the following request body might be sent.

firstname=James&flavor=Rocky+Road

The following script can then be used.

Welcome,  <%= Request.Form("firstname") %>.
Your favorite flavor is <%= Request.Form("flavor") %>.

The following output is the result.

Welcome, James. Your favorite flavor is Rocky Road.

If the following script is used

The unparsed form data is:  <%= Request.Form %>

the output would be

The unparsed form data is:  firstname=James&flavor=Rocky+Road

Applies To

Request Object

See Also

ClientCertificate, Cookies, QueryString, ServerVariables


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

<A HREF= "example?string=this is a sample">string sample</A>

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 their 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 any integer value in the range 1 to Request.QueryString(variable).Count.

Remarks

The QueryString collection is a parsed version of the QUERY_STRING variable in the ServerVariables collection. It enables you to retrieve the QUERY_STRING variables by name. The value of Request.QueryString(parameter) is an array of all of the values of parameter that occur in QUERY_STRING. You can determine the number of values of a parameter by calling Request.QueryString(parameter).Count. If a variable does not have multiple data sets associated with it, the count is 1. If the variable is not found, the count is 0.

To reference a QueryString variable in one of multiple data sets, you specify a value for index. The index parameter may 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://NAMES.ASP?Q=Fred&Q=Sally

and Names.asp contained the following script,

---NAMES.ASP---
<%
For Each item In Request.QueryString("Q")
  Response.Write item & "<BR>"
Next
%>

Names.asp would display the following.

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

The client request

/scripts/directory-lookup.asp?name=fred&age=22

results in the following QUERY_STRING value.

name=fred&age=22.

The QueryString collection would then contain two members, name and age. You can then use the following script.

Welcome,  <%= Request.QueryString("name") %>.
Your age is  <%= Request.QueryString("age") %>.

The output would be

Welcome, Fred. Your age is 22.

If the following script is used

The unparsed query string is:  <%=Request.QueryString %>

The output would be

The unparsed query string is: name=fred&age=22

Applies To

Request Object

See Also

ClientCertificate, Cookies, Form, ServerVariables


ServerVariables

The ServerVariables collection retrieves the values of predetermined environment variables.

Syntax

Request.ServerVariables (server environment variable)

Parameters

server environment variable
Specifies the name of the server environment variable to retrieve. It can be one of the following values.
Variable | Description
ALL_HTTP | All HTTP headers sent by the client.
ALL_RAW | Retrieves all headers in the raw-form. The difference between ALL_RAW and ALL_HTTP is that ALL_HTTP places an HTTP_ prefix before the header name and the header-name is always capitalized. In ALL_RAW the header name and values appear as they are sent by the client.
APPL_MD_PATH | Retrieves the metabase path for the (WAM) Application for the ISAPI DLL.
APPL_PHYSICAL_PATH | Retrieves the physical path corresponding to the metabase path. IIS converts the APPL_MD_PATH to the physical (directory) path to return this value.
AUTH_PASSWORD | The value entered in the client's authentication dialog. This variable is only available if Basic authentication is used.
AUTH_TYPE | The authentication method that the server uses to validate users when they attempt to access a protected script.
AUTH_USER | Raw authenticated user name.
CERT_COOKIE | Unique ID for client certificate, Returned as a string. Can be used as a signature for the whole client certificate.
CERT_FLAGS bit0 is set to 1 if the client certificate is present.

bit1 is set to 1 if the Certifying Authority of the client certificate is invalid (not in the list of recognized CA on the server).
CERT_ISSUER | Issuer field of the client certificate (O=MS, OU=IAS, CN=user name, C=USA).
CERT_KEYSIZE | Number of bits in Secure Sockets Layer connection key size. For example, 128.
CERT_SECRETKEYSIZE | Number of bits in server certificate private key. For example, e.g. 1024.
CERT_SERIALNUMBER | Serial number field of the client certificate.
CERT_SERVER_ISSUER | Issuer field of the server certificate.
CERT_SERVER_SUBJECT | Subject field of the server certificate.
CERT_SUBJECT | Subject field of the client certificate.
CONTENT_LENGTH | The length of the content as given by the client.
CONTENT_TYPE | The data type of the content. Used with queries that have attached information, such as the HTTP queries GET, POST, and PUT.
GATEWAY_INTERFACE | The revision of the CGI specification used by the server. The format is CGI/revision.
HTTP_<HeaderName> The value stored in the header HeaderName. Any header other than those listed in this table must be prefixed by HTTP_ in order for the ServerVariables collection to retrieve its value.

Note The server interprets any underscore (_) characters in HeaderName as dashes in the actual header. For example if you specify HTTP_MY_HEADER, the server searches for a header sent as MY-HEADER.

HTTPS | Returns ON if the request came in through secure channel (SSL) or it returns OFF if the request is for a non-secure channel.
HTTPS_KEYSIZE | Number of bits in Secure Sockets Layer connection key size. For example, 128.
HTTPS_SECRETKEYSIZE | Number of bits in server certificate private key. For example, 1024.
HTTPS_SERVER_ISSUER | Issuer field of the server certificate.
HTTPS_SERVER_SUBJECT | Subject field of the server certificate.
INSTANCE_ID | The ID for the IIS instance in textual format. If the instance ID is 1, it appears as a string. You can use this variable to retrieve the ID of the Web-server instance (in the metabase) to which the request belongs.
INSTANCE_META_PATH | The metabase path for the instance of IIS that responds to the request.
LOCAL_ADDR | Returns the Server Address on which the request came in. This is important on multi-homed machines where there can be multiple IP addresses bound to a machine and you want to find out which address the request used.
LOGON_USER | The Windows NT® account that the user is logged into.
PATH_INFO | Extra path information as given by the client. You can access scripts by using their virtual path and the PATH_INFO server variable. If this information comes from a URL, it is decoded by the server before it is passed to the CGI script.
PATH_TRANSLATED | A translated version of PATH_INFO that takes the path and performs any necessary virtual-to-physical mapping.
QUERY_STRING | Query information stored in the string following the question mark (?) in the HTTP request.
REMOTE_ADDR | The IP address of the remote host making the request.
REMOTE_HOST | The name of the host making the request. If the server does not have this information, it will set REMOTE_ADDR and leave this empty.
REMOTE_USER | Unmapped user-name string sent in by the User. This is the name that is really sent by the user as opposed to the ones that are modified by any authentication filter installed on the server.
REQUEST_METHOD | The method used to make the request. For HTTP, this is GET, HEAD, POST, and so on.
SCRIPT_NAME | A virtual path to the script being executed. This is used for self-referencing URLs.
SERVER_NAME | The server's host name, DNS alias, or IP address as it would appear in self-referencing URLs.
SERVER_PORT | The port number to which the request was sent.
SERVER_PORT_SECURE | A string that contains either 0 or 1. If the request is being handled on the secure port, then this will be 1. Otherwise, it will be 0.
SERVER_PROTOCOL | The name and revision of the request information protocol. The format is protocol/revision.
SERVER_SOFTWARE | The name and version of the server software that answers the request and runs the gateway. The format is name/version.
URL | Gives the base portion of the URL.

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 this header

SomeNewHeader:SomeNewValue

you could retrieve SomeNewValue by using the following syntax

<% Request.ServerVariables("HTTP_SomeNewHeader") %>

You can use an iterator to loop through each server variable name. For example, the following script prints out all of the server variables in a table.

<TABLE>
<TR><TD><B>Server Variable</B></TD><TD><B>Value</B></TD></TR>
<% For Each name In Request.ServerVariables %>
<TR><TD> <%= name %> </TD><TD>  <%= Request.ServerVariables(name) %> </TD></TR>
</TABLE>
<% Next %>

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.

<A HREF = "http://<%= Request.ServerVariables("SERVER_NAME") %>
/scripts/MyPage.asp">Link to MyPage.asp</A>

Applies To

Request Object

See Also

ClientCertificate, Cookies, Form, QueryString


Request Properties

The Request object supports this property:

  • 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

The Request object supports the following method:

  • 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.
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 binread
Dim bytecount
bytecount = Request.TotalBytes
binread = Request.BinaryRead(bytecount)
%>

Applies To

Request Object

See Also

TotalBytes, ClientCertificate, Cookies, Form, QueryString, ServerVariables


Response Object

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

Buffer | Indicates whether page output is buffered.
CacheControl | Determines whether proxy servers are able to cache the output generated by ASP.
Charset | Appends the name of the character set to the content-type header.
ContentType | Specifies the HTTP content type for the response.
Expires | Specifies the length of time before a page cached on a browser expires.
ExpiresAbsolute | Specifies the date and time on which a page cached on a browser expires.
IsClientConnected | Indicates whether the client has disconnected from the server.
Pics | Adds the value of a PICS label to the pics-label field of the response header.
Status | The value of the status line returned by the server.

Methods

AddHeader | Sets the HTML header name to value.
AppendToLog | Adds a string to the end of the Web server log entry for this request.
BinaryWrite | Writes the given information to the current HTTP output without any character-set conversion.
Clear | Erases any buffered HTML output.
End | Stops processing the .asp file and returns the current result.
Flush | Sends buffered output immediately.
Redirect | Sends a redirect message to the browser, causing it to attempt to connect to a different URL.
Write | Writes a variable to the current HTTP output as a string.

See Also

Request Object


Response Collections

The Response object has the following collection.

  • 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

If a cookie with a key is created, as in the following script,

<%
Response.Cookies("mycookie")("type1") = "sugar"
Response.Cookies("mycookie")("type2") = "ginger snap"
%>

this header is sent.

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.

<% Response.Cookies("myCookie") = "chocolate chip" %>

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 nonkey values the cookie contained. For example, if after the preceding code you call Response.Cookies with the following

<% Response.Cookies("myCookie")("newType") = "peanut butter" %>

The value chocolate chip is discarded and newType would be set to peanut butter.

To determine whether a cookie has keys, use the following syntax.

<%= Response.Cookies("myCookie").HasKeys %>

If myCookie is a cookie dictionary, the preceding value is TRUE. Otherwise, it is FALSE.

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).Expires = #July 4, 1997#
Next
%>

You can also use an iterator to set the values of all the cookies in a collection, or all the keys in a cookie. However, the iterator, when invoked on a cookie that does not have keys, does not execute. 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 key
%>

Examples

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").Expires = "July 31, 1997"
Response.Cookies("Type").Domain = "msn.com"
Response.Cookies("Type").Path = "/www/home/"
Response.Cookies("Type").Secure = FALSE
%>

Applies To

Response Object

See Also

Request.Cookies


Response Properties

The Response object has the following 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. This is the default value. The server sends output to the client as it is processed.
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 script 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 IIS Metabase in the Programmer's Reference.

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

Response.CacheControl [= Cache Control Header ]

Parameters

Cache Control Header
A cache control header that will be either Public or Private.

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

If the same .asp file included

<% Response.Charset("ISO-LATIN-7") %>

the content-type header would be

content-type:text/html; charset=ISO-LATIN-7

Remarks

This function inserts any string in the header, 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 the Macintosh, 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 specifed, 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.

Examples

The following example sets the content type to Channel Definition Format(CDF).

<% Response.ContentType = "application/x-cdf" %>

The following examples set the ContentType property to other common values.

<% Response.ContentType = "text/HTML" %>
<% Response.ContentType = "image/GIF" %>
<% Response.ContentType = "image/JPEG" %>

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. Set this parameter to 0 to have the cached page expire immediately.

Remarks

If this property is set more than once on a page, the shortest time is used.

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

Response.ExpiresAbsolute [= [date] [time]]

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, 1996.

<% Response.ExpiresAbsolute=#May 31,1996 13:30:15# %>

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 since the last Response.Write.

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

The PICS property adds a value to the pics-label field of the response header.

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 field in the response header.

Example

For an .asp file that includes

<%
Response.PICS("(PICS-1.1 <http://www.rsac.org/ratingv01.html> labels on " & chr(34) & "1997.01.05T08:15-0500" & chr(34) & " until" & chr(34) & "1999.12.31T23:59-0000" & chr(34) & " ratings (v 0 s 0 l 0 n 0))")
%>

the following header would be added

PICS-label:(PICS-1.1 <http://www.rsac.org/ratingv01.html> labels on "1997.01.05T08:15-0500" until "1999.12.31T23:59-0000" ratings (v 0 s 0 l 0 n 0))

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.

Examples

The following example sets the response status.

<% Response.Status = "401 Unauthorized" %>

Applies To

Response Object


Response Methods

The Response object has the following 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.

This method is for advanced use only. If another Response method will provide the functionality you require, it is recommended that you use that method instead.

Syntax

Response.AddHeader name, value

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.

<% Request.ServerVariables("HTTP_MY_HEADER") %>

Because HTTP protocol requires that all headers be sent before content, you must call AddHeader in your script before any output (such as that generated by HTML code or the Write method) is sent to the client. The exception to this rule is when the Buffer property is set to TRUE. If the output is buffered, you can call the AddHeader method at any point in the script, as long as it precedes any calls to Flush. Otherwise, the call to AddHeader will generate a run-time error.

The following two .asp files illustrate this point.

-------file1.asp---------
<% Response.AddHeader "WARNING", "Error Message Text" %>
<HTML>
Some text on the Web page.
</HTML>

In the preceding example, the page is not buffered. The script works, however, because the AddHeader method is called before the server sends the output

Some text on the Web page

to the client. If the order were reversed, the call to the AddHeader method would generate a run-time error.

------file2.asp----------
<% Response.Buffer = TRUE %>
<HTML>
Here's some text on your Web page.
<% Response.AddHeader "WARNING", "Error Message Text" %> Here's some more interesting and illuminating text.
<% Response.Flush %>
<%= Response.Write("some string") %>
</HTML>

In the preceding example, the page is buffered, and as a result, the server will not send output to the client until all the ASP scripts on the 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.

<% Response.Addheader "WWW-Authenticate", "BASIC" %>

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

Flush, Write, Buffer


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 IIS log are comma-delimited, this string cannot contain any comma characters (,). The maximum length of this string is 80 characters.

Remarks

In order for the specified string to be recorded in the log file, you must enable the URI Query option of the Extended Logging Properties sheet for the site whose activity you wish to log. For more information on configuring Extended Logging, see Customizing W3C Extended Logging.

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 nonstring information such as binary data required by a custom application.

Syntax

Response.BinaryWrite data

Parameters

data
The data to write to the HTTP output.

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 BinGen = Server.CreateObject(MY.BinaryGenerator)
Pict = BinGen.MakePicture
Response.BinaryWrite Pict
%>

Applies To

Response Object

See Also

Write


Clear

The Clear method erases any buffered HTML output. However, the Clear method only erases 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
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.

HTTP/1.0 302 Object Moved
Location URL

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 will translate the escape sequence when it processes the script.

Examples

The following examples use the Response.Write method to send output to the client.

I just want to say <% Response.Write "Hello World." %>
Your name is: <% Response.Write Request.Form("name") %>

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

<% Response.Write "<TABLE WIDTH = 100%\>" %>

produces the output

<TABLE WIDTH = 100%>

Applies To

Response Object

See Also

BinaryWrite


Server Object

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

CreateObject | Creates an instance of a server component.
HTMLEncode | Applies HTML encoding to the specified string.
MapPath | Maps the specified virtual path, either the absolute path on the current server or the path relative to the current page, into a physical path.
URLEncode | Applies URL encoding rules, including escape characters, to the string.


Server Properties

The Server object has the following property.

  • 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 About the Metabase

Example

The following example causes scripts to time out if the server takes longer than 100 seconds to process them.

<% Server.ScriptTimeout = 100 %>

The following example retrieves the current value of the ScriptTimeout property and stores it in the variable TimeOut.

<% TimeOut = Server.ScriptTimeout %>

Applies To

Server Object

See Also

AspScriptTimeout


Server Methods

The Server object has the following methods.

  • CreateObject
  • HTMLEncode
  • MapPath
  • 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 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.

<% Set Session("ad") = Server.CreateObject("MSWC.AdRotator")%>

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.

<% Session("ad") = Nothing %>
<% Session("ad") = "some other value" %>

You cannot create an object instance with the same name as a built-in object. For example, the following returns an error.

<% Set Response = Server.CreateObject("Response") %>

Example

<% Set MyAd = Server.CreateObject("MSWC.AdRotator") %>

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 Creating Components for ASP.

Applies To

Server Object


HTMLEncode

The HTMLEncode method applies HTML encoding to a specified string.

Syntax

Server.HTMLEncode( string )

Parameters

string
Specifies the string to encode.

Example

The following script

<%= Server.HTMLEncode("The paragraph tag: <P>") %>

produces the output

The paragraph tag: &lt;P&gt;

Note The preceding output will be displayed by a Web browser as

The paragraph tag: <P>

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 support relative path syntax (.) or (..). For example, the following relative path, ../MyDir/MyFile.txt, returns an error.

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.

Examples

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>

produces the output

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>

produce the following output

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>

produce the following output

c:\inetpub\script\data.txt<BR>
c:\inetpub\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>

produce the following output

c:\inetpub\wwwroot<BR>
c:\inetpub\wwwroot<BR>

Applies To

Server Object


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

The following script

<%Response.Write(Server.URLEncode("http://www.microsoft.com")) %>

produces the output

http%3A%2F%2Fwww%2Emicrosoft%2Ecom

Applies To

Server Object

See Also

HTMLEncode


Session Object

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; instead, these variables persist for the entire user-session.

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 codepage 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.

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.

<% Set Session("Obj1") = Server.CreateObject("MyComponent.class1") %>

You can then call the methods and properties exposed by MyComponent.class1 on subsequent Web pages, by using the following.

<% Session("Obj1").MyMethod %>

Or by extracting a local copy of the object and 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. For more information, see Selecting a Threading Model in Creating Components for ASP.

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.

<% Session("StoredArray")(3) = "new value" %>

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 all over 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"

'Storing the array in the Session object
Session("StoredArray") = MyArray

Response.Redirect("file2.asp")
%>

---file2.asp---
<%
'Retrieving the array from the Session Object
'and modifying its second element
LocalArray = Session("StoredArray")
LocalArray(1) = " there"

'printing out the string "hello there"
Response.Write(LocalArray(0)&LocalArray(1))

'Re-storing the array in the Session object
'This overwrites the values in StoredArray with the new values
Session("StoredArray") = LocalArray
%>

Examples

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

The Session Object supports the following collections.

  • Contents
  • StaticObjects


Session Contents Collection

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.

<%
Dim sessitem
For Each sessitem in Session.Contents
  Response.write(sessitem & " : " & Session.Contents(sessitem) & "<BR>")
Next
%>


Session StaticObjects Collection

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 a 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
  Response.write(objproperty & " : " & Session.StaticObjects(objprop) & "<BR>")
Next
%>


Session Properties

The Session object has the following properties.

  • CodePage
  • LCID
  • SessionID
  • Timeout


CodePage

The CodePage property determines the codepage that will be used to display dynamic content.

Syntax

Session.CodePage(=Codepage)

Parameters

Codepage
An unsigned integer that represents a valid codepage for the system that is running the ASP scripting engine.

Remarks

A codepage is a character set that can include numbers, punctuation marks, and other glyphs. Different languages and locales may use different codepages. 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 codepage can be represented in a table as a mapping of characters to single-byte values or multibyte values. Many codepages 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.

Applies To

Session Object


SessionID

The SessionID property returns the session identification for this user. Each session has 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 autoincrement 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 20 minutes.

Applies To

Session Object

See Also

Abandon


Session Methods

The Session object has the following method.

  • Abandon


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.

Examples

The following example causes the session state to be released when the server finishes processing the current page.

<% Session.Abandon %>

Applies To

Session Object

See Also

Timeout


@ Directives Reference

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 4.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

<%@ CODEPAGE=codepage%>

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

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

<%@ ENABLESESSIONSSTATE=True|False %>

Remarks

For more information about session tracking, see Managing Session States


@LANGUAGE

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

<%@ LANGUAGE=scriptengine %>

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 IIS Admin Objects.


@LCID

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

<%@ LCID=localeidentifier %>

Parameters

localeidentifer
A valid locale identifier.

See Also

Session.LCID


@TRANSACTION

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, Microsoft Transaction Server (MTS) will create a transaction to coordinate the updating of resources.

Syntax

<%@ TRANSACTION=value %>

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.

See Also

ObjectContext


Installable Components for ASP

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.

Ad Rotator | Creates an AdRotator object that automatically rotates advertisements displayed on a page according to a specified schedule.
Browser Capabilities | Creates a BrowserType object that determines the capabilities, type, and version of each browser that accesses your Web site.
Database Access | Provides access to databases using ActiveX™ Data Objects (ADO).
Content Linking | Creates a NextLink object that creates tables of contents for Web pages, and links them together sequentially like pages in a book.
File Access Component | Provides access to file input and output.
Collaboration Data Objects for NTS Component | Lets you quickly and easily add the ability to send and receive messages to your Web page. This component is only available on Internet Information Server for Windows NT® Server.
Tools | Creates a Tools object that provides utilities that enable you to easily add sophisticated functionality to your web pages.
Status | 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.
MyInfo | Creates a MyInfo object that keeps track of personal information, such as the site administrator's name, address, and display choices.
Counters | Creates a Counters object that can create, store, increment, and retrieve any number of individual counters.
Content Rotator | Automates the rotation of HTML content strings on a Web page.
Page Counter | Counts and displays the number of times a Web page has been opened.
Permission Checker | Uses the password authentication protocols provided in Microsoft® Internet Information Server (IIS) to determine whether a Web user has been granted permissions to read a file.

For more information on server scripting with ASP, see Web Applications. For more information on the built-in objects supplied with the ASP, see Built in ASP Objects Reference.

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 more information on how to change the primary scripting language, see Working with Scripting Languages.


Ad Rotator Component

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. For more information on activity logs, see Logging Web Site Activity.

File Names

adrot.dll | The Ad Rotator component.
Redirection File | An optional file that implements redirection and enables the Ad Rotator component to record how many users click on each advertisement.
Rotator Schedule File | A text file that contains the display schedule and file information for advertisements. This file must be available on a Web server virtual path.

Syntax

Set AdRotator = Server.CreateObject("MSWC.AdRotator")

Parameters

AdRotator
Specifies the name of the AdRotator object created by the call to Server.CreateObject.

Registry Entries

None.

Properties

Border | Specifies the size of the border around the advertisement.
Clickable | Specifies whether the advertisement is a hyperlink.
TargetFrame | Specifies the name of the frame in which to display the advertisement.

Methods

GetAdvertisement Gets the specifications for the next scheduled advertisement from the data file and formats it as HTML.

Example

The following example displays a different advertisement each time a user views the Web page.

<%  Set ad = Server.CreateObject("MSWC.AdRotator") %>

<%= ad.GetAdvertisement("/ads/adrot.txt") %>

The following HTML is generated by the GetAdvertisement method and 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>


Rotator Schedule File

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 4,294,967,295 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.

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 redirect the user to the URL associated with the advertisement that they 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

The AdRotator object has the following properties.

  • Border
  • Clickable
  • TargetFrame


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

The following example displays the advertisements without a border.

<%
Set ad = Server.CreateObject("MSWC.AdRotator")
ad.Border = 0
%>
<%= ad.GetAdvertisement("/ads/adrot.txt") %>

Applies To

Ad Rotator Component

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 | Meaning
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") %>

Applies To

Ad Rotator Component

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

The following example displays the advertisements in the frame AdFrame.

<%
Set ad = Server.CreateObject("MSWC.AdRotator")
ad.TargetFrame = AdFrame
%>
<%= ad.GetAdvertisement("/ads/adrot.txt") %>

Applies To

Ad Rotator Component

See Also

Border, Clickable


Ad Rotator Methods

The AdRotator object has the following method.

  • GetAdvertisement


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

Returns HTML that displays the advertisement in the current page.

Example

The following example gets an advertisement from the Adrot.txt file in the /Ads/ virtual directory.

<% Set NextAd = Server.CreateObject("MSWC.AdRotator") %>
<%= NextAd.GetAdvertisement("/ads/adrot.txt") %>

Applies To

Ad Rotator Component


Browser Capabilities Component

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 a User Agent HTTP 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 takes on the default browser properties. If the object does not find a match and default browser settings have not been specified in the browscap.ini file, it 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

browscap.dll | The Browser Capabilities component.
browscap.ini | A text file that maps browser capabilities to the HTTP User Agent header. This file must be in the same directory as browscap.dll.

Syntax

Set BrowserType = Server.CreateObject("MSWC.BrowserType")

Parameters

BrowserType
Specifies the name of the BrowserType object created by the call to Server.CreateObject.

Registry Entries

None.

Example

The following example uses the BrowserType object to display a table showing some of the capabilities of the current browser.

<%  Set bc = Server.CreateObject("MSWC.BrowserType") %>
<table border=1>
<tr><td>Browser</td><td>  <%= bc.browser  %>
<tr><td>Version</td><td>  <%= bc.version  %>  </td></TR>
<tr><td>Frames</td><td>
<%  if (bc.frames = TRUE) then  %>  TRUE
<%  else  %>  FALSE
<%  end if  %> </td></TR>
<tr><td>Tables</td><td>
<%  if (bc.tables = TRUE) then  %>  TRUE
<%  else  %> FALSE
<%  end if  %> </td></TR>
<tr><td>BackgroundSounds</td><td>
<%  if (bc.BackgroundSounds = TRUE) then  %>  TRUE
<%  else  %> FALSE
<%  end if  %> </td></TR>
<tr><td>VBScript</td><td>
<%  if (bc.vbscript = TRUE) then  %>  TRUE
<%  else  %> FALSE
<%  end if  %> </td></TR>
<tr><td>JScript</td><td>
<%  if (bc.javascript = TRUE) then  %>  TRUE
<%  else  %> FALSE
<%  end if  %> </td></TR>
</table>


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]

[Default Browser Capability Settings]

[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.

For example, if you specified the following string for HTTPUserAgentHeader:

[Mozilla/2.0 (compatible; MSIE 3.0;* Windows 95)]

It would match all of the following User Agent headers:

[Mozilla/2.0 (compatible; MSIE 3.0; Windows 95)]
[Mozilla/2.0 (compatible; MSIE 3.0; AK; Windows 95)]
[Mozilla/2.0 (compatible; MSIE 3.0; SK; Windows 95)]
[Mozilla/2.0 (compatible; MSIE 3.0; AOL; Windows 95)]

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 first matching definition.

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.

The following table lists some possible properties:
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 3.01 definition inherits all the properties of Microsoft® Internet Explorer 3.0 definition (for example, frames=TRUE, tables=TRUE, and cookies=TRUE). It adds platform-specific information by adding the line, platform=Win95, and overwrites the version information in the line, version=3.01.

;;ie 3.0
[IE 3.0]
browser=IE
Version=3.0
majorver=#3
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 3.01
[Mozilla/2.0 (compatible; MSIE 3.01*; Windows 95)]
parent=IE 3.0
version=3.01
minorver=01
platform=Win95

; Default Browser
[Default Browser Capability Settings]
browser=Default
frames=FALSE
tables=TRUE
cookies=FALSE
backgroundsounds=FALSE
vbscript=FALSE
javascript=FALSE


Database Access Component

The Database Access component uses ActiveX Data Objects (ADO) to access information stored in a database or other tabular data structure.

For more information about the objects available in ADO, see Microsoft Data Access.

Note To use the constants specified in the ADO Reference, you must include a file that contains information about the ADO constants. For example, to use:

<% rs.Open "Customers", Conn, adOpenStatic, adLockOptimistic %>

Instead of:

<% rs.Open "Customers", Conn, 3, 3 %>

You must include the ADO Constants Include file in the .asp file by using a server-side include (SSI) statement.

If your primary scripting language is VBScript, the file you should include is named ADOVBS.INC. If you are using JScript™, you should include the file named ADOJAVS.INC.

You can include them in your .asp file by using the following:

<!--#include virtual="/PROGRAM FILES/COMMON FILES/SYSTEM/ADO/ADOVBS.INC"-->
or
<!--#include virtual="/PROGRAM FILES/COMMON FILES/SYSTEM/ADO/ADOJAVAS.INC"-->

For more information about how to include files, see Including Files in Web Applications.


Content Linking Component

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

nextlink.dll | The Content Linking component.
Content Linking List | A text file that contains a list of Web pages in the order in which they should be displayed. This file must be available on a Web server virtual path.

Syntax

Set NextLink = Server.CreateObject("MSWC.NextLink")

Parameters

NextLink
Specifies the name of the object created by the call to Server.CreateObject.

Registry Entries

None.

Methods

GetListCount | Counts the number of items linked in the Content Linking List file.
GetNextURL | Gets the URL of the next page listed in the Content Linking List file.
GetPreviousDescription | Gets the description line of the previous page listed in the Content Linking List file.
GetListIndex | Gets the index of the current page in the Content Linking List file.
GetNthDescription | Gets the description of the Nth page listed in the Content Linking List file.
GetPreviousURL | Gets the URL of the previous pages listed in the Content Linking List file.
GetNextDescription | Gets the description of the next page listed in the Content Linking List file.
GetNthURL | Gets the URL of the Nth page listed in the Content Linking List file.

Example

The following example builds a table of contents.

<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 %>

<a href="  <%= NextLink.GetPreviousURL ("/data/nextlink.txt")  %>  ">

Previous Page</a>
<%  End If  %>
<a href="  <%= NextLink.GetNextURL ("/data/nextlink.txt")  %>  ">Next Page</a>


Content Linking List File

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

Web-page-URL [ text-description [ comment]]

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
main.htm Return to the table of contents


Content Linking Methods

The NextLink object has the following methods.

  • GetListCount
  • GetNextURL
  • GetPreviousDescription
  • GetListIndex
  • GetNthDescription
  • GetPreviousURL
  • GetNextDescription
  • GetNthURL


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

This method returns an integer.

Applies To

Content Linking Component

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.

Applies To

Content Linking Component

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.

Applies To

Content Linking Component

See Also

GetNextURL, GetPreviousDescription, GetNthDescription


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.

Applies To

Content Linking Component

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.

<%  Set NextLink = Server.CreateObject ("MSWC.NextLink") %>

<A HREF="<%= NextLink.GetNextURL ("/data/nextlink.txt") %>">Next Page </A>

See Also

GetPreviousURL, GetNthURL, GetNextDescription


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

This method returns a string.

Applies To

Content Linking Component

See Also

GetNextDescription, GetPreviousDescription, GetNthURL


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

This method returns a string.

Applies To

Content Linking Component

See Also

GetNextURL, GetPreviousURL, GetNthDescription


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.

Applies To

Content Linking Component

See Also

GetNextDescription, GetNthDescription, GetPreviousURL


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.

Applies To

Content Linking Component

See Also

GetNextURL, GetNthURL, GetPreviousDescription


File Access Component

The File Access component exposes methods and properties you can use to access a computer's file sytem. 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.

For further information on the FileSystemObject, see Objects in the VB Script Language Reference.


Content Rotator Component

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.

The following files are used by the Content Rotator component:

FileNames |
controt.dll | The Content Rotator component.
Content Schedule File | A text file that contains the display schedule and file information for Web content. This file must be available on a Web server virtual path.

Syntax

<% Set oVar = Server.CreateObject("MSWC.ContentRotator") %>

Parameters

oVar
Specifies the name of the ContentRotator object created by the call to Server.CreateObject.

Registry Entries

None.

Methods

ChooseContent | Retrieves and displays a content string.
GetAllContent | Retrieves and displays all the content strings in the Content Schedule file.

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")
%>

Note This component is not installed with IIS. You can install it from the Microsoft Web site at: http://www.microsoft.com/iis/, or from the CD included with the IIS Resource Kit.


Content Schedule File

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 65,535 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.

A Weight of 0 will cause a content entry to be ignored.

If Weight is not specified, the default value is 1.

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.

%% #2 // Content can be more that one line long
%% // Additional line of comments
%% // Yet another line of comments
<FONT FACE="ARIAL,HELVETICA" SIZE="2">
  Let a
  <H1>smile</H1>
  be your umbrella.
</FONT>

%% #3 // This is our favorite image, so show it most often
<IMG SRC="/images/happy.gif">

%%
Here's the <A HREF="secret.asp">secret link.</A>


ChooseContent

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

Returns an HTML content string from the Content Schedule file.

Applies To

Content Rotator Component

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

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.

Applies To

Content Rotator Component

Example

The following example uses the GetAllContent method to display all of the entries in the Content Schedule file.

<H1>Tips Stored in the Content Schedule File:</H1>
<%
Set Tips = Server.CreateObject("MSWC.ContentRotator") Tips.GetAllContent("/Tips/Content.txt")
%>

The preceding example produces HTML output such as the following:

<H1>Tips Stored in the Content Schedule File:</H1>
<HR>

Don't run with scissors.
<HR>

<FONT FACE="ARIAL,HELVETICA" SIZE="2">
  Let a
  <H1>smile</H1>
  be your umbrella.
</FONT>
<HR>

<IMG SRC="/images/happy.gif">
<HR>

Here's the <A HREF="secret.asp">secret link.</A>
<HR>


Page Counter Component

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.

The Page Counter component uses the following files:

File Names
pagecnt.dll | The Page Counter component.
Hit Count Data file | The text file to which the Page Counter component saves the current hit count.

Syntax

<% Set oVar = Server.CreateObject("MSWC.PageCounter") %>

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.

Named Value | Description
File_Location | A string that specifies the path and filename of the Hit Count Data file. The default filename is hitcnt.cnt. This file is located in your Windows directory.
Save_Count | A DWORD that specifies the number of hits before the hit count is saved to the Hit Count Data file. Note that this is the total number of hits, not the number of hits per page. The default value is 25.

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 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 %>

Note This component is not installed with IIS. You can install it from the Microsoft Web site at: http://www.microsoft.com/iis/, or from the CD included with the IIS Resource Kit.


Hit Count Data file

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.

For more information, see the Readme file included with the Page Counter component.


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.

<% Set MyPageCounter = Server.CreateObject("MSWC.PageCounter") %>

This Web page has been viewed <%= MyPageCount.Hits %> times.
<P>
Page Myscript.asp has been viewed <%= MyPageCounter.Hits("/VirtualDir1/Myscript.asp") %> times.

Applies To

Page Counter Component

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.

Applies To

Page Counter Component

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.

Return Values

None.

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")
%>

(The following two values should be 0) <BR>
Hits to this page = <%= MyPageCount.Hits %> <BR>
Hits to Mypage.asp = <%= MyPageCount.Hits("/VirtualDir1/Mypage.asp") <BR>

Applies To

Page Counter Component

See Also

Hits


Permission Checker Component

The Permission Checker component creates a PermissionChecker object that uses the password authentication protocols provided in Microsoft® Internet Information Server (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

Set oVar = Server.CreateObject("MSWC.PermissionChecker")

Parameters

oVar
Specifies the name of the PermissionChecker object created by the call to Server.CreateObject.

Registry Entries

None.

Methods

HasAccess Determines whether the user has permissions to access a specified file.

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.

<% Set pmck = Server.CreateObject("MSWC.PermissionChecker") %>

Physical Path Access = <%= pmck.HasAccess("c:\pages\abc\default.htm") %>
Virtual Path  Access = <%= pmck.HasAccess("/abc/default.htm") %>

Remarks

IIS supports the following three types of password authentication in any combination:

  • Anonymous
  • Basic
  • Windows NT® Challenge/Response (NTLM)

When anonymous password 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 NTLM or Basic. Then if you deny anonymous access to a specific page, the server will attempt to authenticate the user by using either NTLM 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.

    This is illustrated in the following example.

    <%
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.

Note This component is not installed with IIS. You can install it from the Microsoft Web site at: http://www.microsoft.com/iis/, or from the CD included with the IIS Resource Kit.


HasAccess

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 %>


Counters Component

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 counters.dll file.

File Names

counters.dll | The Counters component.
counters.txt | The file that stores all individual counters on a site. counters.txt is a UTF8-encoded file. You can have any Unicode characters in a counter name.

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>

Registry Entries

None.

Remarks

Only create one Counters object in your site. This single Counters object can create any number of individual counters.

Note For Personal Web Server on Windows® 95, 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

Get | Returns the value of the counter.
Increment | Increases the counter by 1.
Remove | Removes the counter from the counters.txt file.
Set | Sets the value of the counter to a specific integer.

Example

Create an instance of the Counters object in the global.asa file with the ID attribute set to Counter:

<OBJECT RUNAT=Server SCOPE=Application ID=Counter PROGID="MSWC.Counters"> </OBJECT>

You can then use that Counters object on one page to create all the counters you need:

There have been <%= Counter.Increment('defaultPageHits') %> to this site.

Then on another page you can increment the counter in the following manner:

You are visitor number<%= Counter.Increment('LinksPageHits') %> to this page.

Note You can obtain this component from the CD included with the IIS Resource Kit.


Get

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") %>

Applies To

Counters component

See Also

Increment, Remove, Set


Increment

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.

The following code implements a one-line page-hit counter.

<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.

Applies To

Counters component

See Also

Get, Remove, Set


Remove

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 counters.txt file.

<% Counters.Remove(hitscounter) %>

Applies To

Counters component

See Also

Get, Increment, Set


Set

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.

To retrieve the value of a counter, use Counters.Get. To increment a counter by 1, use Counters.Increment.

Syntax

Counters.Set(CounterName, int)

Parameters

CounterName
A string containing the name of the counter.
int
The new integer value for CounterName.

Example

The following code resets the hit counter pageHits to 0:

<% Counters.Set(pageHits, 0) %>

Applies To

Counter component

See Also

Get, Increment, Remove


MyInfo Component

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 an ASP script.

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 Server interface.

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 NT® and to the root directory on Windows® 95.

File Names

myinfo.dll | The MyInfo component.
myinfo.xml | The file that stores the values of the MyInfo properties.

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>

Registry Entries

None.

Remarks

Only create one MyInfo object in your site.

You can create a MyInfo object with Set MyInfoObject = Server.CreateObject('MSWC.MyInfo').

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

Properties Set by Personal Web Server

MyInfo.PageType | Returns a number corresponding to the value in the "This site is ..." pop-up menu in the Personal Web Server control panel. These are the pop-up menu options with their corresponding numerical values: 1 = About My Company 2 = About My Life 3 = About My School 4 = About My Organization 5 = About My Community
MyInfo.PersonalName | Returns the owner's name.
MyInfo.PersonalAddress | Returns the owner's address.
MyInfo.PersonalPhone | Returns the owner's phone number.
MyInfo.PersonalMail | Returns the owner's e-mail address.
MyInfo.PersonalWords | Returns additional text associated with the owner.
MyInfo.CompanyName | Returns the name of the owner's company.
MyInfo.CompanyAddress | Returns the address of the owner's company.
MyInfo.CompanyPhone | Returns the phone number of the owner's company.
MyInfo.CompanyDepartment | Returns the owner's department name.
MyInfo.CompanyWords | Returns additional text associated with the owner's company.
MyInfo.HomeOccupation | Returns the owner's occupation.
MyInfo.HomePeople | Returns text listing the people the owner lives with.
MyInfo.HomeWords | Returns additional text associated with the owner.
MyInfo.SchoolName | Returns the name of the owner's school.
MyInfo.SchoolAddress | Returns the address of the owner's school.
MyInfo.SchoolPhone | Returns the phone number of the owner's school.
MyInfo.SchoolDepartment | Returns the owner's department or class.
MyInfo.SchoolWords | Returns text associated with the owner's school.
MyInfo.OrganizationName | Returns the name of the organization featured on the site.
MyInfo.OrganizationAddress | Returns the address of the organization.
MyInfo.OrganizationPhone | Returns the phone number of the organization.
MyInfo.OrganizationWords | Returns text describing the organization.
MyInfo.CommunityName | Returns the name of the community featured on the site.
MyInfo.CommunityLocation | Returns the location of the community.
MyInfo.CommunityPopulation | Returns the population of the community.
MyInfo.CommunityWords | Returns text describing the community.
MyInfo.URL(n) | Returns the nth user-defined URL. Corresponds to the nth link description in MyInfo.URLWords.
MyInfo.URLWords(n) | Returns a string containing the nth user-defined description of a link. Corresponds to the nth URL in MyInfo.URL.
MyInfo.Style | Returns the relative URL (starting with '/') of a style sheet.
MyInfo.Background | Returns the background for the site.
MyInfo.Title | Returns the user-defined title for the home page.
MyInfo.Guestbook | Returns –1 if the guest book should be available on the site. Otherwise, returns 0. The default value is "".
MyInfo.Messages | Returns –1 if the private message form should be available on the site. Otherwise, returns 0. The default value is "".


Tools Component

The Tools component creates a Tools object that provides utilities that enable you to easily add sophisticated functionality to your Web pages.

File Names

tools.dll The Tools component.

Syntax

Set Tools = Server.CreateObject("MSWC.Tools")

Parameters

Tools
Specifies the name of the Tools object created by the call to Server.CreateObject.

Registry Entries

None.

Remarks

In Personal Web Server for Windows® 95, 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 | Checks for the existence of a file.
Owner | Checks if the current user is the site owner.
PluginExists | Checks the existence of a server plug-in (on Macintosh only).
ProcessForm | Processes an HTML form.
Random | Generates a random integer.

Note You can obtain this component from the CD included with the IIS Resource Kit.


FileExists

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 code is derived from the default.asp page used by Microsoft® Personal Web Server for Macintosh.

<%If Tools.FileExists("ie_animated.gif") then %>
    <p> <a href="http://www.microsoft.Com/ie/"><img src="ie_animated.gif"></a>
<% End If %>

Applies To

Tools Component

See Also

ProcessForm, Random


Owner

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 Server 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.

Applies To

Tools Component

See Also

FileExists, ProcessForm, Random


PluginExists

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, PluginExists always returns 0.

Applies To

Tools Component

See Also

FileExists, ProcessForm, Random


ProcessForm

The ProcessForm method processes the contents of a form that has been submitted by a visitor to the Web site.

Syntax

Tools.ProcessForm(OutputFileURL, TemplateURL, [InsertionPoint])

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.

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

The following code is derived from the messageresponse.asp page used by Microsoft® Personal Web Server.

<%
Tools.processform("/$Received Messages/default.asp","MessageInsert.process","<SPAN>*")
%>

Applies To

Tools Component

See Also

FileExists, Random


Random

The Random method returns an integer between –32768 to 32767.

Syntax

Tools.random

Remarks

This method is similar to the Rnd function but returns an integer.

To get a positive random integer, use the Abs function.

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, -13067.
<% = ( 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. For example, 63.

Applies To

Tools Component

See Also

FileExists, ProcessForm


Status Component

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

status.dll The Status component.

Syntax

Set Status = Server.CreateObject("MSWC.Status")

Parameters

Status
Specifies the name of the Status object created by the call to Server.CreateObject.

Registry Entries

None.

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

VisitorsSinceStart | The number of unique visitors (IP addresses or domain names) since the server started up.
RequestsSinceStart | The number of requests since the server started up.
ActiveHTTPSessions | The current number of http connections.
HighHTTPSessions | The highest number of concurrent http connections since the server started up.
ServerVersion | The Personal Web Server version string.
StartTime | The time the server started up.
StartDate | The date the server started up.
FreeMem | The amount of unused memory available to the server.
FreeLowMem | The lowest value for the amount of unused memory available to the server since it started up.
VisitorsToday | Number of unique visitors (IP addresses or domain names) since midnight.
RequestsToday | The number of requests since midnight.
BusyConnections | The total number of requests that were rejected because the server was already handling the maximum number of connections it can handle.
RefusedConnections | The total number of requests that were refused because the authentication was invalid.
TimedoutConnections | The total number of connections that were closed without a request having been received.
Ktransferred | The total number of kilobytes sent by the server since the server started up.
TotalRequests | The total number of requests received since the status counters were reset using the admin tool.
CurrentThreads | The sum of the number active http connections and the number of threads in the connection thread pool that are not currently handling connections.
AvailableThreads | The number of threads in the connection thread pool that are not currently handling connections.
RecentVisitors | An HTML table listing the 32 most recent unique visitors. This table includes each visitor's domain name (or IP address if the domain name is not available) and the number of requests generated by each visitor.
PopularPages | An HTML table listing the 32 most recently visited pages. This table includes each page's URL and the number of requests for each page.

Note You can obtain this component from the CD included with the IIS Resource Kit.


Collaboration Data Objects for NTS Component

The Microsoft® CDO for NTS Library (Collaboration Data Objects for Windows NT® Server) version 1.2 exposes messaging objects for use by Microsoft® Visual Basic®, C/C++, Microsoft® Visual C++®, and Visual Basic Scripting Edition (VBScript) applications. The library lets you quickly and easily add to your application the ability to send and receive messages. You can create programmable messaging objects, then use their properties and methods to meet the needs of your application.

The CDO for NTS Library is intended to run on a Microsoft® Windows NT® Server, for example from Active Server Pages (ASP) script on a Microsoft® Internet Information Server (IIS). It is not intended to run on a client process. No user dialog is invoked or supported by CDO for NTS.

The CDO for NTS objects are described in the remainder of this section. The following table lists these objects in alphabetic order and gives the purpose of each one.

Object | Purpose
AddressEntry | Specify addressing information for an individual messaging user.
Attachment | Associate an additional object with a message.
Attachments collection | Access all attachments on a message; create new attachments.
Folder | Open the default Inbox or Outbox folder in a message store.
Message | Compose, populate, send, and receive an e-mail document.
Messages collection | Access all messages in a folder; create new messages.
NewMail | Send a message without having to log on to a session.
Recipient | Specify information for a messaging user intended to receive a message.
Recipients collection | Access all recipients of a message; create new recipients.
Session | Establish a connection between an application and a messaging system.

All these objects can be declared using Object for their data type, but it is preferable to take advantage of early binding, to enforce type checking and generate more efficient code:

Dim objMsg As Message ' in preference to Dim As Object
  Dim colAtts As Attachments

You can also use an object's full type name in order to distinguish it from identically named objects available to a Visual Basic program through other object libraries such as the CDO Library:

Dim objSess As CDONTS.Session ' distinguished from MAPI.Session
  Dim colRecips As CDONTS.Recipients

The CDO for NTS Library interfaces with the SMTP server component of Microsoft® Internet Information Server (IIS) version 4.0 and later. The Session object uses the LogonSMTP method to differentiate the access from the Logon method of the the CDO Library, which interfaces with Microsoft® Exchange Server.

The SMTP server component of IIS has its own message store mechanism. The Inbox and Outbox are mapped to directories in the file system, and no other folders exist. Message transfer takes place in such a way that spooling appears instantaneous, so the Inbox has no incoming queue and the Outbox is always empty.

When CDO for NTS is running with IIS, the Inbox is a single common folder shared by all SMTP recipients and applications. It contains all messages received by IIS and destined for the local domains the SMTP server is configured for. However, the incoming messages are segregated by the CDO for NTS Library according to their recipients. An application can only access messages destined for the address it used when it logged on.

When CDO for NTS is running with the Microsoft Exchange Server, the Inbox is the regular Inbox of the messaging user's mailbox. When CDO for NTS is running with Microsoft Exchange Express, the Inbox is the messaging user's Post Office Protocol version 3 (POP3) server Inbox.

Applications developed to run with CDO for NTS can also run with CDO for Exchange provided they do not use the NewMail object. Also, the Session object's LogonSMTP method should be changed to the CDO for Exchange session's Logon method.


About Installation

To use the CDO for NTS Library, make sure it is referenced by the automation controller you are using. With Microsoft Visual Basic, for example, run the References command and select the check box for Microsoft CDO for NTS 1.2 Library.

To successfully run the CDONTS.DLL file, which holds both the in-process server and the type library, you must have installed Microsoft® Internet Explorer version 4.0 or later. A minimal installation is sufficient, and the Internet Explorer does not have to be actually running.

CDO for NTS is automatically installed during the typical installation of IIS 4.0. Microsoft Exchange does not have to be installed at the IIS computer on which CDO for NTS is being installed.

To run with Microsoft Exchange version 5.5, a minimal installation of Internet Explorer 4.0 is still required on the server. If the Microsoft Exchange Server is already installed, you can install Internet Explorer 4.0 on the server and then run the Internet Mail Service (IMS) Setup Wizard to enable CDO for NTS. This configures CDO for NTS to use the SMTP services that Exchange provides.

If you are installing the Microsoft Exchange Server on the same machine as IIS 4.0, Internet Explorer 4.0 should already be installed. You must also run the IMS Wizard in order to configure CDO for NTS correctly. If the IMS Wizard is not run, CDO for NTS continues to use the SMTP services provided by IIS 4.0.

For proper delivery of mail, you must have the SMTP server component of IIS configured to send mail to the addresses you specify. This is done through the Domain Name System (DNS). For more information, see Microsoft SMTP Service in the Microsoft Windows NT 4.0 Option Pack Documentation.


Objects, Properties, and Methods

This reference contains property and method information for the CDO for NTS Library objects.

The following table summarizes each object's properties and methods.

Object | Available since version | Properties | Methods
AddressEntry | 1.2 | Address, Application, Class, Name, Parent, Session, Type | (none)
Attachment | 1.2 | Application, Class, ContentBase, ContentID, ContentLocation, Name, Parent, Session, Source, Type | Delete, ReadFromFile, WriteToFile
Attachments collection | 1.2 | Application, Class, Count, Item, Parent, Session | Add, Delete
Folder | 1.2 | Application, Class, Messages, Name, Parent, Session | (none)
Message | 1.2 | Application, Attachments, Class, ContentBase, ContentID, ContentLocation, HTMLText, Importance, MessageFormat, Parent, Recipients, Sender, Session, Size, Subject, Text, TimeReceived, TimeSent | Delete, Send
Messages collection | 1.2 | Application, Class, Count, Item, Parent, Session | Add, Delete, GetFirst, GetLast, GetNext, GetPrevious
NewMail | 1.2 | Bcc, Body, BodyFormat, Cc, ContentBase, ContentLocation, From, Importance, MailFormat, Subject, To, Value, Version | AttachFile, AttachURL, Send, SetLocaleIDs
Recipient | 1.2 | Address, Application, Class, Name, Parent, Session, Type | Delete
Recipients collection | 1.2 | Application, Class, Count, Item, Parent, Session | Add, Delete
Session | 1.2 | Application, Class, Inbox, MessageFormat, Name, Outbox, Parent, Session, Version | GetDefaultFolder, Logoff, LogonSMTP, SetLocaleIDs

This reference is organized by object. For each object there is a summary topic, followed by reference documentation for each property or method that belongs to the object. The properties and methods are organized alphabetically.

Each property or method topic in the reference displays a Group button following the topic title. Clicking this button displays the summary topic for the object to which the property or method belongs. The summary topic includes tables of the object's properties and methods.


Object Model

The object model for the CDO for NTS Library is hierarchical. The following table shows the containment hierarchy. Each indented object is a child of the object under which it is indented. An object is the parent of every object at the next level of indentation under it. For example, an Attachments collection and a Recipients collection are both child objects of a Message object, and a Messages collection is a parent object of a Message object. However, a Messages collection is not a parent object of a Recipients collection.

Session
Folder (Inbox or Outbox)
Messages collection
Message
AddressEntry
Attachments collection
Attachment
Recipients collection
Recipient
NewMail

The AddressEntry object is not hierarchically contained by the Message object, but its only access is through the message's Sender property, so it returns the Message object in its Parent property. The NewMail object is independent of the rest of the hierarchy and and does not access any of the other objects.


Properties Common to All CDO for NTS Library Objects

All Microsoft® CDO for NTS Library objects except the NewMail object expose the properties Application, Class, Parent, and Session. The Application and Session properties have the same values for all objects within a given session. The Parent property indicates the immediate parent of the object, and the Class property is an integer value that identifies the CDO for NTS Library object.

The NewMail object is self-contained and does not expose any of these properties.

All four of these common properties have read-only access in all objects. Note that for the Session object, the Parent and Session properties are assigned the value Nothing. The Session object represents the highest level in the CDO for NTS Library object hierarchy and has no parent.

To reduce duplication, the detailed reference for these properties appears only once, in this section. The following table lists the properties that are common to all CDO for NTS Library objects and that have the same meaning for all objects.

Properties

Name | Type | Access
Application | String | Read-only
Class | Long | Read-only
Parent | Object | Read-only
Session | Session object | Read-only


Application Property (All CDONTS Library Objects)

The Application property returns the name of the active application, namely the Microsoft® CDO for NTS Library. Read-only.

Syntax

object.Application

Data Type

String

Remarks

The Application property always contains the string "Collaboration Data Objects for NTS version 1.2".

The version number of the CDO for NTS Library is available through the Session object's Version property.

Example

' Function: Session_Application
' Purpose: Display the Application property of the Session object
' See documentation topic: Application property
Function Session_Application()
Dim objSession As Object ' or Dim objSession As CDONTS.Session
' error handling ...
Set objSession = CreateObject("CDONTS.Session")
If Not objSession Is Nothing Then
   objSession.LogonSMTP("My Name", "myaddress@mycompany.com")
   MsgBox "Session's Application property = " & objSession.Application
End If
' error handling
End Function


Class Property (All CDONTS Library Objects)

The Class property returns the object class of the object. Read-only.

Syntax

object.Class

Data Type

Long

Remarks

The Class property contains a numeric constant that identifies the CDO for NTS Library object. The following values are defined:

CDO for NTS Library object | Class value | Type library constant
AddressEntry | 8 | CdoAddressEntry
Attachment | 5 | CdoAttachment
Attachments collection | 18 | CdoAttachments
Folder | 2 | CdoFolder
Message | 3 | CdoMsg
Messages collection | 16 | CdoMessages
Recipient | 4 | CdoRecipient
Recipients collection | 17 | CdoRecipients
Session | 0 | CdoSession

Example

' Function: Util_DecodeObjectClass
' Purpose: Decode the long integer class value,
'          show the related object name
' See documentation topic: Class property
Function Util_DecodeObjectClass(lClass As Long)
' error handling here ...
Select Case (lClass)
    Case CdoSession:
        MsgBox ("Session object; Class = " & lClass)
    Case CdoMsg:
        MsgBox ("Message object; Class = " & lClass)
End Select
' error handling ...
End Function

' Function: TestDrv_Util_DecodeObjectClass
' Purpose: Call the utility function DecodeObjectClass for Class values
' See documentation topic: Class property
Function TestDrv_Util_DecodeObjectClass()
' error handling here ...
If objSession Is Nothing Then
    MsgBox "Need to set the Session object: Session->LogonSMTP"
    Exit Function
End If
' expect type CdoSession = 0 for Session object
Util_DecodeObjectClass (objSession.Class)
Set objMessages = objSession.Inbox.Messages
Set objOneMsg = objMessages.GetFirst
If objOneMsg Is Nothing Then
    MsgBox "Inbox is empty"
    Exit Function
End If
' expect type CdoMessage = 3 for Message object
Util_DecodeObjectClass (objOneMsg.Class)
' error handling here ...
End Function


Parent Property (All CDONTS Library Objects)

The Parent property returns the parent of the object. Read-only.

Syntax

Set objParent = object.Parent

Data Type

Object

Remarks

The Parent property in the CDO for NTS Library returns the immediate parent of an object. The immediate parent for each object is shown in the following table.

CDO for NTS Library object | Immediate parent in object hierarchy
AddressEntry | Message
Attachment | Attachments collection
Attachments collection | Message
Folder | Session
Message | Messages collection
Messages collection | Folder, including Inbox or Outbox
Recipient | Recipients collection
Recipients collection | Message
Session | Set to Nothing

The Parent property represents the immediate parent of the object, rather than the logical parent. For example, a folder contains a Messages collection, which contains Message objects. The Parent property for a message is the immediate parent, the Messages collection, rather than the logical parent, the Folder object.

The Session object represents the highest level in the hierarchy of CDO for NTS Library objects and its Parent property is set to Nothing. The AddressEntry object does not have a true hierarchical parent but can only be obtained through the Sender property of a Message object. Its Parent property returns the Message object.

For more information on the CDO for NTS Library object hierarchy, see Object Model.

Example

This code fragment displays the Class of the parent Messages collection of a Message object:

' Function: Message_Parent
Function Message_Parent()
' error handling here ...
If objOneMsg Is Nothing Then
    MsgBox "Need to select a message; see Messages->Get*"
    Exit Function
End If
' Immediate parent of message is the Messages collection
MsgBox "Message immediate parent class = " & objOneMsg.Parent.Class
' error handling code ...
End Function

To get to the Folder object, you have to take the parent of the Messages collection:

' Function: Messages_Parent
' Purpose: Display the Messages collection Parent class value
' See documentation topic: Parent property
Function Messages_Parent()
Set objMessages = objOneMsg.Parent
' error handling here ...
If objMessages Is Nothing Then
    MsgBox "No Messages collection available"
    Exit Function
End If
MsgBox "Messages collection parent class = " & objMessages.Parent.Class
Exit Function
' error handling here ...
End Function


Session Property (All CDONTS Library Objects)

The Session property returns the top-level Session object associated with the specified CDO for NTS Library object. Read-only.

Syntax

Set objSession = object.Session

Data Type

Object (Session)

Remarks

The Session object represents the highest level in the CDO for NTS Library object hierarchy. If you invoke the Session property of a Session object, it returns the same Session object.

Example

' Function: Folder_Session
' Purpose: Access the Folder's Session property and display its name
' See documentation topic: Session property
Function Folder_Session()
Dim objSession2 As Session ' Session object to get the property
' error handling here ...
If objFolder Is Nothing Then
    MsgBox "No folder supplied; please select Session->Inbox"
    Exit Function
End If
Set objSession2 = objFolder.Session
If objSession2 Is Nothing Then
    MsgBox "Unable to access Session property"
    Exit Function
End If
MsgBox "Folder's Session property's Name = " & objSession2.Name
Set objSession2 = Nothing
' error handling here ...
End Function


AddressEntry Object (CDONTS Library)

The AddressEntry object defines addressing information valid for a given messaging system.

At a Glance

Specified in type library: | CDONTS.DLL
First available in: | CDO for NTS Library version 1.2
Parent objects: | Message (obtainable through Sender property of Message object)
Child objects: | (none)
Default property: | Name

Properties

Name | Available since version | Type | Access
Address | 1.2 | String | Read-only
Application | 1.2 | String | Read-only
Class | 1.2 | Long | Read-only
Name | 1.2 | String | Read-only
Parent | 1.2 | Message object | Read-only
Session | 1.2 | Session object | Read-only
Type | 1.2 | String | Read-only

Methods

(None.)

Remarks

An address usually represents a person or process to which the messaging system can deliver messages.

The AddressEntry object is only available through the Sender property of a Message object. It is used to obtain the sender's name, e-mail address, and address type for use in constructing a new Recipient object on an outbound message.


Address Property (CDONTS AddressEntry Object)

The Address property specifies the messaging address of an address entry. Read-only.

Syntax

objAddressEntry.Address

Data Type

String

Remarks

The AddressEntry object's Address property contains a unique string that identifies a messaging user and provides routing information for messaging systems. The format of the address string is specific to each messaging system.

Example

' Set up a series of object variables
' assume valid Session object
Set objInbox = objSession.GetDefaultFolder(CdoDefaultFolderInbox)
Set collInMessages = objInbox.Messages
Set objMessage = collInMessages.GetFirst
Set objAddrEntry = objMessage.Sender
strMsg = "Sender name " & objAddrEntry.Name
strMsg = strMsg & "; address type = " & objAddrEntry.Type
strMsg = strMsg & "; e-mail address = " & objAddrEntry.Address
MsgBox strMsg


Name Property (CDONTS AddressEntry Object)

The Name property returns the display name or alias of the AddressEntry object as a string. Read-only.

Syntax

objAddressEntry.Name

The Name property is the default property of an AddressEntry object, meaning that objAddressEntry is syntactically equivalent to objAddressEntry.Name in Microsoft® Visual Basic® code.

Data Type

String

Example

See the example for the AddressEntry object's Address property.


Type Property (CDONTS AddressEntry Object)

The Type property specifies the address type, such as SMTP. Read-only.

Syntax

objAddressEntry.Type

Data Type

String

Remarks

The address type is usually a tag referring to the messaging system that routes messages to this address, such as SMTP.

The Type property always returns SMTP in the current version of CDO for NTS.

Example

See the example for the AddressEntry object's Address property.


Attachment Object (CDONTS Library)

The Attachment object represents a file or message that is an attachment of a message.

At a Glance

Specified in type library: | CDONTS.DLL
First available in: | CDO for NTS Library version 1.2
Parent objects: | Attachments collection
Child objects: | (none)
Default property: | Name

No modifications are permitted to messages in the Inbox, except for message deletion. Therefore, all properties on an Attachment object are treated as read-only when the grandparent Message object is in the Inbox. When the access is described as read/write in the following table, that access applies only to attachments on messages in the Outbox.

Properties

Name | Available since version | Type | Access
Application | 1.2 | String | Read-only
Class | 1.2 | Long | Read-only
ContentBase | 1.2 | String | Read-only
ContentID | 1.2 | String | Read-only
ContentLocation | 1.2 | String | Read-only
Name | 1.2 | String | Read/write
Parent | 1.2 | Attachments collection object | Read-only
Session | 1.2 | Session object | Read-only
Source | 1.2 | String or Message object | Read/write
Type | 1.2 | Long | Read/write

Methods

Name | Available since version | Parameters
Delete | 1.2 | (none)
ReadFromFile | 1.2 | fileName as String
WriteToFile | 1.2 | fileName as String

Remarks

An attachment is an object, such as a file or another object, that is associated with and transmitted with a Message object. The Attachment object does not specify its location within the message. The client application makes all the display decisions for a message, including whether its attachments are to be displayed, and if so, when and where.

The CDO for NTS Library does not manage the actual display of the attachment. The properties of the Attachment object simply provide information that the displaying application can use to find and open the attachment, and to convert its contents into a display.


ContentBase Property (CDONTS Attachment Object)

The ContentBase property returns the Content-Base header of a MIME (Multipurpose Internet Mail Extensions) message attachment. Read-only.

Syntax

objAttach.ContentBase

Data Type

String

Remarks

The ContentBase property is used for MHTML (MIME HTML) support. It represents the Content-Base header for the appropriate MIME body part.

For more information on MHTML, see the RFC 2110 document.


ContentID Property (CDONTS Attachment Object)

The ContentID property returns the Content-ID header of a MIME (Multipurpose Internet Mail Extensions) message attachment. Read-only.

Syntax

objAttach.ContentID

Data Type

String

Remarks

The ContentID property is used for MHTML (MIME HTML) support. It represents the Content-ID header for the appropriate MIME body part.

The CDO for NTS Library does not generate Content-ID headers for outgoing messages or attachments. This property is provided to inspect an incoming message for Content-ID headers.

For more information on MHTML, see the RFC 2110 document.


ContentLocation Property (CDONTS Attachment Object)

The ContentLocation property returns the Content-Location header of a MIME (Multipurpose Internet Mail Extensions) message attachment. Read-only.

Syntax

objAttach.ContentLocation

Data Type

String

Remarks

The ContentLocation property is used for MHTML (MIME HTML) support. It represents the Content-Location header for the appropriate MIME body part.

For more information on MHTML, see the RFC 2110 document.


Delete Method (CDONTS Attachment Object)

The Delete method removes the Attachment object from the Attachments collection.

Syntax

objAttach.Delete( )

Remarks

The Delete method performs an irreversible operation on the collection. It calls Release on the collection's reference to the Attachment object. If you have another reference to the attachment, you can still access its properties and methods, but you can never again associate it with any collection because the Add method always creates a new object. You should Set your reference variable either to Nothing or to another attachment.

The final Release on the Attachment object takes place when you call Delete if you had no other reference, or when you assign your reference variable to Nothing. At this point the object is removed from memory. Attempted access to a released object results in an error return of CdoE_INVALID_OBJECT.

The effect of the Delete operation is not permanent until you use the Send or Delete method on the Message object to which this attachment belongs.

The immediate parent of this Attachment object is an Attachments collection, which is a child of the message. You can delete all the message's attachments by calling the collection's Delete method.

The CDO for NTS Library does not permit any modifications to messages in the Inbox, other than deleting the entire message. Prohibited modifications include adding, deleting, or modifying any attachment; adding, deleting, or modifying any recipient; and modifying any message property, even one with read/write access.

Example

This code fragment illustrates the two situations previously explained. The Set statement calls AddRef on the first Attachment object. That reference survives the call to Delete and has to be reassigned. The second Attachment object is deleted without creating another reference, and no other action is necessary.

' assume valid Message object
Set objAttach = objMessage.Attachments.Item(1)
objAttach.Delete ' still have a reference from Set statement
' ... other operations on objAttachment possible but pointless ...
Set objAttach = Nothing ' necessary to remove reference
' ...
objMessage.Attachments.Item(2).Delete ' no reference to remove


Name Property (CDONTS Attachment Object)

The Name property returns or sets the display name of the Attachment object as a string. Read/write (read-only for an attachment on a message in the Inbox).

Syntax

objAttach.Name

The Name property is the default property of an Attachment object, meaning that objAttach is syntactically equivalent to objAttach.Name in Microsoft® Visual Basic® code.

Data Type

String

Remarks

Before setting or changing the Name property, you should be sure that the Source property is already set. Setting Source after setting Name can result in an incorrect value for Name.

If the attachment's Type property is set to CdoEmbeddedMessage, any setting of the Name property is ignored in the current version of CDO for NTS. If the MessageFormat property of the grandparent Message object is set to CdoMime, the embedded message's Subject property is used for the attachment name. If the grandparent message's MessageFormat is CdoText, CDO for NTS randomly creates an attachment name in the format ATT00099.EML.

The Name property can also be set at the time of creation of the attachment by supplying the name parameter to the Add method of the Attachments collection.


ReadFromFile Method (CDONTS Attachment Object)

The ReadFromFile method loads the contents of an attachment from a file.

Syntax

objAttach.ReadFromFile(fileName)
objAttach
Required. The Attachment object.
fileName
Required. String. The full path and file name to read from, for example C:\DOCUMENT\BUDGET.XLS.

Remarks

The ReadFromFile method replaces the existing contents of the Attachment object, if any.

The ReadFromFile method operates differently, depending on the value of the Attachment object's Type property. The following table describes its operation:

Attachment Type property | ReadFromFile operation
CdoFileData | Copies the contents of the specified file to the attachment.
CdoEmbeddedMessage | (Not supported)

Note The current version of the CDO for NTS Library does not support ReadFromFile for CdoEmbeddedMessage attachments. These calls generate the run-time error CdoE_NO_SUPPORT.

You can load the contents of an attachment when you first create it by specifying the type and source parameters when you call the Add method of the Attachments collection.


Source Property (CDONTS Attachment Object)

The Source property returns or sets information specifying the location of the data for the attachment. Read/write (read-only for an attachment on a message in the Inbox).

Syntax

objAttach.Source

Data Type

String or Object (Message)

Remarks

The Source property is not used for CdoFileData attachments. For CdoEmbeddedMessage attachments, the Source property returns or sets the Message object to be embedded. An embedded message is copied into the attachment at creation time.

Note The Source property is a string except when it returns the source of a CdoEmbeddedMessage attachment.

The return value or setting of the Source property depends on the value of the Type property, as described in the following table:

Type property | Source property
CdoFileData | Not used; contains an empty string. The source for this type of attachment must be specified in the call to the Add method.
CdoEmbeddedMessage | Specifies the Message object to be embedded.

Note You must set Type before you set Source. Failure to do this can result in a return of CdoE_NOT_FOUND from the ReadFromFile or WriteToFile method.

The Source property can also be set at the time of creation of the attachment by supplying the source parameter to the Add method of the Attachments collection. For attachments of type CdoFileData, the Add method is the only place the source file can be specified. However, you can reset it later with the Attachment object's ReadFromFile method.


Type Property (CDONTS Attachment Object)

The Type property describes the attachment type. Read/write (read-only for an attachment on a message in the Inbox).

Syntax

objAttach.Type

Data Type

Long

Remarks

The following attachment types are supported:

Type property | Value | Description
CdoFileData | 1 | Attachment is the contents of a file. (Default value.)
CdoEmbeddedMessage | 4 | Attachment is an embedded message.

The value of the Type property determines the valid values for the Source property. Consequently, you must set Type before setting Source in order for the ReadFromFile and WriteToFile methods to work correctly.

The Type property can also be set at the time of creation of the attachment by supplying the type parameter to the Add method of the Attachments collection.

Example

See the example for the Attachment object's Source property.


WriteToFile Method (CDONTS Attachment Object)

The WriteToFile method saves the attachment to a file in the file system.

Syntax

objAttach.WriteToFile(fileName)
objAttach
Required. The Attachment object.
fileName
Required. String. The full path and file name for the saved attachment, for example C:\DOCUMENT\BUDGET.XLS.

Remarks

The WriteToFile method overwrites the file without warning if a file of that name already exists. Your application should check for the existence of the file before calling WriteToFile.

The WriteToFile method operates differently, depending on the value of the Attachment object's Type property. The following table describes its operation:

Attachment Type property | WriteToFile operation
CdoFileData | Copies the contents of the attachment to the specified file.
CdoEmbeddedMessage | (Not supported)

Note The current version of the CDO for NTS Library does not support WriteToFile for CdoEmbeddedMessage attachments. These calls generate the run-time error CdoE_NO_SUPPORT.


Attachments Collection Object (CDONTS Library)

The Attachments collection object contains zero or more Attachment objects.

At a Glance

Specified in type library: | CDONTS.DLL
First available in: | CDO for NTS Library version 1.2
Parent objects: | Message
Child objects: | Attachment
Default property: | Item

Properties

Name | Available since version | Type | Access
Application | 1.2 | String | Read-only
Class | 1.2 | Long | Read-only
Count | 1.2 | Long | Read-only
Item | 1.2 | Attachment object | Read-only
Parent | 1.2 | Message object | Read-only
Session | 1.2 | Session object | Read-only

Methods

Name | Available since version | Parameters
Add | 1.2 | (optional) name as String, (optional) type as Long, (optional) source as String or Object, (optional) ContentLocation as String, (optional) ContentBase as String
Delete | 1.2 | (none)


Add Method (CDONTS Attachments Collection)

The Add method creates and returns a new Attachment object in the Attachments collection.

Syntax

Set objAttach = collAttachments.Add( [name] [, type] [, source] [, ContentLocation] [, ContentBase] )
objAttach
On successful return, contains the new Attachment object.
collAttachments
Required. The Attachments collection object.
name
Optional. String. The display name of the attachment. The default value is an empty string. To allow a user to click on the attachment that appears in the message and activate an associated application, supply the full file name, including the file extension.
type
Optional. Long. The type of attachment; either CdoFileData or CdoEmbeddedMessage. The default value is CdoFileData.
source
Optional. String or Object. The path and file name of the file containing the data for the attachment, or the Message object to be embedded. The path and file name must be in the appropriate format for the attachment type, specified by the type parameter. The default value is an empty string.
ContentLocation
Optional. String. The content location header for the appropriate body part of a MIME message attachment.
ContentBase
Optional. String. The content base header for the appropriate body part of a MIME message attachment.

Remarks

The name, type, source, ContentLocation, and ContentBase parameters correspond to the Name, Type, Source, ContentLocation, and ContentBase properties of the Attachment object. The source parameter is also closely related to the ReadFromFile method's fileName parameter.

You can supply the data for the attachment at the same time that you add it to the collection. The Add method operates differently depending on the value of the type parameter. The following table describes its operation.

Value of type parameter | Value of source parameter
CdoFileData | Specifies a full path and file name that contains the data for the attachment, for example C:\DOCUMENT\BUDGET.XLS. Must be supplied with the Add method. The data is read into the attachment.
CdoEmbeddedMessage | Specifies the Message object to be embedded. The message is copied into the attachment.

If the type parameter is set to CdoEmbeddedMessage, any setting of the name parameter is ignored in the current version of CDO for NTS. If the MessageFormat property of the parent Message object is set to CdoMime, the embedded message's Subject property is used for the attachment name. If the parent message's MessageFormat is CdoText, CDO for NTS randomly creates an attachment name in the format ATT00099.EML.

You should set the message's MessageFormat to CdoMime if you are running with the Microsoft® Exchange Server and plan to add attachments of type CdoEmbeddedMessage. This allows the greatest flexibility in opening and reading such an attachment.

The attachment is saved in persistent storage when you call the Send method on the Message object containing the Attachments collection.

The Add method returns CdoE_NO_ACCESS when called on a message in the Inbox.

The CDO for NTS Library does not permit any modifications to messages in the Inbox, other than deleting the entire message. Prohibited modifications include adding, deleting, or modifying any attachment; adding, deleting, or modifying any recipient; and modifying any message property, even one with read/write access.


Count Property (CDONTS Attachments Collection)

The Count property returns the number of Attachment objects in the collection. Read-only.

Syntax

collAttachments.Count

Data Type

Long

Example

This code fragment stores in an array the names of all Attachment objects in the collection. It shows the Count and Item properties working together.

' from the sample function, TstDrv_Util_SmallCollectionCount
' collAttachments is an Attachments collection
x = Util_SmallCollectionCount(collAttachments)

Function Util_SmallCollectionCount(objColl As Object)
Dim strItemName(100) As String ' Names of objects in collection
Dim i As Integer               ' loop counter
    On Error GoTo error_amsmtp
    If objColl Is Nothing Then
        MsgBox "Must supply a valid collection object as a parameter"
        Exit Function
    End If
    If 0 = objColl.Count Then
        MsgBox "No messages in the collection"
        Exit Function
    End If
    For i = 1 To objColl.Count Step 1
        strItemName(i) = objColl.Item(i).Name
        If 100 = i Then ' max size of string array
            Exit Function
        End If
    Next i
    ' error handling here...
End Function


Delete Method (CDONTS Attachments Collection)

The Delete method removes all the Attachment objects from the Attachments collection.

Syntax

collAttachments.Delete( )

Remarks

The Delete method performs an irreversible operation on the collection. It calls Release on the collection's reference to every Attachment object. If you have another reference to an attachment, you can still access its properties and methods, but you can never again associate it with any collection because the Add method always creates a new object. You should Set your reference variable either to Nothing or to another attachment.

The final Release on each Attachment object takes place when you call Delete if you had no other reference, or when you assign your reference variable to Nothing. At this point the object is removed from memory. Attempted access to a released object results in an error return of CdoE_INVALID_OBJECT.

Be cautious using the Delete method with a collection, because it deletes all the collection's member objects. To delete only one Attachment object, use the Delete method specific to that object.

The effect of the Delete method is not permanent until you use the Send or Delete method on the Message object containing the Attachments collection. A permanently deleted member cannot be recovered. However, the collection itself is still valid, and you can Add new members to it.

The CDO for NTS Library does not permit any modifications to messages in the Inbox, other than deleting the entire message. Prohibited modifications include adding, deleting, or modifying any attachment; adding, deleting, or modifying any recipient; and modifying any message property, even one with read/write access.


Item Property (CDONTS Attachments Collection)

The Item property returns a single Attachment object from the Attachments collection. Read-only.

Syntax

collAttachments.Item(index)
index
Long. An integer ranging from 1 to collAttachments.Count.

The Item property is the default property of an Attachments collection, meaning that collAttachments(index) is syntactically equivalent to collAttachments.Item(index) in Microsoft® Visual Basic® code.

Data Type

Object (Attachment)

Remarks

The Item property works like an accessor property for small collections.

The Item(index) syntax selects an arbitrary Attachment object within the Attachments collection.

Although the Item property itself is read-only, the Attachment object it returns can be accessed in the normal manner, and its properties retain their respective read/write or read-only accessibility.

Example

This code fragment shows the Count and Item properties working together to traverse the collection:

' from Util_SmallCollectionCount(collAttachments As Object)
Dim strItemName(100) as String
Dim i As Integer ' loop counter
' error handling omitted from this fragment ...
For i = 1 To collAttachments.Count Step 1
    strItemName(i) = collAttachments.Item(i).Name
    ' or = collAttachments(i) since Item and Name are default properties
    If 100 = i Then ' max size of string array
        Exit Function
    End If
Next i


Folder Object (CDONTS Library)

The Folder object represents a folder or container in a message store.

At a Glance

Specified in type library: | CDONTS.DLL
First available in: | CDO for NTS Library version 1.2
Parent objects: | Session
Child objects: | Messages collection
Default property: | Messages

Properties

Name | Available since version | Type | Access
Application | 1.2 | String | Read-only
Class | 1.2 | Long | Read-only
Messages | 1.2 | Messages collection object | Read-only
Name | 1.2 | String | Read-only
Parent | 1.2 | Session object | Read-only
Session | 1.2 | Session object | Read-only

Methods

(None.)

Remarks

The CDO for NTS Library does not permit any modifications to messages in the Inbox, other than deleting the entire message. Prohibited modifications include adding, deleting, or modifying any attachment; adding, deleting, or modifying any recipient; and modifying any message property, even one with read/write access.


Messages Property (CDONTS Folder Object)

The Messages property returns a Messages collection object within the folder. Read-only.

Syntax

objFolder.Messages

The Messages property is the default property of a Folder object, meaning that objFolder is syntactically equivalent to objFolder.Messages in Microsoft® Visual Basic® code.

Data Type

Object (Messages collection)

Remarks

Although the Messages property itself is read-only, the collection it returns can be accessed in the normal manner through its Add and Delete methods, and the properties on its member Message objects retain their respective read/write or read-only accessibility.

The CDO for NTS Library does not permit any modifications to messages in the Inbox, other than deleting the entire message. Prohibited modifications include adding, deleting, or modifying any attachment; adding, deleting, or modifying any recipient; and modifying any message property, even one with read/write access.

Example

This code fragment shows how a Messages collection of Message objects is obtained from a folder which is in turn obtained from a Session object:

Dim objInbox as Folder
Dim collInMessages as Messages
' assume valid Session object
Set objInbox = objSession.GetDefaultFolder(CdoDefaultFolderInbox)
Set collInMessages = objInbox.Messages


Name Property (CDONTS Folder Object)

The Name property returns the name of the Folder object as a string. Read-only.

Syntax

objFolder.Name

Data Type

String

Example

Dim objInbox As Folder ' assume valid
Dim objOutbox As Folder ' assume valid
' assume valid Session object
Set objInbox = objSession.GetDefaultFolder(CdoDefaultFolderInbox)
Set objOutbox = objSession.GetDefaultFolder(CdoDefaultFolderOutbox)
MsgBox "Inbox name = " & objInbox.Name
MsgBox "Outbox name = " & objOutbox.Name


Message Object (CDONTS Library)

The Message object represents a single message, item, document, or form in a folder.

At a Glance

Specified in type library: | CDONTS.DLL
First available in: | CDO for NTS Library version 1.2
Parent objects: | Messages collection
Child objects: | Attachments collection Recipients collection
Default property: | Subject

No modifications are permitted to messages in the Inbox, except for message deletion. Therefore, all properties on a Message object are treated as read-only when the message is in the Inbox. When the access is described as read/write in the following table, that access applies only to messages in the Outbox.

Properties

Name | Available since version | Type | Access
Application | 1.2 | String | Read-only
Attachments | 1.2 | Attachment object or Attachments collection object | Read-only
Class | 1.2 | Long | Read-only
ContentBase | 1.2 | String | Read/write
ContentID | 1.2 | String | Read-only
ContentLocation | 1.2 | String | Read/write
HTMLText | 1.2 | IStream object or String | Read/write
Importance | 1.2 | Long | Read/write
MessageFormat | 1.2 | Long | Write-only
Parent | 1.2 | Messages collection object | Read-only
Recipients | 1.2 | Recipient object or Recipients collection object | Read-only
Sender | 1.2 | AddressEntry object | Read-only
Session | 1.2 | Session object | Read-only
Size | 1.2 | Long | Read-only
Subject | 1.2 | String | Read/write
Text | 1.2 | IStream object or String | Read/write
TimeReceived | 1.2 | Variant (vbDate format) | Read-only
TimeSent | 1.2 | Variant (vbDate format) | Read-only

Methods

Name | Available since version | Parameters
Delete | 1.2 | (none)
Send | 1.2 | (none)

Remarks

Microsoft® Visual Basic® programmers can create new Message objects using the Messages collection's Add method.

A message can be obtained from its parent Messages collection using the collection's Item property. To get to the Messages collection in a folder, use the Folder object's Messages property.

The CDO for NTS Library does not permit any modifications to messages in the Inbox, other than deleting the entire message. Prohibited modifications include adding, deleting, or changing any attachment; adding, deleting, or changing any recipient; and writing to any message property, even one with read/write access.


Attachments Property (CDONTS Message Object)

The Attachments property returns a single Attachment object or an Attachments collection object. Read-only.

Syntax

Set collAttachments = objMessage.Attachments
Set objAttach = objMessage.Attachments(index)
collAttachments
Object. An Attachments collection object.
objMessage
Object. The Message object.
objAttach
Object. A single Attachment object.
index
Long. Specifies the number of the attachment within the Attachments collection. Ranges from 1 to the value specified by the Attachments collection's Count property.

Data Type

Object (Attachment or Attachments collection)

Remarks

You can change individual Attachment objects within the Attachments collection, Add them to the collection, and Delete them from the collection.

Although the Attachments property itself is read-only, the collection it returns can be accessed in the normal manner through its Add and Delete methods, and the properties on its member Attachment objects retain their respective read/write or read-only accessibility.

The CDO for NTS Library does not permit any modifications to messages in the Inbox, other than deleting the entire message. Prohibited modifications include adding, deleting, or modifying any attachment; adding, deleting, or modifying any recipient; and modifying any message property, even one with read/write access.

Example

This code fragment uses the Attachments property to retrieve an attachment of the message:

Set collAttachments = objMessage.Attachments
If collAttachments Is Nothing Then
   MsgBox "Unable to set Attachments collection"
   Exit Function
Else
   MsgBox "Attachments count for this message: " & collAttachments.Count
   iAttachCollIndex = 0 ' reset global index variable
End If
' from the sample function Attachments_FirstItem
iAttachCollIndex = 1
Set objAttach = collAttachments.Item(iAttachCollIndex)


ContentBase Property (CDONTS Message Object)

The ContentBase property returns or sets the Content-Base header of a MIME (Multipurpose Internet Mail Extensions) message body. Read/write (read-only for a message in the Inbox).

Syntax

objMessage.ContentBase

Data Type

String

Remarks

The ContentBase property is used for MHTML (MIME HTML) support. It represents the Content-Base header for the appropriate MIME body part.

For more information on MHTML, see the RFC 2110 document.


ContentID Property (CDONTS Message Object)

The ContentID property returns or sets the Content-ID header of a MIME (Multipurpose Internet Mail Extensions) message body. Read-only.

Syntax

objAttach.ContentID

Data Type

String

Remarks

The ContentID property is used for MHTML (MIME HTML) support. It represents the Content-ID header for the appropriate MIME body part.

The CDO for NTS Library does not generate Content-ID headers for outgoing messages or attachments. This property is provided to inspect an incoming message for Content-ID headers.

For more information on MHTML, see the RFC 2110 document.


ContentLocation Property (CDONTS Message Object)

The ContentLocation property returns or sets the Content-Location header of a MIME (Multipurpose Internet Mail Extensions) message body. Read/write (read-only for a message in the Inbox).

Syntax

objMessage.ContentLocation

Data Type

String

Remarks

The ContentLocation property is used for MHTML (MIME HTML) support. It represents the Content-Location header for the appropriate MIME body part.

For more information on MHTML, see the RFC 2110 document.


Delete Method (CDONTS Message Object)

The Delete method removes the Message object from the Messages collection.

Syntax

objMessage.Delete( )

Remarks

The Delete method performs an irreversible operation on the collection. It calls Release on the collection's reference to the Message object. If you have another reference to the message, you can still access its properties and methods, but you can never again associate it with any collection because the Add method always creates a new object. You should Set your reference variable either to Nothing or to another message.

The final Release on the Message object takes place when you call Delete if you had no other reference, or when you assign your reference variable to Nothing. At this point the object is removed from memory. Attempted access to a released object results in an error return of CdoE_INVALID_OBJECT.

The action of the Delete method is permanent, and the Message object cannot be restored to the collection. Before calling Delete, your application can prompt the user to verify whether the message should be permanently deleted.

You can delete all the messages in the Messages collection by calling the collection's Delete method. The ability to delete any message depends on the permissions granted to the user. The Delete method returns an error code if called with insufficient permissions.

The CDO for NTS Library does not permit any modifications to messages in the Inbox, other than deleting the entire message. Prohibited modifications include adding, deleting, or modifying any attachment; adding, deleting, or modifying any recipient; and modifying any message property, even one with read/write access.

Example

This code fragment illustrates the two situations previously explained. The Set statement calls AddRef on the first Message object. That reference survives the call to Delete and has to be reassigned. The second Message object is deleted without creating another reference, and no other action is necessary.

' assume valid Folder object (only Inbox meaningful in this context)
Set objMessage = objFolder.Messages.Item(1)
objMessage.Delete ' still have a reference from Set statement
' ... other operations on objMessage possible but pointless ...
Set objMessage = Nothing ' necessary to remove reference
' ...
objFolder.Messages.Item(2).Delete ' no reference to remove


HTMLText Property (CDONTS Message Object)

The HTMLText property returns or sets the Hypertext Markup Language (HTML) representation of the message's text. Read/write (read-only for a message in the Inbox).

Syntax

objMessage.HTMLText

Data Type

Object (IStream) or String

Remarks

The text is the principal content of an interpersonal message, typically displayed to each recipient as an immediate result of opening the message. It specifically excludes various other message properties such as Subject, Attachments, and Recipients.

The text of a message is represented by its HTMLText and Text properties. The CDO for NTS Library always keeps these two properties in synchronization with each other. A sending client can set either property and the other is automatically computed. A receiving client can read either property depending on its content type preference.

Only C/C++ and Java programs can use an IStream object for this property. They should pass an IUnknown object that returns an IStream interface in response to QueryInterface. Microsoft® Visual Basic® supports the IDispatch interface and not IUnknown, so it cannot use an IStream object.

The maximum size of the text can be limited by the tool that you use to manipulate string variables (for example, Visual Basic).


Importance Property (CDONTS Message Object)

The Importance property returns or sets the importance of the message. Read/write (read-only for a message in the Inbox).

Syntax

objMessage.Importance

Data Type

Long

Remarks

The following values are defined:

Constant | Value | Description
CdoLow | 0 | Low importance
CdoNormal | 1 | Normal importance (default)
CdoHigh | 2 | High importance

Example

This code fragment sets the importance of a message as high:

' assume valid Outbox folder object from GetDefaultFolder method
Set objMessage = objOutbox.Messages.Add
' ... check here to verify the message was created ...
objMessage.Subject = "I'm locked in my office"
objMessage.Text = "Somebody please get the key and let me out."
objMessage.Importance = CdoHigh
objMessage.Send

See Also

Send Method (Message Object)


MessageFormat Property (CDONTS Message Object)

The MessageFormat property sets the encoding format of the message. Write-only.

Syntax

objMessage.MessageFormat

Data Type

Long

Remarks

The MessageFormat property determines how a message is encoded. The following values are defined:

MessageFormat setting | Value | Description
CdoMime | 0 | The message is in MIME format.
CdoText | 1 | The message is in uninterrupted plain text.

The MessageFormat property is not used on incoming messages in the Inbox.

You should set MessageFormat to CdoMime if you are running with the Microsoft® Exchange Server and plan to attach embedded messages to this message. This allows the greatest flexibility in opening and reading such an attachment.

The MessageFormat property defaults to the current setting of the MessageFormat property of the Session object.


Recipients Property (CDONTS Message Object)

The Recipients property returns a single Recipient object or a Recipients collection object. Read-only.

Syntax

Set collRecips = objMessage.Recipients
Set objRecip = objMessage.Recipients(index)
collRecips
Object. A Recipients collection object.
objMessage
Object. The Message object.
objRecip
Object. A single Recipient object.
index
Long. Specifies the number of the recipient within the Recipients collection. Ranges from 1 to the value specified by the Recipients collection's Count property.

Data Type

Object (Recipient or Recipients collection)

Remarks

You can change individual Recipient objects within the Recipients collection, Add them to the collection, and Delete them from the collection.

The CDO for NTS Library does not permit any modifications to messages in the Inbox, other than deleting the entire message. Prohibited modifications include adding, deleting, or modifying any attachment; adding, deleting, or modifying any recipient; and modifying any message property, even one with read/write access.

Example

This code fragment uses a loop to create a copy of every valid recipient of the original message objMessage in the copy message objCopyItem. For each copied recipient, it also copies important properties from the original.

For i = 1 To objMessage.Recipients.Count Step 1
   Set objRecip = objMessage.Recipients.Item(i)
   If Not objRecip Is Nothing Then
      Set objCopyRecip = objCopyItem.Recipients.Add
      If objCopyRecip Is Nothing Then
         MsgBox "Unable to create recipient in message copy"
         Exit Function
      End If
      ' Now copy the most important properties
      objCopyRecip.Address = objRecip.Address
      objCopyRecip.Name = objRecip.Name
      objCopyRecip.Type = objRecip.Type
   End If
Next i


Send Method (CDONTS Message Object)

The Send method sends the message to the recipients through the messaging system.

Syntax

objMessage.Send( )
objMessage
Required. The Message object.

Remarks

The Send method saves all changes to the message in the messaging system and moves the message to the current user's Outbox folder. Messaging systems retrieve messages from the Outbox and transport them to the recipients. After it is transported, a message is removed from the Outbox and deleted.

You must compose your new messages in your Outbox. The Send method only deals with messages located in the Outbox and returns CdoE_NO_ACCESS for any attempt to create a message in the Inbox.

The Send method invalidates the composed Message object but does not remove it from memory. The programmer should Set the invalidated object to Nothing to remove it from memory, or reassign it to another message. Attempted access to a sent message results in a return of CdoE_INVALID_OBJECT.


Sender Property (CDONTS Message Object)

The Sender property returns the sender of a message as an AddressEntry object. Read-only.

Syntax

Set objAddrEntry = objMessage.Sender
objAddrEntry
Object. The returned AddressEntry object that represents the messaging user that sent the message.
objMessage
Object. The Message object.

Data Type

Object (AddressEntry)

Example

This code fragment displays the name of the sender of a message:

' from the sample function Message_Sender
Set objAddrEntry = objMessage.Sender
If objAddrEntry Is Nothing Then
   MsgBox "Could not set the AddressEntry object from the Sender"
   Exit Function
End If
MsgBox "Message was sent by " & objAddrEntry.Name


Size Property (CDONTS Message Object)

The Size property returns the approximate size in bytes of the message. Read-only.

Syntax

objMessage.Size

Data Type

Long

Remarks

The Size property contains the sum, in bytes, of the sizes of all properties on this Message object, including in particular the Attachments property. It can be considerably greater than the size of the Text property alone.

The Size property is computed by the message store and is not valid until after the Send operation. Note that not all message stores support this property.


Subject Property (CDONTS Message Object)

The Subject property returns or sets the subject of the message as a string. Read/write (read-only for a message in the Inbox).

Syntax

objMessage.Subject

The Subject property is the default property of a Message object, meaning that objMessage is syntactically equivalent to objMessage.Subject in Microsoft® Visual Basic® code.

Data Type

String

Remarks

You can set the Subject property to an empty string, although that limits the ability of the recipients to sort and filter received messages.

Example

This code fragment sets the subject of a message:

Dim objMessage As Message ' assume valid message
objMessage.Subject = "Test message"

See Also

Text Property (Message Object)


Text Property (CDONTS Message Object)

The Text property returns or sets the plain text representation of the message's text. Read/write (read-only for a message in the Inbox).

Syntax

objMessage.Text

Data Type

Object (IStream) or String

Remarks

The text is the principal content of an interpersonal message, typically displayed to each recipient as an immediate result of opening the message. It specifically excludes various other message properties such as Subject, Attachments, and Recipients.

The text of a message is represented by its HTMLText and Text properties. The CDO for NTS Library always keeps these two properties in synchronization with each other. A sending client can set either property and the other is automatically computed. A receiving client can read either property depending on its content type preference.

Only C/C++ and Java programs can use an IStream object for this property. They should pass an IUnknown object that returns an IStream interface in response to QueryInterface. Microsoft® Visual Basic® supports the IDispatch interface and not IUnknown, so it cannot use an IStream object.

The maximum size of the text can be limited by the tool that you use to manipulate string variables (for example, Visual Basic).

Example

This code fragment sets the text of a message:

Dim objMessage As Message ' assume valid message
objMessage.Text = "Text of test message."


TimeReceived Property (CDONTS Message Object)

The TimeReceived property sets or returns the date and time the message was received as a vbDate variant data type. Read-only.

Syntax

objMessage.TimeReceived

Data Type

Variant (vbDate format)

Remarks

If the time of reception is not available, the TimeReceived property returns the date and time the message was sent.

The TimeReceived and TimeSent properties set and return dates and times as the local time for the user's system.

Example

This code fragment displays the date and time a message was sent and received:

' from the sample function Message_TimeSentAndReceived
' verify that objMessage is valid, then ...
With objMessage
   strMsg = "Message sent " & Format(.TimeSent, "Short Date")
   strMsg = strMsg & ", " & Format(.TimeSent, "Long Time")
   strMsg = strMsg & "; received "
   strMsg = strMsg & Format(.TimeReceived, "Short Date") & ", "
   strMsg = strMsg & Format(.TimeReceived, "Long Time")
   MsgBox strMsg
End With


TimeSent Property (CDONTS Message Object)

The TimeSent property sets or returns the date and time the message was sent as a vbDate variant data type. Read-only.

Syntax

objMessage.TimeSent

Data Type

Variant (vbDate format)

Remarks

The TimeReceived and TimeSent properties set and return dates and times as the local time for the user's system.

Example

See the example for the Message object's TimeReceived property.


Messages Collection Object (CDONTS Library)

The Messages collection object contains zero or more Message objects.

At a Glance

Specified in type library: | CDONTS.DLL
First available in: | CDO for NTS Library version 1.2
Parent objects: | Folder
Child objects: | Message
Default property: | Item

Properties

Name | Available since version | Type | Access
Application | 1.2 | String | Read-only
Class | 1.2 | Long | Read-only
Count | 1.2 | Long | Read-only
Item | 1.2 | Message object | Read-only
Parent | 1.2 | Folder object | Read-only
Session | 1.2 | Session object | Read-only

Methods

Name | Available since version | Parameters
Add | 1.2 | (optional) subject as String, (optional) text as Object or String, (optional) importance as Long
Delete | 1.2 | (none)
GetFirst | 1.2 | (none)
GetLast | 1.2 | (none)
GetNext | 1.2 | (none)
GetPrevious | 1.2 | (none)

Remarks

The order that messages are returned by GetFirst, GetLast, GetNext, and GetPrevious is not predictable. The best programming approach to use with unsorted collections is to assume that the access functions are able to access all messages within the collection, but that the order of the objects is not defined.

The CDO for NTS Library does not permit any modifications to messages in the Inbox, other than deleting the entire message. Prohibited modifications include adding, deleting, or modifying any attachment; adding, deleting, or modifying any recipient; and modifying any message property, even one with read/write access.


Add Method (CDONTS Messages Collection)

The Add method creates and returns a new Message object in the Messages collection.

Syntax

Set objMessage = collMessages.Add( [subject] [, text] [, importance] )
objMessage
On successful return, represents the new Message object added to the collection.
collMessages
Required. The Messages collection object.
subject
Optional. String. The subject line for the message.
text
Optional. IStream object or String. The text of the message.
importance
Optional. Long. The importance associated with the message.

Remarks

The subject, text, and importance parameters correspond to the Subject, Text, and Importance properties on the Message object.

You must create all new messages in the Outbox folder.

Only C/C++ and Java programs can use an IStream object for the text parameter. They should pass an IUnknown object that returns an IStream interface in response to QueryInterface. Microsoft® Visual Basic® supports the IDispatch interface and not IUnknown, so it cannot use an IStream object.

Example

This code fragment replies to an original message:

' from the sample function Util_ReplyToConversation
Set objOutbox = objSession.GetDefaultFolder(CdoDefaultFolderOutbox)
Set objNewMsg = objOutbox.Messages.Add
' verify objNewMsg created successfully ... then supply properties
Set objSenderAE = objOriginalMsg.Sender ' sender as AddressEntry
With objNewMsg
   .Text = "Here is a reply to your message." ' new text
   .Subject = objOriginalMsg.Subject ' copy original properties
   Set objRecip = .Recipients.Add(name:=objsenderAE.Name, _
                type:=CdoTo, _
                address:=objSenderAE.Type & ":" & objSenderAE.Address)
   ' ** the preceding line is not strictly necessary with CDO for NTS,
   ' ** but it allows this code to run with CDO for Exchange, where
   ' ** Recipient.Address requires a FULL address concatenated from
   ' ** AddressEntry.Type, ":", and AddressEntry.Address
   .Send
End With


Count Property (CDONTS Messages Collection)

The Count property returns the number of Message objects in the collection, or a very large number if the exact count is not available. Read-only.

Syntax

collMessages.Count

Data Type

Long

Remarks

The use of the Item property in conjunction with the Count property in a large collection can be seen in the following example.

Example

This code fragment searches for a Message object with subject "Bonus":

Dim i As Integer ' loop index / object counter
Dim collMessages As Messages ' assume collection already provided
Dim objMessage As Message
If collMessages Is Nothing Then
    MsgBox "Messages collection object is invalid"
    ' Exit
ElseIf 0 = collMessages.Count Then ' collection is empty
    MsgBox "No messages in collection"
    ' Exit
End If
' look for message about "Bonus" in collection
For i = 1 To collMessages.Count Step 1
    Set objMessage = collMessages.Item(i)
    ' or collMessages(i) since Item is default property
    If objMessage Is Nothing Then ' end of collection
        MsgBox "No such message found in collection"
        Exit For
    ElseIf 0 = StrComp(objMsg.Subject, "Bonus") Then
    ' or objMessage since Subject is default property
        MsgBox "Desired message is at index " & i
        Exit For
    End If
Next i


Delete Method (CDONTS Messages Collection)

The Delete method removes all the Message objects from the Messages collection.

Syntax

collMessages.Delete( )

Remarks

The Delete method performs an irreversible operation on the collection. It calls Release on the collection's reference to every Message object. If you have another reference to a message, you can still access its properties and methods, but you can never again associate it with any collection because the Add method always creates a new object. You should Set your reference variable either to Nothing or to another item.

The final Release on each Message object takes place when you call Delete if you had no other reference, or when you assign your reference variable to Nothing. At this point the object is removed from memory. Attempted access to a released object results in an error return of CdoE_INVALID_OBJECT.

Be cautious using the Delete method with a collection, because it deletes all the collection's member objects. To delete only one Message object, use the Delete method specific to that object.

The Delete method on a large collection takes effect immediately and is permanent. A deleted member cannot be recovered. However, the collection itself is still valid, and you can Add new members to it.


GetFirst Method (CDONTS Messages Collection)

The GetFirst method returns the first Message object in the Messages collection. It returns Nothing if no first object exists.

Syntax

Set objMessage = collMessages.GetFirst( )
objMessage
On successful return, represents the first Message object in the collection.
collMessages
Required. The Messages collection object.


GetLast Method (CDONTS Messages Collection)

The GetLast method returns the last Message object in the Messages collection. It returns Nothing if no last object exists.

Syntax

Set objMessage = collMessages.GetLast( )
objMessage
On successful return, represents the last Message object in the collection.
collMessages
Required. The Messages collection object.


GetNext Method (CDONTS Messages Collection)

The GetNext method returns the next Message object in the Messages collection. It returns Nothing if no next object exists, for example if already positioned at the end of the collection.

Syntax

Set objMessage = collMessages.GetNext( )
objMessage
On successful return, represents the next Message object in the collection.
collMessages
Required. The Messages collection object.

Remarks

If the GetFirst method has not been called since the Messages collection was initialized, the behavior of the GetNext method is not defined. This can produce unexpected results if the collection is reinitialized with a Set statement in every iteration of a loop. The recommended procedure is to Set an explicit variable for the collection before entering the loop.

If the collection is empty, calling GetNext can produce unexpected results even if GetFirst has been called.


GetPrevious Method (CDONTS Messages Collection)

The GetPrevious method returns the previous Message object in the Messages collection. It returns Nothing if no previous object exists, for example if already positioned at the beginning of the collection.

Syntax

Set objMessage = collMessages.GetPrevious( )
objMessage
On successful return, represents the previous Message object in the collection.
collMessages
Required. The Messages collection object.

Remarks

If the GetLast method has not been called since the Messages collection was initialized, the behavior of the GetPrevious method is not defined. This can produce unexpected results if the collection is reinitialized with a Set statement in every iteration of a loop. The recommended procedure is to Set an explicit variable for the collection before entering the loop.

If the collection is empty, calling GetPrevious can produce unexpected results even if GetLast has been called.


Item Property (CDONTS Messages Collection)

The Item property returns a single Message object from the Messages collection. Read-only.

Syntax

collMessages.Item(index)
index
A long integer ranging from 1 to the size of the Messages collection.

The Item property is the default property of a Messages collection, meaning that collMessages(index) is syntactically equivalent to collMessages.Item(index) in Microsoft® Visual Basic® code.

Data Type

Object (Message)

Remarks

The Item(index) syntax returns the Message object at the indicated position in the collection. It can be used in an indexed loop, such as the For ... Next construction in Visual Basic. The first item in the collection has an index of 1.

Although the Item property itself is read-only, the Message object it returns can be accessed in the normal manner, and its properties retain their respective read/write or read-only accessibility.

For more information on using the Count and Item properties in a collection, see the example in the Count property.


NewMail Object (CDONTS Library)

The NewMail object provides for sending a message with very few lines of code.

At a Glance

Specified in type library: | CDONTS.DLL
First available in: | CDO for NTS Library version 1.2
Parent objects: | (none)
Child objects: | (none)
Default property: | Value

Properties

Name | Available since version | Type | Access
Bcc | 1.2 | String | Write-only
Body | 1.2 | IStream object or String | Write-only
BodyFormat | 1.2 | Long | Write-only
Cc | 1.2 | String | Write-only
ContentBase | 1.2 | String | Write-only
ContentLocation | 1.2 | String | Write-only
From | 1.2 | String | Write-only
Importance | 1.2 | Long | Write-only
MailFormat | 1.2 | Long | Write-only
Subject | 1.2 | String | Write-only
To | 1.2 | String | Write-only
Value | 1.2 | String | Write-only
Version | 1.2 | String | Read-only

Methods

Name | Available since version | Parameters
AttachFile | 1.2 | Source as Object or String, (optional) FileName as String, (optional) EncodingMethod as Long
AttachURL | 1.2 | Source as Object or String, ContentLocation as String, (optional) ContentBase as String, (optional) EncodingMethod as Long
Send | 1.2 | (optional) From as String, (optional) To as String, (optional) Subject as String, (optional) Body as Object or String, (optional) Importance as Long
SetLocaleIDs | 1.2 | CodePageID as Long

Remarks

The NewMail object is not built on the normal API architecture. It is meant for rapid generation of notification mail by an automated process running in the Microsoft® Windows NT® Server. No user interface is supplied, and no interaction with human users is expected during the generation and sending of the message. Therefore the NewMail object's properties are not designed to be read back and inspected. With the sole exception of Version, they can only be written.

The NewMail object is self-contained and does not expose any of the Properties Common to All CDO for NTS Library Objects.

Attachments and recipients, once added to the NewMail object, cannot be removed, and the NewMail object itself cannot be deleted. When the Send method completes successfully, the NewMail object is invalidated but not removed from memory. The programmer should Set the invalid object to Nothing to remove it from memory, or reassign it to another NewMail object. Attempted access to a sent NewMail object results in a return of CdoE_INVALID_OBJECT.

The NewMail object does not belong to the hierarchy encompassing the other CDO for NTS Library objects. It cannot access, nor can it be accessed from, any of the other objects. Like the Session object, it is considered a top-level object and is created directly from a Microsoft® Visual Basic® program. Its ProgID is CDONTS.NewMail. This code fragment creates a NewMail object through early binding:

Dim objNewMail As CDONTS.NewMail
  Set objNewMail = CreateObject("CDONTS.NewMail")

The main advantage of the NewMail object is the ease and simplicity with which you can generate and send a message. You do not have to log on to a session nor deal with a folder or a messages collection. You have only to create the NewMail object, send it, and Set it to Nothing. You can supply critical information in the parameters of the Send method. In many cases you only need three lines of code:

Set objNewMail = CreateObject("CDONTS.NewMail")
  objNewMail.Send("me@company.com", "you@company.com", "Hello", _
                  "I sent this in 3 statements!", 0) ' low importance
  Set objNewMail = Nothing ' canNOT reuse it for another message

Including an attachment can add as little as one statement to your code, because you can pass information in the parameters of the AttachFile method:

Set objNewMail = CreateObject("CDONTS.NewMail")
  objNewMail.AttachFile("\\server\schedule\sched.xls", "SCHED.XLS")
  objNewMail.Send("Automated Schedule Generator", "you@company.com", _
                  "Schedule", "Here's the latest master schedule", 0)
  Set objNewMail = Nothing


AttachFile Method (CDONTS NewMail Object)

The AttachFile method adds an attachment to the message by reading a file.

Syntax

objNewMail.AttachFile(Source [, FileName] [, EncodingMethod] )
objNewMail
Required. This NewMail object.
Source
Required. IStream object or String. The full path and file name of the file to be attached to the message, or a pointer to an IStream object containing the file data.
FileName
Optional. String. The file name to appear in the attachment's placeholder in the message. If FileName is not supplied, the file name from the Source parameter is used.
EncodingMethod
Optional. Long. The manner of encoding the attachment. The following values are possible:
EncodingMethod setting | Value | Description
CdoEncodingUUencode | 0 | The attachment is to be in UUEncode format (default).
CdoEncodingBase64 | 1 | The attachment is to be in base 64 format.

Remarks

The default value for the EncodingMethod parameter can change if you set the MailFormat property. If MailFormat is set to CdoMailFormatText, the default value is CdoEncodingUUencode. If MailFormat is set to CdoMailFormatMime, the default value is CdoEncodingBase64. However, if you add an attachment encoded in base 64 format, the value of the MailFormat property is automatically set to CdoMailFormatMime.

Only C/C++ and Java programs can use an IStream object for the Source parameter. They should pass an IUnknown object that returns an IStream interface in response to QueryInterface. Microsoft® Visual Basic® supports the IDispatch interface and not IUnknown, so it cannot use an IStream object.


AttachURL Method (CDONTS NewMail Object)

The AttachURL method adds an attachment to the message and associates a Uniform Resource Locator (URL) with the attachment.

Syntax

objNewMail.AttachURL(Source, ContentLocation [, ContentBase] [, EncodingMethod] )
objNewMail
Required. This NewMail object.
Source
Required. IStream object or String. The full path and file name of the resource to be attached to the message, or a pointer to an IStream object containing the file data.
ContentLocation
Required. String. The absolute or relative prefix for the URL that the rendering client can use to reference this attachment.
ContentBase
Optional. String. A base for the URL used to reference this attachment.
EncodingMethod
Optional. Long. The manner of encoding the attachment. The following values are possible:
EncodingMethod setting | Value | Description
CdoEncodingUUencode | 0 | The attachment is to be in UUEncode format (default).
CdoEncodingBase64 | 1 | The attachment is to be in base 64 format.

Remarks

You must supply at least the ContentLocation parameter to specify a URL for the attachment. If you also supply the ContentBase parameter, it is combined with the ContentLocation parameter to define the full URL path by which this attachment is to be referenced. For more information on constructing URL paths, see the ContentLocation property.

The default value for the EncodingMethod parameter can change if you set the MailFormat property. If MailFormat is set to CdoMailFormatText, the default value is CdoEncodingUUencode. If MailFormat is set to CdoMailFormatMime, the default value is CdoEncodingBase64. However, if you add an attachment encoded in base 64 format, the value of the MailFormat property is automatically set to CdoMailFormatMime.

Only C/C++ and Java programs can use an IStream object for the Source parameter. They should pass an IUnknown object that returns an IStream interface in response to QueryInterface. Microsoft® Visual Basic® supports the IDispatch interface and not IUnknown, so it cannot use an IStream object.

Example

This code fragment illustrates the preparation and sending of an MHTML (MIME HTML) message and attachment using the AttachURL method:

Dim myMail
Set myMail = CreateObject("CDONTS.NewMail")

HTML = "<!DOCTYPE HTML PUBLIC ""-//IETF//DTD HTML//EN"">" & NL
HTML = HTML & "<html>"
HTML = HTML & "<head>"
HTML = HTML & "<meta http-equiv=""Content-Type"""
HTML = HTML & "content=""text/html; charset=iso-8859-1"">"
HTML = HTML & "<meta name=""GENERATOR"" content=""Microsoft FrontPage 2.0"">"
HTML = HTML & "<title>Exchange CDO Example</title>"
HTML = HTML & "</head>"
HTML = HTML & "<body bgcolor=""#FFFFFF"">"
HTML = HTML & "<p><font size=""6"" face=""Arial Black""><strong>Exchange CDO "
HTML = HTML & "Sample<img src=CDO.gif>"
HTML = HTML & "</strong></font></p>"
HTML = HTML & "<p>CDO for NTS allows an easy way to send mail."
HTML = HTML & "This example shows how the content can be an HTML page"
HTML = HTML & "which allows you to send rich text and inline graphics.</p>"
HTML = HTML & "</body>"
HTML = HTML & "</html>"

myMail.AttachURL "D:\wwwroot\CDO.gif", "CDO.gif"
myMail.From = "Example@Microsoft.com"
myMail.To = "Someone@Microsoft.com"
myMail.Subject = "Sample Message"
myMail.BodyFormat = 0
myMail.MailFormat = 0
myMail.Body = HTML
myMail.Send


Bcc Property (CDONTS NewMail Object)

The Bcc property adds to the list of blind copy (Bcc) recipients for the NewMail object. Write-only.

Syntax

objNewMail.Bcc

Data Type

String

Remarks

The value you use to set the Bcc property can represent a single recipient or a list of recipients. Each recipient must be represented by a full messaging address:

"useraddress@company.com"

Multiple recipients on the list are separated by semicolons:

"user1@company1.com;user2@company2.com;user3@company3.com"


Body Property (CDONTS NewMail Object)

The Body property sets the text of the NewMail object. Write-only.

Syntax

objNewMail.Body

Data Type

Object (IStream) or String

Remarks

The Body property can contain either plain text or HTML. The BodyFormat property should be set to indicate whether or not the Body property includes any HTML.

Only C/C++ and Java programs can use an IStream object for this property. They should pass an IUnknown object that returns an IStream interface in response to QueryInterface. Microsoft® Visual Basic® supports the IDispatch interface and not IUnknown, so it cannot use an IStream object.


BodyFormat Property (CDONTS NewMail Object)

The BodyFormat property sets the text format of the NewMail object. Write-only.

Syntax

objNewMail.BodyFormat

Data Type

Long

Remarks

BodyFormat can contain exactly one of the following values:

BodyFormat setting | Value | Description
CdoBodyFormatHTML | 0 | The Body property is to include Hypertext Markup Language (HTML).
CdoBodyFormatText | 1 | The Body property is to be exclusively in plain text (default value).

Example

This code fragment shows the usage of the BodyFormat property in preparing and sending an HTML message:

Dim myMail
Set myMail = CreateObject("CDONTS.NewMail")

HTML = "<!DOCTYPE HTML PUBLIC ""-//IETF//DTD HTML//EN"">" & NL
HTML = HTML & "<html>"
HTML = HTML & "<head>"
HTML = HTML & "<meta http-equiv=""Content-Type"""
HTML = HTML & "HTML = HTML & ""content=""text/html; charset=iso-8859-1"">"""
HTML = HTML & "<title>Sample NewMail</title>"
HTML = HTML & "</head>"
HTML = HTML & "<body>"
HTML = HTML & "This is a sample message being sent using HTML. <BR></body>"
HTML = HTML & "</html>"

myMail.From = "Example@Microsoft.com"
myMail.To = "Someone@Company.com"
myMail.Subject = "Sample Message"
myMail.BodyFormat = 0
myMail.MailFormat = 0
myMail.Body = HTML
myMail.Send
Set myMail = Nothing


Cc Property (CDONTS NewMail Object)

The Cc property adds to the list of copy (Cc) recipients for the NewMail object. Write-only.

Syntax

objNewMail.Cc

Data Type

String

Remarks

The value you use to set the Cc property can represent a single recipient or a list of recipients. Each recipient must be represented by a full messaging address:

"useraddress@company.com"

Multiple recipients on the list are separated by semicolons:

"user1@company1.com;user2@company2.com;user3@company3.com"


ContentBase Property (CDONTS NewMail Object)

The ContentBase property sets a base for all URLs relating to the NewMail object's message body. Write-only.

Syntax

objNewMail.ContentBase

Data Type

String

Remarks

The ContentBase property is used for MHTML (MIME HTML) support. It represents the Content-Base header for URLs pertaining to the main body of a MIME message. ContentBase corresponds to the ContentBase property of a Message object.

The ContentBase property is used in conjunction with the ContentLocation property to provide an absolute path for all URLs pertaining to the message body. These include the URL used to reference the message body itself, and also any URLs within HTML tags in the Body property of the NewMail object.

ContentBase is meant to be combined with ContentLocation to produce an absolute path. For more information on constructing URL paths, see the ContentLocation property.

For more information on MHTML, see the RFC 2110 document.


ContentLocation Property (CDONTS NewMail Object)

The ContentLocation property sets an absolute or relative path for all URLs relating to the NewMail object's message body. Write-only.

Syntax

objNewMail.ContentLocation

Data Type

String

Remarks

The ContentLocation property is used for MHTML (MIME HTML) support. It represents the Content-Location header for URLs pertaining to the main body of a MIME message. ContentLocation corresponds to the ContentLocation property of a Message object.

If the ContentLocation property is set, it is taken as an absolute or relative URL that can be used to refer to the message body of the NewMail object. If the ContentBase property is also set, ContentLocation is taken as relative and is joined to the base provided by ContentBase.

The Body property of the NewMail object can also contain HTML tags that use URLs, for example <IMG> and <FORM>. If the resource for such a URL is not local to the recipient of the NewMail object, you must provide a path to locate the URL on the Internet. One way to do this is to provide the full path in the URL itself:

<IMG SRC=HTTP://www.abc.com/graphs/Oct1997/21Oct97/today.gif>

It is often more flexible, however, to supply the path externally and put only the resource name in the URL:

<IMG SRC=today.gif>

When this approach is taken, the ContentLocation and ContentBase properties can be used to supply the path. ContentLocation can contain an absolute path:

objNewMail.ContentLocation = "HTTP://www.abc.com/graphs/Oct1997/21Oct97/"

or a relative path:

objNewMail.ContentLocation = "Oct1997/21Oct97/"

If ContentLocation contains a relative path, the base URL is supplied in ContentBase:

objNewMail.ContentBase = "HTTP://www.abc.com/graphs/"

When ContentBase and ContentLocation are combined using standard URL combination rules, the result is an absolute path to the resource referenced by the URL.

Often a resource is included as an attachment to the NewMail object. When this is the case, the ContentLocation and ContentBase parameters of the AttachURL method are used to specify the attachment's URL. They are combined the same way the ContentLocation and ContentBase properties are combined. The URL specified by the attachment must match the URL requested by the HTML tag in the Body property, or the tag is not successfully resolved.

The simplest case of attaching with URLs is when your message body refers to the attachments by their ContentLocation parameter values. In this case you do not need either the ContentLocation or the ContentBase property, and the attachments only need resource names in their ContentLocation parameters. This code fragment sends a weekly review of sales activity with two chart images attached:

Set objNewMail = CreateObject("CDONTS.NewMail")
  strBody = "<HTML><HEAD></HEAD><BODY>" _
          & "This is the sales chart for the past week:" & vbCrLf _
          & "<IMG SRC=week.gif>" & vbCrLf _
          & "and this is the sales chart for the month:" & vbCrLf _
          & "<IMG SRC=month.gif>" & "</BODY></HTML>"
  objNewMail.AttachURL("\\myserver\sales\pastweek.gif", "week.gif")
  objNewMail.AttachURL("\\myserver\sales\thismnth.gif", "month.gif")
  objNewMail.Send("Automated Sales Report", "you@company.com", _
                  "Sales Charts", strBody, 0)
  Set objNewMail = Nothing ' canNOT reuse it for another message

Note that the URL string specified in the ContentLocation parameter of the AttachURL method does not have to match the file name of the underlying resource. The only requirement is that it match the URL requested by the HTML tag in the message body.

For more information on MHTML, see the RFC 2110 document.


From Property (CDONTS NewMail Object)

The From property sets the full messaging address to be used for the sender of this NewMail object. Write-only.

Syntax

objNewMail.From

Data Type

String

Remarks

The full messaging address must take the form

"senderaddress@company.com"

You cannot use a semicolon anywhere in the From string. Semicolons are reserved for multiple messaging addresses in a list, and the CDO for NTS Library does not permit multiple senders.


Importance Property (CDONTS NewMail Object)

The Importance property sets the importance associated with the NewMail object. Write-only.

Syntax

objNewMail.Importance

Data Type

Long

Remarks

The following values are defined:

Constant | Value | Description
CdoLow | 0 | Low importance
CdoNormal | 1 | Normal importance (default)
CdoHigh | 2 | High importance


MailFormat Property (CDONTS NewMail Object)

The MailFormat property sets the encoding for the NewMail object. Write-only.

Syntax

objNewMail.MailFormat

Data Type

Long

Remarks

MailFormat can contain exactly one of the following values:

MailFormat setting | Value | Description
CdoMailFormatMime | 0 | The NewMail object is to be in MIME format.
CdoMailFormatText | 1 | The NewMail object is to be in uninterrupted plain text (default value).

The setting of the MailFormat property determines the default value for the EncodingMethod parameter in the AttachFile and AttachURL methods. However, if you add an attachment encoded in base 64 format, the value of the MailFormat property is automatically set to CdoMailFormatMime.

For more information on Multipurpose Internet Mail Extensions (MIME), see the RFC 1341 document.


Send Method (CDONTS NewMail Object)

The Send method sends the NewMail object to the specified recipients.

Syntax

objNewMail.Send( [From] [, To] [, Subject] [, Body] [, Importance] )
objNewMail
Required. This NewMail object.
From
Optional. String. The full messaging address to be identified as the sender.
To
Optional. String. A list of full messaging addresses of recipients. The individual recipient addresses are separated by semicolons.
Subject
Optional. String. The subject line for the message.
Body
Optional. IStream object or String. The text of the message.
Importance
Optional. Long. The importance associated with the message.

Remarks

The From, To, Subject, Body, and Importance parameters correspond to the From, To, Subject, Body, and Importance properties on the NewMail object.

If both the To property and the To parameter of the Send method are supplied, the NewMail object is sent to all recipients on both lists.

Only C/C++ and Java programs can use an IStream object for the Body parameter. They should pass an IUnknown object that returns an IStream interface in response to QueryInterface. Microsoft® Visual Basic® supports the IDispatch interface and not IUnknown, so it cannot use an IStream object.

The NewMail object becomes invalid upon successful completion of the Send method, and you cannot reuse it for another message. You should Set it to Nothing to release the memory. Attempted access to a sent NewMail object results in a return of CdoE_INVALID_OBJECT.

Example

This code fragment demonstrates a simple usage of the NewMail object and its Send method:

Dim myMail
Set myMail = CreateObject("CDONTS.NewMail")
myMail.From = "Example@Microsoft.com"
myMail.To = "Someone@company.com"
myMail.Subject = "Sample Message"
myMail.Body = "This is a sample message."
myMail.AttachFile "d:\sample.txt"
myMail.Send
Set myMail = Nothing


SetLocaleIDs Method (CDONTS NewMail Object)

The SetLocaleIDs method sets identifiers that define a messaging user's locale.

Syntax

objNewMail.SetLocaleIDs(CodePageID)
objNewMail
Required. This NewMail object.
CodePageID
Required. Long. The code page identifier to be used for this messaging user.

Remarks

A locale is the set of features of a messaging user's environment that are dependent on language, country, culture, and conventions. These features include the character selection, the collating sequence and sort order, and the date, time, and currency formats. The SetLocaleIDs method sets identifiers that determine the behavior of locale-sensitive operations.

A code page identifier is a long integer specifying the ordered character set to use when displaying text. Information about a code page can be obtained from the Windows NT GetCPInfo function.

When you first create a NewMail object it uses the locale values in the user's registry. However, you can change a NewMail object's locale after its creation by calling the its SetLocaleIDs method. Such a call does not affect the locale of any other Message or NewMail object, nor does it alter the settings established by a Session object's SetLocaleIDs method.

SetLocaleIDs tests the validity of the code page specified by the CodePageID parameter before actually setting the locale identifiers. If the code page is not valid, CdoE_INVALID_PARAMETER is returned.


Subject Property (CDONTS NewMail Object)

The Subject property sets the subject of the NewMail object as a string. Write-only.

Syntax

objNewMail.Subject

Data Type

String

Remarks

You can set the Subject property to an empty string, although that limits the ability of the recipients to sort and filter received messages.


To Property (CDONTS NewMail Object)

The To property adds to the list of principal (To) recipients for the NewMail object. Write-only.

Syntax

objNewMail.To

Data Type

String

Remarks

The value you use to set the To property can represent a single recipient or a list of recipients. Each recipient must be represented by a full messaging address:

"useraddress@company.com"

Multiple recipients on the list are separated by semicolons:

"user1@company1.com;user2@company2.com;user3@company3.com"

If both the To property and the To parameter of the Send method are supplied, the NewMail object is sent to all recipients on both lists.


Value Property (CDONTS NewMail Object)

The Value property sets the value and contents of an additional header for the NewMail object. Write-only.

Syntax

objNewMail.Value(header) = strHdrValue
header
A character string containing the name of the header to be added.
strHdrValue
A character string containing the value of the header to be added.

The Value property is the default property of a NewMail object, meaning that objNewMail(header) is syntactically equivalent to objNewMail.Value(header) in Microsoft® Visual Basic® code.

Data Type

String

Remarks

The Value property is used to add one or more headers to the automatically generated headers such as "To", "From", "Subject", and "Date". Possibilities for additional headers include "File", "Keywords", and "Reference".

Certain headers, such as "Reply-To", are widely accepted and used by various messaging systems. If you wish such a header to be recognized by the recipients of the NewMail object, you must be sure that the character string in the header's name exactly matches the accepted string.

In principle you can put any combination of ASCII characters in the string, but some messaging systems may have restrictions on the character set. The safest procedure is to limit the string to alphanumeric characters, dashes, and slashes, and in particular to avoid spaces.

You can set the Value property more than once. Each setting generates another header to be included with the existing headers.

Example

This code fragment adds two headers to a NewMail object before sending it:

' strBody set in advance for message body
  objNewMail.Value("Reply-To") = "The Boss<myemail@mycompany.com>"
  objNewMail.Value("Confidential") = "For my direct reports only"
  objNewMail.Send("myemail@mycompany.com", _
                  "myreports@mycompany.com", _
                  "Reorganization", strBody, 2) ' high importance
  Set objNewMail = Nothing


Version Property (CDONTS NewMail Object)

The Version property returns the version of the CDO for NTS Library. Read-only.

Syntax

objNewMail.Version

Data Type

String

Remarks

The Version property currently returns "1.2".


Recipient Object (CDONTS Library)

The Recipient object represents a recipient of a message.

At a Glance

Specified in type library: | CDONTS.DLL
First available in: | CDO for NTS Library version 1.2
Parent objects: | Recipients collection
Child objects: | (none)
Default property: | Name

No modifications are permitted to messages in the Inbox, except for message deletion. Therefore, all properties on a Recipient object are treated as read-only when the grandparent Message object is in the Inbox. When the access is described as read/write in the following table, that access applies only to recipients on messages in the Outbox.

Properties

Name | Available since version | Type | Access
Address | 1.2 | String | Read/write
Application | 1.2 | String | Read-only
Class | 1.2 | Long | Read-only
Name | 1.2 | String | Read/write
Parent | 1.2 | Recipients collection object | Read-only
Session | 1.2 | Session object | Read-only
Type | 1.2 | Long | Read/write

Methods

Name | Available since version | Parameters
Delete | 1.2 | (none)


Address Property (CDONTS Recipient Object)

The Address property specifies the full messaging address for the recipient. Read/write (read-only for a recipient on a message in the Inbox).

Syntax

objRecip.Address

Data Type

String

Remarks

The Recipient object's Address property represents the complete messaging address used by the messaging system.

Example

' assume valid Recipient object
  objRecip.Address = "myname@mycompany.com"


Delete Method (CDONTS Recipient Object)

The Delete method removes the Recipient object from the Recipients collection.

Syntax

objRecip.Delete( )

Remarks

The Delete method performs an irreversible operation on the collection. It calls Release on the collection's reference to the Recipient object. If you have another reference to the recipient, you can still access its properties and methods, but you can never again associate it with any collection because the Add method always creates a new object. You should Set your reference variable either to Nothing or to another recipient.

The final Release on the Recipient object takes place when you assign your reference variable to Nothing, or when you call Delete if you had no other reference. At this point the object is removed from memory. Attempted access to a released object results in an error return of CdoE_INVALID_OBJECT.

The effect of the Delete operation is not permanent until you use the Send or Delete method on the Message object to which this recipient belongs.

The immediate parent of this Recipient object is a Recipients collection, which is a child of the message. You can delete all the message's recipients by calling the collection's Delete method.

The CDO for NTS Library does not permit any modifications to messages in the Inbox, other than deleting the entire message. Prohibited modifications include adding, deleting, or modifying any attachment; adding, deleting, or modifying any recipient; and modifying any message property, even one with read/write access.

Example

This code fragment illustrates the two situations previously explained. The Set statement calls AddRef on the first Recipient object. That reference survives the call to Delete and has to be reassigned. The second Recipient object is deleted without creating another reference, and no other action is necessary.

' assume valid Message object
Set objRecip = objMessage.Recipients.Item(1)
objRecip.Delete ' still have a reference from Set statement
' ... other operations on objRecip possible but pointless ...
Set objRecip = Nothing ' necessary to remove reference
' ...
objMessage.Recipients.Item(2).Delete ' no reference to remove


Name Property (CDONTS Recipient Object)

The Name property returns or sets the name of the Recipient object as a string. Read/write (read-only for a recipient on a message in the Inbox).

Syntax

objRecip.Name

The Name property is the default property of a Recipient object, meaning that objRecip is syntactically equivalent to objRecip.Name in Microsoft® Visual Basic® code.

Data Type

String

Remarks

The Name property returns an empty string if it has never been set or cannot be found.

Example

Dim strMsg As String
' ... validate objects ... then display
    strMsg = "Recipient address = " & objRecip.Address
    strMsg = strMsg & "; Recipient name = " & objRecip.Name
    MsgBox strMsg ' display recipient parts


Type Property (CDONTS Recipient Object)

The Type property specifies the recipient type of the Recipient object, that is, whether it is a To, Cc, or Bcc recipient. Read/write (read-only for a recipient on a message in the Inbox).

Syntax

objRecip.Type

Data Type

Long

Remarks

The Type property has the following defined values:

Recipient type | Value | Description
CdoTo | 1 | The recipient is on the To line (default).
CdoCc | 2 | The recipient is on the Cc line.
CdoBcc | 3 | The recipient is on the Bcc line.

See Also

Address Property (Recipient Object)


Recipients Collection Object (CDONTS Library)

The Recipients collection object contains zero or more Recipient objects and specifies the recipients of a message.

At a Glance

Specified in type library: | CDONTS.DLL
First available in: | CDO for NTS Library version 1.2
Parent objects: | Message
Child objects: | Recipient
Default property: | Item

Properties

Name | Available since version | Type | Access
Application | 1.2 | String | Read-only
Class | 1.2 | Long | Read-only
Count | 1.2 | Long | Read-only
Item | 1.2 | Recipient object | Read-only
Parent | 1.2 | Message object | Read-only
Session | 1.2 | Session object | Read-only

Methods

Name | Available since version | Parameters
Add | 1.2 | (optional) name as String, (optional) address as String, (optional) type as Long
Delete | 1.2 | (none)


Add Method (CDONTS Recipients Collection)

The Add method creates and returns a new Recipient object in the Recipients collection.

Syntax

Set objRecip = collRecips.Add( [name] [, address] [, type])
objRecip
On successful return, represents the new Recipient object added to the collection.
collRecips
Required. The Recipients collection object.
name
Optional. String. The display name of the recipient. When this parameter is not present, the new Recipient object's Name property is set to an empty string.
address
Optional. String. The full messaging address of the recipient. When this parameter is not present, the new Recipient object's Address property is set to an empty string.
type
Optional. Long. The recipient type; the initial value for the new recipient's Type property. The following values are valid:
Recipient type | Value | Description
CdoTo | 1 | The recipient is on the To line (default).
CdoCc | 2 | The recipient is on the Cc line.
CdoBcc | 3 | The recipient is on the Bcc line.

Remarks

The name, address, and type parameters correspond to the Recipient object's Name, Address, and Type properties, respectively.

When no parameters are present, an empty Recipient object is created.

The new recipient is saved in persistent storage when you call the Send method on the Message object containing the Recipients collection.

The Add method returns CdoE_NO_ACCESS when called on a message in the Inbox.

The CDO for NTS Library does not permit any modifications to messages in the Inbox, other than deleting the entire message. Prohibited modifications include adding, deleting, or modifying any attachment; adding, deleting, or modifying any recipient; and modifying any message property, even one with read/write access.

Example

This code fragment adds a recipient to a message using information from an existing valid AddressEntry object

' from the sample function "Using Addresses"
' assume valid address entry ID from an existing message
Set objRecip = objNewMessage.Recipients.Add(type:=CdoTo, _
                                            name:=objAdrEnt.Name)
objRecip.Address = objAddrEnt.Type & ":" & objAddrEnt.Address
   ' ** the preceding line is not strictly necessary with CDO for NTS,
   ' ** but it allows this code to run with CDO for Exchange, where
   ' ** Recipient.Address requires a FULL address concatenated from
   ' ** AddressEntry.Type, ":", and AddressEntry.Address
If objRecip Is Nothing Then
    MsgBox "Unable to add existing AddressEntry using ID"
    Exit Function
End If

objNewMessage.Text = "Expect 1 recipient."
MsgBox ("Count = " & objNewMessage.Recipients.Count)


Count Property (CDONTS Recipients Collection)

The Count property returns the number of Recipient objects in the collection. Read-only.

Syntax

collRecips.Count

Data Type

Long

Example

This code fragment uses the Count property as a loop terminator to copy all Recipient objects from one message's Recipients collection to another message's collection. It shows the Count and Item properties working together. Note how much more code this requires than copying the Message object's Recipients property from the original message to the copy.

' Copy all Recipient objects from one message's collection to another
Dim objMessage, objCopyItem as Message
Dim collRecips as Recipients ' source message Recipients collection
Dim objRecip as Recipient ' individual recipient in target message
' ... verify valid messages ...
Set collRecips = objMessage.Recipients
For i = 1 To collRecips.Count Step 1
    strRecipName = collRecips.Item(i).Name
'   could be collRecips(i).Name since Item is default property
    If strRecipName <> "" Then
        Set objRecip = objCopyItem.Recipients.Add
        If objRecip Is Nothing Then
            MsgBox "Unable to create recipient in message copy"
            Exit Function
        End If
        objRecip.Name = strRecipName
        objRecip.Address = collRecips.Item(i).Address
        objRecip.Type = collRecips.Item(i).Type
    End If
Next i


Delete Method (CDONTS Recipients Collection)

The Delete method removes all the Recipient objects from the Recipients collection.

Syntax

collRecips.Delete( )

Remarks

The Delete method performs an irreversible operation on the collection. It calls Release on the collection's reference to every Recipient object. If you have another reference to a recipient, you can still access its properties and methods, but you can never again associate it with any collection because the Add method always creates a new object. You should Set your reference variable either to Nothing or to another recipient.

The final Release on each Recipient object takes place when you call Delete if you had no other reference, or when you assign your reference variable to Nothing. At this point the object is removed from memory. Attempted access to a released object results in an error return of CdoE_INVALID_OBJECT.

Be cautious using the Delete method with a collection, because it deletes all the collection's member objects. To delete only one Recipient object, use the Delete method specific to that object.

The effect of the Delete method is not permanent until you use the Send or Delete method on the Message object containing the Recipients collection. A permanently deleted member cannot be recovered. However, the collection itself is still valid, and you can Add new members to it.

The CDO for NTS Library does not permit any modifications to messages in the Inbox, other than deleting the entire message. Prohibited modifications include adding, deleting, or modifying any attachment; adding, deleting, or modifying any recipient; and modifying any message property, even one with read/write access.


Item Property (CDONTS Recipients Collection)

The Item property returns a single Recipient object from the Recipients collection. Read-only.

Syntax

collRecips.Item(index)
index
A long integer ranging from 1 to collRecips.Count, or a string that specifies the name of the object.

The Item property is the default property of a Recipients collection, meaning that collRecips(index) is syntactically equivalent to collRecips.Item(index) in Microsoft® Visual Basic® code.

Data Type

Object (Recipient)

Remarks

The Item property works like an accessor property for small collections.

Although the Item property itself is read-only, the Recipient object it returns can be accessed in the normal manner, and its properties retain their respective read/write or read-only accessibility.

Example

This code fragment shows the Count and Item properties working together:

' list all recipient names in the collection
strRecips = "" ' initialize string
Set collRecips = objMessage.Recipients
Count = collRecips.Count
For i = 1 To Count Step 1
    Set objRecip = collRecips.Item(i) ' or collRecips(i)
    strRecips = strRecips & objRecip.Name & "; "
Next i
MsgBox "Message recipients: " & strRecips


Session Object (CDONTS Library)

The Session object contains session-wide settings and options.

At a Glance

Specified in type library: | CDONTS.DLL
First available in: | CDO for NTS Library version 1.2
Parent objects: | (none)
Child objects: | Folder
Default property: | Name

Properties

Name | Available since version | Type | Access
Application | 1.2 | String | Read-only
Class | 1.2 | Long | Read-only
Inbox | 1.2 | Folder object | Read-only
MessageFormat | 1.2 | Long | Read/write
Name | 1.2 | String | Read-only
Outbox | 1.2 | Folder object | Read-only
Parent | 1.2 | Object; set to Nothing | Read-only
Session | 1.2 | Session object (itself) | Read-only
Version | 1.2 | String | Read-only

Methods

Name | Available since version | Parameters
GetDefaultFolder | 1.2 | folderType as Long
Logoff | 1.2 | (none)
LogonSMTP | 1.2 | DisplayName as String, Address as String
SetLocaleIDs | 1.2 | CodePageID as Long

Remarks

A Session object is considered a top-level object, meaning it can be created directly from a Microsoft® Visual Basic® program. In the CDO for NTS Library it has a ProgID of CDONTS.Session. This code fragment creates a Session object through early binding:

Dim objSession As CDONTS.Session
Set objSession = CreateObject ("CDONTS.Session")
objSession.LogonSMTP

This code fragment creates a Session object through late binding:

Dim objSession As Object
Set objSession = CreateObject ("CDONTS.Session")
objSession.LogonSMTP

Generally, early binding is preferable, because it enforces type checking and generates more efficient code. Note that you specify the full ProgID "CDONTS.Session" instead of just "Session" in order to distinguish a CDO application from other types of applications available to a Visual Basic program through other object libraries.

In both cases, after you create a new Session object, you call its LogonSMTP method to initialize it. No other activities with the CDO for NTS Library are permitted prior to a successful LogonSMTP call. The only exception to this rule is the Session object's SetLocaleIDs method.


GetDefaultFolder Method (CDONTS Session Object)

The GetDefaultFolder method returns a Folder object from a message store.

Syntax

Set objFolder = objSession.GetDefaultFolder(folderType)
objFolder
On successful return, contains the store's default Folder object of the specified type. When the folder does not exist, GetDefaultFolder returns Nothing.
objSession
Required. The Session object.
folderType
Required. Long. The folder type. This parameter can have exactly one of the following values:

folderType setting 		Decimal
value
Meaning
CdoDefaultFolderInbox | 1 | The CDO for NTS Library's Inbox.
CdoDefaultFolderOutbox | 2 | The CDO for NTS Library's Outbox.

Remarks

The GetDefaultFolder method allows you to obtain the message store's default Inbox or Outbox folder. No other folders are accessible through this method.

Example

This code fragment uses the GetDefaultFolder method to obtain the Inbox folder from a message store:

Dim objSession As Session
Dim objInbox As Folder ' default Inbox or Outbox
Dim collMessages As Messages ' messages in folder

Set objSession = CreateObject ("CDONTS.Session")
objSession.LogonSMTP("My Name", "myaddress@mycompany.com")
Set objInbox = objSession.GetDefaultFolder(CdoDefaultFolderInbox)
If objInbox Is Nothing Then
    Set collMessages = Nothing
    MsgBox "Unable to retrieve default folder"
    Exit Function
Else
    Set collMessages = objInbox.Messages
    MsgBox "Folder set to " & objInbox.Name
End If


Inbox Property (CDONTS Session Object)

The Inbox property returns a Folder object representing the current messaging user's Inbox folder. Read-only.

Syntax

objSession.Inbox

Data Type

Object (Folder)


Logoff Method (CDONTS Session Object)

The Logoff method uninitializes the Session object.

Syntax

objSession.Logoff( )

Remarks

The Logoff method terminates all activity on the Session object initialized by the LogonSMTP method. You can call LogonSMTP on the same Session object again. Attempted access to the Session object before initialization results in a return of CdoE_NOT_INITIALIZED.

Objects you create while you are active on a Session object become invalid when you call Logoff. You should Set your reference variables to Nothing for all such objects.

Example

This code fragment logs off from the messaging system:

' from the function Session_Logoff
If Not objSession Is Nothing Then
    objSession.Logoff
    MsgBox "Logged off; reset global variables"
Else
    MsgBox "No active session; cannot log off"
End If


LogonSMTP Method (CDONTS Session Object)

The LogonSMTP method initializes the Session object.

Syntax

objSession.LogonSMTP(DisplayName, Address)
objSession
Required. The Session object.
DisplayName
Required. String. The display name to use for the messaging user logging on, such as "John Q. Doe".
Address
Required. String. The full e-mail address to use for the messaging user logging on, such as "jdoe@company.com".

Remarks

Your application must call LogonSMTP before it can use any CDO for NTS Library object, including the Session object. An attempt to access any programming element prior to a successful LogonSMTP call results in a CdoE_NOT_INITIALIZED error return. The only exception to this rule is the Session object's SetLocaleIDs method.

An application using the CDO for NTS Library binds by address to the mailbox you specify in the LogonSMTP parameters:

   objSession.LogonSMTP("My Name", "myaddress@mycompany.com")

The identity of a user logging on with this syntax is not authenticated. The user can assume any arbitrary identity.

When CDO for NTS is running with IIS, the Inbox is a common folder shared by all recipients and applications, and containing all undeleted messages received by Microsoft® Internet Information Server (IIS). However, your application can access only those messages destined for the mailbox you bind to in the LogonSMTP call.

When CDO for NTS is running with the Microsoft Exchange Server, the Inbox is the regular Inbox of the messaging user's mailbox. When CDO for NTS is running with Microsoft Exchange Express, the Inbox is the messaging user's POP3 server Inbox.

The session is terminated by the Logoff method.


MessageFormat Property (CDONTS Session Object)

The MessageFormat property returns or sets the default message encoding. Read/write.

Syntax

objSession.MessageFormat

Data Type

Long

Remarks

The MessageFormat property has the following defined values:

MessageFormat setting | Value | Description
CdoMime | 0 | The message is in MIME format.
CdoText | 1 | The message is in uninterrupted plain text (default value).

The MessageFormat property defaults to CdoMime. It serves as the default value for the MessageFormat property of the Message object.


Name Property (CDONTS Session Object)

The Name property returns the display name used to log on to this session. Read-only.

Syntax

objSession.Name

The Name property is the default property of a Session object, meaning that objSession is syntactically equivalent to objSession.Name in Microsoft® Visual Basic® code.

Data Type

String

Example

' from the function Session_Name
If objSession Is Nothing Then
    MsgBox "Must log on first: see Session menu"
    Exit Function
End If
MsgBox "Profile name for this session = " & objSession.Name


Outbox Property (CDONTS Session Object)

The Outbox property returns a Folder object representing the current messaging user's Outbox folder. Read-only.

Syntax

objSession.Outbox

Data Type

Object (Folder)


SetLocaleIDs Method (CDONTS Session Object)

The SetLocaleIDs method sets identifiers that define a messaging user's locale.

Syntax

objSession.SetLocaleIDs(CodePageID)
objSession
Required. The Session object.
CodePageID
Required. Long. The code page identifier to be used for this messaging user.

Remarks

A locale is the set of features of a messaging user's environment that are dependent on language, country, culture, and conventions. These features include the character selection, the collating sequence and sort order, and the date, time, and currency formats. The SetLocaleIDs method sets identifiers that determine the behavior of locale-sensitive operations.

A code page identifier is a long integer specifying the ordered character set to use when displaying text. Information about a code page can be obtained from the Windows NT GetCPInfo function.

Before SetLocaleIDs is called, the locale and code page are set to the values in the user's registry.

If SetLocaleIDs is to be called, it must be called before the Session object's LogonSMTP method is called. This allows the messaging user's profile to be set for the appropriate locale. A call to SetLocaleIDs following logon returns CdoE_CALL_FAILED.

Note that the SetLocaleIDs method is the sole exception to the rule that a call to a session's LogonSMTP method must precede any other access to that session.

Every new message you create within the current session uses the locale established by your most recent call to the Session object's SetLocaleIDs method, or the default settings if you have never called SetLocaleIDs. A Message object created by the Messages collection's Add method cannot subsequently change its locale, even if SetLocaleIDs is called again. However, you can change a NewMail object's locale after its creation by calling the NewMail object's SetLocaleIDs method. Such a call does not affect the locale of any other Message or NewMail object, nor does it alter the settings established by the Session object's SetLocaleIDs method.

SetLocaleIDs tests the validity of the code page specified by the CodePageID parameter before actually setting the locale identifiers. If the code page is not valid, CdoE_INVALID_PARAMETER is returned.


Version Property (CDONTS Session Object)

The Version property returns the version of the CDO for NTS Library. Read-only.

Syntax

objSession.Version

Data Type

String

Remarks

The Version property currently returns "1.2".


Global.asa Reference

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.

Global.asa files can contain only the following:

  • 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.

However, saving changes to a file that is included by the Global.asa file does not cause the server to recompile Global.asa. In order for the server to recognize changes in the included file, you must once again save the Global.asa file.

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. You typically give include files an .inc extension.

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

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 LANGUAGE=ScriptLanguage RUNAT=Server>
Sub Application_OnStart
. . .
End Sub

</SCRIPT>

Parameters

ScriptLanguage
Specifies the scripting language used to write the event script. It may be any supported scripting language, such as VB Script or JScript. If more than one event uses the same scripting language, they can be combined under a single set of <SCRIPT> tags.

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 LANGUAGE=ScriptLanguage RUNAT=Server>
Sub Application_OnEnd
. . .
End Sub

</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

You cannot call the MapPath method in the Application_OnEnd script.

See Also

Application_OnStart, Session_OnEnd


Session Events

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.


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 LANGUAGE=ScriptLanguage RUNAT=Server>
Sub Session_OnStart
. . .
End Sub

</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.

<SCRIPT RUNAT=Server Language=VBScript>
Sub Session_OnStart
    ' Make sure that new users start on the correct
    ' page of the ASP application.

    ' Replace the value given to startPage below
    ' with the virtual path to your application's
    ' start page.

    startPage = "/MyApp/StartHere.asp"
    currentPage = Request.ServerVariables("SCRIPT_NAME")

    ' Do a case-insensitive compare, and if they
    ' don't match, send the user to the start page.

    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 LANGUAGE=VBScript RUNAT=Server>
   Sub Session_OnStart
      ' Session initialization script
      Response.Redirect "http:/server/app/StartHere.asp"
   End sub
</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 LANGUAGE=ScriptLanguage RUNAT=Server>
Sub Session_OnEnd
. . .
End Sub

</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

You cannot call the MapPath method in the Session_OnEnd script.

See Also

Session_OnStart, Application_OnEnd


<OBJECT> Declarations

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.

Syntax

<OBJECT RUNAT=Server SCOPE=Scope ID=Identifier {PROGID="progID"|CLASSID="ClassID"}>
. . .

</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.

<OBJECT RUNAT=Server SCOPE=Session ID=MyConnection
PROGID="ADODB.Connection">
REM Object Script
</OBJECT>

<OBJECT RUNAT=Server SCOPE=Session ID=MyConnection
CLASSID="Clsid:8AD3067A-B3FC-11CF-A560-00A0C9081C21">
REM Object Script
</OBJECT>

Remarks

The objects declared in the Global.asa file can be used by any script in the application. For example, if you declared the following object.

---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

It is very common for ActiveX components to describe any constants that the component supports in a type library. A type library is a file that contains information about objects and types supported by an ActiveX component. If your Web application relies on ActiveX 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 data types 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 identifer 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 an error is returned (optional).
minorversionnumber
Used for selecting version. If the requested version is not found, then an error is returned (optional).
localeid
The locale identifier to be used for the type library. If the requested locale is not found, then an error is returned (optional)

Error Values

The server can return one of the following error messages.

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.

Example

MyComponent in the following example was developed with Visual Basic 5.0. MyComponent defines the constant MyError with the following statement.

Public Const MyError = "You are not using MyComponent correctly."

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. This example uses the optional STARTSPAN and ENDSPAN tags. These tags are not required by IIS.

<!--METADATA TYPE="TypeLib"
FILE="MyComponent.lib"
-->

Any ASP 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
%>


Windows Scripting Host Programmer's Reference

The following information is presented in this programmer's reference:

  • About Windows Scripting Host
  • Using Windows Scripting Host
  • Windows Scripting Host Object Reference


About Windows Scripting Host

The Microsoft® Windows® Scripting Host is a language-independent scripting host for ActiveX™ scripting engines on 32-bit Windows platforms. Windows Scripting Host will be integrated into Windows® 98, Windows NT® Workstation version 5.0, and Windows NT Server version 5.0.

Both Microsoft® Visual Basic® Scripting Edition (VBScript) and Microsoft® JScript™ scripting engines are provided with Windows Scripting Host. Other software companies will provide ActiveX™ scripting engines for languages such as Perl, TCL, REXX, Python, and others.

Windows Scripting Host can be run from either the Windows-based host (Wscript.exe), or the command-shell-based host (Cscript.exe).


ActiveX Scripting Hosts

ActiveX scripting architecture supports powerful scripting using languages such as VBScript, JScript, Perl, and others. Microsoft currently provides three hosts for running these scripting languages across the Windows platform:

  • Microsoft® Internet Explorer. Internet Explorer can execute scripts on client computers from within HTML pages.
  • Internet Information Server (IIS). IIS supports Active Server Pages, so scripts can run on Web servers. In other words, IIS supports server-side scripting over the Internet or an intranet.
  • Windows Scripting Host. Windows Scripting Host provides a low-memory scripting host so scripts can execute directly on the Windows desktop or Command Prompt window; the scripts do not need to be embedded in an HTML document. Windows Scripting Host is an ideal host for non-interactive scripts that perform logon and administrative tasks.

In addition to having a smaller footprint than the other two scripting hosts, the Windows Scripting Host does not rely on an HTML SCRIPT tag or LANGUAGE attribute to identify a scripting engine. Instead Windows Scripting Host uses the extension of the script file to determine which scripting engine to use. As a result, the script writer does not need to obtain a scripting engine ProgID. The scripting host itself maintains a mapping of script extensions to ProgIDs and uses the Windows association model to launch the appropriate engine for a given script.

For more information about how Windows Scripting Host works, see:

http://www.microsoft.com/management/wsh.htm.


Overview of the Windows Scripting Host Object Model

The Windows Scripting Host object model provides two main categories of ActiveX interfaces:

  1. Script execution and troubleshooting: Properties and methods that are directly related to script execution. This set of interfaces allows scripts to manipulate Windows Scripting Host, display messages on the screen, and perform basic functions such as CreateObject and GetObject.
  2. Helper functions: Properties and methods that map network drives, connect to printers, retrieve and modify environment variables, and manipulate registry keys. These functions are provided so administrators can use Windows Scripting Host to create simple logon scripts.

In addition to the object interfaces provided by Windows Scripting Host, administrators can use any ActiveX controls that expose Automation interfaces to perform various tasks on the Windows platform. For example, administrators can write scripts that use the Active Directory to manage the Windows NT Directory Service.


Using Windows Scripting Host

The following section describes how you can use Windows® Scripting Host.


Writing a Scripting Engine for Windows Scripting Host

The principal requirement for a third-party scripting engine is that it support the ActiveX™ IActiveScriptParse COM interface.

The Windows Scripting Host reads and passes the contents of a specified script file to a registered scripting engine using the scripting engine's IActiveScriptParse::ParseScriptText method.

A scripting engine can also call Wshom.ocx, an ActiveX control that supports the IDispatch COM interface. If the scripting engine supports ActiveX control creation in a script, Wshom.ocx can be called from within the script.

If the scripting engine itself calls Wshom.ocx, you should obtain Iwshom.idl, Iwshom.h and Iwshom.iid from the Platform SDK. With these files, you can call methods in Wshom.ocx using the normal COM calling sequence. Wshom.ocx supports a dual interface, aggregation, and the IErrorInfo COM interface.

Example

#include <IWSHom.h>

HRESULT
Use_WSHShell() {
    HRESULT hr;
    IWSHShell* pShell;

    hr = ::CoCreateInstance(CLSID_IWSHShell,
                       NULL,
                       CTX_INPROCSERVER,
                       IID_IWSHShell,
                       (LPVOID*) &pShell );
    if (FAILED(hr)) return hr;

    hr = pShell->Run(bstrCommand,
 &varWindowStyle,
 &varWaitOnReturn,
               &nExitCode );
    pShell->Release();

    return hr;
}


How Windows Scripting Host Uses the Registry

An ActiveX scripting engine is registered for use with Windows Scripting Host by adding registry entries under the HKEY_CURRENT_USER (HKCU) key. Windows Scripting Host determines which scripting engine to use to execute a script by examining the ScriptEngine key. For example, if a user types the following command in a Command Prompt window to look up the scripting engine for the Chart.vbs file:

cscript chart.vbs

Windows Scripting Host does the following:

  1. Searches HKCU\.vbs to obtain a script identifier, such as VBSfile.
  2. Searches HKCU\VBSFile\ScriptEngine to get a scripting engine identifier, such as VBScript.
  3. Finds the CLSID from the scripting engine identifier; in this example, the CLSID is located in HKCU\VBScript\CLSID.
  4. Calls CoCreateInstance with the CLSID and IUnknown.
  5. Calls QueryInterface to get the IActiveScriptParse COM interface.


Registering a Scripting Engine for Windows Scripting Host

If you have written an ActiveX scripting engine with the following characteristics:

  • The scripting engine identifier is MyScriptLanguage (for example).
  • The file extension for scripts is .msl.
  • The script identifier is MyScriptFile.

The following table shows the registry entries that are necessary to register this engine (none of these has a value name).

For Windows 98, use REG_SZ instead of REG_EXPAND_SZ and change the path of Wscript.exe and Cscript.exe as shown in the following table.

 | Windows NT | Windows 98
Wscript | %SystemRoot%\System32\Wscript.exe | C:\Windows\Wscript.exe
Cscript | %SystemRoot%\System32\Cscript.exe | C:\Windows\Command\Cscript.exe


Running Scripts Using Wscript.Exe

Using Wscript.exe, you can run scripts under Windows in three ways:

  • Double-clicking files or icons. These can be files or icons listed in My Computer, Windows Explorer, the Find window, the Start menu, or on the Desktop.
  • Entering a script name at the Run command on the Start Menu. Click Start, click Run, and enter the full name of the script you want to run, including file extension and any necessary path information.
  • Entering Wscript.exe followed by a script name at the Run command. Click Start, click Run, and enter Wscript, followed by the full name and path of the script you want to run

If you double-click a script file whose extension has not yet been associated with Wscript.exe, an Open With dialog box displays, prompting you to select the program with which to open the file. After selecting Wscript, if you select the Always use this program to open this type of file check box, Wscript is registered as the default application for all files having the same extension as the one you double-clicked. For example, if you select this check box when you run Chart.vbs, Wscript.exe becomes the default application for all files having the .vbs extension.

Wscript.exe has a properties page associated with it that provides the following options:

Property
Function 		CSCRIPT equivalent
Stop script after nn seconds. Specifies a maximum number of seconds that a script can run (the default is no limit). //T:nn
Display logo when script runs in a command console. Display a banner before running the script. (This is the default. The opposite is //nologo.) //logo or
//nologo

By using the Wscript.exe Properties page, you can set global scripting options for all scripts that Wscript runs on the local computer. It is also possible to set options for individual scripts, using a .wsh file, as described in the next section.


Creating .WSH Files to Record Script Options

You can record specific settings for each script you run by creating a control file for that script with a .wsh file extension.

A .wsh file is a text file that uses a format similar to that of .ini files. It is created automatically when you set the properties for a supported script file.

The following steps describe how to create a .wsh file for a script:

To create a .wsh file for a given script
  1. Right-click the given script file in Windows Explorer.
  2. Click Properties on the context menu that appears.
  3. Choose the settings you want for the script on the properties page.
  4. Click OK or Apply.

A .wsh file is automatically created. It has the same name as the script file you right-clicked. A sample .wsh file might contain the following text:

[ScriptFile]
Path=C:\WINNT\Samples\WSH\showprop.vbs

[Options]
Timeout=0
DisplayLogo=1
BatchMode=0

The Path setting in the [ScriptFile] section identifies the script file associated with this .wsh file. The keys in the [Options] section correspond to settings in the Script tab within the Properties dialog box.


Using .WSH Files to Run Scripts

A .wsh file is analagous to the .pif files used to run older 16-bit applications. The .wsh file can be treated as if it were an executable or batch file.

For example, suppose you have a script named Myscript.vbs for which you have created a .wsh file named Myscript.wsh. To run Myscript.vbs with the options recorded in Myscript.wsh, you can double-click Myscript.wsh in Windows Explorer. You can also pass Myscript.wsh as a script argument to CScript.exe or WScript.exe by typing the following in the Command Prompt window:

cscript Myscript.wsh

Administrators in particular will find .wsh files useful. By creating multiple different .wsh files for a given script, an administrator can tailor the way that script runs to the needs of specific groups or even individuals within an organization.

The same logon script, for example, might serve two very different groups if invoked by two different .wsh files containing different settings and parameters.


Running Scripts Using Cscript.exe

To use Cscript.exe, open a Command Prompt window and type a Cscript command line. CScript uses the following syntax:

cscript [script name] [host options...] [script options]
  • Script name is the name of the script file, complete with extension and any necessary path information, such as: d:\admin\vbscripts\chart.vbs.
  • Host options enable or disable various Windows Scripting Host features. Host options are always preceeded by two slashes (//).
  • Script options are passed to the script. Script parameters are always preceeded by only one slash (/).

Each parameter is optional; however, you cannot specify script options without specifying a script name. If you do not specify parameters, Cscript displays the Cscript syntax and the valid host parameters.

Cscript.exe supports the host parameters shown in the following table.

Parameter | Description
//I | Interactive Mode: allows display of user prompts and script errors (this is the default, and the opposite of //B).
//B | Batch Mode: suppresses command-line display of user prompts and script errors.
//T:nn | Enables time-out: the maximum number of seconds the script can run. The default is no limit. (See the text following this table for more information on this parameter.)
//logo | Displays a banner (default; opposite of //nologo).
//nologo | Prevents display of an execution banner at run time.
//H:Cscript or //H:Wscript | Registers Cscript.exe or Wscript.exe as the default application for running scripts. If neither is specified, Wscript.exe is assumed as the default.
//S | Saves the current command-line options for this user.
//? | Shows command usage (same as with parameters).

The //T parameter prevents excessive execution of scripts; it does this by setting a timer. When execution time exceeds the specified value, Cscript interrupts the scripting engine using the IActiveScript::InterruptThread method and terminates the process.

A Cscript Example

Several sample scripts are installed when you install the final release of the Windows Scripting Host. These are also available for download at:

http://www.microsoft.com/management/wsh.htm

Suppose, for the purposes of this example, that you have copied the Chart.vbs sample script to the following folder on your computer:

c:\sample scripts\chart.vbs

You can run the script with and without a logo, as follows:

  1. Click Start, point to Programs, and click Command Prompt.
  2. Type the following commands at the command prompt (if your sample scripts are located in a different folder, these lines should be modified accordingly):
    cscript //logo c:\”sample scripts”\chart.vbs
cscript //nologo c:\”sample scripts”\chart.vbs

When Windows Scripting Host ships with Windows NT 5.0, you will no longer need to provide the script file extension. Instead, you can type just the script name, or double-click the script in Windows Explorer.


Document Conventions

Variable prefixes in parameter listings and code examples have the following meanings.

Prefix | Description
any | Any type
b | Boolean
int | Integer
nat | Natural number or nonnegative integer
obj | Object (Idispatch interface)
str | String

Scripting examples are written in the Microsoft® Visual Basic® Scripting Edition (VBScript).

Methods written in Microsoft Jscript™ are case-sensitive. In general, you should use the same case as the syntax examples shown in this document.

Parameters in brackets (for example, [anyValue]) are optional.


Windows Scripting Host Object Reference

Objects provided by Wscript.exe

Wscript | Exposed to scripting engine as Wscript.
WshArguments | Not exposed; accessed through the Wscript.Arguments property.

Objects provided by WSHom.Ocx

WshShell | Automation object. The ProgID is Wscript.WshShell.
WshNetwork | Automation object. The ProgID is Wscript.WshNetwork.
WshShortcut | Not exposed; accessed through the WshShell.CreateShortcut method.
WshUrlShortcut | Not exposed; accessed through the WshShell.CreateShortcut method .
WshCollection | Not exposed; accessed through the WshNetwork.EnumNetworkDrives or WshNetwork.EnumPrinterConnection method.
WshEnvironment | Not exposed; accessed through the WshShell.Environment property.
WshSpecialFolders | Not exposed; accessed through the WshShell.Folder property.


Wscript Object

ProgID | N/A
File name | Wscript.exe or Cscript.exe
CLSID | 60254CA2-953b-11CF-8C96-00AA00B8708C
IID | 60254CA1-953b-11CF-8C96-00AA00B8708C

The following table describes the properties associated with the Wscript object.

Property | Description
Application | The IDispatch interface for Wscript.
Arguments | A parameters collection object.
FullName | Full path to the host executable.
Name | Friendly name of Wscript (the default property).
Path | Name of the directory where Wscript.exe or Cscript.exe resides.
ScriptFullName | Full path to the script being run by the Windows Scripting Host.
ScriptName | File name of the script being run by the Windows Scripting Host.
Version | A version string for the Windows Scripting Host.

The following table describes the methods associated with the Wscript object.

Method | Description
CreateObject | Creates an object and establishes its event handling.
DisconnectObject | Disconnects a previously connected object from Windows Scripting Host.
Echo | Displays parameters in window or in a Command Prompt window.
GetObject | Retrieves an Automation object from a file.
Quit | Quits execution with a specified error code.


Wscript.Application

The Application property provides the IDispatch interface on the Wscript object.

Syntax

Wscript.Application = objWscript


Wscript.Arguments

The Arguments property provides a WshArguments collection object.

Syntax

Wscript.Arguments = objArguments

Example

' Display all command-line parameters
Set objArgs = Wscript.Arguments
For I = 0 to objArgs.Count - 1
          Wscript.Echo objArgs(I)
Next


Wscript.FullName

The FullName property provides a string containing the full path to the host executable.

Syntax

Wscript.FullName = strFullName

Example

Wscript.FullName = C:\WinNT\System32\wscript.exe

See Also

Wscript.Path property.


Wscript.Name

The Name property provides a string containing the friendly name of the Wscript object. This is the default property.

Syntax

Wscript.Name = strName

Example

Wscript.Name = Windows Scripting Host
Wscript = Windows Scripting Host


Wscript.Path

The Path property provides a string containing the name of the directory where Wscript.Exe or Cscript.Exe reside.

Syntax

Wscript.Path  = strPath

Example

Wscript.Path = C:\WinNT\System32

See Also

Wscript.FullName property


Wscript.ScriptFullName

The ScriptFullName property provides the full path to the script being run by the Windows Scripting Host.

Syntax

Wscript.ScriptFullName = strScriptFullName

Example

Wscript.ScriptFullName = C:\Users\Default\WSH\Sample.VBS

See Also

Wscript.ScriptName property


Wscript.ScriptName

The ScriptName property provides the file name of the script being run by the Windows Scripting Host.

Syntax

Wscript.ScriptName = strScriptName

Example

Wscript.ScriptName = Sample.VBS

See Also

Wscript.ScriptFullName property


Wscript.Version

The Version property provides a version string for the Windows Scripting Host.

Syntax

Wscript.Version = strVersion

Example

Wscript.Version = 5.0


Wscript.CreateObject

The CreateObject method creates an object specified by the strProgID parameter. If the parameter strPrefix is specified, Windows Scripting Host connects the object's outgoing interface to the script file after creating the object. When the object fires an event, Windows Scripting Host calls a subroutine named strPrefix and the event name.

For example, if strPrefix is "MYOBJ_" and the object fires an event named "OnBegin", Windows Scripting Host calls the "MYOBJ_OnBegin" subroutine located in the script.

Syntax

Wscript.CreateObject(strProgID, [strPrefix]) = objObject

See Also

Wscript.GetObject method, Wscript.DisconnectObject method


Wscript.DisconnectObject

The DisconnectObject method disconnects a previously connected object (obj) from Windows Scripting Host. If the specified object is not already connected to Windows Scripting Host, this method does nothing.

Syntax

Wscript.DisconnectObject obj

Example

' This code fragment instantiates a fictitious object and
' connects it to the script file. The script then calls the
' "SomeMethod" method on the object.
' If an error called "Event" occurs in the object, then the
' MyEvent_Event subroutine is called.

Set MyObject = Wscript.CreateObject("SomeObject", "MyEvent")

MyObject.SomeMethod

Sub MyEvent_Event(strName)
        Wscript.Echo strName
End Sub

' When done with the object, disconnect it from the script
' and then set it to Nothing
Wscript.DisconnectObject MyObject
Set MyObject = Nothing

See Also

Wscript.CreateObject method, Wscript.GetObject method


Wscript.Echo

The Echo method displays parameters in a window (in Wscript.exe) or in a Command Prompt window (in Cscript.exe).

Parameters are delimited by one space. Under Cscript.exe, this method outputs a carriage-return/line feed pair (CR LF) after the last parameter displayed.

Syntax

Wscript.Echo [anyArg...]

Example

Wscript.Echo
Wscript.Echo 1, 2, 3
Wscript.Echo "Windows Scripting Host is cool."


Wscript.GetObject

The GetObject method retrieves an Automation object from a file, or an object specified by strProgID parameter. Use the GetObject method when there is a current instance of the object, or if you want to create the object from a file that is already loaded. If there is no current instance and you don't want the object started from a file that is already loaded, use the CreateObject method.

Syntax

Wscript.GetObject(strPathname [,strProgID] ], [strPrefix]) = objObject

Parameters

strPathname
The full path and the name of the file containing the object to retrieve. The strPathname parameter is required.
strProgID
A string representing the program identifier (ProgID) of the object.
strPrefix
If the strPrefix parameter is specified, Windows Scripting Host connects the object's outgoing interface to the script file after creating the object. When the object fires an event, Windows Scripting Host calls a subroutine named strPrefix and the event name.

For example, if strPrefix is "MYOBJ_" and the object fires an event named "OnBegin", Windows Scripting Host calls the "MYOBJ_OnBegin" subroutine located in the script.

Return

objObject
The Automation object retrieved.

Remarks

If an object has registered itself as a single-instance object (for example, the Word.Basic object in Microsoft Word 7.0), only one instance of the object is created, no matter how many times CreateObject is executed. In addition, with a single-instance object, GetObject always returns the same instance when called with the zero-length string syntax (""), and it causes an error if the path parameter is omitted. You can't use GetObject to obtain a reference to a Visual Basic® class created with Visual Basic 4.0 or earlier.

GetObject works with all COM classes, independent of the language used to create the object.

Examples

Dim MyObject As Object
    Set MyObject = GetObject(""C:\CAD\SCHEMA.CAD"")
    = MyCAD.Application

When this code is executed, the application associated with the specified strPathname is started, and the object in the specified file is activated.

If strPathname is a zero-length string (""), GetObject returns a new object instance of the specified type. If the strPathname parameter is omitted entirely, GetObject returns a currently active object of the specified type. If no object of the specified type exists, an error occurs.

Some applications allow you to activate part of a file. To do this, add an exclamation point (!) to the end of the file name and follow it with a string that identifies the part of the file you want to activate. For information on how to create this string, see the documentation for the application that created the object. For example, in a drawing application you might have multiple layers of a drawing stored in a file. You could use the following code to activate a layer within a drawing file called schema.cad:

Set LayerObject = GetObject("C:\CAD\SCHEMA.CAD!Layer3")

If you do not specify the object's class, COM determines the application to start and the object to activate according to the file name you provide. Some files however, may support more than one class of object. For example, a drawing might support three different types of objects: an application object, a drawing object, and a toolbar object, all of which are part of the same file. To specify which object in a file you want to activate, use the optional class parameter. For example:

Dim MyObject As Object
Set MyObject = GetObject("C:\DRAWINGS\SAMPLE.DRW", "FIGMENT.DRAWING")

In the preceding example, FIGMENT is the name of a drawing application and DRAWING is one of the object types it supports.

After an object is activated, you reference it in code using the object variable you defined. In the preceding example, you access properties and methods of the new object using the object variable MyObject. For example:

MyObject.Line 9, 90
MyObject.InsertText 9, 100, "Hello, world."
MyObject.SaveAs "C:\DRAWINGS\SAMPLE.DRW"

See Also

Wscript.CreateObject method, Wscript.DisconnectObject method


Wscript.Quit

The Quit method quits execution with a specified error code.

Syntax

Wscript.Quit [intErrorCode]

Parameters

intErrorCode
If this parameter is included, Wscript returns it as the process exit code. Otherwise, if intErrorCode is omitted, Wscript returns zero (0) as the process exit code.

Example

Wscript.Quit(1)


WshArguments Object

This object is not exposed directly; access it using the Wscript.Arguments property

ProgID | N/A
File name | Wscript.Exe or Cscript.Exe
CLSID | 60254CA4-953b-11CF-8C96-00AA00B8708C
IID | 60254CA3-953b-11CF-8C96-00AA00B8708C

The following table describes the properties associated with the WshArguments object.

Property | Description
Item | The nth command-line parameter (the default property).
Count | The number of command-line parameters.
length | The number of command-line parameters (JScript).


WshArguments.Item

The Item property contains the natIndexth command-line parameter as a string. It is the default property.

Syntax

Arguments(natIndex)
Arguments.Item(natIndex) = strArgument

Example

Set oArgs = Wscript.Arguments.
Wscript.Echo oArgs(0)
Wscript.Echo oArgs.Item(0)

See Also

Wscript.Arguments property


WshArguments.Count

The Count property provides the number of command-line parameters.

Syntax

Arguments.Count = natNumberOfArguments

See Also

Wscript.Arguments property, WshArguments.length property


WshArguments.length

The length property provides the number of command-line parameters. This property provides the same functionality as the Count property and is provided for Microsoft JScript™ compatibility

Syntax

Arguments.length = natNumberOfArguments

See Also

Wscript.Arguments property, WshArguments.Count property


WshShell Object

ProgID | Wscript.WshShell
File name | WSHom.Ocx
CLSID | F935DC22-1CF0-11d0-ADB9-00C04FD58A0B
IID | F935DC21-1CF0-11d0-ADB9-00C04FD58A0B

The following table describes the properties associated with the WshShell object.

Property | Description
Environment | Returns the WshEnvironment collection object.
SpecialFolders | Provides access to Windows shell folders such as the desktop folder, Start menu folder, and personal document folder, using the WshSpecialFolders object.

The following table describes the methods associated with the WshShell object.

Method | Description
CreateShortcut | Creates a WshShortcut object and returns it.
ExpandEnvironmentStrings | Expands a PROCESS environment variable and returns the result string.
Popup | Displays a message box window containing a specified message.
RegDelete | Deletes a specified key or value from the registry.
RegRead | Returns a specified key or value from the registry.
RegWrite | Sets a specified key or value in the registry.
Run | Creates a new process that executes a specified command with a specified window style.


WshShell.Environment

The Environment property returns the WshEnvironment object.

Syntax

WshShell.Environment ( [strType]) = objWshEnvironment

Remarks

If strType specifies where the environment variable resides, possible values are "System", "User", "Volatile", and "Process". If strType is not supplied, this method retrieves the system environment variables in Windows NT or the process environment variables in Windows 95.

For Windows 95, only "Process" is supported in the strType parameter.

The following variables are provided with the Windows operating system. Scripts can also get environment variables that were set by other applications.

Name | Description
NUMBER_OF_PROCESSORS | Number of processors running on the computer.
PROCESSOR_ARCHITECTURE | Processor type of the user's workstation.
PROCESSOR_IDENTIFIER | Processor ID of the user's workstation.
PROCESSOR_LEVEL | Processor level of the user's workstation.
PROCESSOR_REVISION | Processor version of the user's workstation.
OS | Operating system on the user's workstation.
COMSPEC | Executable for command Command Prompt (typically cmd.exe).
HOMEDRIVE | Primary local drive (typically the C drive).
HOMEPATH | Default directory for users (on Windows NT this is typically \users\default.
PATH | PATH environment variable.
PATHEXT | Extensions for executable files (typically .com, .exe, .bat, or .cmd).
PROMPT | Command prompt (typically $P$G).
SYSTEMDRIVE | Local drive on which system directory resides (for example, c:\).
SYSTEMROOT | System directory (for example, c:\winnt). This is the same as WINDIR.
WINDIR | System directory (for example, c:\winnt). This is the same as SYSTEMROOT.
TEMP | Directory for storing temporary files (for example, c:\temp). User, Volatile
TMP | Directory for storing temporary files (for example, c:\temp). User, Volatile

Example

' Retrieve the NUMBER_OF_PROCESSORS system environment variable
    Set WshShell = Wscript.CreateObject("Wscript.Shell")

    Set WshSysEnv = WshShell.Environment("SYSTEM")
    Wscript.Echo WshSysEnv("NUMBER_OF_PROCESSORS")

See Also

WshEnvironment object


WshShell.SpecialFolders

The SpecialFolders property provides the WshSpecialFolders object for accessing Windows shell folders such as the desktop folder, Start menu folder, and personal document folder.

Syntax

WshShell.SpecialFolders = objWshSpecialFolders

Example

' This code fragment shows how to access the desktop folder
    Set WshShell = Wscript.CreateObject("Wscript.Shell")
    MsgBox "Your desktop is " & WshShell.SpecialFolders("Desktop")

See Also

WshSpecialFolders object


WshShell.CreateShortcut

The CreateShortcut method creates a WshShortcut object and returns it. If the shortcut title ends with .url, a WshURLShortcut object is created.

Syntax

WshShell.CreateShortcut(strPathname) = objShortcut

Example

' This code fragment creates a shortcut
' to the currently executing script
    Set WshShell = Wscript.CreateObject("Wscript.Shell")
    Set oShellLink = WshShell.CreateShortcut("Current Script.lnk")
    oShellLink.TargetPath = Wscript.ScriptFullName
    oShellLink.Save
    Set oUrlLink = WshShell.CreateShortcut("Microsoft Web Site.URL")
    oUrlLink.TargetPath = "http://www.microsoft.com"
    oUrlLink.Save

See Also

WshShortcut object, WshUrlShortcut object


WshShell.ExpandEnvironmentStrings

The ExpandEnvironmentStrings method expands the PROCESS environment variable in strString and returns the result string. Variables are enclosed by the '%' character.

The environment variable name is not case-sensitive.

Syntax

WshShell.ExpandEnvironmentStrings(strString) = strExpandedString

Example

MsgBox "Prompt is " & WshShell.ExpandEnviromentStrings("%PROMPT%")


WshShell.Popup

The Popup method displays a popup message box window that contains the message contained in strText. The window title of this message box is specified by strTitle. If strTitle is omitted, the window title is Windows Scripting Host.

Syntax

WshShell.Popup(strText, [natSecondsToWait], [strTitle], [natType]) = intButton

Remarks

If natSecondsToWait is supplied and its value is greater than zero, the message box window will be closed after natSecondsToWait seconds.

The meaning of natType is the same as in the Win32® MessageBox function. The following table shows the value and its meaning in natType. You can combine values in the following tables.

Button Types

Value | Description
0 | Show [OK] button
1 | Show [OK] and [Cancel] buttons
2 | Show [Abort], [Retry] and [Ignore] buttons
3 | Show [Yes], [No] and [Cancel] buttons
4 | Show [Yes] and [No] buttons
5 | Show [Retry] and [Cancel] buttons

Icon Types

Value | Description
16 | Show Stop Mark icon
32 | Show Question Mark icon
48 | Show Exclamation Mark icon
64 | Show Information Mark icon

The preceding two tables do not cover all values for natType. For a complete list, see the Win32 documentation.

The return value intButton denotes the number of the button that the user clicked. If the user does not click a button before natSecondsToWait seconds, intButton is set to -1.

Value | Description
1 | [OK] button
2 | [Cancel] button
3 | [Abort] button
4 | [Retry] button
5 | [Ignore] button
6 | [Yes] button
7 | [No] button

Example

Set WshShell = Wscript.CreateObject("Wscript.Shell")
WshShell.Popup "Where do you want to go today?"

See Also

Wscript.Echo method


WshShell.RegDelete

The RegDelete method deletes from the registry the key or value named strName.

Syntax

WshShell.RegDelete strName

Parameters

strName
If strName ends with a backslash character (\), this method deletes the key instead of the value.

The strName parameter must begin with one of following root key names:
Short | Long
HKCU | HKEY_CURRENT_USER
HKLM | HKEY_LOCAL_MACHINE
HKCR | HKEY_CLASSES_ROOT
HKEY_USERS
HKEY_CURRENT_CONFIG

Example

Set WshShell = Wscript.CreateObject("Wscript.Shell")

WshShell.RegDelete "HKCU\ScriptEngine\Value"    ' Delete value "Value"
WshShell.RegDelete "HKCU\ScriptEngine\Key\"     ' Delete key "Key"

See Also

WshShell.RegRead method, WshShell.RegWrite method


WshShell.RegRead

The RegRead method returns the registry key or value named by strName.

Syntax

WshShell.RegRead(strName) = strValue

Parameters

strName
If strName ends with the backslash character (\), this method returns the key instead of the value.

The strName parameter must begin with one of following root key names.
Short | Long
HKCU | HKEY_CURRENT_USER
HKLM | HKEY_LOCAL_MACHINE
HKCR | HKEY_CLASSES_ROOT
HKEY_USERS
HKEY_CURRENT_CONFIG

Remarks

The RegRead method supports only REG_SZ, REG_EXPAND_SZ, REG_DWORD, REG_BINARY, and REG_MULTI_SZ data types. If the registry has other data types, RegRead returns DISP_E_TYPEMISMATCH.

Example

Set WshShell = Wscript.CreateObject("Wscript.Shell")

WshShell.RegRead("HKCU\ScriptEngine\Val")    ' Read from value "Val"
WshShell.RegRead("HKCU\ScriptEngine\Key\")   ' Read from key "Key"

See Also

WshShell.RegDelete method, WshShell.RegWrite method


WshShell.RegWrite

The RegWrite method sets the registry key or value named by strName.

Syntax

WshShell.RegWrite strName, anyValue, [strType]

Parameters

strName
If strName ends with a backslash character (\), this method sets the key instead of the value.

The strName parameter must begin with one of following root key names.
Short | Long
HKCU | HKEY_CURRENT_USER
HKLM | HKEY_LOCAL_MACHINE
HKCR | HKEY_CLASSES_ROOT
HKEY_USERS
HKEY_CURRENT_CONFIG

anyValue
The RegWrite method automatically converts anyValue to a string when strType is REG_SZ or REG_EXPAND_SZ. If strType is REG_DWORD, anyValue is converted to an integer. If strType is REG_BINARY, anyValue must be an integer.
strType
The RegWrite method supports strType as REG_SZ, REG_EXPAND_SZ, REG_DWORD and REG_BINARY. If another data type is passed as strType, RegWrite returns E_INVALIDARG.

Example

Set WshShell = Wscript.CreateObject("Wscript.Shell")

WshShell.RegWrite "HKCU\ScriptEngine\Value", "Some string value"
WshShell.RegWrite "HKCU\ScriptEngine\Key\", 1 "REG_DWORD"

See Also

WshShell.RegDelete method, WshShell.RegWrite method


WshShell.Run

The Run method creates a new process that executes strCommand with window style intWindowStyle.

Syntax

WshShell.Run (strCommand, [intWindowStyle], [blnWaitOnReturn])

Parameters

strCommand
Environment variables within the strCommand parameter are automatically expanded.
intWindowStyle
This is the value to which the wShowWindow element is set in the STARTUPINFO structure for the new process. Its significance is the same as the nCmdShow parameter of the ShowWindow function, and it may take one of the following values.
Name Value Meaning
SW_HIDE
 0 Hides the window and activates another window.
SW_MINIMIZE
 6 Minimizes the specified window and activates the next top-level window in the Z order.
SW_RESTORE
 9 Activates and displays the window. If the window is minimized or maximized, Windows restores it to its original size and position. An application should specify this flag when restoring a minimized window.
SW_SHOW
 5 Activates the window and displays it in its current size and position.
SW_SHOWMAXIMIZED
 3 Activates the window and displays it as a maximized window.
SW_SHOWMINIMIZED
 2 Activates the window and displays it as a minimized window.
SW_SHOWMINNOACTIVE
 7 Displays the window as a minimized window. The active window remains active.
SW_SHOWNA
 8 Displays the window in its current state. The active window remains active.
SW_SHOWNOACTIVATE
 4 Displays a window in its most recent size and position. The active window remains active.
SW_SHOWNORMAL
 1 Activates and displays a window. If the window is minimized or maximized, Windows restores it to its original size and position.

blnWaitOnReturn
If blnWaitOnReturn is not specified or FALSE, this method immediately returns to script execution rather than waiting for the process termination.

If blnWaitOnReturn is set to TRUE, the Run method returns any error code returned by the application. If blnWaitOnReturn is not specified or is FALSE, Run returns an error code of 0 (zero).

Example

' This fragment launches Notepad with the current executed script
  Set WshShell = Wscript.CreateObject("Wscript.Shell")
  WshShell.Run ("notepad " & Wscript.ScriptFullName)
  WshShell.Run ("%windir%\notepad" & Wscript.ScriptFullName)

' This fragment returns the error code from the executed application
  Return = WshShell.Run("notepad " & Wscript.ScriptFullName, 1, TRUE)


WshNetwork Object

ProgID | Wscript.WshNetwork
File name | WSHom.Ocx
CLSID | F935DC26-1CF0-11d0-ADB9-00C04FD58A0B
IID | F935DC25-1CF0-11d0-ADB9-00C04FD58A0B

The following table describes the properties associated with the WshNetwork object.

Property | Description
ComputerName | A string representation of the computer name.
UserDomain | A string representation of the user's domain name.
UserName | A string representation of the user's name.

The following table describes the methods associated with the WshNetwork object.

Method | Description
AddPrinterConnection | Maps a remote printer to a local resource name.
EnumNetworkDrives | Returns the current network drive mappings.
EnumPrinterConnections | Returns the current network drive mappings.
MapNetworkDrive | Maps a share point to a local resource name.
RemoveNetworkDrive | Removes the current resource connection.
RemovePrinterConnection | Removes a current resource connection.
SetDefaultPrinter | Sets the default printer.


WshNetwork.ComputerName

The ComputerName property provides a string representation of the computer name.

Syntax

WshNetwork.ComputerName = strComputerName


WshNetwork.UserDomain

The UserDomain property provides a string representation of the user domain name.

Syntax

WshNetwork.UserDomain = strDomain


WshNetwork.UserName

The UserName property provides a string representation of the user name.

Syntax

WshNetwork.UserName = strName


WshNetwork.AddPrinterConnection

The AddPrinterConnection method maps the remote printer specified by strRemoteName to the local resource name strLocalName.

Syntax

WshNetwork.AddPrinterConnection strLocalName, strRemoteName, [bUpdateProfile], [strUser], [strPassword]

Parameters

strLocalName
Local resource to map to.
strRemoteName
Remote printer to map.
bUpdateProfile
If bUpdateProfile is supplied and its value is TRUE, this mapping is stored in the user profile.
strUser
If you are mapping a remote printer using the credentials of someone other than current user, you can specify strUser and strPassword.
strPassword
If you are mapping a remote printer using the credentials of someone other than current user, you can specify strUser and strPassword.

Example

Set WshNetwork = Wscript.CreateObject("Wscript.Network")
WshNetwork.AddPrinterConnection "LPT1", "\\Server\Print1"


WshNetwork.EnumNetworkDrives

The EnumNetworkDrives method returns the current network drive mappings as a WshCollection object. Items in this collection are local names and remote names.

Syntax

WshNetwork.EnumNetworkDrive = objWshCollection

Example

Set WshNetwork = Wscript.CreateObject("Wscript.Network")

Set oDrives = WshNetwork.EnumNetworkDrives

Wscript.Echo oDrives.Item(0) = "Z:"
Wscript.Echo oDrives.Item(1) = "\\Server\Share"

See Also

WshNetwork.MapNetworkDrive method, WshNetwork.RemoveNetworkDrive method, WshCollection object


WshNetwork.EnumPrinterConnections

The EnumPrinterConnections method returns the current network drive mappings as a WshCollection object. Items in this collection are local names and remote names.

Syntax

WshNetwork.EnumPrinterConnections = objWshCollection

Example

Set WshNetwork = Wscript.CreateObject("Wscript.Network")
Set oPrinters = WshNetwork.EnumPrinterConnections

Wscript.Echo oPrinters.Item(0) = "LPT1:"
Wscript.Echo oPrinters.Item(1) \\Server\Printer1"

See Also

WshNetwork.AddPrinterConnection method, WshNetwork.RemovePrinterConnection method, WshCollection object


WshNetwork.MapNetworkDrive

The MapNetworkDrive method maps the share point specified by strRemoteName to the local resource name, strLocalName.

Syntax

WshNetwork.MapNetworkDrive strLocalName, strRemoteName, [bUpdateProfile], [strUser], [strPassword]

Parameters

strLocalName
Local resource name to map to.
strRemoteName
Remote share to map.
bUpdateProfile
If bUpdateProfile is supplied and its value is TRUE, this mapping is stored in the user profile.
strUser
If you are mapping the share point using the credentials of someone other than current user, you can specify strUser and strPassword.
strPassword
If you are mapping the share point using the credentials of someone other than current user, you can specify strUser and strPassword.

Example

Set WshNetwork = Wscript.CreateObject("Wscript.Network")
WshNetwork.MapNetworkDrive "Z:", "\\Server\Share"


WshNetwork.RemoveNetworkDrive

The RemoveNetworkDrive method removes the current resource connection denoted by strName.

Syntax

WshNetwork.RemoveNetworkDrive strName, [bForce], [bUpdateProfile]

Parameters

strName
The strName parameter can be either a local name or a remote name, depending on how the drive is mapped. If the drive has a mapping between a local name (drive letter) and a remote name, then strName must be set to the local name. If the network path does not have a local name (drive letter) mapping, then strName must be set to the remote name.
bForce
If bForce is supplied and its value is TRUE, this method removes the connections whether the resource is used or not.
bUpdateProfile
If bUpdateProfile is supplied and its value is TRUE, this mapping is stored in the user profile.

Example

Set WshNetwork = Wscript.CreateObject("Wscript.Network")

' Local name mapped to remote share
  WshNetwork.MapNetworkDrive "Z:", "\\Server\Share"
  WshNetwork.RemoveNetworkDrive "Z:"
' No local name mapping, such as:
' NET USE \\Server\ShareWshNetwork.RemoveNetworkDrive "\\Server\Share"
  WshNetwork.MapNetworkDrive "\\Server\Share"
  WshNetwork.RemoveNetworkDrive "\\Server\Share"


WshNetwork.RemovePrinterConnection

The RemovePrinterConnection method removes the current resource connection denoted by strName.

Syntax

WshNetwork.RemovePrinterConnection strName, [bForce], [bUpdateProfile]

Parameters

strName
The strName parameter can be either a local name or a remote name, depending on how the printer is connected. If the printer has a mapping between a local name (for example, LPT1) and a remote name, then strName must be set to the local name. If the network path does not have a local name mapping, then strName must be set to the remote name.
bForce
If bForce is supplied and its value is TRUE, this method removes the connection whether the resource is used or not.
bUpdateProfile
If bUpdateProfile is supplied and its value is TRUE, this mapping is stored in the user profile.

Example

Set WshNetwork = Wscript.CreateObject("Wscript.Network")
' Local name mapped to remote share
  WshNetwork.RemovePrinterConnection "LPT1:"
' No local name mapping. e.g. NET USE "\\Server\Printer1"
  WshNetwork.RemovePrinterConnection "\\Server\Printer1"


WshNetwork.SetDefaultPrinter

The SetDefaultPrinter method sets default print to the remote printer specified by strPrinterName.

Syntax

WshNetwork.SetDefaultPrinter strPrinterName

Parameters

strPrinterName
Remote printer name to set as default, such as "\\Server\Printer1". Note that strPrinterName cannot be a local name such as "LPT1:".


WshCollection Object

The WshCollection object is not exposed directly. For access to it, use WshNetwork.EnumNetworkDrives or WshNetwork.EnumPrinterConnections.

ProgID | N/A
File name | WSHom.Ocx
CLSID | F935DC24-1CF0-11d0-ADB9-00C04FD58A0B
IID | F935DC23-1CF0-11d0-ADB9-00C04FD58A0B

The following table describes the properties associated with the WshCollection object.

Property | Description
Item | Provides the nth enumerated item as a string.
Count | The number of enumerated items.
length | The number of enumerated items (JScript).


WshCollection.Item

The Item property provides the natIndexth enumerated item as a string. It is the default property.

Syntax

WshCollection(natIndex) = strEnumeratedItem
WshCollection.Item(natIndex) = strEnumeratedItem

Example

Set WshNetwork = Wscript.CreateObject("Wscript.Network")
Set oDrives = WshNetwork.EnumNetworkDrives

Wscript.Echo oDrives.Item(0) = " "Z:"
Wscript.Echo oDrives.Item(1) = "\\Server\Share"


WshCollection.Count

The Count property provides the number of enumerated items.

Syntax

WshCollection.Count = natNumberOfItemsl

See Also

WshCollection.length property


WshCollection.length

The length property provides the number of enumerated items. This property provides the same functionality as the Count property and is provided for compatibility with JScript.

Syntax

WshCollection.length = natNumberOfItems

See Also

WshCollection.Count property


WshEnvironment Object

The WshEnvironment object is not exposed directly. For access to it, use the WshShell.Environment property.

ProgID | N/A
File name | WSHom.Ocx
CLSID |
IID |

The following table describes the properties associated with the WshEnvironment object.

Property | Description
Item | Gets or sets the value of a specified environment variable.
Count | The number of enumerated items.
length | The number of enumerated items (JScript).

The following table describes the method associated with the WshEnvironment object.

Method | Description
Remove | Deletes a specified environment variable.


WshEnvironment.Item

The Item property sets or returns the value for the strName environment variable. It is the default property.

Syntax

WshEnvironment.Item("strName") = strValue
WshEnvironment("strName") = strValue

Example

' Get the value of NUMBER_OF_PROCESSORS environment variable
  Set WshShell = Wscript.CreateObject("Wscript.Shell")
  Set WshSysEnv = WshShell.Environment("SYSTEM")
  Wscript.Echo WshSysEnv("NUMBER_OF_PROCESSORS")

' Set the value of EXAMPLE volatile environment variable to A_VALUE
  Set WshShell = Wscript.CreateObject("Wscript.Shell")
  Set WshEnv = WshShell.Environment("VOLATILE")
  WshEnv("EXAMPLE")= "A_VALUE"

' List all system environment variables
  Set WshShell = Wscript.CreateObject("Wscript.Shell")
  For Each strVarName In WshShell.Environment("SYSTEM")
    MsgBox strVarName
  Next

See Also

WshShell.Environment property


WshEnvironment.Count

The Count property provides the number of enumerated items.

Syntax

WshEnvironment.Count = natNumberOfItems

See Also

WshEnvironment.length property


WshEnvironment.length

The length property provides the number of enumerated items. This property provides the same functionality as the Count property and is provided for compatibility with JScript.

Syntax

WshEnvironment.length = natNumberOfItems

See Also

WshEnvironment.Count property


WshEnvironment.Remove

The Remove method deletes the environment variable specified by strName.

Syntax

WshEnvironment.Remove(strName)

Example

' Delete the EXAMPLE volatile environment variable
  Set WshShell = Wscript.CreateObject("Wscript.Shell")
  WshShell.Environment("VOLATILE").Remove("EXAMPLE")

' Delete multiple variables
  Set WshUsrEnv = Wscript.Environment("User")
  WshUsrEnv.Remove("EXAMPLE_1")
  WshUsrEnv.Remove("EXAMPLE_2")
  WshUsrEnv.Remove("EXAMPLE_3")
  WshUsrEnv.Remove("EXAMPLE_4")

See Also

WshShell.Environment property


WshShortcut Object

This object is not exposed directly. To get the WshShortcut object, use the WshShell.CreateShortcut method.

ProgID | N/A
File name | WSHom.Ocx
CLSID | F935DC28-1CF0-11d0-ADB9-00C04FD58A0B
IID | F935DC27-1CF0-11d0-ADB9-00C04FD58A0B

The following table describes the properties associated with the WshShortcut object.

Property | Description
Arguments | Parameters to a shortcut object.
Description | A description of a shortcut object.
Hotkey | The hot key of a shortcut object.
IconLocation | The icon location of a shortcut object.
TargetPath | The target path of a shortcut object.
WindowStyle | The window style of a shortcut object.
WorkingDirectory | The working directory of a shortcut object.

The following table describes the method associated with the WshShortcut object.

Method | Description
Save | Saves a shortcut into a specified file system.


WshShortcut.Arguments

The Arguments property provides parameters to a shortcut object.

Syntax

WshShortcut.Arguments = strArguments


WshShortcut.Description

The Description property provides a description of a shortcut object.

Syntax

WshShortcut.Description = strDescription


WshShortcut.FullName

The FullName property provides the full path of a shortcut object.

Syntax

WshShortcut.FullName = strFullName


WshShortcut.Hotkey

The HotKey property provides the hot key of a shortcut object. A hot key is a keyboard shortcut to start or switch to a program.

Syntax

WshShortcut.HotKey = strHotKey

Remarks

BNF syntax of strHotKey is as follows:

Hotkey   ::=   modifier* keyname
modifier ::=   "ALT+" | "CTRL+" | "SHIFT+" | "EXT+"
keyname  ::=   "A" .. "Z" |
               "0".. "9" |
               "Back" | "Tab" | "Clear" | "Return" |
               "Escape" | "Space" | "Prior" | ...

Complete key names are found in WINUSER.H. Hotkey is case-insensitive.

Hotkeys can only activate shortcuts located on the Windows desktop or the Windows Start menu .

Windows Explorer does not accept ESC, ENTER, TAB, SPACE, PRINT SCREEN, or BACKSPACE, even though WshShortcut.Hotkey supports these in compliance with the Win32 API. It is therefore recommended that you not use these keys in your shortcut.

Example

Set WshShell = Wscript.CreateObject("Wscript.WshShell")
strDesktop = WshShell.SpecialFolders("Desktop")
Set oMyShortcut = WshShell.CreateShortcut(strDesktop & "\a_key.lnk")
OMyShortcut.TargetPath = "%windir%\notepad.exe"
oMyShortCut.Hotkey = "ALT+CTRL+F"
oMyShortCut.Save
Wscript.Echo oMyShortCut.HotKey = "Alt+Ctrl+F"

See Also

WshSpecialFolders object


WshShortcut.IconLocation

The IconLocation property provides the icon location of a shortcut object. The format of the icon location should be "Path,index".

Syntax

WshShortcut.IconLocation = strIconLocation


WshShortcut.TargetPath

The TargetPath property provides the target path of a shortcut object.

Syntax

WshShortcut.TargetPath = strTargetPath


WshShortcut.WindowStyle

The WindowStyle property provides the window style of a shortcut object.

Syntax

WshShortcut.WindowStyle = natWindowStyle


WshShortcut.WorkingDirectory

The WorkingDirectory property provides the working directory of a shortcut object.

Syntax

WshShortcut.WorkingDirectory = strWorkingDirectory


WshShortcut.Save

The Save method saves the shortcut object to the location specified by the FullName property.

Syntax

WshShortcut.Save


WshSpecialFolders Object

This object is not exposed directly. To get the WshSpecialFolders object, use the WshShell.SpecialFolders property.

ProgID | N/A
File name | WSHom.Ocx
CLSID |
IID |

The following table describes the properties associated with the WshSpecialFolders object.

Property | Description
Item | The full path of the specified special folder (default).
Count | The number of enumerated items.
length | The number of enumerated items (JScript).


WshSpecialFolders.Item

The Item property returns the full path for the special folder specified by strFolderName. It is the default property.

Syntax

WshShell.SpecialFolders.Item("strFolderName") = strFolderPath
WshShell.SpecialFolders("strFolderName") = strFolderPath

Remarks

WshShell.SpecialFolders("strFolderName") returns NULL if the requested folder (strFolderName) is not available. For example, Windows 95 does not have an AllUsersDesktop folder and returns NULL if strFolderName = AllUsersDesktop

The following special folders are provided with the Windows 95 and Windows NT 4.0 operating systems:

AllUsersDesktop

AllUsersStartMenu

AllUsersPrograms

AllUsersStartup

Desktop

Favorites

Fonts

MyDocuments

NetHood

PrintHood

Programs

Recent

SendTo

StartMenu

Startup

Templates

Example

' This fragment returns the full path for the Windows Desktop folder
  Set WshShell = Wscript.CreateObject("Wscript.Shell")
  StrMyDesktop = WshShell.SpecialFolders("Desktop")

' List all special folders
  For Each strFolder In WshShell.SpecialFolders
    MsgBox strFolder
  Next

See Also

WshShell.SpecialFolders property


WshSpecialFolders.Count

The Count property provides the number of enumerated items.

Syntax

WshSpecialFolders.Count = natNumberOfItems

See Also

WshSpecialFolders.length property


WshSpecialFolders.length

The length property provides the number of enumerated items. This property provides the same functionality as the Count property and is provided for compatibility with JScript.

Syntax

WshSpecialFolders.length = natNumberOfItems

See Also

WshSpecialFolders.Count property


WshUrlShortcut Object

This object is not exposed directly. To get the WshUrlShortcut object, use the WshShell.CreateShortcut method.

ProgID | N/A
File name | WSHom.Ocx
CLSID |
IID |

The following table describes the properties associated with the WshUrlShortcut object.

Property | Description
FullName | The full path of a URL shortcut object.
TargetPath | The target path of a URL shortcut object.

The following table describes the method associated with the WshUrlShortcut object.

Property | Description
Save | Saves a shortcut into a specified file system.


WshUrlShortcut.FullName

The FullName property provides the full path of a shortcut object.

Syntax

WshUrlShortcut.FullName = strFullName


WshUrlShortcut.TargetPath

The TargetPath property provides the target path of a shortcut object.

Syntax

WshUrlShortcut.TargetPath = strTargetPath


WshUrlShortcut.Save

The Save method saves a shortcut to the location specified by the FullName property.

Syntax

WshUrlShortcut.Save


Topic Not Found

No matching topic was found. Some possible reasons and remedies are as follows:

  • The file (.chm) that contains the destination topic is not in the expected location.

Remedy: Rerun the MSDN Library Setup.

  • The file (.chm) that contains the current topic or destination topic is out-of-date and the link is no longer valid.

Remedy: Install the latest version of the MSDN Library.

  • The MSDN Library CD is not in the CD-ROM drive.

Remedy: Insert the MSDN Library CD into the CD-ROM drive.